CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-telethon

Full-featured Telegram client library for Python 3

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

chat-management.mddocs/

Chat Management

Chat and channel administration including member management, permissions, admin operations, and participant handling in Telethon.

Capabilities

Participant Management

Retrieve and iterate through chat participants with filtering options.

def iter_participants(
    self,
    entity,
    limit: int = None,
    *,
    search: str = '',
    filter=None,
    chunk_size: int = 200,
    aggressive: bool = False
):
    """
    Iterate through participants in a chat or channel.
    
    Parameters:
    - entity: Chat, channel, or supergroup
    - limit: Maximum number of participants to retrieve
    - search: Search for participants by name
    - filter: Participant filter (admins, bots, recent, etc.)
    - chunk_size: Number of participants per API request
    - aggressive: Use more API calls for complete results
    
    Yields:
    User: Individual participant objects with permissions
    
    Available filters:
    - ChannelParticipantsAdmins: Only administrators
    - ChannelParticipantsBots: Only bots
    - ChannelParticipantsKicked: Banned users
    - ChannelParticipantsRecent: Recent participants
    - ChannelParticipantsSearch: Search by name
    """

async def get_participants(
    self,
    *args,
    **kwargs
) -> TotalList:
    """
    Get all participants matching criteria.
    
    Parameters same as iter_participants().
    
    Returns:
    TotalList: List of User objects with total count
    """

Admin Operations

Manage administrator permissions and roles in chats and channels.

async def edit_admin(
    self,
    entity,
    user,
    *,
    change_info: bool = None,
    post_messages: bool = None,
    edit_messages: bool = None,
    delete_messages: bool = None,
    ban_users: bool = None,
    invite_users: bool = None,
    pin_messages: bool = None,
    add_admins: bool = None,
    anonymous: bool = None,
    manage_call: bool = None,
    other: bool = None,
    title: str = None,
    is_admin: bool = None,
    manage_topics: bool = None
) -> types.Updates:
    """
    Edit administrator permissions for a user.
    
    Parameters:
    - entity: Chat or channel to edit admin in
    - user: User to promote/demote or edit permissions
    - change_info: Can change chat info and photo
    - post_messages: Can post messages (channels)
    - edit_messages: Can edit any messages (channels)
    - delete_messages: Can delete any messages
    - ban_users: Can ban/unban users
    - invite_users: Can invite new users
    - pin_messages: Can pin messages
    - add_admins: Can add new administrators
    - anonymous: Messages appear as channel (channels)
    - manage_call: Can manage voice chats
    - other: All other permissions
    - title: Custom admin title
    - is_admin: Promote (True) or demote (False)
    - manage_topics: Can manage forum topics
    
    Returns:
    Updates object with admin change results
    
    Raises:
    - ChatAdminRequiredError: If not admin in chat
    - UserAdminInvalidError: If cannot edit this admin
    - RightForbiddenError: If permission not available
    """

User Permissions

Manage individual user permissions and restrictions.

async def edit_permissions(
    self,
    entity,
    user=None,
    until_date=None,
    *,
    view_messages: bool = True,
    send_messages: bool = True,
    send_media: bool = True,
    send_stickers: bool = True,
    send_gifs: bool = True,
    send_games: bool = True,
    send_inline: bool = True,
    embed_link_previews: bool = True,
    send_polls: bool = True,
    change_info: bool = True,
    invite_users: bool = True,
    pin_messages: bool = True,
    manage_topics: bool = True
) -> types.Updates:
    """
    Edit user permissions in a chat or set default permissions.
    
    Parameters:
    - entity: Chat or supergroup to edit permissions in
    - user: Specific user (None for default permissions)
    - until_date: Restriction end date (None for permanent)
    - view_messages: Can view chat messages
    - send_messages: Can send text messages
    - send_media: Can send photos, videos, files
    - send_stickers: Can send stickers
    - send_gifs: Can send GIFs and games
    - send_games: Can send games
    - send_inline: Can use inline bots
    - embed_link_previews: Can show link previews
    - send_polls: Can send polls
    - change_info: Can change chat info
    - invite_users: Can invite new users
    - pin_messages: Can pin messages
    - manage_topics: Can manage forum topics
    
    Returns:
    Updates object with permission change results
    
    Raises:
    - ChatAdminRequiredError: If admin rights required
    - UserRestrictedError: If user already restricted
    """

async def get_permissions(
    self,
    entity,
    user
) -> ParticipantPermissions:
    """
    Get current permissions for a user in a chat.
    
    Parameters:
    - entity: Chat or channel
    - user: User to check permissions for
    
    Returns:
    ParticipantPermissions: Object with permission flags
    """

User Management

Kick, ban, and unban users from chats.

async def kick_participant(
    self,
    entity,
    user
) -> types.Updates:
    """
    Remove a user from a chat.
    
    Parameters:
    - entity: Chat or supergroup
    - user: User to remove
    
    Returns:
    Updates object with kick result
    
    Note:
    In supergroups, this bans the user permanently.
    Use edit_permissions to restrict instead of ban.
    
    Raises:
    - ChatAdminRequiredError: If admin rights required
    - UserNotParticipantError: If user not in chat
    """

Admin Log

Access and monitor admin actions and chat history.

def iter_admin_log(
    self,
    entity,
    limit: int = None,
    *,
    max_id: int = 0,
    min_id: int = 0,
    search: str = None,
    admins=None,
    events=None,
    join_leave: bool = None,
    invite: bool = None,
    restrict: bool = None,
    unrestrict: bool = None,
    ban: bool = None,
    unban: bool = None,
    kick: bool = None,
    unkick: bool = None,
    promote: bool = None,
    demote: bool = None,
    info: bool = None,
    settings: bool = None,
    pinned: bool = None,
    edit: bool = None,
    delete: bool = None,
    group_call: bool = None
):
    """
    Iterate through admin log events.
    
    Parameters:
    - entity: Channel or supergroup
    - limit: Maximum number of events to retrieve
    - max_id: Start from this event ID
    - min_id: End at this event ID
    - search: Search in event descriptions
    - admins: Filter by specific admin users
    - events: Filter by specific event types
    - join_leave: Include join/leave events
    - invite: Include invite events
    - restrict: Include restriction events
    - unrestrict: Include unrestriction events
    - ban: Include ban events
    - unban: Include unban events
    - kick: Include kick events
    - unkick: Include unkick events
    - promote: Include promotion events
    - demote: Include demotion events
    - info: Include info change events
    - settings: Include settings change events
    - pinned: Include pin/unpin events
    - edit: Include message edit events
    - delete: Include message delete events
    - group_call: Include voice chat events
    
    Yields:
    AdminLogEvent: Individual admin log entries
    """

async def get_admin_log(
    self,
    *args,
    **kwargs
) -> TotalList:
    """
    Get admin log events matching criteria.
    
    Parameters same as iter_admin_log().
    
    Returns:
    TotalList: List of AdminLogEvent objects
    """

Chat Actions

Send typing indicators and other chat actions.

async def action(
    self,
    entity,
    action,
    *,
    delay: float = 4,
    auto_cancel: bool = True
):
    """
    Send a chat action (typing, uploading, etc.).
    
    Parameters:
    - entity: Chat to send action to
    - action: Action type or string
    - delay: How long to show action (seconds)
    - auto_cancel: Automatically cancel action after delay
    
    Action types:
    - 'typing': Typing text
    - 'upload_photo': Uploading photo
    - 'upload_video': Uploading video
    - 'upload_audio': Uploading audio
    - 'upload_document': Uploading document
    - 'choose_sticker': Choosing sticker
    - 'speaking': Speaking in voice chat
    - 'cancel': Cancel current action
    
    Usage:
    async with client.action(chat, 'typing'):
        # Do something that takes time
        await asyncio.sleep(3)
        await client.send_message(chat, 'Done!')
    """

Profile Photos

Manage and retrieve profile photos for users and chats.

def iter_profile_photos(
    self,
    entity,
    limit: int = None,
    *,
    offset: int = 0,
    max_id: int = 0
):
    """
    Iterate through profile photos of a user or chat.
    
    Parameters:
    - entity: User, chat, or channel
    - limit: Maximum number of photos to retrieve
    - offset: Skip this many photos
    - max_id: Start from photos with ID less than this
    
    Yields:
    Photo: Individual profile photo objects
    """

async def get_profile_photos(
    self,
    *args,
    **kwargs
) -> TotalList:
    """
    Get profile photos for an entity.
    
    Parameters same as iter_profile_photos().
    
    Returns:
    TotalList: List of Photo objects
    """

Chat Statistics

Get statistics and analytics for channels and supergroups.

async def get_stats(
    self,
    entity,
    message=None
) -> Union[types.stats.BroadcastStats, types.stats.MegagroupStats]:
    """
    Get statistics for a channel or supergroup.
    
    Parameters:
    - entity: Channel or supergroup
    - message: Specific message to get stats for
    
    Returns:
    BroadcastStats for channels or MegagroupStats for supergroups
    
    Contains:
    - View counts
    - Subscriber growth
    - Message statistics
    - Interaction data
    
    Raises:
    - ChatAdminRequiredError: If admin rights required
    - StatisticsForbiddenError: If statistics not available
    """

Usage Examples

Basic Participant Management

import asyncio
from telethon import TelegramClient

async def manage_participants():
    client = TelegramClient('session', api_id, api_hash)
    await client.start()
    
    chat = 'your_group_or_channel'
    
    # Get all participants
    participants = await client.get_participants(chat)
    print(f"Total participants: {participants.total}")
    
    # Iterate through participants
    async for user in client.iter_participants(chat, limit=50):
        print(f"User: {user.first_name} (@{user.username})")
        
        # Check if user is admin
        permissions = await client.get_permissions(chat, user)
        if permissions.is_admin:
            print(f"  - Admin: {user.first_name}")
    
    # Search for specific users
    async for user in client.iter_participants(chat, search='john'):
        print(f"Found user named John: {user.first_name}")
    
    await client.disconnect()

asyncio.run(manage_participants())

Admin Management

from telethon.tl.types import ChannelParticipantsAdmins

async def manage_admins():
    client = TelegramClient('session', api_id, api_hash)
    await client.start()
    
    chat = 'your_supergroup'
    user_to_promote = 'username_to_promote'
    
    # Get current admins
    admins = await client.get_participants(
        chat, 
        filter=ChannelParticipantsAdmins
    )
    print(f"Current admins: {len(admins)}")
    
    # Promote user to admin with specific permissions
    await client.edit_admin(
        chat,
        user_to_promote,
        change_info=True,       # Can change chat info
        delete_messages=True,   # Can delete messages
        ban_users=True,         # Can ban users
        invite_users=True,      # Can invite users
        pin_messages=True,      # Can pin messages
        title='Moderator'       # Custom admin title
    )
    print(f"Promoted {user_to_promote} to admin")
    
    # Demote admin (remove admin rights)
    await client.edit_admin(
        chat,
        user_to_promote,
        is_admin=False
    )
    print(f"Demoted {user_to_promote}")
    
    await client.disconnect()

User Permissions and Restrictions

from datetime import datetime, timedelta

async def manage_permissions():
    client = TelegramClient('session', api_id, api_hash)
    await client.start()
    
    chat = 'your_supergroup'
    user_to_restrict = 'username_to_restrict'
    
    # Restrict user for 1 hour
    restriction_end = datetime.now() + timedelta(hours=1)
    
    await client.edit_permissions(
        chat,
        user_to_restrict,
        until_date=restriction_end,
        send_messages=False,    # Cannot send messages
        send_media=False,       # Cannot send media
        send_stickers=False,    # Cannot send stickers
        embed_link_previews=False  # Cannot embed links
    )
    print(f"Restricted {user_to_restrict} for 1 hour")
    
    # Remove restrictions (restore default permissions)
    await client.edit_permissions(
        chat,
        user_to_restrict,
        until_date=None,        # Remove time limit
        send_messages=True,     # Can send messages
        send_media=True,        # Can send media
        send_stickers=True      # Can send stickers
    )
    print(f"Removed restrictions from {user_to_restrict}")
    
    # Set default chat permissions (for all members)
    await client.edit_permissions(
        chat,
        user=None,              # None = default permissions
        send_polls=False,       # Members cannot send polls
        pin_messages=False      # Members cannot pin messages
    )
    print("Updated default permissions")
    
    await client.disconnect()

Admin Log Monitoring

async def monitor_admin_log():
    client = TelegramClient('session', api_id, api_hash)
    await client.start()
    
    channel = 'your_channel_or_supergroup'
    
    # Get recent admin actions
    async for event in client.iter_admin_log(channel, limit=20):
        print(f"Event: {event.action}")
        print(f"Admin: {event.user.first_name}")
        print(f"Date: {event.date}")
        
        # Check specific event types
        if hasattr(event.action, 'message'):
            print(f"Message involved: {event.action.message.message}")
        
        if hasattr(event.action, 'participant'):
            print(f"User affected: {event.action.participant.user_id}")
        
        print("---")
    
    # Filter for specific events
    async for event in client.iter_admin_log(
        channel,
        ban=True,           # Only ban events
        limit=10
    ):
        print(f"Ban event by {event.user.first_name}")
        if hasattr(event.action, 'participant'):
            user_id = event.action.participant.user_id
            print(f"Banned user ID: {user_id}")
    
    await client.disconnect()

Chat Actions (Typing Indicators)

async def chat_actions():
    client = TelegramClient('session', api_id, api_hash)
    await client.start()
    
    chat = 'username'
    
    # Show typing indicator
    async with client.action(chat, 'typing'):
        # Simulate typing for 3 seconds
        await asyncio.sleep(3)
        await client.send_message(chat, 'Hello! I was typing...')
    
    # Show uploading photo indicator
    async with client.action(chat, 'upload_photo'):
        # Simulate photo upload preparation
        await asyncio.sleep(2)
        await client.send_file(chat, 'photo.jpg')
    
    # Manual action control
    await client.action(chat, 'upload_document')
    await asyncio.sleep(1)
    await client.action(chat, 'cancel')  # Cancel action
    
    await client.disconnect()

Chat Statistics

async def get_chat_statistics():
    client = TelegramClient('session', api_id, api_hash)
    await client.start()
    
    channel = 'your_channel'
    
    try:
        stats = await client.get_stats(channel)
        
        if hasattr(stats, 'views_graph'):
            print(f"Channel statistics:")
            print(f"Period: {stats.period}")
            print(f"Followers: {stats.followers.current}")
            print(f"Views: {stats.views_per_post.current}")
            print(f"Shares: {stats.shares_per_post.current}")
            
        # Get message-specific stats
        async for message in client.iter_messages(channel, limit=5):
            msg_stats = await client.get_stats(channel, message)
            if hasattr(msg_stats, 'views_graph'):
                print(f"Message {message.id} views: {msg_stats.views_graph}")
                
    except Exception as e:
        print(f"Could not get statistics: {e}")
    
    await client.disconnect()

Types

from typing import Union, List, Optional, AsyncIterator
from datetime import datetime
from telethon.tl import types
from telethon import custom

EntityLike = Union[int, str, types.User, types.Chat, types.Channel]
UserLike = Union[int, str, types.User]
AdminFilter = Union[types.ChannelParticipantsFilter, None]

class ParticipantPermissions:
    """User permissions in a chat"""
    is_admin: bool
    is_creator: bool
    can_change_info: bool
    can_post_messages: bool
    can_edit_messages: bool
    can_delete_messages: bool
    can_ban_users: bool
    can_invite_users: bool
    can_pin_messages: bool
    can_add_admins: bool

class AdminLogEvent:
    """Admin log event entry"""
    id: int
    date: datetime
    user: types.User
    action: types.ChannelAdminLogEventAction

Install with Tessl CLI

npx tessl i tessl/pypi-telethon

docs

authentication-sessions.md

chat-management.md

client-management.md

error-handling.md

event-system.md

file-handling.md

index.md

message-operations.md

utilities-helpers.md

tile.json