Types

This section contains most custom types used by the library. Events and filters and the Client class get their own section to prevent the page from growing out of control.

Some of these are further divided into additional submodules. This keeps them neatly grouped and avoids polluting a single module too much.

Core types

Classes for the various objects the library returns.

class telethon.types.AdminRight(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

A right that can be granted to a chat’s administrator.

Note

The specific values of the enumeration are not covered by semver. They also may do nothing in future updates if Telegram decides to change them.

BAN_USERS = 'ban_users'

Allows setting the banned rights of other users in a group or channel.

CHANGE_INFO = 'change_info'

Allows editing the description in a group or channel.

DELETE_MESSAGES = 'delete_messages'

Allows deleting messages in a group or channel.

DELETE_STORIES = 'delete_stories'

Allows deleting stories in a channel.

EDIT_MESSAGES = 'edit_messages'

Allows editing messages in a group or channel.

EDIT_STORIES = 'edit_stories'

Allows editing stories in a channel.

INVITE_USERS = 'invite_users'

Allows inviting other users to the group or channel.

MANAGE_ADMINS = 'add_admins'

Allows setting the same or less administrator rights to other users in the group or channel.

MANAGE_CALLS = 'manage_call'

Allows managing group or channel calls.

MANAGE_TOPICS = 'manage_topics'

Allows managing the topics in a group.

OTHER = 'other'

Unspecified.

PIN_MESSAGES = 'pin_messages'

Allows pinning a message to the group or channel.

POST_MESSAGES = 'post_messages'

Allows sending messages in a broadcast channel.

POST_STORIES = 'post_stories'

Allows posting stories in a channel.

REMAIN_ANONYMOUS = 'anonymous'

Allows the administrator to remain anonymous.

class telethon.types.AlbumBuilder

Bases: object

Album builder to prepare albums with multiple files before sending it all at once.

This class is constructed by calling telethon.Client.prepare_album().

async add_photo(file, *, size=None, caption=None, caption_markdown=None, caption_html=None)

Add a photo to the album.

Parameters:
Return type:

None

async add_video(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)

Add a video to the album.

Parameters:
Return type:

None

async send(chat, *, reply_to=None)

Send the album.

Returns:

All sent messages that are part of the album.

Parameters:
Return type:

List[Message]

Example

album = await client.prepare_album()
for photo in ('a.jpg', 'b.png'):
    await album.add_photo(photo)

messages = await album.send(chat)
class telethon.types.AsyncList

Bases: ABC, Generic[T]

An asynchronous list.

It can be awaited to get all the items as a normal list, or iterated over via async for.

Both approaches will perform as many requests as needed to retrieve the items, but awaiting will need to do it all at once, which can be slow.

Using asynchronous iteration will perform the requests lazily as needed, and lets you break out of the loop at any time to stop fetching items.

The len() of the asynchronous list will be the “total count” reported by the server. It does not necessarily reflect how many items will actually be returned. This count can change as more items are fetched. Note that this method cannot be awaited.

Example

telethon.Client.get_messages() returns an AsyncList[Message]. This means:

# You can await it directly:
messages = await client.get_messages(chat, 1)
# ...and now messages is a normal list with a single Message.

# Or you can use async for:
async for mesasge in client.get_messages(chat, 1):
    ...  # the messages are fetched lazily, rather than all up-front.
class telethon.types.Button(text)

Bases: object

The button base type.

All other buttons inherit this class.

You can only click buttons that have been received from Telegram. Attempting to click a button you created will fail with an error.

Not all buttons can be clicked, and each button will do something different when clicked. The reason for this is that Telethon cannot interact with any user to complete certain tasks. Only straightforward actions can be performed automatically, such as sending a text message.

To check if a button is clickable, use hasattr() on the 'click' method.

Parameters:

text (str) – See below.

property text: str

The button’s text that is displayed to the user.

class telethon.types.CallbackAnswer

Bases: object

A bot’s Callback answer().

property text: str | None

The answer’s text, usually displayed as a toast.

property url: str | None

The answer’s URL.

class telethon.types.Channel

Bases: Chat

A broadcast channel.

You can get a channel from messages via telethon.types.Message.chat, or from methods such as telethon.Client.resolve_username().

property id: int

The chat’s integer identifier.

This identifier is always a positive number.

This property is always present.

property name: str

The channel’s title.

This property is always present, but may be the empty string.

pack()

Pack the chat into a compact and reusable object.

This object can be easily serialized and saved to persistent storage. Unlike resolving usernames, packed chats can be reused without costly calls.

See also

Chats

Return type:

PackedChat | None

property username: str | None

The primary @username of the chat.

The returned string will not contain the at-sign @.

class telethon.types.Chat

Bases: ABC

The base class for all chat types.

This will either be a User, Group or Channel.

abstract property id: int

The chat’s integer identifier.

This identifier is always a positive number.

This property is always present.

abstract property name: str

The full name of the user, group or channel.

For users, this will be the User.first_name concatenated with the User.last_name.

For groups and channels, this will be their title.

If there is no name (such as for deleted accounts), an empty string '' will be returned.

abstract pack()

Pack the chat into a compact and reusable object.

This object can be easily serialized and saved to persistent storage. Unlike resolving usernames, packed chats can be reused without costly calls.

See also

Chats

Return type:

PackedChat | None

abstract property username: str | None

The primary @username of the chat.

The returned string will not contain the at-sign @.

class telethon.types.ChatRestriction(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

A restriction that may be applied to a banned chat’s participant.

A banned participant is completley banned from a chat if they are forbidden to VIEW_MESSAGES.

A banned participant that can VIEW_MESSAGES is restricted, but can still be part of the chat,

Note

The specific values of the enumeration are not covered by semver. They also may do nothing in future updates if Telegram decides to change them.

CHANGE_INFO = 'change_info'

Prevents changing the description of the chat.

Prevents sending messages that include links to external URLs to the chat.

INVITE_USERS = 'invite_users'

Prevents inviting users to the chat.

MANAGE_TOPICS = 'manage_topics'

Prevents managing the topics of the chat.

PIN_MESSAGES = 'pin_messages'

Prevents pinning messages to the chat.

SEND_AUDIOS = 'send_audios'

Prevents sending audio media files to the chat.

SEND_DOCUMENTS = 'send_docs'

Prevents sending document media files to the chat.

SEND_GAMES = 'send_games'

Prevents sending @bot inline games to the chat.

SEND_GIFS = 'send_gifs'

Prevents sending muted looping video media (“GIFs”) to the chat.

SEND_INLINE = 'send_inline'

Prevents sending messages via @bot inline to the chat.

SEND_MEDIA = 'send_media'

Prevents sending messages with media such as photos or documents to the chat.

SEND_MESSAGES = 'send_messages'

Prevents sending messages to the chat.

SEND_PHOTOS = 'send_photos'

Prevents sending photo media files to the chat.

SEND_PLAIN_MESSAGES = 'send_plain'

Prevents sending plain text messages with no media to the chat.

SEND_POLLS = 'send_polls'

Prevents sending poll media to the chat.

SEND_ROUND_VIDEOS = 'send_roundvideos'

Prevents sending round video media files to the chat.

SEND_STICKERS = 'send_stickers'

Prevents sending sticker media to the chat.

SEND_VIDEOS = 'send_videos'

Prevents sending video media files to the chat.

SEND_VOICE_NOTES = 'send_voices'

Prevents sending voice note audio media files to the chat.

VIEW_MESSAGES = 'view_messages'

Prevents being in the chat and fetching the message history.

Applying this restriction will kick the participant out of the group.

class telethon.types.Dialog

Bases: object

A dialog.

This represents an open conversation your chat list.

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

You can obtain dialogs with methods such as telethon.Client.get_dialogs().

property chat: Chat

The chat where messages are sent in this dialog.

property draft: Draft | None

The message draft within this dialog, if any.

This property does not update when the draft changes.

property latest_message: Message | None

The latest message sent or received in this dialog, if any.

This property does not update when new messages arrive.

property unread_count: int

The amount of unread messages in this dialog.

This property does not update when messages are read or sent.

class telethon.types.Draft

Bases: object

A draft message in a chat.

You can obtain drafts with methods such as telethon.Client.get_drafts().

property chat: Chat

The chat where the draft is saved.

This is also the chat where the message will be sent to by send().

property date: datetime | None

The date when the draft was last updated.

async delete()

Clear the contents of this draft to delete it.

Return type:

None

async edit(text=None, *, markdown=None, html=None, link_preview=False, reply_to=None)

Replace the current draft with a new one.

Parameters:
Returns:

The edited draft.

Return type:

Draft

Example

new_draft = await old_draft.edit('new text', link_preview=False)

True if the link preview is allowed to exist when sending the message.

property replied_message_id: int | None

Get the message identifier of message this draft will reply to once sent.

async send()

Send the contents of this draft to the chat.

The draft will be cleared after being sent.

Returns:

The sent message.

Return type:

Message

Example

await draft.send(clear=False)
property text: str | None

The text of the message that will be sent.

property text_html: str | None

The text_html of the message that will be sent.

property text_markdown: str | None

The text_markdown of the message that will be sent.

class telethon.types.File

Bases: object

File information of media sent to Telegram that can be downloaded.

You can get a file from messages via telethon.types.Message.file, or from methods such as telethon.Client.get_profile_photos().

async download(file)

Alias for telethon.Client.download().

Parameters:

file (str | Path | OutFileLike) – See download().

Return type:

None

property ext: str

The file extension, including the leading dot ..

If the name is not known, the mime-type is used in mimetypes.guess_extension().

If no extension is known for the mime-type, the empty string will be returned. This makes it safe to always append this property to a file name.

property height: int | None

The width of the image or video, if available.

property name: str | None

The file name, if known.

property thumbnails: List[File]

The file thumbnails.

For photos, these are often downscaled versions of the original size.

For documents, these will be the thumbnails present in the document.

property width: int | None

The width of the image or video, if available.

class telethon.types.Group

Bases: Chat

A small group or supergroup.

You can get a group from messages via telethon.types.Message.chat, or from methods such as telethon.Client.resolve_username().

property id: int

The chat’s integer identifier.

This identifier is always a positive number.

This property is always present.

property is_megagroup: bool

Whether the group is a supergroup.

These are known as “megagroups” in Telegram’s API, and are different from “gigagroups”.

property name: str

The group’s title.

This property is always present, but may be the empty string.

pack()

Pack the chat into a compact and reusable object.

This object can be easily serialized and saved to persistent storage. Unlike resolving usernames, packed chats can be reused without costly calls.

See also

Chats

Return type:

PackedChat | None

async set_default_restrictions(restrictions, *, until=None)

Alias for telethon.Client.set_chat_default_restrictions().

Parameters:
Return type:

None

property username: str | None

The primary @username of the chat.

The returned string will not contain the at-sign @.

class telethon.types.InlineButton(text)

Bases: Button

Inline button base type.

Inline buttons appear directly under a message (inline in the chat history).

You cannot create a naked InlineButton directly. Instead, it can be used to check whether a button is inline or not.

Buttons that behave as a “custom key” and replace the user’s virtual keyboard can be tested by checking that they are not inline.

Example

from telethon.types import buttons

is_inline_button = isinstance(button, buttons.Inline)
is_keyboard_button = not isinstance(button, buttons.Inline)
Parameters:

text (str) – See below.

class telethon.types.InlineResult

Bases: object

A single inline result from an inline query made to a bot.

This is returned when calling telethon.Client.inline_query().

property description: str | None

The description of the result, if available.

async send(chat=None)

Send the result to the desired chat.

Parameters:

chat (Chat | PackedChat | int | str | None) –

The chat where the inline result should be sent to.

This can be omitted if a chat was previously specified in the inline_query().

Returns:

The sent message.

Return type:

Message

property title: str

The title of the result, or the empty string if there is none.

property type: str
class telethon.types.LoginToken

Bases: object

Result of requesting a login code via telethon.Client.request_login_code().

property timeout: int | None

Number of seconds before this token expires.

This property does not return different values as the current time advances. To determine when the token expires, add the timeout to the current time as soon as the token is obtained.

class telethon.types.Message

Bases: object

A sent message.

You can get a message from telethon.events.NewMessage, or from methods such as telethon.Client.get_messages().

Empty messages can occur very rarely when fetching the message history. In these cases, only the id and :attr`peer` properties are guaranteed to be present. To determine whether a message is empty, its truthy value can be checked via object.__bool__():

async for message in client.iter_messages(chat):
    if not message:
        print('Found empty message with ID', message.id)
property audio: File | None

The audio media file in the message.

This can also be used as a way to check that the message media is an audio.

property buttons: List[List[Button]] | None

The buttons attached to the message.

These are displayed under the message if they are InlineButton, and replace the user’s virtual keyboard otherwise.

The returned value is a list of rows, each row having a list of buttons, one per column. The amount of columns in each row can vary. For example:

buttons = [
    [col_0,        col_1],  # row 0
    [       col_0       ],  # row 1
    [col_0, col_1, col_2],  # row 2
]

row = 2
col = 1
button = buttons[row][col]  # the middle button on the bottom row
property can_forward: bool
property chat: Chat

The chat when the message was sent.

property date: datetime | None

The date when the message was sent.

async delete(*, revoke=True)

Alias for telethon.Client.delete_messages().

Parameters:

revoke (bool) – See delete_messages().

Return type:

None

async edit(text=None, markdown=None, html=None, link_preview=False, buttons=None)

Alias for telethon.Client.edit_message().

Parameters:
Return type:

Message

property file: File | None

The downloadable file in the message.

This might also come from a link preview.

Unlike photo, audio and video, this property does not care about the media type, only whether it can be downloaded.

This means the file will be None for other media types, such as polls, venues or contacts.

async forward(target)

Alias for telethon.Client.forward_messages().

Parameters:

target (Chat | PackedChat | int | str) – See forward_messages().

Return type:

Message

property forward_info: None
async get_replied_message()

Alias for telethon.Client.get_messages_with_ids().

If all you want is to check whether this message is a reply, use replied_message_id.

Return type:

Message | None

property grouped_id: int | None

If the message is grouped with others in an album, return the group identifier.

Messages with the same grouped_id will belong to the same album.

Note that there can be messages in-between that do not have a grouped_id.

property id: int

The message identifier.

See also

Messages, which contains an in-depth explanation of message counters.

property incoming: bool

True if the message is incoming. This would mean another user sent it, and the currently logged-in user received it.

This is usually the opposite of outgoing, although some messages can be neither.

property outgoing: bool

True if the message is outgoing. This would mean the currently logged-in user sent it.

This is usually the opposite of incoming, although some messages can be neither.

property photo: File | None

The compressed photo media file in the message.

This can also be used as a way to check that the message media is a photo.

async pin()

Alias for telethon.Client.pin_message().

Return type:

Message

async read()

Alias for telethon.Client.read_message().

Return type:

None

property replied_message_id: int | None

Get the message identifier of the replied message.

async reply(text=None, *, markdown=None, html=None, link_preview=False, buttons=None)

Alias for telethon.Client.send_message() with the reply_to parameter set to this message.

Parameters:
Return type:

Message

async respond(text=None, *, markdown=None, html=None, link_preview=False, buttons=None)

Alias for telethon.Client.send_message().

Parameters:
Return type:

Message

property sender: Chat | None

The chat that sent the message.

This will usually be a User, but can also be a Channel.

If there is no sender, it means the message was sent by an anonymous user.

property silent: bool

True if the message is silent and should not cause a notification.

property text: str | None

The message text without any formatting.

property text_html: str | None

The message text formatted using standard HTML elements.

See Formatting messages to learn the HTML elements used.

property text_markdown: str | None

The message text formatted as CommonMark’s markdown.

See Formatting messages to learn the formatting characters used.

async unpin()

Alias for telethon.Client.unpin_message().

Return type:

None

property video: File | None

The video media file in the message.

This can also be used as a way to check that the message media is a video.

class telethon.types.PackedChat(ty, id, access_hash)

Bases: object

A compact representation of a chat.

You can reuse it as many times as you want.

You can call chat.pack() on User, Group or Channel to obtain it.

See also

Chats

Parameters:
access_hash
classmethod from_bytes(data)
Parameters:

data (bytes) –

Return type:

Self

classmethod from_hex(hex)

Convenience method to convert hexadecimal numbers into bytes then passed to from_bytes():

Parameters:

hex (str) – Hexadecimal numbers to convert from.

Return type:

Self

assert PackedChat.from_hex(packed.hex) == packed
property hex: str

Convenience property to convert to bytes and represent them as hexadecimal numbers:

assert packed.hex == bytes(packed).hex()
id
is_channel()
Return type:

bool

is_chat()
Return type:

bool

is_user()
Return type:

bool

ty
class telethon.types.PackedType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: IntFlag

The type of a PackedChat.

BOT = 3
BROADCAST = 48
CHAT = 4
GIGAGROUP = 56
MEGAGROUP = 40
USER = 2
class telethon.types.Participant

Bases: object

A participant in a chat, including the corresponding user and permissions.

You can obtain participants with methods such as telethon.Client.get_participants().

property admin_rights: Set[AdminRight] | None

The set of administrator rights this participant has been granted, if they are an administrator.

property banned: Chat | None

The banned participant.

This will usually be a User.

property creator: bool

True if the participant is the creator of the chat.

property left: Chat | None

The participant that has left the group.

This will usually be a User.

property restrictions: Set[ChatRestriction] | None

The set of restrictions applied to this participant, if they are banned.

async set_admin_rights(rights)

Alias for telethon.Client.set_participant_admin_rights().

Parameters:

rights (Sequence[AdminRight]) –

Return type:

None

async set_restrictions(restrictions, *, until=None)

Alias for telethon.Client.set_participant_restrictions().

Parameters:
Return type:

None

property user: User | None

The user participant that is currently present in the chat.

This will be None if the participant was instead banned or has left.

class telethon.types.PasswordToken

Bases: object

Result of attempting to sign_in() to a 2FA-protected account.

property hint: str

The password hint, or the empty string if none is known.

class telethon.types.RecentAction

Bases: object

A recent action in a chat, also known as an “admin log event action” or ChannelAdminLogEvent.

Only administrators of the chat can access these.

You can obtain recent actions with methods such as telethon.Client.get_admin_log().

property id: int

The identifier of this action.

This identifier is not the same as the one in the message that was edited or deleted.

class telethon.types.User

Bases: Chat

A user, representing either a bot account or an account created with a phone number.

You can get a user from messages via telethon.types.Message.sender, or from methods such as telethon.Client.resolve_username().

property bot: bool
property first_name: str
property id: int

The chat’s integer identifier.

This identifier is always a positive number.

This property is always present.

property last_name: str
property name: str

The user’s full name.

This property joins both the first_name and last_name into a single string.

This property is always present, but may be the empty string.

pack()

Pack the chat into a compact and reusable object.

This object can be easily serialized and saved to persistent storage. Unlike resolving usernames, packed chats can be reused without costly calls.

See also

Chats

Return type:

PackedChat | None

property phone: str | None
property username: str | None

The primary @username of the chat.

The returned string will not contain the at-sign @.

Keyboard buttons

Keyboard buttons.

This includes both the buttons returned by telethon.types.Message.buttons and those you can define when using telethon.Client.send_message():

from telethon.types import buttons

# As a user account, you can search for and click on buttons:
for row in message.buttons:
    for button in row:
        if isinstance(button, buttons.Callback) and button.data == b'data':
            await button.click()

# As a bot account, you can send them:
await bot.send_message(chat, text, buttons=[
    buttons.Callback('Demo', b'data')
])
class telethon.types.buttons.Callback(text, data=None)

Bases: InlineButton

Inline button that will trigger a telethon.events.ButtonCallback with the button’s data.

Parameters:
  • text (str) – See below.

  • data (bytes | None) – See below.

async click()

Click the button, sending the button’s data to the bot.

The bot will receive a ButtonCallback event which they must quickly answer().

The bot’s answer will be returned, or None if they don’t answer in time.

Return type:

CallbackAnswer | None

property data: bytes

The button’s binary payload.

This data will be received by telethon.events.ButtonCallback when the button is pressed.

class telethon.types.buttons.RequestGeoLocation(text)

Bases: Button

Keyboard button that will prompt the user to share the geo point with their current location.

Parameters:

text (str) – See below.

class telethon.types.buttons.RequestPhone(text)

Bases: Button

Keyboard button that will prompt the user to share the contact with their phone number.

Parameters:

text (str) – See below.

class telethon.types.buttons.RequestPoll(text, *, quiz=False)

Bases: Button

Keyboard button that will prompt the user to create a poll.

Parameters:
  • text (str) – See below.

  • quiz (bool) –

class telethon.types.buttons.SwitchInline(text, query=None)

Bases: InlineButton

Inline button that will switch the user to inline mode to trigger telethon.events.InlineQuery.

Parameters:
  • text (str) – See below.

  • query (str | None) – See below.

property query: str

The query string to set by default on the user’s message input.

class telethon.types.buttons.Text(text)

Bases: Button

This is the most basic keyboard button and only has text.

Note that it is not possible to distinguish between a click() to this button being and the user typing the text themselves.

Parameters:

text (str) – See below.

async click()

Click the button, sending a message to the chat as-if the user typed and sent the text themselves.

Return type:

Message

property text: str

The button’s text that is both displayed to the user and will be sent on click().

class telethon.types.buttons.Url(text, url=None)

Bases: InlineButton

Inline button that will prompt the user to open the specified URL when clicked.

Parameters:
  • text (str) – See below.

  • url (str | None) – See below.

property url: str

The URL to open.

Errors

class telethon.RpcError(*, code=0, name='', value=None, caused_by=None)

Bases: ValueError

A Remote Procedure Call Error.

Only occurs when the answer to a request sent to Telegram is not the expected result. The library will never construct instances of this error by itself.

This is the parent class of all telethon.errors subtypes.

Parameters:
  • code (int) – See below.

  • name (str) – See below.

  • value (int | None) – See below.

  • caused_by (int | None) – Constructor identifier of the request that caused the error.

See also

RPC Errors

property code: int

Integer code of the error.

This usually reassembles an HTTP status code.

property name: str

Name of the error, usually in SCREAMING_CASE.

property value: int | None

Integer value contained within the error.

For example, if the name is 'FLOOD_WAIT', this would be the number of seconds.

telethon.errors

Factory-object returning subclasses of RpcError.

You can think of it as a module with an infinite amount of error types in it.

When accessing any attribute in this object, a subclass of RpcError will be returned.

The returned type will catch RpcError if the RpcError.name matches the attribute converted to SCREAMING_CASE.

For example:

from telethon import errors

try:
    await client.send_message(chat, text)
except errors.FloodWait as e:
    await asyncio.sleep(e.value)

Note how the RpcError.value field is still accessible, as it’s a subclass of RpcError. The code above is equivalent to the following:

from telethon import RpcError

try:
    await client.send_message(chat, text)
except RpcError as e:
    if e.name == 'FLOOD_WAIT':
        await asyncio.sleep(e.value)
    else:
        raise

This factory object is merely a convenience.

There is one exception, and that is when the attribute name starts with 'Code' and ends with a number:

try:
    await client.send_message(chat, text)
except errors.Code420:
    await asyncio.sleep(e.value)

The above snippet is equivalent to checking RpcError.code instead:

try:
    await client.send_message(chat, text)
except RpcError as e:
    if e.code == 420:
        await asyncio.sleep(e.value)
    else:
        raise

Private definitions

Warning

These are not intended to be imported directly. They are not available from telethon.types.

This section exists for documentation purposes only.

telethon._impl.client.types.async_list.T

Generic parameter used by AsyncList.

class telethon._impl.client.events.filters.combinators.Combinable

Bases: ABC

Subclass that enables filters to be combined.

Filters combined this way will be merged. This means multiple | or & will lead to a single Any or All being used. Multiple ~ will toggle between using Not and not using it.

class telethon._impl.client.types.file.InFileLike(*args, **kwargs)

Bases: Protocol

A file-like object used for input only. The read() method can be async.

This is never returned and should never be constructed. It’s only used in function parameters.

read(n)

Read from the file or buffer.

Parameters:

n (int) – Maximum amount of bytes that should be returned.

Return type:

bytes | Coroutine[Any, Any, bytes]

class telethon._impl.client.types.file.OutFileLike(*args, **kwargs)

Bases: Protocol

A file-like object used for output only. The write() method can be async.

This is never returned and should never be constructed. It’s only used in function parameters.

write(data)

Write all the data into the file or buffer.

Parameters:

data (bytes) – Data that must be written to the buffer entirely.

Return type:

Any | Coroutine[Any, Any, Any]

class telethon._impl.mtsender.sender.AsyncReader(*args, **kwargs)

Bases: Protocol

A asyncio.StreamReader-like class.

async read(n)

Must behave like asyncio.StreamReader.read().

Parameters:

n (int) – Amount of bytes to read at most.

Return type:

bytes

class telethon._impl.mtsender.sender.AsyncWriter(*args, **kwargs)

Bases: Protocol

A asyncio.StreamWriter-like class.

close()

Must behave like asyncio.StreamWriter.close().

Return type:

None

async drain()

Must behave like asyncio.StreamWriter.drain().

Return type:

None

async wait_closed()

Must behave like asyncio.StreamWriter.wait_closed().

Return type:

None

write(data)

Must behave like asyncio.StreamWriter.write().

Parameters:

data (bytes) – Data that must be entirely written or buffered until drain() is called.

Return type:

None

class telethon._impl.mtsender.sender.Connector(*args, **kwargs)

Bases: Protocol

A Connector is any function that takes in the following two positional parameters as input:

  • The ip address as a str. This might be either a IPv4 or IPv6.

  • The port as a int. This will be a number below 2¹⁶, often 443.

and returns a tuple[AsyncReader, AsyncWriter].

You can use a custom connector to connect to Telegram through proxies. The library will only ever open remote connections through this function.

The default connector is asyncio.open_connection(), defined as:

default_connector = lambda ip, port: asyncio.open_connection(ip, port)

If your connector needs additional parameters, you can use either the lambda syntax or functools.partial().

See also

The Data centers concept has examples on how to combine proxy libraries with Telethon.