API Reference

Client

class telegrampy.Client(token: str, *, loop: AbstractEventLoop | None = None, timeout: int = 10, api_url: str = 'https://api.telegram.org', is_local: bool = False)

A client that polls updates and make requests to Telegram.

Parameters:
  • token (str) – The bot token used to authenticate the account.

  • loop (asyncio.AbstractEventLoop | None) – The event loop associated with the client. Uses asyncio.get_event_loop() if left unspecified.

  • timeout (int) – The long polling timeout in seconds. Defaults to 10.

  • api_url (str) – The URL of a selfhosted API server. Otherwise, Telegram’s servers will be used.

  • api_is_local (bool) – Whether the API server is in local mode.

loop

The event loop that the bot is running on.

Type:

asyncio.AbstractEventLoop

add_inline_keyboard(message_id: int, keyboard: InlineKeyboard) None

Binds InlineKeyboard to a specific message on the client, to listen for updates. This is intended to be used when you want the inline keyboard to last longer than the lifecycle of the program.

add_listener(func: CoroFunc, name: str | None = None) None

Registers a function as a listener.

Parameters:
  • func – The function to register.

  • name (str | None) – The name of the event to register the function as.

event(func: CoroFunc) CoroFunc

Turns a function into an event handler.

Parameters:

func – The function to make an event handler.

await get_chat(chat_id: int) Chat

This function is a coroutine.

Fetches a chat by ID.

Parameters:

chat_id (int) – The ID of the chat to fetch.

Returns:

The chat that was fetched.

Return type:

telegrampy.Chat

Raises:

telegrampy.HTTPException – Fetching the chat failed.

await get_me() ClientUser

This function is a coroutine.

Fetches the authenticated bot account.

Returns:

The user that was fetched.

Return type:

telegrampy.ClientUser

Raises:

telegrampy.HTTPException – Fetching the bot user failed.

get_partial_chat(chat_id) PartialChat

Returns a partial chat for the given ID, without fetching anything from Telegram.

This is useful for interacting with chat that you have an ID for, without making extra API calls.

Returns:

The partial chat that can be interacted with.

Return type:

telegrampy.PartialChat

listen(name: str | None = None) Callable[[CoroFunc], CoroFunc]

A decorator that registers a function as a listener.

Parameters:

name (str | None) – The name of the event to register the function as.

remove_listener(func: CoroFunc) None

Removes a listener.

Parameters:

func – The function that is registered as a listener.

run() None

Runs the bot.

await set_description(description: str | None, *, language_code: str | None = None, short: bool = False) None

This function is a coroutine.

Sets the description that is shown for the bot.

Parameters:
  • description (str) – The new description. Maxmium of 512 characters for full description and 120 for short description.

  • language_code (str) – The two-letter ISO 639-1 language code for this description.

  • short (str) – Whether to set the short or full description. The full description appears on empty chats with the bot, while the long decription appears on the profile page.

await set_name(name: str | None, *, language_code: str | None = None) None

This function is a coroutine.

Sets the description that is shown for the bot.

Parameters:

name (str) – The display name of the bot, no longer than 64 chatacters.

await setup_hook() None

This function is a coroutine.

Called before the bot begins polling updates. This is meant to be overrided by subclasses that require asynchronous setup.

await start() None

This function is a coroutine.

Starts the bot.

Raises:

RuntimeError – This instance of the bot is already running.

await stop() None

This function is a coroutine.

Stops the bot.

Raises:

RuntimeError – This instance of the bot is not running.

await wait_for(event: str, *, check: Callable[..., bool] | None = None, timeout: float | None = None) Any

This function is a coroutine.

Waits for an event.

Parameters:

event (str) – The name of the event to wait for.

Events

telegrampy.on_message(message: telegrampy.Message)

Called when a message is sent.

telegrampy.on_message_edit(message: telegrampy.Message)

Called when a message is edited.

telegrampy.on_post(message: telegrampy.Message)

Called when a channel post is sent.

telegrampy.on_post_edit(message: telegrampy.Message)

Called when a channel post is edited.

telegrampy.on_callback_query(query: telegrampy.CallbackQuery)

Called when a callback query is received from an inline keyboard button. Instead of trying to handle callbacks yourself, consider using InlineKeyboard, which handles this for you.

telegrampy.on_member_update(member_update: telegrampy.MemberUpdated)

Called when a chat member is updated.

telegrampy.on_poll(poll: telegrampy.Poll)

Called when a poll is sent.

telegrampy.on_poll_answer(answer: telegrampy.PollAnswer)

Called when someone answers a non-anonymous poll.

telegrampy.on_error(error)

Called when an error occurs within an event handler.

Utilities

telegrampy.utils.escape_markdown(text: str, *, version: Version = 2) str

Tool that escapes markdown from a given string.

Parameters:
  • text (str) – The text to escape markdown from.

  • version (int | None) – The Telegram markdown version to use. Only 1 and 2 are supported.

Returns:

The escaped text.

Return type:

str

Raises:

ValueError – An unsupported version was provided.

Telegram Models

Base

class telegrampy.Messageable

Represents any Telegram resource that messages can be sent to.

This is implemented by the following subclasses:

action(action: str) MessageableAction

Returns a context manager that sends a chat action to the destination until completed or for up to 5 seconds if called with await.

Usage:

async with chat.action("typing"):
    # do some computing here

await chat.send("Done!")

Usage:

await chat.action("typing")
Parameters:

action (str) – The action to send.

await send(content: str, *, parse_mode: ParseMode | None = None, reply_markup: ReplyMarkup | None = None) Message

This function is a coroutine.

Sends a message to the destination.

Parameters:
Returns:

The message sent.

Return type:

telegrampy.Message

Raises:

errors.HTTPException – Sending the message failed.

await send_document(document: io.BytesIO | str, *, filename: str | None = None, caption: str | None = None, parse_mode: str | None = None, reply_markup: ReplyMarkup | None = None) Message

This function is a coroutine.

Sends a document to the destination.

Parameters:
  • document (io.BytesIO | str) – The document to send. Either a file or the path to one.

  • filename (str | None) – The filename of the document.

  • caption (str | None) – The document’s caption.

  • parse_mode (str | None) – The parse mode for the caption.

  • reply_markup (InlineKeyboard | ReplyKeyboard | ReplyKeyboardRemove | ForceReply | None) – The reply markup interface to send with the message.

Raises:

errors.HTTPException – Sending the document failed.

await send_photo(photo: io.BytesIO | str, *, filename: str | None = None, caption: str | None = None, parse_mode: str | None = None, reply_markup: ReplyMarkup | None = None) Message

This function is a coroutine.

Sends a photo to the destination.

Parameters:
  • photo (io.BytesIO | str) – The photo to send. Either a file or the path to one.

  • filename (str | None) – The filename of the photo.

  • caption (str | None) – The caption for the photo.

  • parse_mode (str | None) – The parse mode for the caption.

  • reply_markup (InlineKeyboard | ReplyKeyboard | ReplyKeyboardRemove | ForceReply | None) – The reply markup interface to send with the message.

Raises:

errors.HTTPException – Sending the photo failed.

await send_poll(question: str, options: list[str]) Poll

This function is a coroutine.

Sends a poll to the destination.

Parameters:
  • question (str) – The question of the poll.

  • options (list[str]) – The options in the poll.

  • reply_markup (InlineKeyboard | ReplyKeyboard | ReplyKeyboardRemove | :class:`ForceReply | None) – The reply markup interface to send with the message.

Returns:

The poll sent.

Return type:

telegrampy.Poll

Raises:

telegrampy.HTTPException – Sending the poll failed.

typing() MessageableAction

Returns a context manager that shows a typing indicicator in the destination. This is eqivalent to calling action("typing")()

Chat

class telegrampy.PartialChat

Represents a partial chat that can be interacted with, without containing information.

x == y

Checks if two partial chats are equal.

x != y

Checks if two chats partial are not equal.

id

The given ID of the partial chat.

Type:

int

action(action: str) MessageableAction

Returns a context manager that sends a chat action to the destination until completed or for up to 5 seconds if called with await.

Usage:

async with chat.action("typing"):
    # do some computing here

await chat.send("Done!")

Usage:

await chat.action("typing")
Parameters:

action (str) – The action to send.

await clear_pins() None

This function is a coroutine.

Removes all pins from the chat. Must have administrator with proper permissions.

Raises:

telegrampy.HTTPException – Clearing all pins failed.

await get_member(user_id: int) Member

This function is a coroutine.

Fetches a member in the chat.

Parameters:

user_id (int) – The user ID of the member.

Returns:

The member fetched.

Return type:

telegrampy.Member

Raises:

telegrampy.HTTPException – Fetching the member failed.

await get_member_count() int

This function is a coroutine.

Fetches the member count of the chat.

Returns:

The number of members in the chat.

Return type:

int

Raises:

telegrampy.HTTPException – Fetching the member count failed.

get_partial_message(message_id: int) PartialMessage

Returns a partial message for the given ID, without fetching anything from Telegram.

This is useful for interacting with the messages if you only have an ID.

Returns:

The partial message that can be interacted with.

Return type:

telegrampy.PartialMessage

await leave() None

This function is a coroutine.

Removes the logged in bot from a non-private chat.

Raises:

telegrampy.HTTPException – Leaving the chat failed.

await send(content: str, *, parse_mode: ParseMode | None = None, reply_markup: ReplyMarkup | None = None) Message

This function is a coroutine.

Sends a message to the destination.

Parameters:
Returns:

The message sent.

Return type:

telegrampy.Message

Raises:

errors.HTTPException – Sending the message failed.

await send_document(document: io.BytesIO | str, *, filename: str | None = None, caption: str | None = None, parse_mode: str | None = None, reply_markup: ReplyMarkup | None = None) Message

This function is a coroutine.

Sends a document to the destination.

Parameters:
  • document (io.BytesIO | str) – The document to send. Either a file or the path to one.

  • filename (str | None) – The filename of the document.

  • caption (str | None) – The document’s caption.

  • parse_mode (str | None) – The parse mode for the caption.

  • reply_markup (InlineKeyboard | ReplyKeyboard | ReplyKeyboardRemove | ForceReply | None) – The reply markup interface to send with the message.

Raises:

errors.HTTPException – Sending the document failed.

await send_photo(photo: io.BytesIO | str, *, filename: str | None = None, caption: str | None = None, parse_mode: str | None = None, reply_markup: ReplyMarkup | None = None) Message

This function is a coroutine.

Sends a photo to the destination.

Parameters:
  • photo (io.BytesIO | str) – The photo to send. Either a file or the path to one.

  • filename (str | None) – The filename of the photo.

  • caption (str | None) – The caption for the photo.

  • parse_mode (str | None) – The parse mode for the caption.

  • reply_markup (InlineKeyboard | ReplyKeyboard | ReplyKeyboardRemove | ForceReply | None) – The reply markup interface to send with the message.

Raises:

errors.HTTPException – Sending the photo failed.

await send_poll(question: str, options: list[str]) Poll

This function is a coroutine.

Sends a poll to the destination.

Parameters:
  • question (str) – The question of the poll.

  • options (list[str]) – The options in the poll.

  • reply_markup (InlineKeyboard | ReplyKeyboard | ReplyKeyboardRemove | :class:`ForceReply | None) – The reply markup interface to send with the message.

Returns:

The poll sent.

Return type:

telegrampy.Poll

Raises:

telegrampy.HTTPException – Sending the poll failed.

await set_description(description: str | None) None

This function is a coroutine.

Changes the description of the chat. This only works in non-private chats with administrator privillages.

Parameters:

description (str) – The new description of the chat, up to 255 characters.

Raises:

telegrampy.HTTPException – Changing the description failed.

await set_photo(photo: BytesIO | str | None) None

This function is a coroutine.

Sets the photo for the chat. This does not work in private chats.

Parameters:

photo (io.BytesIO | str) – The new profile photo for the chat. Pass None to clear.

await set_title(title: str) None

This function is a coroutine.

Changes the title of the chat. This only works in non-private chats with administrator privillages.

Parameters:

title (str) – The new name of the chat, from 1 to 128 characaters.

Raises:

telegrampy.HTTPException – Changing the title failed.

typing() MessageableAction

Returns a context manager that shows a typing indicicator in the destination. This is eqivalent to calling action("typing")()

class telegrampy.Chat

Represents a chat in Telegram.

x == y

Checks if two chats are equal.

x != y

Checks if two chats are not equal.

str(x)

Returns the chat’s title.

id

The ID of the chat.

Type:

int

type

The type of the chat. Can be “private”, “group”, “supergroup”, or “channel”.

Type:

str

title

The title of the chat, if applicable..

Type:

str | None

username

The username of the chat, if applicable.

Type:

str | None

first_name

The first name of the user, if applicable.

Type:

str | None

last_name

The last name of the user, if applicable.

Type:

str | None

is_forum

Whether the chat is set up as a forum.

Type:

str | None

action(action: str) MessageableAction

Returns a context manager that sends a chat action to the destination until completed or for up to 5 seconds if called with await.

Usage:

async with chat.action("typing"):
    # do some computing here

await chat.send("Done!")

Usage:

await chat.action("typing")
Parameters:

action (str) – The action to send.

await clear_pins() None

This function is a coroutine.

Removes all pins from the chat. Must have administrator with proper permissions.

Raises:

telegrampy.HTTPException – Clearing all pins failed.

property display_name: str

The display name of the chat, as it appears in the client.

Type:

str

await get_member(user_id: int) Member

This function is a coroutine.

Fetches a member in the chat.

Parameters:

user_id (int) – The user ID of the member.

Returns:

The member fetched.

Return type:

telegrampy.Member

Raises:

telegrampy.HTTPException – Fetching the member failed.

await get_member_count() int

This function is a coroutine.

Fetches the member count of the chat.

Returns:

The number of members in the chat.

Return type:

int

Raises:

telegrampy.HTTPException – Fetching the member count failed.

get_partial_message(message_id: int) PartialMessage

Returns a partial message for the given ID, without fetching anything from Telegram.

This is useful for interacting with the messages if you only have an ID.

Returns:

The partial message that can be interacted with.

Return type:

telegrampy.PartialMessage

await leave() None

This function is a coroutine.

Removes the logged in bot from a non-private chat.

Raises:

telegrampy.HTTPException – Leaving the chat failed.

await send(content: str, *, parse_mode: ParseMode | None = None, reply_markup: ReplyMarkup | None = None) Message

This function is a coroutine.

Sends a message to the destination.

Parameters:
Returns:

The message sent.

Return type:

telegrampy.Message

Raises:

errors.HTTPException – Sending the message failed.

await send_document(document: io.BytesIO | str, *, filename: str | None = None, caption: str | None = None, parse_mode: str | None = None, reply_markup: ReplyMarkup | None = None) Message

This function is a coroutine.

Sends a document to the destination.

Parameters:
  • document (io.BytesIO | str) – The document to send. Either a file or the path to one.

  • filename (str | None) – The filename of the document.

  • caption (str | None) – The document’s caption.

  • parse_mode (str | None) – The parse mode for the caption.

  • reply_markup (InlineKeyboard | ReplyKeyboard | ReplyKeyboardRemove | ForceReply | None) – The reply markup interface to send with the message.

Raises:

errors.HTTPException – Sending the document failed.

await send_photo(photo: io.BytesIO | str, *, filename: str | None = None, caption: str | None = None, parse_mode: str | None = None, reply_markup: ReplyMarkup | None = None) Message

This function is a coroutine.

Sends a photo to the destination.

Parameters:
  • photo (io.BytesIO | str) – The photo to send. Either a file or the path to one.

  • filename (str | None) – The filename of the photo.

  • caption (str | None) – The caption for the photo.

  • parse_mode (str | None) – The parse mode for the caption.

  • reply_markup (InlineKeyboard | ReplyKeyboard | ReplyKeyboardRemove | ForceReply | None) – The reply markup interface to send with the message.

Raises:

errors.HTTPException – Sending the photo failed.

await send_poll(question: str, options: list[str]) Poll

This function is a coroutine.

Sends a poll to the destination.

Parameters:
  • question (str) – The question of the poll.

  • options (list[str]) – The options in the poll.

  • reply_markup (InlineKeyboard | ReplyKeyboard | ReplyKeyboardRemove | :class:`ForceReply | None) – The reply markup interface to send with the message.

Returns:

The poll sent.

Return type:

telegrampy.Poll

Raises:

telegrampy.HTTPException – Sending the poll failed.

await set_description(description: str | None) None

This function is a coroutine.

Changes the description of the chat. This only works in non-private chats with administrator privillages.

Parameters:

description (str) – The new description of the chat, up to 255 characters.

Raises:

telegrampy.HTTPException – Changing the description failed.

await set_photo(photo: BytesIO | str | None) None

This function is a coroutine.

Sets the photo for the chat. This does not work in private chats.

Parameters:

photo (io.BytesIO | str) – The new profile photo for the chat. Pass None to clear.

await set_title(title: str) None

This function is a coroutine.

Changes the title of the chat. This only works in non-private chats with administrator privillages.

Parameters:

title (str) – The new name of the chat, from 1 to 128 characaters.

Raises:

telegrampy.HTTPException – Changing the title failed.

typing() MessageableAction

Returns a context manager that shows a typing indicicator in the destination. This is eqivalent to calling action("typing")()

class telegrampy.ChatInvite

Represents an invite to a chat in the form of a link.

The invite link.

Type:

str

creator

The user who created the link

Type:

telegrampy.User

creates_join_request

Whether users joining the chat need to be approved by the administrators.

Type:

bool

is_primary

Whether this is the primary link for the chat.

Type:

bool

is_revoked

Whether the link has been revoked.

Type:

bool

name

The name of the invite link.

Type:

str | None

expire_date

The time that the link will expire or the time it expired at if it already has.

Type:

datetime.datetime | None

member_limit

The maxmimum number of users that can be simultaneous chat members, by joining through this link.

Type:

int | None

pending_join_request_count

The number of pending join requests for users of the link.

Type:

int | None

subscription_period

The number of seconds the subscription will be active for before the next payment

Type:

;class:int | None

subscription_price

The number of stars a chat member must pay initally and after each following subscription period.

Type:

int | None

Message

class telegrampy.PartialMessage(message_id: int, chat: PartialChat)

Represents a partial message that can be interacted with, without containing information.

x == y

Checks if two partial chats are equal.

x != y

Checks if two chats partial are not equal.

id

The given ID of the partial chat.

Type:

int

chat

The chat the partial message was sent in.

Type:

telegrampy.PartialChat | telegrampy.Chat

await delete() None

This function is a coroutine.

Deletes the message.

Raises:

telegrampy.HTTPException – Deleting the message failed.

await edit(*, content: str, parse_mode: ParseMode | None = None) Message | None

This function is a coroutine.

Edits the message.

Parameters:
  • content (str) – The content of the new message.

  • parse_mode (str) – The parse mode of the new message.

Raises:

telegrampy.HTTException – Editing the message failed.

await forward(destination: Chat) Message

This function is a coroutine.

Forwards the message to a destination.

Parameters:

destination (telegrampy.PartialChat | telegrampy.Chat) – The chat forward the message to.

Returns:

The message sent.

Return type:

telegrampy.Message

Raises:

telegrampy.HTTPException – Forwarding the message failed.

await pin(*, silent: bool = False) None

This function is a coroutine.

Pins the message to the chat.

Parameters:

silent (bool) – Whether to not notify chat members when a message is sent. Notifications are never sent for channels and private chats.

Raises:

telegrampy.HTTPException – Pinning the message failed.

await reply(content: str, parse_mode: ParseMode | None = None, reply_markup: ReplyMarkup | None = None) Message

This function is a coroutine.

Sends a reply to the message.

Parameters:
  • content (str) – The content of the message to send.

  • parse_mode (str | None) – The parse mode of the message to send.

  • reply_markup (InlineKeyboard | ReplyKeyboard | ReplyKeyboardRemove |:class:`ForceReply) – The reply markup interface to send with the message.

Returns:

The message sent.

Return type:

telegrampy.Message

Raises:

telegrampy.HTTPException – Sending the message failed.

await unpin() None

This function is a coroutine.

Unpins the message from the chat.

Raises:

telegrampy.HTTPException – Unpinning the message failed.

class telegrampy.Message

Represents a message in Telegram.

x == y

Checks if two messages are equal.

x != y

Checks if two messages are not equal.

id

The ID of the message.

Type:

int

thread_id

The ID of the thread the message was sent in.

Type:

int | None

author

The user who sent the message.

Type:

int | None

created_at

The time the message was created.

Type:

int | None

edited_at

The time the message was edited.

Type:

datetime.datetime | None

content

The content of the message, for text messages.

Type:

str | None

chat

The chat the message was sent in.

Type:

telegrampy.Chat

await delete() None

This function is a coroutine.

Deletes the message.

Raises:

telegrampy.HTTPException – Deleting the message failed.

await edit(*, content: str, parse_mode: ParseMode | None = None) Message | None

This function is a coroutine.

Edits the message.

Parameters:
  • content (str) – The content of the new message.

  • parse_mode (str) – The parse mode of the new message.

Raises:

telegrampy.HTTException – Editing the message failed.

await forward(destination: Chat) Message

This function is a coroutine.

Forwards the message to a destination.

Parameters:

destination (telegrampy.PartialChat | telegrampy.Chat) – The chat forward the message to.

Returns:

The message sent.

Return type:

telegrampy.Message

Raises:

telegrampy.HTTPException – Forwarding the message failed.

await pin(*, silent: bool = False) None

This function is a coroutine.

Pins the message to the chat.

Parameters:

silent (bool) – Whether to not notify chat members when a message is sent. Notifications are never sent for channels and private chats.

Raises:

telegrampy.HTTPException – Pinning the message failed.

await reply(content: str, parse_mode: ParseMode | None = None, reply_markup: ReplyMarkup | None = None) Message

This function is a coroutine.

Sends a reply to the message.

Parameters:
  • content (str) – The content of the message to send.

  • parse_mode (str | None) – The parse mode of the message to send.

  • reply_markup (InlineKeyboard | ReplyKeyboard | ReplyKeyboardRemove |:class:`ForceReply) – The reply markup interface to send with the message.

Returns:

The message sent.

Return type:

telegrampy.Message

Raises:

telegrampy.HTTPException – Sending the message failed.

await unpin() None

This function is a coroutine.

Unpins the message from the chat.

Raises:

telegrampy.HTTPException – Unpinning the message failed.

class telegrampy.MessageEntity

Represents a message entity.

type

The type of entity.

Type:

str

offset

The offset of the start of the entity.

Type:

int

length

The length of the entity.

Type:

int

url

The URL that will be opened, for text_link.

Type:

str | None

user

The mentioned user for text_mention.

Type:

telegrampy.User | None

language

The programming language of the entity text, for pre.

Type:

str | None

custom_emoji_id

The ID, for custom_emoji.

Type:

str | None

value

The text value of the message entity.

Type:

str

User

class telegrampy.User

Represents a Telegram user.

x == y

Checks if two users are equal.

x != y

Checks if two users are not equal.

str(x)

Returns the user’s name.

id

The ID of the user.

Type:

int

is_bot

Whether the user is a bot.

Type:

bool

first_name

The first name of the user, if exists.

Type:

str

last_name

The last name of the user, if exists.

Type:

str | None

username

The username of the user, if applicable.

Type:

str | None

language_code

The IETF language tag for the user’s language, if applicable.

Type:

str | None

added_to_attachment_menu

Whether the logged in bot is added to this user’s attachment menu.

Type:

bool

is_premium

Whether the user is subscribed to Telegram Premium.

Type:

bool

class telegrampy.ClientUser

Represents your Telegram user.

x == y

Checks if two users are equal.

x != y

Checks if two users are not equal.

str(x)

Returns the user’s name.

id

The ID of the user.

Type:

int

is_bot

Whether the user is a bot.

Type:

bool

first_name

The first name of the user, if exists.

Type:

str

last_name

The last name of the user, if exists.

Type:

str | None

username

The username of the user, if applicable.

Type:

str | None

language_code

The IETF language tag for the user’s language, if applicable.

Type:

str | None

added_to_attachment_menu

Whether the logged in bot is added to this user’s attachment menu.

Type:

bool

is_premium

Whether the user is subscribed to Telegram Premium.

Type:

bool

can_join_groups

Whether the logged in bot can join groups.

Type:

bool

can_read_all_group_messages

Whether privacy mode is disabled for the logged in bot.

Type:

bool

supports_inline_queries

Whether the logged in bot has inline queries enabled.

Type:

bool

can_connect_to_business

Whether the logged in bot can be connected to a Telegram business account to receive its messages.

Type:

bool

has_main_web_app

Whether the logged in bot has a main web app.

Type:

bool

class telegrampy.UserProfilePhotos

Represents a collection of profile photos that belong to a user.

total_count

The total amount of profile photos the user has.

Type:

int

photos

The photos that belong to the user. Each contained list contains one photo in up to four varying sizes.

Type:

list[list[PhotoSize]]

Member

class telegrampy.Member

Represents a chat member, a superset of telegrampy.User containing chat-specific details.

status

The status or role of the user in the chat.

Type:

str

chat

The chat that the user belongs to.

Type:

telegrampy.PartialChat | telegrampy.Chat

id

The ID of the user.

Type:

int

is_bot

If the user is a bot.

Type:

bool

first_name

The first name of the user, if exists.

Type:

str

last_name

The last name of the user, if exists.

Type:

str | None

username

The username of the user, if applicable.

Type:

str | None

language_code

The IETF language tag for the user’s language, if applicable.

Type:

str | None

added_to_attachment_menu

Whether the logged in bot is added to this user’s attachment menu.

Type:

bool

is_premium

Whether the user is subscribed to Telegram Premium.

Type:

bool

action(action: str) MessageableAction

Returns a context manager that sends a chat action to the destination until completed or for up to 5 seconds if called with await.

Usage:

async with chat.action("typing"):
    # do some computing here

await chat.send("Done!")

Usage:

await chat.action("typing")
Parameters:

action (str) – The action to send.

property full_name: str

The user’s full name.

Type:

str

await get_profile_photos(*, offset: int | None = None, limit: int = 100) UserProfilePhotos

Fetches the profile pictures for the user.

:param int | None: The sequential number of the first photo to be retrieved.

If unspecified, all photos will be retrieved.

Parameters:

limit (int) – The maximum number of photos to be retrieved. Defaults to and cannot be more than 100.

The t.me link for the user, if applicable.

Type:

str | None

mention(text: str | None = None, parse_mode: ParseMode = 'HTML') str

Returns a mention for the user.

Parameters:
  • text (str) – The mention text.

  • parse_mode (str) – The parse mode for the mention.

Returns:

The mention string.

Return type:

str

property name: str

Username if the user has one. Otherwise the full name of the user.

Type:

str

await send(content: str, *, parse_mode: ParseMode | None = None, reply_markup: ReplyMarkup | None = None) Message

This function is a coroutine.

Sends a message to the destination.

Parameters:
Returns:

The message sent.

Return type:

telegrampy.Message

Raises:

errors.HTTPException – Sending the message failed.

await send_document(document: io.BytesIO | str, *, filename: str | None = None, caption: str | None = None, parse_mode: str | None = None, reply_markup: ReplyMarkup | None = None) Message

This function is a coroutine.

Sends a document to the destination.

Parameters:
  • document (io.BytesIO | str) – The document to send. Either a file or the path to one.

  • filename (str | None) – The filename of the document.

  • caption (str | None) – The document’s caption.

  • parse_mode (str | None) – The parse mode for the caption.

  • reply_markup (InlineKeyboard | ReplyKeyboard | ReplyKeyboardRemove | ForceReply | None) – The reply markup interface to send with the message.

Raises:

errors.HTTPException – Sending the document failed.

await send_photo(photo: io.BytesIO | str, *, filename: str | None = None, caption: str | None = None, parse_mode: str | None = None, reply_markup: ReplyMarkup | None = None) Message

This function is a coroutine.

Sends a photo to the destination.

Parameters:
  • photo (io.BytesIO | str) – The photo to send. Either a file or the path to one.

  • filename (str | None) – The filename of the photo.

  • caption (str | None) – The caption for the photo.

  • parse_mode (str | None) – The parse mode for the caption.

  • reply_markup (InlineKeyboard | ReplyKeyboard | ReplyKeyboardRemove | ForceReply | None) – The reply markup interface to send with the message.

Raises:

errors.HTTPException – Sending the photo failed.

await send_poll(question: str, options: list[str]) Poll

This function is a coroutine.

Sends a poll to the destination.

Parameters:
  • question (str) – The question of the poll.

  • options (list[str]) – The options in the poll.

  • reply_markup (InlineKeyboard | ReplyKeyboard | ReplyKeyboardRemove | :class:`ForceReply | None) – The reply markup interface to send with the message.

Returns:

The poll sent.

Return type:

telegrampy.Poll

Raises:

telegrampy.HTTPException – Sending the poll failed.

typing() MessageableAction

Returns a context manager that shows a typing indicicator in the destination. This is eqivalent to calling action("typing")()

class telegrampy.MemberUpdated

Contains information about any change regarding a chat member.

chat

The chat that the update occured in.

Type:

telegrampy.Chat

author

The user who performed the action resulting in a change.

Type:

telegrampy.User

taken_at

The time that the action was taken at.

Type:

datetime.datetime

old_member

The affected chat member, prior to the change.

Type:

telegrampy.Member

new_member

The affected chat member, after the change.

Type:

telegrampy.Member

The invite link used to join the chat, if applicable.

Type:

ChatInviteLink | None

via_join_request

Whether the user joined the chat with a direct join request.

Type:

bool

Whether the the user joined the chat with a chat folder invite link.

Type:

bool

Poll

class telegrampy.Poll

A Telegram poll.

x == y

Checks if two polls are equal.

x != y

Checks if two polls are not equal.

str(x)

Returns the poll’s question.

id

The ID of the poll.

Type:

int

question

The question of the poll.

Type:

str

options

The options of the poll.

Type:

list

total_voter_count

The total voter count of the poll.

Type:

int

is_closed

Whether the poll is closed.

Type:

bool

is_anonymous

Whether the poll is anonymous.

Type:

bool

type

The type of the poll.

Type:

str

allow_multiple_answers

Whether the poll allows multiple answers.

Type:

bool

class telegrampy.PollAnswer

An answer to a non-anonymous poll.

poll_id

The ID of the poll.

Type:

int

user

The user that answered the poll.

Type:

telegrampy.User

option_ids

The options that the user selected.

Type:

list[int]

Files

class telegrampy.File

Represents basic information about a uploaded file.

id

Identifier of the file, which is useful for downloading or reusing it.

Type:

str

unique_id

The globally unique identifier of the file, which is supposed to be permanent. This cannot be used for downloading or resuing the file.

Type:

str

size

The size of the file’s content in bytes.

Type:

int | None

path

The relative path of the file on the server. In local mode, this is the absolute path on the filesystem, which may contain sensitive information such as the bot’s token. The path is guaranteed to be valid for at least an hour. It is preferable to use read() or save() rather than using this directly.

Type:

str | None

await read() bytes

This function is a coroutine.

Retrieves the contenst of the file.

Returns:

The content of the file.

Return type:

bytes

Raises:
  • HTTPException – Fetching the content of the file failed.

  • ClientException – The file has an absolute path to the local filesystem or none was provided.

await refresh() File

This function is a coroutine.

Creates a new file with an updated path.

Return type:

The refreshed file.

Raises:

HTTPException – Fetching the updated file failed.

await save(fp: str | BytesIO, *, seek_begin: bool = True) int

This function is a coroutine.

Writes the content of the file to the disk or a file-like object.

Parameters:
  • fp (str | io.BytesIO) – The file-like object to write the content to or a filename to use.

  • seek_being (bool) – Whether to seek the beginning of the bytes-like object passed, after writing to it.

Returns:

The length of the content written, in bytes.

Return type:

int

Raises:
  • HTTPException – Fetching the content of the file failed.

  • RuntimeError – The file has no download path associated with it.

class telegrampy.PhotoSize

Represents a photo of a specific size. Also used for thumbnails of files and stickers.

file_id

Identifier of the file, which is useful for downloading or reusing it.

Type:

str

file_unique_id

The globally unique identifier of the file, which is supposed to be permanent. This cannot be used for downloading or resuing the file.

Type:

str

width

The width of the photo.

Type:

int

height

The height of the photo.

Type:

int

file_size

The size of the file’s content in bytes.

Type:

int | None

await get_file() File

This function is a coroutine.

Fetches the file associated with the photo, whiches basic information and allows for downloading.

Returns:

The associated file.

Return type:

File

Raises:

HTTPException – Fetching the associated file failed.

Markup

class telegrampy.InlineKeyboard

Represents an inline keyboard that appears as buttons on the message it is sent in.

property active: bool

bool Whether the view is currently receiving callbacks.

add_button(button: InlineKeyboardButton) None

Removes a button from the keyboard.

property buttons: list[InlineKeyboardButton]

The list of buttons added to the inline keyboard.

Type:

list[InlineKeyboardButton]

await on_error(query: CallbackQuery, error: Exception, button: InlineKeyboardButton) None

This function is a coroutine.

Called when a button inside the inline keyboard experiences an unhandled exception.

Paramaters

query: CallbackQuery | None

The callback query that triggered the button callback.

error: Exception | None

The exception that was raised.

button: InlineKeyboardButton | None

The button associated with the callback query.

remove_button(button: InlineKeyboardButton) None

Adds a button to the keyboard.

stop() None

Stops dispatching callback queries to this keyboard.

property stopped: bool

bool Whether the view has been stopped.

class telegrampy.InlineKeyboardButton(*, text: str, url: str | None = None, data: str | None = None, row: int | None = None)

Represents a button that can be added to an InlineKeyboard.

Parameters:
  • text (str) – The label of the button.

  • url (str | None) – The HTTP or tg:// URL to be opened upon clicking the button.

  • data (str | None) – A unique piece of data to identify the button in a callback query. Only for buttons without a URL.

  • row (int] | None) – The row to show the button on inside of the keyboard.

row

The row to show the button on inside of the keyboard.

Type:

int | None

await callback(query: CallbackQuery) None

This function is a coroutine.

Called when the button is clicked. This should be implemented by subclasses.

Parameters:

query (CallbackQuery) – The callback query that triggered the button.

property keyboard: InlineKeyboard | None

InlineKeyboard | None The inline keyboard that the button belongs to.

@telegrampy.inline_keyboard_button(**kwargs: Any) Callable[[InlineKeyboardCallbackType], InlineKeyboardCallbackType]

Creates a button inside of an InlineKeyboard class, by using the decorated function as the callback.

The wrapped function should take three positional parameters: the current instance of the InlineKeyboard, the CallbackQuery that triggered the button, and the InlineKeyboardButton being pressed.

Parameters:

kwargs – The keyword arguments to pass into the constructor when added to the InlineKeyboard instance.

class telegrampy.ReplyKeyboard(*, persistent: bool = False, resize: bool = False, one_time: bool = False, input_placeholder: str | None = None, selective: bool = False)

Represents a custom keyboard with reply options that is shown to a user.

Parameters:
  • persistent (bool) – Whether the keyboard should always be shown.

  • resize (bool) – Whether clients should shrink/expand the keyboard to fit the buttons more optimially. If False, the keyboard will always take up the same amount of space as the standard keyboard.

  • one_time (bool) – Whether to close the keyboard after using it. Users will still be able to upon it up later.

  • placeholder (bool) – The placeholder to show in the input field when the keyboard is active.

  • selective (bool) – Whether to target all users in the chat or specific users. If selective, the markup will only be applied to users mentioned in the message and the author of the reply message.

property buttons: list[ReplyKeyboardButton]

The list of buttons added to the reply keyboard.

Type:

list[ReplyKeyboardButton]

class telegrampy.ReplyKeyboardButton(*, text: str, row: int | None = None)

Represents a button that can be added to a reply keyboard.

text: str

The label of the button.

row: int | None

The row to show the button on inside of the keyboard.

row

The row to show the button on inside of the keyboard.

Type:

int | None

class telegrampy.ReplyKeyboardRemove(selective: bool = False)

Removes a reply keyboard from the chat when sent as a reply markup.

Parameters:

selective (bool) – Whether to target all users in the chat or specific users. If selective, the markup will only be applied to users mentioned in the message and the author of the reply message.

class telegrampy.ForceReply(*, placeholder: str | None = None, selective: bool = False)

Populates a reply interface in the chat when sent as a reply markup.

Parameters:
  • placeholder (str | None) – The placeholder that will be shown in the input field when the reply interface is active.

  • selective (bool) – Whether to target all users in the chat or specific users. If selective, the markup will only be applied to users mentioned in the message and the author of the reply message.

class telegrampy.CallbackQuery(http: HTTPClient, data: CallbackQueryPayload)

A callback query triggered by a button on an inline keyboard.

Paramaters

id: str

The ID of the callback query

user: User

The user who sent the callback query.

message: PartialMessage | None

The message containing the button that originated the query, if sent by the bot.

inline_message_id: str | None

The ID of the message sent by the through in inline mode that originated the query.

chat_instance: str

Global unique ID for the chat which the message with the button was sent in.

data: str | None

The data associated with the button that triggered the query.

game_short_name: str | None

The short name of the game to be returned, serving as a unique ID.

await answer(*, text: str | None = None, show_alert: bool = False, url: str | None = None, cache_time: int = 0) None

This function is a coroutine.

Responds to a callback query. The answer will be displayed to the user as notification at the top of their screen or as an alert.

Paramaters
text: str

The text that will be shown to the user. If not passed, nothing will be shown to the user.

show_alert: bool

Whether to show an alert instead of a notification at the top of the screen to the user.

url: bool

Specifies the URL that opens your game for callback games buttons. Otherwise the link must be a t.me link that opens your bot with a specific parameter.

cache_time: int

The amount of time the callback query may be cached client side.

Exceptions

class telegrampy.TelegramException

Base exception for errors relating to telegram.py.

class telegrampy.ClientException

Raised when something miscellaneous goes wrong.

class telegrampy.HTTPException(response: aiohttp.ClientResponse, message: str)

Raised when an HTTP request fails.

This inherits from telegrampy.TelegramException.

response

The response for the request that failed.

Type:

aiohttp.ClientResponse

messsage

The message for the request that failed.

Type:

str | None

class telegrampy.BadRequest(response: aiohttp.ClientResponse, message: str)

Raised when a bad request is made.

This inherits from telegrampy.HTTPException.

class telegrampy.InvalidToken(response: aiohttp.ClientResponse, message: str)

Raised when a token is invalid.

This inherits from telegrampy.HTTPException.

class telegrampy.Forbidden(response: aiohttp.ClientResponse, message: str)

Raised when something is forbidden.

This inherits from telegrampy.HTTPException.

class telegrampy.Conflict(response: aiohttp.ClientResponse, message: str)

Raised when another instance of the bot is running.

This inherits from telegrampy.HTTPException.

class telegrampy.ServerError(response: aiohttp.ClientResponse, message: str)

Raised when telegram returns a 500 error.

This inherits from telegrampy.HTTPException.