Client class

The Client class is the “entry point” of the library.

Most client methods have an alias in the respective types. For example, Client.forward_messages() can also be invoked from types.Message.forward(). With a few exceptions, client.verb_object methods also exist as object.verb.

class telethon.Client(session, api_id, api_hash=None, *, catch_up=False, check_all_handlers=False, flood_sleep_threshold=None, logger=None, update_queue_limit=None, device_model=None, system_version=None, app_version=None, system_lang_code=None, lang_code=None, datacenter=None, connector=None)

Bases: object

A client capable of connecting to Telegram and sending requests.

This class can be used as an asynchronous context manager to automatically connect() and disconnect():

async with Client(session, api_id, api_hash) as client:
    ...  # automatically connect()-ed

...  # after exiting the block, disconnect() was automatically called
Parameters:
  • session (str | Path | Storage | None) – A name or path to a .session file, or a different storage.

  • api_id (int) –

    The API ID. See Signing in to learn how to obtain it.

    This is required to initialize the connection.

  • api_hash (str | None) –

    The API hash. See Signing in to learn how to obtain it.

    This is required to sign in, and can be omitted otherwise.

  • catch_up (bool) –

    Whether to “catch up” on updates that occured while the client was not connected.

    If True, all updates that occured while the client was offline will trigger your event handlers.

  • check_all_handlers (bool) –

    Whether to always check all event handlers or stop early.

    The library will call event handlers in the order they were added. By default, the library stops checking handlers as soon as a filter returns True.

    By setting check_all_handlers=True, the library will keep calling handlers after the first match. Use telethon.events.Continue instead if you only want this behaviour sometimes.

  • flood_sleep_threshold (int | None) – Maximum amount of time, in seconds, to automatically sleep before retrying a request. This sleeping occurs when FLOOD_WAIT (and similar) RpcErrors are raised by Telegram.

  • logger (Logger | None) –

    Logger for the client. Any dependency of the client will use logging.Logger.getChild(). This effectively makes the parameter the root logger.

    The default will get the logger for the package name from the root (usually telethon).

  • update_queue_limit (int | None) –

    Maximum amount of updates to keep in memory before dropping them.

    A warning will be logged on a cooldown if this limit is reached.

  • device_model (str | None) – Device model.

  • system_version (str | None) – System version.

  • app_version (str | None) – Application version.

  • system_lang_code (str | None) – ISO 639-1 language code of the system’s language.

  • lang_code (str | None) –

    ISO 639-1 language code of the application’s language.

  • datacenter (DataCenter | None) – Override the data center to connect to. Useful to connect to one of Telegram’s test servers.

  • connector (Connector | None) –

    Asynchronous function called to connect to a remote address. By default, this is asyncio.open_connection(). In order to use proxies, you can set a custom connector.

    See Connector for more details.

add_event_handler(handler, /, event_cls, filter=None)

Register a callable to be invoked when the provided event type occurs.

Parameters:
  • handler (Callable[[Event], Awaitable[Any]]) – The callable to invoke when an event occurs. This is often just a function object.

  • event_cls (Type[Event]) – The event type to bind to the handler. When Telegram sends an update corresponding to this type, handler is called with an instance of this event type as the only argument.

  • filter (Callable[[Event], bool] | None) – Filter function to call with the event before calling handler. If it returns False, handler will not be called. See the filters module to learn more.

Return type:

None

Example

async def my_print_handler(event):
    print(event.chat.name, event.text)

# Register a handler to be called on new messages
client.add_event_handler(my_print_handler, events.NewMessage)

# Register a handler to be called on new messages if they contain "hello" or "/start"
from telethon.events import filters

client.add_event_handler(
    my_print_handler,
    events.NewMessage,
    filters.Any(filters.Text(r'hello'), filters.Command('/start')),
)

See also

on(), used to register handlers with the decorator syntax.

async bot_sign_in(token)

Sign in to a bot account.

Parameters:

token (str) – The bot token obtained from @BotFather. It’s a string composed of digits, a colon, and characters from the base-64 alphabet.

Returns:

The bot user corresponding to yourself.

Return type:

User

Example

user = await client.bot_sign_in('12345:abc67DEF89ghi')
print('Signed in to bot account:', user.name)

Caution

Be sure to check is_authorized() before calling this function. Signing in often when you don’t need to will lead to RPC Errors.

See also

request_login_code(), used to sign in as a user instead.

async check_password(token, password)

Check the two-factor-authentication (2FA) password. If it is correct, completes the login.

Parameters:
Returns:

The user corresponding to yourself.

Return type:

User

Example

from telethon.types import PasswordToken

login_token = await client.request_login_code('+1 23 456')
password_token = await client.sign_in(login_token, input('code: '))
assert isinstance(password_token, PasswordToken)

user = await client.check_password(password_token, '1-L0V3+T3l3th0n')
print('Signed in to 2FA-protected account:', user.name)
async connect()

Connect to the Telegram servers.

Example

await client.connect()
# success!
Return type:

None

property connected: bool

True if connect() has been called previously.

This property will be set back to False after calling disconnect().

This property does not check whether the connection is alive. The only way to check if the connection still works is to make a request.

async delete_dialog(dialog, /)

Delete a dialog.

This lets you leave a group, unsubscribe from a channel, or delete a one-to-one private conversation.

Note that the group or channel will not be deleted (other users will remain in it).

Note that bot accounts do not have dialogs, so this method will fail when used in a bot account.

Parameters:

dialog (Peer | PeerRef) – The peer representing the dialog to delete.

Return type:

None

Example

async for dialog in client.iter_dialogs():
    if 'dog pictures' in dialog.chat.name:
        # You've realized you're more of a cat person
        await client.delete_dialog(dialog.chat)
async delete_messages(chat, /, message_ids, *, revoke=True)

Delete messages.

Parameters:
  • chat (Peer | PeerRef) –

    The peer where the messages are.

    Warning

    When deleting messages from private conversations or small groups, this parameter is currently ignored. This means the message_ids may delete messages in different chats.

  • message_ids (list[int]) – The list of message identifiers to delete.

  • revoke (bool) – When set to True, the message will be deleted for everyone that is part of chat. Otherwise, the message will only be deleted for yourself.

Returns:

The amount of messages that were deleted.

Return type:

int

Example

# Delete two messages from chat for yourself
delete_count = await client.delete_messages(
    chat,
    [187481, 187482],
    revoke=False,
)
print('Deleted', delete_count, 'message(s)')
async disconnect()

Disconnect from the Telegram servers.

This call will only fail if saving the session fails.

Example

await client.disconnect()
# success!
Return type:

None

async download(media, /, file)

Download a file.

Parameters:
Return type:

None

Example

if photo := message.photo:
    await client.download(photo, f'picture{photo.ext}')

if video := message.video:
    with open(f'video{video.ext}', 'wb') as file:
        await client.download(video, file)

See also

get_file_bytes(), for more control over the download.

async edit_draft(peer, /, text=None, *, markdown=None, html=None, link_preview=False, reply_to=None)

Set a draft message in a chat.

This can also be used to clear the draft by setting the text to an empty string "".

Parameters:
Returns:

The created draft.

Return type:

Draft

Example

# Set a draft with no formatting and print the date Telegram registered
draft = await client.edit_draft(chat, 'New text')
print('Set current draft on', draft.date)

# Set a draft using HTML formatting, with a reply, and enabling the link preview
await client.edit_draft(
    chat,
    html='Draft with <em>reply</em> an URL https://example.com',
    reply_to=message_id,
    link_preview=True
)
async edit_message(chat, /, message_id, *, text=None, markdown=None, html=None, link_preview=False, buttons=None)

Edit a message.

Parameters:
Returns:

The edited message.

Return type:

Message

Example

# Edit message to have text without formatting
await client.edit_message(chat, msg_id, text='New text')

# Remove the link preview without changing the text
await client.edit_message(chat, msg_id, link_preview=False)
async forward_messages(target, message_ids, source)

Forward messages from one peer to another.

Parameters:
  • target (Peer | PeerRef) – The peer where the messages will be forwarded to.

  • message_ids (list[int]) – The list of message identifiers to forward.

  • source (Peer | PeerRef) – The source peer where the messages to forward exist.

Returns:

The forwarded messages.

Return type:

list[Message]

Example

# Forward two messages from chat to the destination
messages = await client.forward_messages(
    destination,
    [187481, 187482],
    chat,
)
print('Forwarded', len(messages), 'message(s)')
get_admin_log(chat, /)

Get the recent actions from the administrator’s log.

This method requires you to be an administrator in the peer.

The returned actions are also known as “admin log events”.

Parameters:

chat (Group | Channel | GroupRef | ChannelRef) – The peer to fetch recent actions from.

Returns:

The recent actions.

Return type:

AsyncList[RecentAction]

Example

async for admin_log_event in client.get_admin_log(chat):
    if message := admin_log_event.deleted_message:
        print('Deleted:', message.text)
get_contacts()

Get the users in your contact list.

Returns:

Your contacts.

Return type:

AsyncList[User]

Example

async for user in client.get_contacts():
    print(user.name, user.id)
get_dialogs()

Get the dialogs you’re part of.

This list of includes the groups you’ve joined, channels you’ve subscribed to, and open one-to-one private conversations.

Note that bot accounts do not have dialogs, so this method will fail.

Returns:

Your dialogs.

Return type:

AsyncList[Dialog]

Example

async for dialog in client.get_dialogs():
    print(
        dialog.chat.name,
        dialog.last_message.text if dialog.last_message else ''
    )
get_drafts()

Get all message drafts saved in any dialog.

Returns:

The existing message drafts.

Return type:

AsyncList[Draft]

Example

# Clear all drafts
async for draft in client.get_drafts():
    await draft.delete()
get_file_bytes(media, /)

Get the contents of an uploaded media file as chunks of bytes.

This lets you iterate over the chunks of a file and print progress while the download occurs.

If you just want to download a file to disk without printing progress, use download() instead.

Parameters:

media (File) – The media file to download. This will often come from telethon.types.Message.file.

Return type:

AsyncList[bytes]

Example

if file := message.file:
    with open(f'media{file.ext}', 'wb') as fd:
        downloaded = 0
        async for chunk in client.get_file_bytes(file):
            downloaded += len(chunk)
            fd.write(chunk)
            print(f'Downloaded {downloaded // 1024}/{file.size // 1024} KiB')
get_handler_filter(handler, /)

Get the filter associated to the given event handler.

Parameters:

handler (Callable[[Event], Awaitable[Any]]) – The callable that was previously added as an event handler.

Returns:

The filter, if handler was actually registered and had a filter.

Return type:

Callable[[Event], bool] | None

Example

from telethon.events import filters

# Get the current filter...
filt = client.get_handler_filter(my_handler)

# ...and "append" a new filter that also must match.
client.set_handler_filter(my_handler, filters.All(filt, filt.Text(r'test')))
async get_me()

Get information about yourself.

Returns:

The user associated with the logged-in account, or None if the client is not authorized.

Return type:

User | None

Example

me = await client.get_me()
assert me is not None, "not logged in!"

if me.bot:
    print('I am a bot')

print('My name is', me.name)

if me.phone:
    print('My phone number is', me.phone)
get_messages(chat, /, limit=None, *, offset_id=None, offset_date=None)

Get the message history from a peer, from the newest message to the oldest.

The returned iterator can be reversed() to fetch from the first to the last instead.

Parameters:
  • chat (Peer | PeerRef) – The peer where the messages should be fetched from.

  • limit (int | None) – How many messages to fetch at most.

  • offset_id (int | None) – Start getting messages with an identifier lower than this one. This means only messages older than the message with id = offset_id will be fetched.

  • offset_date (datetime | None) – Start getting messages with a date lower than this one. This means only messages sent before offset_date will be fetched.

Returns:

The message history.

Return type:

AsyncList[Message]

Example

# Get the last message in a chat
last_message = (await client.get_messages(chat, 1))[0]
print(message.sender.name, last_message.text)

# Print all messages before 2023 as HTML
from datetime import datetime

async for message in client.get_messages(chat, offset_date=datetime(2023, 1, 1)):
    print(message.sender.name, ':', message.html_text)

# Print the first 10 messages in a chat as markdown
async for message in reversed(client.get_messages(chat)):
    print(message.sender.name, ':', message.markdown_text)
get_messages_with_ids(chat, /, message_ids)

Get the full message objects from the corresponding message identifiers.

Parameters:
  • chat (Peer | PeerRef) – The peer where the message to fetch is.

  • message_ids (list[int]) – The message identifiers of the messages to fetch.

Returns:

The matching messages. The order of the returned messages is not guaranteed to match the input. The method may return less messages than requested when some are missing.

Return type:

AsyncList[Message]

Example

# Get the first message (after "Channel created") of the chat
first_message = (await client.get_messages_with_ids(chat, [2]))[0]
get_participants(chat, /)

Get the participants in a group or channel, along with their permissions.

Note

Telegram is rather strict when it comes to fetching members. It is very likely that you will not be able to fetch all the members. There is no way to bypass this.

Parameters:

chat (Group | Channel | GroupRef | ChannelRef) – The peer to fetch participants from.

Returns:

The participants.

Return type:

AsyncList[Participant]

Example

async for participant in client.get_participants(chat):
    print(participant.user.name)
get_profile_photos(peer, /)

Get the profile pictures set in a chat, or user avatars.

Parameters:

peer (Peer | PeerRef) – The peer to fetch the profile photo files from.

Returns:

The photo files.

Return type:

AsyncList[File]

Example

i = 0
async for photo in client.get_profile_photos(chat):
    await client.download(photo, f'{i}.jpg')
    i += 1
async inline_query(bot, /, query='', *, peer=None)

Perform a @bot inline query.

It’s known as inline because clients with a GUI display the results inline, after typing on the message input textbox, without sending any message.

Parameters:
  • bot (User | UserRef) – The bot to sent the query string to.

  • query (str) – The query string to send to the bot.

  • peer (Peer | PeerRef | None) – Where the query is being made and will be sent. Some bots display different results based on the type of chat.

Returns:

The query results returned by the bot.

Return type:

AsyncIterator[InlineResult]

Example

i = 0

# This is equivalent to typing "@bot songs" in an official client
async for result in client.inline_query(bot, 'songs'):
    if 'keyword' in result.title:
        await result.send(chat)
        break

    i += 1
    if i == 10:
        break  # did not find 'keyword' in the first few results
async interactive_login(phone_or_token=None, *, password=None)

Begin an interactive login if needed. If the account was already logged-in, this method simply returns yourself.

Parameters:
  • phone_or_token (str | None) – Bypass the phone number or bot token prompt, and use this value instead.

  • password (str | None) – Bypass the 2FA password prompt, and use this value instead.

Returns:

The user corresponding to yourself.

Return type:

User

Example

# Interactive login from the terminal
me = await client.interactive_login()
print('Logged in as:', me.name)

# Automatic login to a bot account
await client.interactive_login('54321:hJrIQtVBab0M2Yqg4HL1K-EubfY_v2fEVR')

See also

In-depth explanation for Signing in.

async is_authorized()

Check whether the client instance is authorized (i.e. logged-in).

Returns:

True if the client instance has signed-in.

Return type:

bool

Example

if not await client.is_authorized():
    ...  # need to sign in

See also

get_me() can be used to fetch up-to-date information about yourself and check if you’re logged-in at the same time.

on(event_cls, /, filter=None)

Register the decorated function to be invoked when the provided event type occurs.

Parameters:
  • event_cls (Type[Event]) – The event type to bind to the handler. When Telegram sends an update corresponding to this type, the decorated function is called with an instance of this event type as the only argument.

  • filter (Callable[[Event], bool] | None) – Filter function to call with the event before calling handler. If it returns False, handler will not be called. See the filters module to learn more.

Returns:

The decorator.

Return type:

Callable[[Callable[[Event], Awaitable[Any]]], Callable[[Event], Awaitable[Any]]]

Example

# Register a handler to be called on new messages
@client.on(events.NewMessage)
async def my_print_handler(event):
    print(event.chat.name, event.text)

# Register a handler to be called on new messages if they contain "hello" or "/start"
from telethon.events.filters import Any, Text, Command

@client.on(events.NewMessage, Any(Text(r'hello'), Command('/start')))
async def my_other_print_handler(event):
    print(event.chat.name, event.text)

See also

add_event_handler(), used to register existing functions as event handlers.

async pin_message(chat, /, message_id)

Pin a message to be at the top.

Parameters:
  • chat (Peer | PeerRef) – The peer where the message to pin is.

  • message_id (int) – The identifier of the message to pin.

Returns:

The service message announcing the pin.

Return type:

Message

Example

# Pin a message, then delete the service message
message = await client.pin_message(chat, 187481)
await message.delete()
prepare_album()

Prepare an album upload to send.

Albums are a way to send multiple photos or videos as separate messages with the same grouped identifier.

Returns:

A new album builder instance, with no media added to it yet.

Return type:

AlbumBuilder

Example

# Prepare a new album
album = await client.prepare_album()

# Add a bunch of photos
for photo in ('a.jpg', 'b.png'):
    await album.add_photo(photo)
# A video in-between
await album.add_video('c.mp4')
# And another photo
await album.add_photo('d.jpeg')

# Album is ready to be sent to as many chats as needed
await album.send(chat)
async read_message(chat, /, message_id)

Mark messages as read.

This will send a read acknowledgment to all messages with identifiers below and up-to the given message identifier.

This is often represented as a blue double-check (✓✓).

A single check (✓) in Telegram often indicates the message was sent and perhaps received, but not read.

A clock (🕒) in Telegram often indicates the message was not yet sent at all. This most commonly occurs when sending messages without a network connection.

Parameters:
  • chat (Peer | PeerRef) – The chat where the messages to be marked as read are.

  • message_id (int | Literal['all']) –

    The identifier of the message to mark as read. All messages older (sent before) this one will also be marked as read.

    The literal 'all' may be used to mark all messages in a chat as read.

Return type:

None

Example

# Mark all messages as read
await client.read_message(chat, 'all')
remove_event_handler(handler, /)

Remove the handler as a function to be called when events occur. This is simply the opposite of add_event_handler(). Does nothing if the handler was not actually registered.

Parameters:

handler (Callable[[Event], Awaitable[Any]]) – The callable to stop invoking when events occur.

Return type:

None

Example

# Register a handler that removes itself when it receives 'stop'
@client.on(events.NewMessage)
async def my_handler(event):
    if 'stop' in event.text:
        client.remove_event_handler(my_handler)
    else:
        print('still going!')
async request_login_code(phone)

Request Telegram to send a login code to the provided phone number.

Parameters:

phone (str) – The phone number string, in international format. The plus-sign + can be kept in the string.

Returns:

Information about the sent code.

Return type:

LoginToken

Example

login_token = await client.request_login_code('+1 23 456...')
print(login_token.timeout, 'seconds before code expires')

Caution

Be sure to check is_authorized() before calling this function. Signing in often when you don’t need to will lead to RPC Errors.

See also

sign_in(), to complete the login procedure.

async resolve_peers(peers, /)

Resolve one or more peer references into peer objects.

This methods also accepts peer objects as input, which will be refetched but not mutated in-place.

Parameters:

peers (Sequence[Peer | PeerRef]) – The peers to fetch.

Returns:

The fetched peers, in the same order as the input.

Return type:

list[Peer]

Example

[user, group, channel] = await client.resolve_peers([
    user_ref, group_ref, channel_ref
])
async resolve_phone(phone, /)

Resolve a phone number into a peer.

This method is rather expensive to call. It is recommended to use it once and then store the types.Peer.ref.

Parameters:

phone (str) – The phone number “+1 23 456” to resolve. The phone number must contain the International Calling Code. You do not need to use include the '+' prefix, but the parameter must be a str, not int.

Returns:

The matching chat.

Return type:

Peer

Example

print(await client.resolve_phone('+1 23 456'))
async resolve_username(username, /)

Resolve a username into a peer.

This method is rather expensive to call. It is recommended to use it once and then store the types.Peer.ref.

Parameters:

username (str) – The public “@username” to resolve. You do not need to use include the '@' prefix. Links cannot be used.

Returns:

The matching chat.

Return type:

Peer

Example

print(await client.resolve_username('@cat'))
async run_until_disconnected()

Keep running the library until a disconnection occurs.

Connection errors will be raised from this method if they occur.

Return type:

None

search_all_messages(limit=None, *, query=None, offset_id=None, offset_date=None)

Perform a global message search. This is used to search messages in no particular chat (i.e. everywhere possible).

Parameters:
  • limit (int | None) – How many messages to fetch at most.

  • query (str | None) – Text query to use for fuzzy matching messages. The rules for how “fuzzy” works are an implementation detail of the server.

  • offset_id (int | None) – Start getting messages with an identifier lower than this one. This means only messages older than the message with id = offset_id will be fetched.

  • offset_date (datetime | None) – Start getting messages with a date lower than this one. This means only messages sent before offset_date will be fetched.

Returns:

The found messages.

Return type:

AsyncList[Message]

Example

async for message in client.search_all_messages(query='hello'):
    print(message.text)
search_messages(chat, /, limit=None, *, query=None, offset_id=None, offset_date=None)

Search messages in a chat.

Parameters:
  • chat (Peer | PeerRef) – The peer where messages will be searched.

  • limit (int | None) – How many messages to fetch at most.

  • query (str | None) – Text query to use for fuzzy matching messages. The rules for how “fuzzy” works are an implementation detail of the server.

  • offset_id (int | None) – Start getting messages with an identifier lower than this one. This means only messages older than the message with id = offset_id will be fetched.

  • offset_date (datetime | None) – Start getting messages with a date lower than this one. This means only messages sent before offset_date will be fetched.

Returns:

The found messages.

Return type:

AsyncList[Message]

Example

async for message in client.search_messages(chat, query='hello'):
    print(message.text)
async send_audio(chat, /, file, *, size=None, name=None, mime_type=None, duration=None, voice=False, title=None, performer=None, caption=None, caption_markdown=None, caption_html=None, reply_to=None, buttons=None)

Send an audio file.

Unlike send_file(), this method will attempt to guess the values for duration, title and performer if they are not provided.

Parameters:
Return type:

Message

Example

await client.send_audio(chat, 'file.ogg', voice=True)
async send_file(chat, /, file, *, size=None, name=None, mime_type=None, compress=False, animated=False, duration=None, voice=False, title=None, performer=None, emoji=None, emoji_sticker=None, width=None, height=None, round=False, supports_streaming=False, muted=False, caption=None, caption_markdown=None, caption_html=None, reply_to=None, buttons)

Send any type of file with any amount of attributes.

This method will not attempt to guess any of the file metadata such as width, duration, title, etc. If you want to let the library attempt to guess the file metadata, use the type-specific methods to send media: send_photo, send_audio or send_file.

Unlike send_photo(), image files will be sent as documents by default.

Parameters:
  • chat (Peer | PeerRef) – The peer where the message will be sent to.

  • path – A local file path or File to send.

  • file (str | Path | InFileLike | File) –

    The file to send.

    This can be a path, relative or absolute, to a local file, as either a str or pathlib.Path.

    It can also be a file opened for reading in binary mode, with its read method optionally being async. Note that the file descriptor will not be seeked back to the start before sending it.

    If you wrote to an in-memory file, you probably want to file.seek(0) first. If you want to send bytes, wrap them in io.BytesIO first.

    You can also pass any File that was previously sent in Telegram to send a copy. This will not download and re-upload the file, but will instead reuse the original without forwarding it.

    Last, a URL can also be specified. For the library to detect it as a URL, the string must start with either http://` or ``https://. Telethon will not download and upload the file, but will instead pass the URL to Telegram. If Telegram is unable to access the media, is too large, or is invalid, the method will fail.

    When using URLs, it is recommended to explicitly pass either a name or define the mime-type. To make sure the URL is interpreted as an image, use send_photo.

  • size (int | None) –

    The size of the local file to send.

    This parameter must be specified when sending a previously-opened or in-memory files. The library will not seek the file to attempt to determine the size.

    This can be less than the real file size, in which case only size bytes will be sent. This can be useful if you have a single buffer with multiple files.

  • name (str | None) –

    Override for the default file name.

    When given a string or path, its name will be used by default only if this parameter is omitted.

    When given a file-like object, if it has a .name str property, it will be used. This is the case for files opened via open().

    This parameter must be specified when sending any other previously-opened or in-memory files.

  • mime_type (str | None) –

    Override for the default mime-type.

    By default, the library will use mimetypes.guess_type() on the name.

    If no mime-type is registered for the name’s extension, application/octet-stream will be used.

  • compress (bool) –

    Whether the image file is allowed to be compressed by Telegram.

    If not, image files will be sent as document.

  • animated (bool) – Whether the sticker is animated (not a static image).

  • duration (float | None) –

    Duration, in seconds, of the audio or video.

    This field should be specified when sending audios or videos from local files.

    The floating-point value will be rounded to an integer.

  • voice (bool) – Whether the audio is a live recording, often recorded right before sending it.

  • title (str | None) – Title of the song in the audio file.

  • performer (str | None) – Artist or main performer of the song in the audio file.

  • emoji (str | None) – Alternative text for the sticker.

  • width (int | None) –

    Width, in pixels, of the image or video.

    This field should be specified when sending images or videos from local files.

  • height (int | None) –

    Height, in pixels, of the image or video.

    This field should be specified when sending images or videos from local files.

  • round (bool) – Whether the video should be displayed as a round video.

  • supports_streaming (bool) –

    Whether clients are allowed to stream the video having to wait for a full download.

    Note that the file format of the video must have streaming support.

  • muted (bool) –

    Whether the sound of the video is or should be missing.

    This is often used for short animations or “GIFs”.

  • caption (str | None) – See Formatting messages.

  • caption_markdown (str | None) – See Formatting messages.

  • caption_html (str | None) – See Formatting messages.

  • emoji_sticker (str | None) –

  • reply_to (int | None) –

  • buttons (list[Button] | list[list[Button]] | None) –

Return type:

Message

Example

await client.send_file(chat, 'picture.jpg')

# Sending in-memory bytes
import io
data = b'my in-memory document'
cawait client.send_file(chat, io.BytesIO(data), size=len(data), name='doc.txt')
async send_message(chat, /, text=None, *, markdown=None, html=None, link_preview=False, reply_to=None, buttons=None)

Send a message.

Parameters:
Return type:

Message

Example

await client.send_message(chat, markdown='**Hello!**')
async send_photo(chat, /, file, *, size=None, name=None, mime_type=None, compress=True, width=None, height=None, caption=None, caption_markdown=None, caption_html=None, reply_to=None, buttons=None)

Send a photo file.

By default, the server will be allowed to compress the image. Only compressed images can be displayed as photos in applications. If compress is set to False, the image will be sent as a file document.

Unlike send_file(), this method will attempt to guess the values for width and height if they are not provided.

Parameters:
Return type:

Message

Example

await client.send_photo(chat, 'photo.jpg', caption='Check this out!')
async send_video(chat, /, file, *, size=None, name=None, mime_type=None, duration=None, width=None, height=None, round=False, supports_streaming=False, muted=False, caption=None, caption_markdown=None, caption_html=None, reply_to=None, buttons)

Send a video file.

Unlike send_file(), this method will attempt to guess the values for duration, width and height if they are not provided.

Parameters:
Return type:

Message

Example

await client.send_video(chat, 'video.mp4', caption_markdown='*I cannot believe this just happened*')
async set_chat_default_restrictions(chat, /, restrictions, *, until=None)

Set the default restrictions to apply to all participant in a chat.

Parameters:
  • chat (Peer | PeerRef) – The peer where the restrictions will be applied.

  • restrictions (Sequence[ChatRestriction]) – The sequence of restrictions to apply.

  • until (datetime | None) – Date until which the restrictions should be applied. By default, restrictions apply for as long as possible.

Return type:

None

Example

from datetime import datetime, timedelta
from telethon.types import ChatRestriction

# Don't allow anyone except administrators to send stickers for a day
await client.set_chat_default_restrictions(
    chat, user, [ChatRestriction.SEND_STICKERS],
    until=datetime.now() + timedelta(days=1))

# Remove all default restrictions from the chat
await client.set_chat_default_restrictions(chat, user, [])
set_handler_filter(handler, /, filter=None)

Set the filter to use for the given event handler.

Parameters:
Return type:

None

Example

from telethon.events import filters

# Change the filter to handle '/stop'
client.set_handler_filter(my_handler, filters.Command('/stop'))

# Remove the filter
client.set_handler_filter(my_handler, None)
async set_participant_admin_rights(chat, /, participant, rights)

Set the administrator rights granted to the participant in the chat.

If an empty sequence of rights is given, the user will be demoted and stop being an administrator.

In small group chats, there are no separate administrator rights. In this case, granting any right will make the user an administrator with all rights.

Parameters:
Return type:

None

Example

from telethon.types import AdminRight

# Make user an administrator allowed to pin messages
await client.set_participant_admin_rights(
    chat, user, [AdminRight.PIN_MESSAGES])

# Demote an administrator
await client.set_participant_admin_rights(chat, user, [])
async set_participant_restrictions(chat, /, participant, restrictions, *, until=None)

Set the restrictions to apply to a participant in the chat.

Restricting the participant to VIEW_MESSAGES will kick them out of the chat.

In small group chats, there are no separate restrictions. In this case, any restriction will kick the participant. The participant’s history will be revoked if the restriction to VIEW_MESSAGES is applied.

Parameters:
  • chat (Group | Channel | GroupRef | ChannelRef) – The peer where the restrictions will be applied.

  • participant (Peer | PeerRef) – The participant to restrict or ban, usually a types.User.

  • restrictions (Sequence[ChatRestriction]) – The sequence of restrictions to apply. Can be empty to remove all restrictions from the participant and unban them.

  • until (datetime | None) – Date until which the restrictions should be applied. By default, restrictions apply for as long as possible.

Return type:

None

Example

from datetime import datetime, timedelta
from telethon.types import ChatRestriction

# Kick the user out of the chat
await client.set_participant_restrictions(
    chat, user, [ChatRestriction.VIEW_MESSAGES])

# Don't allow the user to send media for 5 minutes
await client.set_participant_restrictions(
    chat, user, [ChatRestriction.SEND_MEDIA],
    until=datetime.now() + timedelta(minutes=5))

# Unban the user
await client.set_participant_restrictions(chat, user, [])
async sign_in(token, code)

Sign in to a user account.

Parameters:
  • token (LoginToken) – The login token returned from request_login_code().

  • code (str) – The login code sent by Telegram to a previously-authorized device. This should be a short string of digits.

Returns:

The user corresponding to yourself, or a password token if the account has 2FA enabled.

Return type:

User | PasswordToken

Example

from telethon.types import PasswordToken

login_token = await client.request_login_code('+1 23 456')
user_or_token = await client.sign_in(login_token, input('code: '))

if isinstance(password_token, PasswordToken):
    user = await client.check_password(password_token, '1-L0V3+T3l3th0n')

See also

check_password(), the next step if the account has 2FA enabled.

async sign_out()

Sign out, revoking the authorization of the current session.

Example

await client.sign_out()  # turn off the lights
await client.disconnect()  # shut the door
Return type:

None

async unpin_message(chat, /, message_id)

Unpin one or all messages from the top.

Parameters:
  • chat (Peer | PeerRef) – The peer where the message pinned message is.

  • message_id (int | Literal['all']) – The identifier of the message to unpin, or 'all' to unpin them all.

Return type:

None

Example

# Unpin all messages
await client.unpin_message(chat, 'all')