AsyncTeleBot#

AsyncTeleBot methods#

class telebot.async_telebot.AsyncTeleBot(token: str, parse_mode: ~typing.Optional[str] = None, offset: ~typing.Optional[int] = None, exception_handler: ~typing.Optional[~telebot.async_telebot.ExceptionHandler] = None, state_storage: ~typing.Optional[~telebot.asyncio_storage.base_storage.StateStorageBase] = <telebot.asyncio_storage.memory_storage.StateMemoryStorage object>)#

Bases: object

This is the main asynchronous class for Bot.

It allows you to add handlers for different kind of updates.

Usage:

Using asynchronous implementation of TeleBot.#
from telebot.async_telebot import AsyncTeleBot
bot = AsyncTeleBot('token') # get token from @BotFather
# now you can register other handlers/update listeners,
# and use bot methods.
# Remember to use async/await keywords when necessary.

See more examples in examples/ directory: https://github.com/eternnoir/pyTelegramBotAPI/tree/master/examples

Parameters
  • token (str) – Token of a bot, obtained from @BotFather

  • parse_mode (str, optional) – Default parse mode, defaults to None

  • offset (int, optional) – Offset used in get_updates, defaults to None

  • exception_handler (Optional[ExceptionHandler], optional) – Exception handler, which will handle the exception occured, defaults to None

  • state_storage (telebot.asyncio_storage.StateMemoryStorage, optional) – Storage for states, defaults to StateMemoryStorage()

add_custom_filter(custom_filter: Union[SimpleCustomFilter, AdvancedCustomFilter])#

Create custom filter.

Example on checking the text of a message#
class TextMatchFilter(AdvancedCustomFilter):
    key = 'text'

    async def check(self, message, text):
        return text == message.text
Parameters

custom_filter (telebot.asyncio_filters.SimpleCustomFilter or telebot.asyncio_filters.AdvancedCustomFilter) – Class with check(message) method.

Returns

None

async add_data(user_id: int, chat_id: Optional[int] = None, **kwargs)#

Add data to states.

Parameters
  • user_id (int) – User’s identifier

  • chat_id (int) – Chat’s identifier

  • kwargs – Data to add

Returns

None

async add_sticker_to_set(user_id: int, name: str, emojis: str, png_sticker: Optional[Union[str, Any]] = None, tgs_sticker: Optional[Union[str, Any]] = None, webm_sticker: Optional[Union[str, Any]] = None, mask_position: Optional[MaskPosition] = None) bool#

Use this method to add a new sticker to a set created by the bot. It’s required to pass png_sticker or tgs_sticker. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#addstickertoset

Parameters
  • user_id (int) – User identifier of created sticker set owner

  • name (str) – Sticker set name

  • emojis (str) – One or more emoji corresponding to the sticker

  • png_sticker (str or filelike object) – PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data.

  • tgs_sticker (str or filelike object) – TGS animation with the sticker, uploaded using multipart/form-data.

  • webm_sticker (str or filelike object) – WebM animation with the sticker, uploaded using multipart/form-data.

  • mask_position (telebot.types.MaskPosition) – A JSON-serialized object for position where the mask should be placed on faces

Returns

On success, True is returned.

Return type

bool

async answer_callback_query(callback_query_id: int, text: Optional[str] = None, show_alert: Optional[bool] = None, url: Optional[str] = None, cache_time: Optional[int] = None) bool#

Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert.

Telegram documentation: https://core.telegram.org/bots/api#answercallbackquery

Parameters
  • callback_query_id (int) – Unique identifier for the query to be answered

  • text (str) – Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters

  • show_alert (bool) – If True, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false.

  • url (str) – URL that will be opened by the user’s client. If you have created a Game and accepted the conditions via @BotFather, specify the URL that opens your game - note that this will only work if the query comes from a callback_game button.

  • cache_time – The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0.

Returns

On success, True is returned.

Return type

bool

async answer_inline_query(inline_query_id: str, results: List[Any], cache_time: Optional[int] = None, is_personal: Optional[bool] = None, next_offset: Optional[str] = None, switch_pm_text: Optional[str] = None, switch_pm_parameter: Optional[str] = None) bool#

Use this method to send answers to an inline query. On success, True is returned. No more than 50 results per query are allowed.

Telegram documentation: https://core.telegram.org/bots/api#answerinlinequery

Parameters
  • inline_query_id (str) – Unique identifier for the answered query

  • results (list of types.InlineQueryResult) – Array of results for the inline query

  • cache_time (int) – The maximum amount of time in seconds that the result of the inline query may be cached on the server.

  • is_personal (bool) – Pass True, if results may be cached on the server side only for the user that sent the query.

  • next_offset (str) – Pass the offset that a client should send in the next query with the same text to receive more results.

  • switch_pm_parameter (str) – Deep-linking parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed. Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a ‘Connect your YouTube account’ button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an OAuth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot’s inline capabilities.

  • switch_pm_text (str) – Parameter for the start message sent to the bot when user presses the switch button

Returns

On success, True is returned.

Return type

bool

async answer_pre_checkout_query(pre_checkout_query_id: int, ok: bool, error_message: Optional[str] = None) bool#

Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned.

Note

The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.

Telegram documentation: https://core.telegram.org/bots/api#answerprecheckoutquery

Parameters
  • pre_checkout_query_id (int) – Unique identifier for the query to be answered

  • ok (bool) – Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.

  • error_message (str) – Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. “Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!”). Telegram will display this message to the user.

Returns

On success, True is returned.

Return type

bool

async answer_shipping_query(shipping_query_id: str, ok: bool, shipping_options: Optional[List[ShippingOption]] = None, error_message: Optional[str] = None) bool#

Asks for an answer to a shipping question.

Telegram documentation: https://core.telegram.org/bots/api#answershippingquery

Parameters
  • shipping_query_id (str) – Unique identifier for the query to be answered

  • ok (bool) – Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)

  • shipping_options (list of ShippingOption) – Required if ok is True. A JSON-serialized array of available shipping options.

  • error_message (str) – Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. “Sorry, delivery to your desired address is unavailable’). Telegram will display this message to the user.

Returns

On success, True is returned.

Return type

bool

async answer_web_app_query(web_app_query_id: str, result: InlineQueryResultBase) SentWebAppMessage#

Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned.

Telegram Documentation: https://core.telegram.org/bots/api#answerwebappquery

Parameters
  • web_app_query_id (str) – Unique identifier for the query to be answered

  • result (telebot.types.InlineQueryResultBase) – A JSON-serialized object describing the message to be sent

Returns

On success, a SentWebAppMessage object is returned.

Return type

telebot.types.SentWebAppMessage

async approve_chat_join_request(chat_id: Union[str, int], user_id: Union[int, str]) bool#

Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#approvechatjoinrequest

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)

  • user_id (int or str) – Unique identifier of the target user

Returns

True on success.

Return type

bool

async ban_chat_member(chat_id: Union[int, str], user_id: int, until_date: Optional[Union[int, datetime]] = None, revoke_messages: Optional[bool] = None) bool#

Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#banchatmember

Parameters
  • chat_id (int or str) – Unique identifier for the target group or username of the target supergroup or channel (in the format @channelusername)

  • user_id (int) – Unique identifier of the target user

  • until_date (int or datetime) – Date when the user will be unbanned, unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever

  • revoke_messages (bool) – Bool: Pass True to delete all messages from the chat for the user that is being removed. If False, the user will be able to see messages in the group that were sent before the user was removed. Always True for supergroups and channels.

Returns

Returns True on success.

Return type

bool

async ban_chat_sender_chat(chat_id: Union[int, str], sender_chat_id: Union[int, str]) bool#

Use this method to ban a channel chat in a supergroup or a channel. The owner of the chat will not be able to send messages and join live streams on behalf of the chat, unless it is unbanned first. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#banchatsenderchat

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • sender_chat_id (int or str) – Unique identifier of the target sender chat

Returns

True on success.

Return type

bool

callback_query_handler(func, **kwargs)#

Handles new incoming callback query. As a parameter to the decorator function, it passes telebot.types.CallbackQuery object.

Parameters
  • func (function) – Function executed as a filter

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

channel_post_handler(commands=None, regexp=None, func=None, content_types=None, **kwargs)#

Handles new incoming channel post of any kind - text, photo, sticker, etc. As a parameter to the decorator function, it passes telebot.types.Message object.

Parameters
  • commands (list of str) – Optional list of strings (commands to handle).

  • regexp (str) – Optional regular expression.

  • func (function) – Function executed as a filter

  • content_types (list of str) – Supported message content types. Must be a list. Defaults to [‘text’].

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

chat_join_request_handler(func=None, **kwargs)#

Handles a request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates. As a parameter to the decorator function, it passes telebot.types.ChatJoinRequest object.

Parameters
  • func (function) – Function executed as a filter

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

chat_member_handler(func=None, **kwargs)#

Handles update in a status of a user in a chat. The bot must be an administrator in the chat and must explicitly specify “chat_member” in the list of allowed_updates to receive these updates. As a parameter to the decorator function, it passes telebot.types.ChatMemberUpdated object.

Parameters
  • func (function) – Function executed as a filter

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

chosen_inline_handler(func, **kwargs)#

The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot. As a parameter to the decorator function, it passes telebot.types.ChosenInlineResult object.

Parameters
  • func (function) – Function executed as a filter

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

async close() bool#

Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn’t launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#close

Returns

bool

async close_session()#

Closes existing session of aiohttp. Use this function if you stop polling/webhooks.

async copy_message(chat_id: Union[int, str], from_chat_id: Union[int, str], message_id: int, caption: Optional[str] = None, parse_mode: Optional[str] = None, caption_entities: Optional[List[MessageEntity]] = None, disable_notification: Optional[bool] = None, protect_content: Optional[bool] = None, reply_to_message_id: Optional[int] = None, allow_sending_without_reply: Optional[bool] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, timeout: Optional[int] = None) MessageID#

Use this method to copy messages of any kind.

Telegram documentation: https://core.telegram.org/bots/api#copymessage

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • from_chat_id (int or str) – Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername)

  • message_id (int) – Message identifier in the chat specified in from_chat_id

  • caption (str) – New caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept

  • parse_mode (str) – Mode for parsing entities in the new caption.

  • caption_entities (Array of telebot.types.MessageEntity) – A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode

  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound.

  • protect_content (bool) – Protects the contents of the sent message from forwarding and saving

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if the specified replied-to message is not found

  • reply_markup (telebot.types.InlineKeyboardMarkup or telebot.types.ReplyKeyboardMarkup or telebot.types.ReplyKeyboardRemove or telebot.types.ForceReply) – Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • timeout (int) – Timeout in seconds for the request.

Returns

On success, the sent Message is returned.

Return type

telebot.types.Message

Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object.

Telegram documentation: https://core.telegram.org/bots/api#createchatinvitelink

Parameters
  • chat_id (int or str) – Id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • name (str) – Invite link name; 0-32 characters

  • expire_date (int or datetime) – Point in time (Unix timestamp) when the link will expire

  • member_limit (int) – Maximum number of users that can be members of the chat simultaneously

  • creates_join_request (bool) – True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can’t be specified

Returns

Returns the new invite link as ChatInviteLink object.

Return type

telebot.types.ChatInviteLink

Use this method to create a link for an invoice. Returns the created invoice link as String on success.

Telegram documentation: https://core.telegram.org/bots/api#createinvoicelink

Parameters
  • title (str) – Product name, 1-32 characters

  • description (str) – Product description, 1-255 characters

  • payload (str) – Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.

  • provider_token (str) – Payments provider token, obtained via @Botfather

  • currency (str) – Three-letter ISO 4217 currency code, see https://core.telegram.org/bots/payments#supported-currencies

  • prices (list of types.LabeledPrice) – Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)

  • max_tip_amount (int) – The maximum accepted amount for tips in the smallest units of the currency

  • suggested_tip_amounts (list of int) – A JSON-serialized array of suggested amounts of tips in the smallest units of the currency. At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount.

  • provider_data (str) – A JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider.

  • photo_url (str) – URL of the product photo for the invoice. Can be a photo of the goods or a photo of the invoice. People like it better when they see a photo of what they are paying for.

  • photo_size (int) – Photo size in bytes

  • photo_width (int) – Photo width

  • photo_height (int) – Photo height

  • need_name (bool) – Pass True, if you require the user’s full name to complete the order

  • need_phone_number (bool) – Pass True, if you require the user’s phone number to complete the order

  • need_email (bool) – Pass True, if you require the user’s email to complete the order

  • need_shipping_address (bool) – Pass True, if you require the user’s shipping address to complete the order

  • send_phone_number_to_provider (bool) – Pass True, if user’s phone number should be sent to provider

  • send_email_to_provider (bool) – Pass True, if user’s email address should be sent to provider

  • is_flexible (bool) – Pass True, if the final price depends on the shipping method

Returns

Created invoice link as String on success.

Return type

str

async create_new_sticker_set(user_id: int, name: str, title: str, emojis: str, png_sticker: Optional[Union[str, Any]] = None, tgs_sticker: Optional[Union[str, Any]] = None, webm_sticker: Optional[Union[str, Any]] = None, contains_masks: Optional[bool] = None, mask_position: Optional[MaskPosition] = None) bool#

Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#createnewstickerset

Parameters
  • user_id (int) – User identifier of created sticker set owner

  • name (str) – Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only English letters, digits and underscores. Must begin with a letter, can’t contain consecutive underscores and must end in “_by_<bot_username>”. <bot_username> is case insensitive. 1-64 characters.

  • title (str) – Sticker set title, 1-64 characters

  • emojis (str) – One or more emoji corresponding to the sticker

  • png_sticker (str) – PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data.

  • tgs_sticker (str) – TGS animation with the sticker, uploaded using multipart/form-data.

  • webm_sticker (str) – WebM animation with the sticker, uploaded using multipart/form-data.

  • contains_masks (bool) – Pass True, if a set of mask stickers should be created

  • mask_position (telebot.types.MaskPosition) – A JSON-serialized object for position where the mask should be placed on faces

Returns

On success, True is returned.

Return type

bool

async decline_chat_join_request(chat_id: Union[str, int], user_id: Union[int, str]) bool#

Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#declinechatjoinrequest

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)

  • user_id (int or str) – Unique identifier of the target user

Returns

True on success.

Return type

bool

async delete_chat_photo(chat_id: Union[int, str]) bool#

Use this method to delete a chat photo. Photos can’t be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group.

Telegram documentation: https://core.telegram.org/bots/api#deletechatphoto

Parameters

chat_id (int or str) – Int or Str: Unique identifier for the target chat or username of the target channel (in the format @channelusername)

Returns

True on success.

Return type

bool

async delete_chat_sticker_set(chat_id: Union[int, str]) bool#

Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#deletechatstickerset

Parameters

chat_id (int or str) – Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)

Returns

Returns True on success.

Return type

bool

async delete_message(chat_id: Union[int, str], message_id: int, timeout: Optional[int] = None) bool#

Use this method to delete a message, including service messages, with the following limitations: - A message can only be deleted if it was sent less than 48 hours ago. - A dice message in a private chat can only be deleted if it was sent more than 24 hours ago. - Bots can delete outgoing messages in private chats, groups, and supergroups. - Bots can delete incoming messages in private chats. - Bots granted can_post_messages permissions can delete outgoing messages in channels. - If the bot is an administrator of a group, it can delete any message there. - If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#deletemessage

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • message_id (int) – Identifier of the message to delete

  • timeout (int) – Timeout in seconds for the request.

Returns

Returns True on success.

Return type

bool

async delete_my_commands(scope: Optional[BotCommandScope] = None, language_code: Optional[int] = None) bool#

Use this method to delete the list of the bot’s commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#deletemycommands

Parameters
  • scope (telebot.types.BotCommandScope) – The scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault.

  • language_code (str) – A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands

Returns

True on success.

Return type

bool

async delete_state(user_id: int, chat_id: Optional[int] = None)#

Delete the current state of a user.

Parameters
  • user_id (int) – User’s identifier

  • chat_id (int) – Chat’s identifier

Returns

None

async delete_sticker_from_set(sticker: str) bool#

Use this method to delete a sticker from a set created by the bot. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#deletestickerfromset

Parameters

sticker – File identifier of the sticker

Returns

On success, True is returned.

Return type

bool

async delete_webhook(drop_pending_updates: Optional[bool] = None, timeout: Optional[int] = None) bool#

Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#deletewebhook

Parameters
  • drop_pending_updates – Pass True to drop all pending updates, defaults to None

  • timeout (int, optional) – Request connection timeout, defaults to None

Returns

Returns True on success.

Return type

bool

async download_file(file_path: Optional[str]) bytes#

Downloads file.

Parameters

file_path (str) – Path where the file should be downloaded.

Returns

bytes

Return type

bytes

Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

Telegram documentation: https://core.telegram.org/bots/api#editchatinvitelink

Parameters
  • chat_id (int or str) – Id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • name (str) – Invite link name; 0-32 characters

  • invite_link (str) – The invite link to edit

  • expire_date (int or datetime) – Point in time (Unix timestamp) when the link will expire

  • member_limit (int) – Maximum number of users that can be members of the chat simultaneously

  • creates_join_request (bool) – True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can’t be specified

Returns

Returns the new invite link as ChatInviteLink object.

Return type

telebot.types.ChatInviteLink

async edit_message_caption(caption: str, chat_id: Optional[Union[int, str]] = None, message_id: Optional[int] = None, inline_message_id: Optional[str] = None, parse_mode: Optional[str] = None, caption_entities: Optional[List[MessageEntity]] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None) Union[Message, bool]#

Use this method to edit captions of messages.

Telegram documentation: https://core.telegram.org/bots/api#editmessagecaption

Parameters
  • caption (str) – New caption of the message

  • chat_id (int | str) – Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel

  • message_id (int) – Required if inline_message_id is not specified.

  • inline_message_id (str) – Required if inline_message_id is not specified. Identifier of the inline message.

  • parse_mode (str) – New caption of the message, 0-1024 characters after entities parsing

  • caption_entities (list of types.MessageEntity) – A JSON-serialized array of objects that describe how the caption should be parsed.

  • reply_markup (InlineKeyboardMarkup) – A JSON-serialized object for an inline keyboard.

Returns

On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.

Return type

types.Message | bool

async edit_message_live_location(latitude: float, longitude: float, chat_id: Optional[Union[int, str]] = None, message_id: Optional[int] = None, inline_message_id: Optional[str] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, timeout: Optional[int] = None, horizontal_accuracy: Optional[float] = None, heading: Optional[int] = None, proximity_alert_radius: Optional[int] = None) Message#
Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly

disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.

Telegram documentation: https://core.telegram.org/bots/api#editmessagelivelocation

Parameters
  • latitude (float) – Latitude of new location

  • longitude (float) – Longitude of new location

  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • message_id (int) – Required if inline_message_id is not specified. Identifier of the message to edit

  • reply_markup (telebot.types.InlineKeyboardMarkup or telebot.types.ReplyKeyboardMarkup or telebot.types.ReplyKeyboardRemove or telebot.types.ForceReply) – A JSON-serialized object for a new inline keyboard.

  • timeout (int) – Timeout in seconds for the request.

  • inline_message_id (str) – Required if chat_id and message_id are not specified. Identifier of the inline message

  • horizontal_accuracy (float) – The radius of uncertainty for the location, measured in meters; 0-1500

  • heading (int) – Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.

  • proximity_alert_radius (int) – The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.

Returns

On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.

Return type

telebot.types.Message or bool

async edit_message_media(media: Any, chat_id: Optional[Union[int, str]] = None, message_id: Optional[int] = None, inline_message_id: Optional[str] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None) Union[Message, bool]#

Use this method to edit animation, audio, document, photo, or video messages. If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can’t be uploaded. Use previously uploaded file via its file_id or specify a URL.

Telegram documentation: https://core.telegram.org/bots/api#editmessagemedia

Parameters
  • media (InputMedia) – A JSON-serialized object for a new media content of the message

  • chat_id (int or str) – Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • message_id (int) – Required if inline_message_id is not specified. Identifier of the sent message

  • inline_message_id (str) – Required if chat_id and message_id are not specified. Identifier of the inline message

  • reply_markup (telebot.types.InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) – A JSON-serialized object for an inline keyboard.

Returns

On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.

Return type

types.Message or bool

async edit_message_reply_markup(chat_id: Optional[Union[int, str]] = None, message_id: Optional[int] = None, inline_message_id: Optional[str] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None) Union[Message, bool]#

Use this method to edit only the reply markup of messages.

Telegram documentation: https://core.telegram.org/bots/api#editmessagereplymarkup

Parameters
  • chat_id (int or str) – Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • message_id (int) – Required if inline_message_id is not specified. Identifier of the sent message

  • inline_message_id (str) – Required if chat_id and message_id are not specified. Identifier of the inline message

  • reply_markup (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) – A JSON-serialized object for an inline keyboard.

Returns

On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.

Return type

types.Message or bool

async edit_message_text(text: str, chat_id: Optional[Union[int, str]] = None, message_id: Optional[int] = None, inline_message_id: Optional[str] = None, parse_mode: Optional[str] = None, entities: Optional[List[MessageEntity]] = None, disable_web_page_preview: Optional[bool] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None) Union[Message, bool]#

Use this method to edit text and game messages.

Telegram documentation: https://core.telegram.org/bots/api#editmessagetext

Parameters
  • text (str) – New text of the message, 1-4096 characters after entities parsing

  • chat_id (int or str) – Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • message_id (int) – Required if inline_message_id is not specified. Identifier of the sent message

  • inline_message_id (str) – Required if chat_id and message_id are not specified. Identifier of the inline message

  • parse_mode (str) – Mode for parsing entities in the message text.

  • entities (List of telebot.types.MessageEntity) – List of special entities that appear in the message text, which can be specified instead of parse_mode

  • disable_web_page_preview (bool) – Disables link previews for links in this message

  • reply_markup (InlineKeyboardMarkup) – A JSON-serialized object for an inline keyboard.

Returns

On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.

Return type

types.Message or bool

edited_channel_post_handler(commands=None, regexp=None, func=None, content_types=None, **kwargs)#

Handles new version of a channel post that is known to the bot and was edited. As a parameter to the decorator function, it passes telebot.types.Message object.

Parameters
  • commands (list of str) – Optional list of strings (commands to handle).

  • regexp (str) – Optional regular expression.

  • func (function) – Function executed as a filter

  • content_types (list of str) – Supported message content types. Must be a list. Defaults to [‘text’].

  • kwargs – Optional keyword arguments(custom filters)

Returns

edited_message_handler(commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs)#

Handles new version of a message that is known to the bot and was edited.

As a parameter to the decorator function, it passes telebot.types.Message object.

Parameters
  • commands (list of str) – Optional list of strings (commands to handle).

  • regexp (str) – Optional regular expression.

  • func (function) – Function executed as a filter

  • content_types (list of str) – Supported message content types. Must be a list. Defaults to [‘text’].

  • chat_types (list of str) – list of chat types

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

enable_saving_states(filename='./.state-save/states.pkl')#

Enable saving states (by default saving disabled)

Note

It is recommended to pass a StatePickleStorage instance as state_storage to TeleBot class.

Parameters

filename (str, optional) – Filename of saving file, defaults to “./.state-save/states.pkl”

Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

Telegram documentation: https://core.telegram.org/bots/api#exportchatinvitelink

Parameters

chat_id (int or str) – Id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)

Returns

exported invite link as String on success.

Return type

str

async forward_message(chat_id: Union[int, str], from_chat_id: Union[int, str], message_id: int, disable_notification: Optional[bool] = None, protect_content: Optional[bool] = None, timeout: Optional[int] = None) Message#

Use this method to forward messages of any kind.

Telegram documentation: https://core.telegram.org/bots/api#forwardmessage

Parameters
  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound

  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • from_chat_id (int or str) – Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername)

  • message_id (int) – Message identifier in the chat specified in from_chat_id

  • protect_content (bool) – Protects the contents of the forwarded message from forwarding and saving

  • timeout (int) – Timeout in seconds for the request.

Returns

On success, the sent Message is returned.

Return type

telebot.types.Message

async get_chat(chat_id: Union[int, str]) Chat#

Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.

Telegram documentation: https://core.telegram.org/bots/api#getchat

Parameters

chat_id (int or str) – Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)

Returns

Chat information

Return type

telebot.types.Chat

async get_chat_administrators(chat_id: Union[int, str]) List[ChatMember]#

Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots.

Telegram documentation: https://core.telegram.org/bots/api#getchatadministrators

Parameters

chat_id – Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)

Returns

List made of ChatMember objects.

Return type

list of telebot.types.ChatMember

async get_chat_member(chat_id: Union[int, str], user_id: int) ChatMember#

Use this method to get information about a member of a chat. Returns a ChatMember object on success.

Telegram documentation: https://core.telegram.org/bots/api#getchatmember

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)

  • user_id (int) – Unique identifier of the target user

Returns

Returns ChatMember object on success.

Return type

telebot.types.ChatMember

async get_chat_member_count(chat_id: Union[int, str]) int#

Use this method to get the number of members in a chat.

Telegram documentation: https://core.telegram.org/bots/api#getchatmembercount

Parameters

chat_id (int or str) – Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)

Returns

Number of members in the chat.

Return type

int

get_chat_members_count(**kwargs)#
async get_chat_menu_button(chat_id: Optional[Union[int, str]] = None) MenuButton#

Use this method to get the current value of the bot’s menu button in a private chat, or the default menu button. Returns MenuButton on success.

Telegram Documentation: https://core.telegram.org/bots/api#getchatmenubutton

Parameters

chat_id (int or str) – Unique identifier for the target private chat. If not specified, default bot’s menu button will be returned.

Returns

types.MenuButton

Return type

telebot.types.MenuButton

async get_file(file_id: Optional[str]) File#

Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling get_file again.

Telegram documentation: https://core.telegram.org/bots/api#getfile

Parameters

file_id (str) – File identifier

Returns

telebot.types.File

async get_file_url(file_id: Optional[str]) str#

Get a valid URL for downloading a file.

Parameters

file_id (str) – File identifier to get download URL for.

Returns

URL for downloading the file.

Return type

str

async get_game_high_scores(user_id: int, chat_id: Optional[Union[int, str]] = None, message_id: Optional[int] = None, inline_message_id: Optional[str] = None) List[GameHighScore]#

Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. On success, returns an Array of GameHighScore objects.

This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and their neighbors are not among them. Please note that this behavior is subject to change.

Telegram documentation: https://core.telegram.org/bots/api#getgamehighscores

Parameters
  • user_id (int) – User identifier

  • chat_id (int or str) – Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • message_id (int) – Required if inline_message_id is not specified. Identifier of the sent message

  • inline_message_id (str) – Required if chat_id and message_id are not specified. Identifier of the inline message

Returns

On success, returns an Array of GameHighScore objects.

Return type

List[types.GameHighScore]

async get_me() User#

Returns basic information about the bot in form of a User object.

Telegram documentation: https://core.telegram.org/bots/api#getme

async get_my_commands(scope: Optional[BotCommandScope], language_code: Optional[str]) List[BotCommand]#

Use this method to get the current list of the bot’s commands. Returns List of BotCommand on success.

Telegram documentation: https://core.telegram.org/bots/api#getmycommands

Parameters
  • scope (telebot.types.BotCommandScope) – The scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault.

  • language_code (str) – A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands

Returns

List of BotCommand on success.

Return type

list of telebot.types.BotCommand

async get_my_default_administrator_rights(for_channels: Optional[bool] = None) ChatAdministratorRights#

Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.

Telegram documentation: https://core.telegram.org/bots/api#getmydefaultadministratorrights

Parameters

for_channels (bool) – Pass True to get the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be returned.

Returns

Returns ChatAdministratorRights on success.

Return type

telebot.types.ChatAdministratorRights

async get_state(user_id, chat_id: Optional[int] = None)#

Gets current state of a user. Not recommended to use this method. But it is ok for debugging.

Parameters
  • user_id (int) – User’s identifier

  • chat_id (int) – Chat’s identifier

Returns

state of a user

Return type

int or str or telebot.types.State

async get_sticker_set(name: str) StickerSet#

Use this method to get a sticker set. On success, a StickerSet object is returned.

Telegram documentation: https://core.telegram.org/bots/api#getstickerset

Parameters

name (str) – Sticker set name

Returns

On success, a StickerSet object is returned.

Return type

telebot.types.StickerSet

async get_updates(offset: Optional[int] = None, limit: Optional[int] = None, timeout: Optional[int] = 20, allowed_updates: Optional[List] = None, request_timeout: Optional[int] = None) List[Update]#

Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.

Telegram documentation: https://core.telegram.org/bots/api#getupdates

Parameters
  • offset (int, optional) – Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will forgotten.

  • limit (int, optional) – Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100.

  • timeout (int, optional) – Request connection timeout

  • allowed_updates (list, optional) – Array of string. List the types of updates you want your bot to receive.

  • long_polling_timeout (int, optional) – Timeout in seconds for long polling.

Returns

An Array of Update objects is returned.

Return type

list of telebot.types.Update

async get_user_profile_photos(user_id: int, offset: Optional[int] = None, limit: Optional[int] = None) UserProfilePhotos#

Use this method to get a list of profile pictures for a user. Returns a telebot.types.UserProfilePhotos object.

Telegram documentation: https://core.telegram.org/bots/api#getuserprofilephotos

Parameters
  • user_id (int) – Unique identifier of the target user

  • offset (int) – Sequential number of the first photo to be returned. By default, all photos are returned.

  • limit (int) – Limits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100.

Returns

UserProfilePhotos

Return type

telebot.types.UserProfilePhotos

async get_webhook_info(timeout: Optional[int] = None) WebhookInfo#

Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.

Telegram documentation: https://core.telegram.org/bots/api#getwebhookinfo

Parameters

timeout (int, optional) – Request connection timeout

Returns

On success, returns a WebhookInfo object.

Return type

telebot.types.WebhookInfo

async infinity_polling(timeout: Optional[int] = 20, skip_pending: Optional[bool] = False, request_timeout: Optional[int] = None, logger_level: Optional[int] = 40, allowed_updates: Optional[List[str]] = None, *args, **kwargs)#

Wrap polling with infinite loop and exception handling to avoid bot stops polling.

Parameters
  • timeout (int) – Timeout in seconds for get_updates(Defaults to None)

  • skip_pending (bool) – skip old updates

  • request_timeout (int) – Aiohttp’s request timeout. Defaults to 5 minutes(aiohttp.ClientTimeout).

  • logger_level (int) – Custom logging level for infinity_polling logging. Use logger levels from logging as a value. None/NOTSET = no error logging

  • allowed_updates (list of str) –

    A list of the update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See util.update_types for a complete list of available update types. Specify an empty list to receive all update types except chat_member (default). If not specified, the previous setting will be used.

    Please note that this parameter doesn’t affect updates created before the call to the get_updates, so unwanted updates may be received for a short period of time.

Returns

None

inline_handler(func, **kwargs)#

Handles new incoming inline query. As a parameter to the decorator function, it passes telebot.types.InlineQuery object.

Parameters
  • func (function) – Function executed as a filter

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

async kick_chat_member(chat_id: Union[int, str], user_id: int, until_date: Optional[Union[int, datetime]] = None, revoke_messages: Optional[bool] = None) bool#

This function is deprecated. Use ban_chat_member instead

async leave_chat(chat_id: Union[int, str]) bool#

Use this method for your bot to leave a group, supergroup or channel. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#leavechat

Parameters

chat_id (int or str) – Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)

Returns

bool

async log_out() bool#

Use this method to log out from the cloud Bot API server before launching the bot locally. You MUST log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#logout

Returns

True on success.

Return type

bool

message_handler(commands=None, regexp=None, func=None, content_types=None, chat_types=None, **kwargs)#

Handles ew incoming message of any kind - text, photo, sticker, etc. As a parameter to the decorator function, it passes telebot.types.Message object. All message handlers are tested in the order they were added.

Example:

Usage of message_handler#
bot = TeleBot('TOKEN')

# Handles all messages which text matches regexp.
@bot.message_handler(regexp='someregexp')
async def command_help(message):
    await bot.send_message(message.chat.id, 'Did someone call for help?')

# Handles messages in private chat
@bot.message_handler(chat_types=['private']) # You can add more chat types
async def command_help(message):
    await bot.send_message(message.chat.id, 'Private chat detected, sir!')

# Handle all sent documents of type 'text/plain'.
@bot.message_handler(func=lambda message: message.document.mime_type == 'text/plain',
    content_types=['document'])
async def command_handle_document(message):
    await bot.send_message(message.chat.id, 'Document received, sir!')

# Handle all other messages.
@bot.message_handler(func=lambda message: True, content_types=['audio', 'photo', 'voice', 'video', 'document',
    'text', 'location', 'contact', 'sticker'])
async def default_command(message):
    await bot.send_message(message.chat.id, "This is the default command handler.")
Parameters
  • commands (list of str) – Optional list of strings (commands to handle).

  • regexp (str) – Optional regular expression.

  • func – Optional lambda function. The lambda receives the message to test as the first parameter. It must return True if the command should handle the message.

  • content_types (list of str) – Supported message content types. Must be a list. Defaults to [‘text’].

  • chat_types (list of str) – list of chat types

  • kwargs – Optional keyword arguments(custom filters)

Returns

decorated function

my_chat_member_handler(func=None, **kwargs)#

Handles update in a status of a bot. For private chats, this update is received only when the bot is blocked or unblocked by the user. As a parameter to the decorator function, it passes telebot.types.ChatMemberUpdated object.

Parameters
  • func (function) – Function executed as a filter

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

async pin_chat_message(chat_id: Union[int, str], message_id: int, disable_notification: Optional[bool] = False) bool#

Use this method to pin a message in a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#pinchatmessage

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • message_id (int) – Identifier of a message to pin

  • disable_notification (bool) – Pass True, if it is not necessary to send a notification to all group members about the new pinned message

Returns

True on success.

Return type

bool

poll_answer_handler(func=None, **kwargs)#

Handles change of user’s answer in a non-anonymous poll(when user changes the vote). Bots receive new votes only in polls that were sent by the bot itself. As a parameter to the decorator function, it passes telebot.types.PollAnswer object.

Parameters
  • func (function) – Function executed as a filter

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

poll_handler(func, **kwargs)#

Handles new state of a poll. Bots receive only updates about stopped polls and polls, which are sent by the bot As a parameter to the decorator function, it passes telebot.types.Poll object.

Parameters
  • func (function) – Function executed as a filter

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

async polling(non_stop: bool = False, skip_pending=False, interval: int = 0, timeout: int = 20, request_timeout: Optional[int] = None, allowed_updates: Optional[List[str]] = None, none_stop: Optional[bool] = None)#

Runs bot in long-polling mode in a main loop. This allows the bot to retrieve Updates automagically and notify listeners and message handlers accordingly.

Warning: Do not call this function more than once!

Always gets updates.

Note

Set non_stop=True if you want your bot to continue receiving updates if there is an error.

Parameters
  • non_stop (bool) – Do not stop polling when an ApiException occurs.

  • skip_pending (bool) – skip old updates

  • interval (int) – Delay between two update retrivals

  • timeout (int) – Request connection timeout

  • request_timeout (int) – Timeout in seconds for get_updates(Defaults to None)

  • allowed_updates (list of str) –

    A list of the update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See util.update_types for a complete list of available update types. Specify an empty list to receive all update types except chat_member (default). If not specified, the previous setting will be used.

    Please note that this parameter doesn’t affect updates created before the call to the get_updates, so unwanted updates may be received for a short period of time.

  • none_stop (bool) – Deprecated, use non_stop. Old typo, kept for backward compatibility.

Returns

pre_checkout_query_handler(func, **kwargs)#

New incoming pre-checkout query. Contains full information about checkout. As a parameter to the decorator function, it passes telebot.types.PreCheckoutQuery object.

Parameters
  • func (function) – Function executed as a filter

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

async process_new_updates(updates: List[Update])#

Process new updates. Just pass list of updates - each update should be instance of Update object.

Parameters

updates (list of telebot.types.Update) – list of updates

Returns

None

async promote_chat_member(chat_id: Union[int, str], user_id: int, can_change_info: Optional[bool] = None, can_post_messages: Optional[bool] = None, can_edit_messages: Optional[bool] = None, can_delete_messages: Optional[bool] = None, can_invite_users: Optional[bool] = None, can_restrict_members: Optional[bool] = None, can_pin_messages: Optional[bool] = None, can_promote_members: Optional[bool] = None, is_anonymous: Optional[bool] = None, can_manage_chat: Optional[bool] = None, can_manage_video_chats: Optional[bool] = None, can_manage_voice_chats: Optional[bool] = None) bool#

Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user.

Telegram documentation: https://core.telegram.org/bots/api#promotechatmember

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel ( in the format @channelusername)

  • user_id (int) – Unique identifier of the target user

  • can_change_info (bool) – Pass True, if the administrator can change chat title, photo and other settings

  • can_post_messages (bool) – Pass True, if the administrator can create channel posts, channels only

  • can_edit_messages (bool) – Pass True, if the administrator can edit messages of other users, channels only

  • can_delete_messages (bool) – Pass True, if the administrator can delete messages of other users

  • can_invite_users (bool) – Pass True, if the administrator can invite new users to the chat

  • can_restrict_members (bool) – Pass True, if the administrator can restrict, ban or unban chat members

  • can_pin_messages (bool) – Pass True, if the administrator can pin messages, supergroups only

  • can_promote_members (bool) – Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by him)

  • is_anonymous (bool) – Pass True, if the administrator’s presence in the chat is hidden

  • can_manage_chat (bool) – Pass True, if the administrator can access the chat event log, chat statistics, message statistics in channels, see channel members, see anonymous administrators in supergroups and ignore slow mode. Implied by any other administrator privilege

  • can_manage_video_chats (bool) – Pass True, if the administrator can manage voice chats For now, bots can use this privilege only for passing to other administrators.

  • can_manage_voice_chats (bool) – Deprecated, use can_manage_video_chats.

Returns

True on success.

Return type

bool

register_callback_query_handler(callback: Awaitable, func: Callable, pass_bot: Optional[bool] = False, **kwargs)#

Registers callback query handler.

Parameters
  • callback (Awaitable) – function to be called

  • func (function) – Function executed as a filter

  • pass_bot (bool) – True if you need to pass TeleBot instance to handler(useful for separating handlers into different files)

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

register_channel_post_handler(callback: Awaitable, content_types: Optional[List[str]] = None, commands: Optional[List[str]] = None, regexp: Optional[str] = None, func: Optional[Callable] = None, pass_bot: Optional[bool] = False, **kwargs)#

Registers channel post message handler.

Parameters
  • callback (Awaitable) – function to be called

  • content_types (list of str) – Supported message content types. Must be a list. Defaults to [‘text’].

  • commands (list of str) – list of commands

  • regexp (str) – Regular expression

  • func (function) – Function executed as a filter

  • pass_bot (bool) – True if you need to pass TeleBot instance to handler(useful for separating handlers into different files)

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

register_chat_join_request_handler(callback: Awaitable, func: Optional[Callable] = None, pass_bot: Optional[bool] = False, **kwargs)#

Registers chat join request handler.

Parameters
  • callback (Awaitable) – function to be called

  • func (function) – Function executed as a filter

  • pass_bot (bool) – True if you need to pass TeleBot instance to handler(useful for separating handlers into different files)

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

register_chat_member_handler(callback: Awaitable, func: Optional[Callable] = None, pass_bot: Optional[bool] = False, **kwargs)#

Registers chat member handler.

Parameters
  • callback (Awaitable`) – function to be called

  • func (function) – Function executed as a filter

  • pass_bot (bool) – True if you need to pass TeleBot instance to handler(useful for separating handlers into different files)

  • kwargs – Optional keyword arguments(custom filters)

:return:None

register_chosen_inline_handler(callback: Awaitable, func: Callable, pass_bot: Optional[bool] = False, **kwargs)#

Registers chosen inline handler.

Parameters
  • callback (Awaitable) – function to be called

  • func (function) – Function executed as a filter

  • pass_bot (bool) – True if you need to pass TeleBot instance to handler(useful for separating handlers into different files)

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

register_edited_channel_post_handler(callback: Awaitable, content_types: Optional[List[str]] = None, commands: Optional[List[str]] = None, regexp: Optional[str] = None, func: Optional[Callable] = None, pass_bot: Optional[bool] = False, **kwargs)#

Registers edited channel post message handler.

Parameters
  • callback (Awaitable) – function to be called

  • content_types (list of str) – Supported message content types. Must be a list. Defaults to [‘text’].

  • commands (list of str) – list of commands

  • regexp (str) – Regular expression

  • func (function) – Function executed as a filter

  • pass_bot (bool) – True if you need to pass TeleBot instance to handler(useful for separating handlers into different files)

  • kwargs – Optional keyword arguments(custom filters)

Returns

decorated function

register_edited_message_handler(callback: Awaitable, content_types: Optional[List[str]] = None, commands: Optional[List[str]] = None, regexp: Optional[str] = None, func: Optional[Callable] = None, chat_types: Optional[List[str]] = None, pass_bot: Optional[bool] = False, **kwargs)#

Registers edited message handler.

Parameters
  • callback (Awaitable) – function to be called

  • content_types (list of str) – Supported message content types. Must be a list. Defaults to [‘text’].

  • commands (list of str) – list of commands

  • regexp (str) – Regular expression

  • func (function) – Function executed as a filter

  • chat_types (bool) – True for private chat

  • pass_bot (bool) – True if you need to pass TeleBot instance to handler(useful for separating handlers into different files)

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

register_inline_handler(callback: Awaitable, func: Callable, pass_bot: Optional[bool] = False, **kwargs)#

Registers inline handler.

Parameters
  • callback (Awaitable) – function to be called

  • func (function) – Function executed as a filter

  • pass_bot (bool) – True if you need to pass TeleBot instance to handler(useful for separating handlers into different files)

  • kwargs – Optional keyword arguments(custom filters)

Returns

decorated function

register_message_handler(callback: Awaitable, content_types: Optional[List[str]] = None, commands: Optional[List[str]] = None, regexp: Optional[str] = None, func: Optional[Callable] = None, chat_types: Optional[List[str]] = None, pass_bot: Optional[bool] = False, **kwargs)#

Registers message handler.

Parameters
  • callback (Awaitable) – function to be called

  • content_types (list of str) – Supported message content types. Must be a list. Defaults to [‘text’].

  • commands (list of str) – list of commands

  • regexp (str) –

  • func (function) – Function executed as a filter

  • chat_types (list of str) – List of chat types

  • pass_bot (bool) – True if you need to pass TeleBot instance to handler(useful for separating handlers into different files)

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

register_my_chat_member_handler(callback: Awaitable, func: Optional[Callable] = None, pass_bot: Optional[Callable] = False, **kwargs)#

Registers my chat member handler.

Parameters
  • callback (Awaitable) – function to be called

  • func (function) – Function executed as a filter

  • pass_bot (bool) – True if you need to pass TeleBot instance to handler(useful for separating handlers into different files)

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

register_poll_answer_handler(callback: Awaitable, func: Callable, pass_bot: Optional[bool] = False, **kwargs)#

Registers poll answer handler.

Parameters
  • callback (Awaitable) – function to be called

  • func (function) – Function executed as a filter

  • pass_bot (bool) – True if you need to pass TeleBot instance to handler(useful for separating handlers into different files)

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

register_poll_handler(callback: Awaitable, func: Callable, pass_bot: Optional[bool] = False, **kwargs)#

Registers poll handler.

Parameters
  • callback (Awaitable) – function to be called

  • func (function) – Function executed as a filter

  • pass_bot (bool) – True if you need to pass TeleBot instance to handler(useful for separating handlers into different files)

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

register_pre_checkout_query_handler(callback: Awaitable, func: Callable, pass_bot: Optional[bool] = False, **kwargs)#

Registers pre-checkout request handler.

Parameters
  • callback (Awaitable) – function to be called

  • func – Function executed as a filter

  • pass_bot (bool) – True if you need to pass TeleBot instance to handler(useful for separating handlers into different files)

  • kwargs – Optional keyword arguments(custom filters)

Returns

decorated function

register_shipping_query_handler(callback: Awaitable, func: Callable, pass_bot: Optional[bool] = False, **kwargs)#

Registers shipping query handler.

Parameters
  • callback (Awaitable) – function to be called

  • func (function) – Function executed as a filter

  • pass_bot (bool) – True if you need to pass TeleBot instance to handler(useful for separating handlers into different files)

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

async remove_webhook() bool#

Alternative for delete_webhook but uses set_webhook

async reply_to(message: Message, text: str, **kwargs) Message#

Convenience function for send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)

Parameters
Returns

On success, the sent Message is returned.

Return type

telebot.types.Message

async reset_data(user_id: int, chat_id: Optional[int] = None)#

Reset data for a user in chat.

Parameters
  • user_id (int) – User’s identifier

  • chat_id (int) – Chat’s identifier

Returns

None

async restrict_chat_member(chat_id: Union[int, str], user_id: int, until_date: Optional[Union[int, datetime]] = None, can_send_messages: Optional[bool] = None, can_send_media_messages: Optional[bool] = None, can_send_polls: Optional[bool] = None, can_send_other_messages: Optional[bool] = None, can_add_web_page_previews: Optional[bool] = None, can_change_info: Optional[bool] = None, can_invite_users: Optional[bool] = None, can_pin_messages: Optional[bool] = None) bool#

Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user.

Telegram documentation: https://core.telegram.org/bots/api#restrictchatmember

Parameters
  • chat_id (int or str) – Unique identifier for the target group or username of the target supergroup or channel (in the format @channelusername)

  • user_id (int) – Unique identifier of the target user

  • until_date (int or datetime) – Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever

  • can_send_messages (bool) – Pass True, if the user can send text messages, contacts, locations and venues

  • can_send_media_messages (bool) – Pass True, if the user can send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages

  • can_send_polls (bool) – Pass True, if the user is allowed to send polls, implies can_send_messages

  • can_send_other_messages (bool) – Pass True, if the user can send animations, games, stickers and use inline bots, implies can_send_media_messages

  • can_add_web_page_previews (bool) – Pass True, if the user may add web page previews to their messages, implies can_send_media_messages

  • can_change_info (bool) – Pass True, if the user is allowed to change the chat title, photo and other settings. Ignored in public supergroups

  • can_invite_users (bool) – Pass True, if the user is allowed to invite new users to the chat, implies can_invite_users

  • can_pin_messages (bool) – Pass True, if the user is allowed to pin messages. Ignored in public supergroups

Returns

True on success

Return type

bool

retrieve_data(user_id: int, chat_id: Optional[int] = None)#

Returns context manager with data for a user in chat.

Parameters
  • user_id (int) – User identifier

  • chat_id (int, optional) – Chat’s unique identifier, defaults to user_id

Returns

Context manager with data for a user in chat

Return type

Optional[Any]

Use this method to revoke an invite link created by the bot. Note: If the primary link is revoked, a new link is automatically generated The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

Telegram documentation: https://core.telegram.org/bots/api#revokechatinvitelink

Parameters
  • chat_id (int or str) – Id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • invite_link (str) – The invite link to revoke

Returns

Returns the new invite link as ChatInviteLink object.

Return type

telebot.types.ChatInviteLink

async run_webhooks(listen: Optional[str] = '127.0.0.1', port: Optional[int] = 443, url_path: Optional[str] = None, certificate: Optional[str] = None, certificate_key: Optional[str] = None, webhook_url: Optional[str] = None, max_connections: Optional[int] = None, allowed_updates: Optional[List] = None, ip_address: Optional[str] = None, drop_pending_updates: Optional[bool] = None, timeout: Optional[int] = None, secret_token: Optional[str] = None, secret_token_length: Optional[int] = 20, debug: Optional[bool] = False)#

This class sets webhooks and listens to a given url and port.

Parameters
  • listen – IP address to listen to. Defaults to 0.0.0.0

  • port – A port which will be used to listen to webhooks.

  • url_path – Path to the webhook. Defaults to /token

  • certificate – Path to the certificate file.

  • certificate_key – Path to the certificate key file.

  • webhook_url – Webhook URL.

  • max_connections – Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot’s server, and higher values to increase your bot’s throughput.

  • allowed_updates – A JSON-serialized list of the update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used.

  • ip_address – The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS

  • drop_pending_updates – Pass True to drop all pending updates

  • timeout – Integer. Request connection timeout

  • secret_token – Secret token to be used to verify the webhook request.

Returns

async send_animation(chat_id: Union[int, str], animation: Union[Any, str], duration: Optional[int] = None, width: Optional[int] = None, height: Optional[int] = None, thumb: Optional[Union[str, Any]] = None, caption: Optional[str] = None, parse_mode: Optional[str] = None, caption_entities: Optional[List[MessageEntity]] = None, disable_notification: Optional[bool] = None, protect_content: Optional[bool] = None, reply_to_message_id: Optional[int] = None, allow_sending_without_reply: Optional[bool] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, timeout: Optional[int] = None) Message#

Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.

Telegram documentation: https://core.telegram.org/bots/api#sendanimation

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • animation (str or telebot.types.InputFile) – Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data.

  • duration (int) – Duration of sent animation in seconds

  • width (int) – Animation width

  • height (int) – Animation height

  • thumb (str or telebot.types.InputFile) – Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail’s width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>.

  • caption (str) – Animation caption (may also be used when resending animation by file_id), 0-1024 characters after entities parsing

  • parse_mode (str) – Mode for parsing entities in the animation caption

  • protect_content (bool) – Protects the contents of the sent message from forwarding and saving

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • reply_markup (telebot.types.InlineKeyboardMarkup or telebot.types.ReplyKeyboardMarkup or telebot.types.ReplyKeyboardRemove or telebot.types.ForceReply) – Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound.

  • timeout (int) – Timeout in seconds for the request.

  • caption_entities (list of telebot.types.MessageEntity) – List of special entities that appear in the caption, which can be specified instead of parse_mode

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if the specified replied-to message is not found

Returns

On success, the sent Message is returned.

Return type

telebot.types.Message

async send_audio(chat_id: Union[int, str], audio: Union[Any, str], caption: Optional[str] = None, duration: Optional[int] = None, performer: Optional[str] = None, title: Optional[str] = None, reply_to_message_id: Optional[int] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, parse_mode: Optional[str] = None, disable_notification: Optional[bool] = None, timeout: Optional[int] = None, thumb: Optional[Union[str, Any]] = None, caption_entities: Optional[List[MessageEntity]] = None, allow_sending_without_reply: Optional[bool] = None, protect_content: Optional[bool] = None) Message#

Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.

For sending voice messages, use the send_voice method instead.

Telegram documentation: https://core.telegram.org/bots/api#sendaudio

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • audio (str or telebot.types.InputFile) – Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. Audio must be in the .MP3 or .M4A format.

  • caption (str) – Audio caption, 0-1024 characters after entities parsing

  • duration (int) – Duration of the audio in seconds

  • performer (str) – Performer

  • title (str) – Track name

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • reply_markup (telebot.types.InlineKeyboardMarkup or telebot.types.ReplyKeyboardMarkup or telebot.types.ReplyKeyboardRemove or telebot.types.ForceReply) –

  • parse_mode (str) – Mode for parsing entities in the audio caption. See formatting options for more details.

  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound.

  • timeout (int) – Timeout in seconds for the request.

  • thumb (str) – Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail’s width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>

  • caption_entities (list of telebot.types.MessageEntity) – A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if the specified replied-to message is not found

  • protect_content (bool) – Protects the contents of the sent message from forwarding and saving

Returns

On success, the sent Message is returned.

Return type

telebot.types.Message

async send_chat_action(chat_id: Union[int, str], action: str, timeout: Optional[int] = None) bool#

Use this method when you need to tell the user that something is happening on the bot’s side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.

Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot.

Telegram documentation: https://core.telegram.org/bots/api#sendchataction

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel

  • action (str) – Type of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_voice or upload_voice for voice notes, upload_document for general files, choose_sticker for stickers, find_location for location data, record_video_note or upload_video_note for video notes.

  • timeout (int) – Timeout in seconds for the request.

Returns

Returns True on success.

Return type

bool

async send_contact(chat_id: Union[int, str], phone_number: str, first_name: str, last_name: Optional[str] = None, vcard: Optional[str] = None, disable_notification: Optional[bool] = None, reply_to_message_id: Optional[int] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, timeout: Optional[int] = None, allow_sending_without_reply: Optional[bool] = None, protect_content: Optional[bool] = None) Message#

Use this method to send phone contacts. On success, the sent Message is returned.

Telegram documentation: https://core.telegram.org/bots/api#sendcontact

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel

  • phone_number (str) – Contact’s phone number

  • first_name (str) – Contact’s first name

  • last_name (str) – Contact’s last name

  • vcard (str) – Additional data about the contact in the form of a vCard, 0-2048 bytes

  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound.

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • reply_markup (telebot.types.InlineKeyboardMarkup or telebot.types.ReplyKeyboardMarkup or telebot.types.ReplyKeyboardRemove or telebot.types.ForceReply) – Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • timeout (int) – Timeout in seconds for the request.

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if one of the specified replied-to messages is not found.

  • protect_content (bool) – Protects the contents of the sent message from forwarding and saving

Returns

On success, the sent Message is returned.

Return type

telebot.types.Message

async send_dice(chat_id: Union[int, str], emoji: Optional[str] = None, disable_notification: Optional[bool] = None, reply_to_message_id: Optional[int] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, timeout: Optional[int] = None, allow_sending_without_reply: Optional[bool] = None, protect_content: Optional[bool] = None) Message#

Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.

Telegram documentation: https://core.telegram.org/bots/api#senddice

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • emoji (str) – Emoji on which the dice throw animation is based. Currently, must be one of “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”. Dice can have values 1-6 for “🎲”, “🎯” and “🎳”, values 1-5 for “🏀” and “⚽”, and values 1-64 for “🎰”. Defaults to “🎲”

  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound.

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • reply_markup (telebot.types.InlineKeyboardMarkup or telebot.types.ReplyKeyboardMarkup or telebot.types.ReplyKeyboardRemove or telebot.types.ForceReply) – Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • timeout (int) – Timeout in seconds for the request.

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if the specified replied-to message is not found

  • protect_content (bool) – Protects the contents of the sent message from forwarding

Returns

On success, the sent Message is returned.

Return type

telebot.types.Message

async send_document(chat_id: Union[int, str], document: Union[Any, str], reply_to_message_id: Optional[int] = None, caption: Optional[str] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, parse_mode: Optional[str] = None, disable_notification: Optional[bool] = None, timeout: Optional[int] = None, thumb: Optional[Union[str, Any]] = None, caption_entities: Optional[List[MessageEntity]] = None, allow_sending_without_reply: Optional[bool] = None, visible_file_name: Optional[str] = None, disable_content_type_detection: Optional[bool] = None, data: Optional[Union[str, Any]] = None, protect_content: Optional[bool] = None) Message#

Use this method to send general files.

Telegram documentation: https://core.telegram.org/bots/api#senddocument

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • document (str or telebot.types.InputFile) – (document) File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • caption (str) – Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing

  • reply_markup (telebot.types.InlineKeyboardMarkup or telebot.types.ReplyKeyboardMarkup or telebot.types.ReplyKeyboardRemove or telebot.types.ForceReply) – Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • parse_mode (str) – Mode for parsing entities in the document caption

  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound.

  • timeout (int) – Timeout in seconds for the request.

  • thumb (str or telebot.types.InputFile) – InputFile or String : Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail’s width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>

  • caption_entities (list of telebot.types.MessageEntity) – A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if the specified replied-to message is not found

  • visible_file_name (str) – allows to define file name that will be visible in the Telegram instead of original file name

  • disable_content_type_detection (bool) – Disables automatic server-side content type detection for files uploaded using multipart/form-data

  • data (str) – function typo miss compatibility: do not use it

  • protect_content (bool) – Protects the contents of the sent message from forwarding and saving

Returns

On success, the sent Message is returned.

Return type

telebot.types.Message

async send_game(chat_id: Union[int, str], game_short_name: str, disable_notification: Optional[bool] = None, reply_to_message_id: Optional[int] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, timeout: Optional[int] = None, allow_sending_without_reply: Optional[bool] = None, protect_content: Optional[bool] = None) Message#

Used to send the game.

Telegram documentation: https://core.telegram.org/bots/api#sendgame

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • game_short_name (str) – Short name of the game, serves as the unique identifier for the game. Set up your games via @BotFather.

  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound.

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • reply_markup (InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply) – Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • timeout (int) – Timeout in seconds for waiting for a response from the bot.

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if one of the specified replied-to messages is not found.

  • protect_content (bool) – Pass True, if content of the message needs to be protected from being viewed by the bot.

Returns

On success, the sent Message is returned.

Return type

types.Message

async send_invoice(chat_id: Union[int, str], title: str, description: str, invoice_payload: str, provider_token: str, currency: str, prices: List[LabeledPrice], start_parameter: Optional[str] = None, photo_url: Optional[str] = None, photo_size: Optional[int] = None, photo_width: Optional[int] = None, photo_height: Optional[int] = None, need_name: Optional[bool] = None, need_phone_number: Optional[bool] = None, need_email: Optional[bool] = None, need_shipping_address: Optional[bool] = None, send_phone_number_to_provider: Optional[bool] = None, send_email_to_provider: Optional[bool] = None, is_flexible: Optional[bool] = None, disable_notification: Optional[bool] = None, reply_to_message_id: Optional[int] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, provider_data: Optional[str] = None, timeout: Optional[int] = None, allow_sending_without_reply: Optional[bool] = None, max_tip_amount: Optional[int] = None, suggested_tip_amounts: Optional[List[int]] = None, protect_content: Optional[bool] = None) Message#

Sends invoice.

Telegram documentation: https://core.telegram.org/bots/api#sendinvoice

Parameters
  • chat_id (int or str) – Unique identifier for the target private chat

  • title (str) – Product name, 1-32 characters

  • description (str) – Product description, 1-255 characters

  • invoice_payload (str) – Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.

  • provider_token (str) – Payments provider token, obtained via @Botfather

  • currency (str) – Three-letter ISO 4217 currency code, see https://core.telegram.org/bots/payments#supported-currencies

  • prices (List[types.LabeledPrice]) – Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)

  • start_parameter (str) – Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter

  • photo_url (str) – URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for.

  • photo_size (int) – Photo size in bytes

  • photo_width (int) – Photo width

  • photo_height (int) – Photo height

  • need_name (bool) – Pass True, if you require the user’s full name to complete the order

  • need_phone_number (bool) – Pass True, if you require the user’s phone number to complete the order

  • need_email (bool) – Pass True, if you require the user’s email to complete the order

  • need_shipping_address (bool) – Pass True, if you require the user’s shipping address to complete the order

  • is_flexible (bool) – Pass True, if the final price depends on the shipping method

  • send_phone_number_to_provider (bool) – Pass True, if user’s phone number should be sent to provider

  • send_email_to_provider (bool) – Pass True, if user’s email address should be sent to provider

  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound.

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • reply_markup (str) – A JSON-serialized object for an inline keyboard. If empty, one ‘Pay total price’ button will be shown. If not empty, the first button must be a Pay button

  • provider_data (str) – A JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider.

  • timeout (int) – Timeout of a request, defaults to None

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if the specified replied-to message is not found

  • max_tip_amount (int) – The maximum accepted amount for tips in the smallest units of the currency

  • suggested_tip_amounts (list of int) – A JSON-serialized array of suggested amounts of tips in the smallest units of the currency. At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount.

  • protect_content (bool) – Protects the contents of the sent message from forwarding and saving

Returns

On success, the sent Message is returned.

Return type

types.Message

async send_location(chat_id: Union[int, str], latitude: float, longitude: float, live_period: Optional[int] = None, reply_to_message_id: Optional[int] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, disable_notification: Optional[bool] = None, timeout: Optional[int] = None, horizontal_accuracy: Optional[float] = None, heading: Optional[int] = None, proximity_alert_radius: Optional[int] = None, allow_sending_without_reply: Optional[bool] = None, protect_content: Optional[bool] = None) Message#

Use this method to send point on the map. On success, the sent Message is returned.

Telegram documentation: https://core.telegram.org/bots/api#sendlocation

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • latitude (float) – Latitude of the location

  • longitude (float) – Longitude of the location

  • live_period (int) – Period in seconds for which the location will be updated (see Live Locations, should be between 60 and 86400.

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • reply_markup (telebot.types.InlineKeyboardMarkup or telebot.types.ReplyKeyboardMarkup or telebot.types.ReplyKeyboardRemove or telebot.types.ForceReply) – Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound.

  • timeout (int) – Timeout in seconds for the request.

  • horizontal_accuracy (float) – The radius of uncertainty for the location, measured in meters; 0-1500

  • heading (int) – For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.

  • proximity_alert_radius (int) – For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if the specified replied-to message is not found

  • protect_content (bool) – Protects the contents of the sent message from forwarding and saving

Returns

On success, the sent Message is returned.

Return type

telebot.types.Message

async send_media_group(chat_id: Union[int, str], media: List[Union[InputMediaAudio, InputMediaDocument, InputMediaPhoto, InputMediaVideo]], disable_notification: Optional[bool] = None, protect_content: Optional[bool] = None, reply_to_message_id: Optional[int] = None, timeout: Optional[int] = None, allow_sending_without_reply: Optional[bool] = None) List[Message]#

Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Messages that were sent is returned.

Telegram documentation: https://core.telegram.org/bots/api#sendmediagroup

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • media (list of types.InputMedia) – A JSON-serialized array describing messages to be sent, must include 2-10 items

  • disable_notification (bool) – Sends the messages silently. Users will receive a notification with no sound.

  • protect_content (bool) – Protects the contents of the sent message from forwarding and saving

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • timeout (int) – Timeout in seconds for the request.

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if the specified replied-to message is not found

Returns

On success, an array of Messages that were sent is returned.

Return type

List[types.Message]

async send_message(chat_id: Union[int, str], text: str, parse_mode: Optional[str] = None, entities: Optional[List[MessageEntity]] = None, disable_web_page_preview: Optional[bool] = None, disable_notification: Optional[bool] = None, protect_content: Optional[bool] = None, reply_to_message_id: Optional[int] = None, allow_sending_without_reply: Optional[bool] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, timeout: Optional[int] = None) Message#

Use this method to send text messages.

Warning: Do not send more than about 4096 characters each message, otherwise you’ll risk an HTTP 414 error. If you must send more than 4096 characters, use the split_string or smart_split function in util.py.

Telegram documentation: https://core.telegram.org/bots/api#sendmessage

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • text (str) – Text of the message to be sent

  • parse_mode (str) – Mode for parsing entities in the message text.

  • entities (Array of telebot.types.MessageEntity) – List of special entities that appear in message text, which can be specified instead of parse_mode

  • disable_web_page_preview (bool) – Disables link previews for links in this message

  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound.

  • protect_content (bool) – If True, the message content will be hidden for all users except for the target user

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if the specified replied-to message is not found

  • reply_markup (telebot.types.InlineKeyboardMarkup or telebot.types.ReplyKeyboardMarkup or telebot.types.ReplyKeyboardRemove or telebot.types.ForceReply) – Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • timeout (int) – Timeout in seconds for the request.

Returns

On success, the sent Message is returned.

Return type

telebot.types.Message

async send_photo(chat_id: Union[int, str], photo: Union[Any, str], caption: Optional[str] = None, parse_mode: Optional[str] = None, caption_entities: Optional[List[MessageEntity]] = None, disable_notification: Optional[bool] = None, protect_content: Optional[bool] = None, reply_to_message_id: Optional[int] = None, allow_sending_without_reply: Optional[bool] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, timeout: Optional[int] = None) Message#

Use this method to send photos. On success, the sent Message is returned.

Telegram documentation: https://core.telegram.org/bots/api#sendphoto

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • photo (str or telebot.types.InputFile) – Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo’s width and height must not exceed 10000 in total. Width and height ratio must be at most 20.

  • caption (str) – Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing

  • parse_mode (str) – Mode for parsing entities in the photo caption.

  • caption_entities (list of telebot.types.MessageEntity) – A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode

  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound.

  • protect_content (bool) – Protects the contents of the sent message from forwarding and saving

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if the specified replied-to message is not found

  • reply_markup (telebot.types.InlineKeyboardMarkup or telebot.types.ReplyKeyboardMarkup or telebot.types.ReplyKeyboardRemove or telebot.types.ForceReply) – Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • timeout (int) – Timeout in seconds for the request.

Returns

On success, the sent Message is returned.

Return type

telebot.types.Message

async send_poll(chat_id: Union[int, str], question: str, options: List[str], is_anonymous: Optional[bool] = None, type: Optional[str] = None, allows_multiple_answers: Optional[bool] = None, correct_option_id: Optional[int] = None, explanation: Optional[str] = None, explanation_parse_mode: Optional[str] = None, open_period: Optional[int] = None, close_date: Optional[Union[int, datetime]] = None, is_closed: Optional[bool] = None, disable_notification: Optional[bool] = False, reply_to_message_id: Optional[int] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, allow_sending_without_reply: Optional[bool] = None, timeout: Optional[int] = None, explanation_entities: Optional[List[MessageEntity]] = None, protect_content: Optional[bool] = None) Message#

Use this method to send a native poll. On success, the sent Message is returned.

Telegram documentation: https://core.telegram.org/bots/api#sendpoll

Parameters
  • chat_id (int | str) – Unique identifier for the target chat or username of the target channel

  • question (str) – Poll question, 1-300 characters

  • options (list of str) – A JSON-serialized list of answer options, 2-10 strings 1-100 characters each

  • is_anonymous (bool) – True, if the poll needs to be anonymous, defaults to True

  • type (str) – Poll type, “quiz” or “regular”, defaults to “regular”

  • allows_multiple_answers (bool) – True, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to False

  • correct_option_id (int) – 0-based identifier of the correct answer option. Available only for polls in quiz mode, defaults to None

  • explanation (str) – Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing

  • explanation_parse_mode (str) – Mode for parsing entities in the explanation. See formatting options for more details.

  • open_period (int) – Amount of time in seconds the poll will be active after creation, 5-600. Can’t be used together with close_date.

  • close_date (int | datetime) – Point in time (Unix timestamp) when the poll will be automatically closed.

  • is_closed (bool) – Pass True, if the poll needs to be immediately closed. This can be useful for poll preview.

  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound.

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • allow_sending_without_reply (bool) – Pass True, if the poll allows multiple options to be voted simultaneously.

  • reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply) – Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • timeout (int) – Timeout in seconds for waiting for a response from the user.

  • explanation_entities (list of MessageEntity) – A JSON-serialized list of special entities that appear in the explanation, which can be specified instead of parse_mode

  • protect_content (bool) – Protects the contents of the sent message from forwarding and saving

Returns

On success, the sent Message is returned.

Return type

types.Message

async send_sticker(chat_id: Union[int, str], sticker: Union[Any, str], reply_to_message_id: Optional[int] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, disable_notification: Optional[bool] = None, timeout: Optional[int] = None, allow_sending_without_reply: Optional[bool] = None, protect_content: Optional[bool] = None, data: Optional[Union[str, Any]] = None) Message#

Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned.

Telegram documentation: https://core.telegram.org/bots/api#sendsticker

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • sticker (str or telebot.types.InputFile) – Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .webp file from the Internet, or upload a new one using multipart/form-data.

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • reply_markup (telebot.types.InlineKeyboardMarkup or telebot.types.ReplyKeyboardMarkup or telebot.types.ReplyKeyboardRemove or telebot.types.ForceReply) – Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • disable_notification (bool) – to disable the notification

  • timeout (int) – Timeout in seconds for the request.

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if the specified replied-to message is not found

  • protect_content (bool) – Protects the contents of the sent message from forwarding and saving

  • data (str) – function typo miss compatibility: do not use it

Returns

On success, the sent Message is returned.

Return type

telebot.types.Message

async send_venue(chat_id: Union[int, str], latitude: float, longitude: float, title: str, address: str, foursquare_id: Optional[str] = None, foursquare_type: Optional[str] = None, disable_notification: Optional[bool] = None, reply_to_message_id: Optional[int] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, timeout: Optional[int] = None, allow_sending_without_reply: Optional[bool] = None, google_place_id: Optional[str] = None, google_place_type: Optional[str] = None, protect_content: Optional[bool] = None) Message#

Use this method to send information about a venue. On success, the sent Message is returned.

Telegram documentation: https://core.telegram.org/bots/api#sendvenue

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel

  • latitude (float) – Latitude of the venue

  • longitude (float) – Longitude of the venue

  • title (str) – Name of the venue

  • address (str) – Address of the venue

  • foursquare_id (str) – Foursquare identifier of the venue

  • foursquare_type (str) – Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)

  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound.

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • reply_markup (telebot.types.InlineKeyboardMarkup or telebot.types.ReplyKeyboardMarkup or telebot.types.ReplyKeyboardRemove or telebot.types.ForceReply) – Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • timeout (int) – Timeout in seconds for the request.

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if one of the specified replied-to messages is not found.

  • google_place_id (str) – Google Places identifier of the venue

  • google_place_type (str) – Google Places type of the venue.

  • protect_content (bool) – Protects the contents of the sent message from forwarding and saving

Returns

On success, the sent Message is returned.

Return type

telebot.types.Message

async send_video(chat_id: Union[int, str], video: Union[Any, str], duration: Optional[int] = None, width: Optional[int] = None, height: Optional[int] = None, thumb: Optional[Union[str, Any]] = None, caption: Optional[str] = None, parse_mode: Optional[str] = None, caption_entities: Optional[List[MessageEntity]] = None, supports_streaming: Optional[bool] = None, disable_notification: Optional[bool] = None, protect_content: Optional[bool] = None, reply_to_message_id: Optional[int] = None, allow_sending_without_reply: Optional[bool] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, timeout: Optional[int] = None, data: Optional[Union[str, Any]] = None) Message#

Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document).

Telegram documentation: https://core.telegram.org/bots/api#sendvideo

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • video (str or telebot.types.InputFile) – Video to send. You can either pass a file_id as String to resend a video that is already on the Telegram servers, or upload a new video file using multipart/form-data.

  • duration (int) – Duration of sent video in seconds

  • width (int) – Video width

  • height (int) – Video height

  • thumb (str or telebot.types.InputFile) – Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail’s width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>.

  • caption (str) – Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing

  • parse_mode (str) – Mode for parsing entities in the video caption

  • caption_entities (list of telebot.types.MessageEntity) – List of special entities that appear in the caption, which can be specified instead of parse_mode

  • supports_streaming (bool) – Pass True, if the uploaded video is suitable for streaming

  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound.

  • protect_content (bool) – Protects the contents of the sent message from forwarding and saving

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if the specified replied-to message is not found

  • reply_markup (telebot.types.InlineKeyboardMarkup or telebot.types.ReplyKeyboardMarkup or telebot.types.ReplyKeyboardRemove or telebot.types.ForceReply) – Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • timeout (int) – Timeout in seconds for the request.

  • data (str) – function typo miss compatibility: do not use it

Returns

On success, the sent Message is returned.

Return type

telebot.types.Message

async send_video_note(chat_id: Union[int, str], data: Union[Any, str], duration: Optional[int] = None, length: Optional[int] = None, reply_to_message_id: Optional[int] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, disable_notification: Optional[bool] = None, timeout: Optional[int] = None, thumb: Optional[Union[str, Any]] = None, allow_sending_without_reply: Optional[bool] = None, protect_content: Optional[bool] = None) Message#

As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned.

Telegram documentation: https://core.telegram.org/bots/api#sendvideonote

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • data (str or telebot.types.InputFile) – Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. Sending video notes by a URL is currently unsupported

  • duration (int) – Duration of sent video in seconds

  • length (int) – Video width and height, i.e. diameter of the video message

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • reply_markup (telebot.types.InlineKeyboardMarkup or telebot.types.ReplyKeyboardMarkup or telebot.types.ReplyKeyboardRemove or telebot.types.ForceReply) – Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound.

  • timeout (int) – Timeout in seconds for the request.

  • thumb (str or telebot.types.InputFile) – Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail’s width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>.

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if the specified replied-to message is not found

  • protect_content (bool) – Protects the contents of the sent message from forwarding and saving

Returns

On success, the sent Message is returned.

Return type

telebot.types.Message

async send_voice(chat_id: Union[int, str], voice: Union[Any, str], caption: Optional[str] = None, duration: Optional[int] = None, reply_to_message_id: Optional[int] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, parse_mode: Optional[str] = None, disable_notification: Optional[bool] = None, timeout: Optional[int] = None, caption_entities: Optional[List[MessageEntity]] = None, allow_sending_without_reply: Optional[bool] = None, protect_content: Optional[bool] = None) Message#

Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.

Telegram documentation: https://core.telegram.org/bots/api#sendvoice

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • voice (str or telebot.types.InputFile) – Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data.

  • caption (str) – Voice message caption, 0-1024 characters after entities parsing

  • duration (int) – Duration of the voice message in seconds

  • reply_to_message_id (int) – If the message is a reply, ID of the original message

  • reply_markup (telebot.types.InlineKeyboardMarkup or telebot.types.ReplyKeyboardMarkup or telebot.types.ReplyKeyboardRemove or telebot.types.ForceReply) – Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.

  • parse_mode (str) – Mode for parsing entities in the voice message caption. See formatting options for more details.

  • disable_notification (bool) – Sends the message silently. Users will receive a notification with no sound.

  • timeout (int) – Timeout in seconds for the request.

  • caption_entities (list of telebot.types.MessageEntity) – A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode

  • allow_sending_without_reply (bool) – Pass True, if the message should be sent even if the specified replied-to message is not found

  • protect_content (bool) – Protects the contents of the sent message from forwarding and saving

Returns

On success, the sent Message is returned.

async set_chat_administrator_custom_title(chat_id: Union[int, str], user_id: int, custom_title: str) bool#

Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#setchatadministratorcustomtitle

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)

  • user_id (int) – Unique identifier of the target user

  • custom_title (str) – New custom title for the administrator; 0-16 characters, emoji are not allowed

Returns

True on success.

Return type

bool

async set_chat_description(chat_id: Union[int, str], description: Optional[str] = None) bool#

Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.

Telegram documentation: https://core.telegram.org/bots/api#setchatdescription

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • description (str) – Str: New chat description, 0-255 characters

Returns

True on success.

Return type

bool

async set_chat_menu_button(chat_id: Optional[Union[int, str]] = None, menu_button: Optional[MenuButton] = None) bool#

Use this method to change the bot’s menu button in a private chat, or the default menu button. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#setchatmenubutton

Parameters
  • chat_id (int or str) – Unique identifier for the target private chat. If not specified, default bot’s menu button will be changed.

  • menu_button (telebot.types.MenuButton) – A JSON-serialized object for the new bot’s menu button. Defaults to MenuButtonDefault

Returns

True on success.

Return type

bool

async set_chat_permissions(chat_id: Union[int, str], permissions: ChatPermissions) bool#

Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members admin rights.

Telegram documentation: https://core.telegram.org/bots/api#setchatpermissions

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)

  • permissions (telebot.types..ChatPermissions) – New default chat permissions

Returns

True on success

Return type

bool

async set_chat_photo(chat_id: Union[int, str], photo: Any) bool#

Use this method to set a new profile photo for the chat. Photos can’t be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group.

Telegram documentation: https://core.telegram.org/bots/api#setchatphoto

Parameters
  • chat_id (int or str) – Int or Str: Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • photo (typing.Union[file_like, str]) – InputFile: New chat photo, uploaded using multipart/form-data

Returns

True on success.

Return type

bool

async set_chat_sticker_set(chat_id: Union[int, str], sticker_set_name: str) StickerSet#

Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#setchatstickerset

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)

  • sticker_set_name (str) – Name of the sticker set to be set as the group sticker set

Returns

StickerSet object

Return type

telebot.types.StickerSet

async set_chat_title(chat_id: Union[int, str], title: str) bool#

Use this method to change the title of a chat. Titles can’t be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group.

Telegram documentation: https://core.telegram.org/bots/api#setchattitle

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • title (str) – New chat title, 1-255 characters

Returns

True on success.

Return type

bool

async set_game_score(user_id: Union[int, str], score: int, force: Optional[bool] = None, chat_id: Optional[Union[int, str]] = None, message_id: Optional[int] = None, inline_message_id: Optional[str] = None, disable_edit_message: Optional[bool] = None) Union[Message, bool]#

Sets the value of points in the game to a specific user.

Telegram documentation: https://core.telegram.org/bots/api#setgamescore

Parameters
  • user_id (int or str) – User identifier

  • score (int) – New score, must be non-negative

  • force (bool) – Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters

  • chat_id (int or str) – Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • message_id (int) – Required if inline_message_id is not specified. Identifier of the sent message

  • inline_message_id (str) – Required if chat_id and message_id are not specified. Identifier of the inline message

  • disable_edit_message (bool) – Pass True, if the game message should not be automatically edited to include the current scoreboard

Returns

On success, if the message was sent by the bot, returns the edited Message, otherwise returns True.

Return type

types.Message or bool

async set_my_commands(commands: List[BotCommand], scope: Optional[BotCommandScope] = None, language_code: Optional[str] = None) bool#

Use this method to change the list of the bot’s commands.

Telegram documentation: https://core.telegram.org/bots/api#setmycommands

Parameters
  • commands (list of telebot.types.BotCommand) – List of BotCommand. At most 100 commands can be specified.

  • scope (telebot.types.BotCommandScope) – The scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault.

  • language_code (str) – A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands

Returns

True on success.

Return type

bool

async set_my_default_administrator_rights(rights: Optional[ChatAdministratorRights] = None, for_channels: Optional[bool] = None) bool#

Use this method to change the default administrator rights requested by the bot when it’s added as an administrator to groups or channels. These rights will be suggested to users, but they are are free to modify the list before adding the bot. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#setmydefaultadministratorrights

Parameters
  • rights (telebot.types.ChatAdministratorRights) – A JSON-serialized object describing new default administrator rights. If not specified, the default administrator rights will be cleared.

  • for_channels (bool) – Pass True to change the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be changed.

Returns

True on success.

Return type

bool

async set_state(user_id: int, state: Union[State, int, str], chat_id: Optional[int] = None)#

Sets a new state of a user.

Note

You should set both user id and chat id in order to set state for a user in a chat. Otherwise, if you only set user_id, chat_id will equal to user_id, this means that state will be set for the user in his private chat with a bot.

Parameters
  • user_id (int) – User’s identifier

  • state (int or str or telebot.types.State) – new state. can be string, integer, or telebot.types.State

  • chat_id (int) – Chat’s identifier

Returns

None

async set_sticker_position_in_set(sticker: str, position: int) bool#

Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#setstickerpositioninset

Parameters
  • sticker (str) – File identifier of the sticker

  • position (int) – New sticker position in the set, zero-based

Returns

On success, True is returned.

Return type

bool

async set_sticker_set_thumb(name: str, user_id: int, thumb: Optional[Union[str, Any]] = None)#

Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#setstickersetthumb

Parameters
  • name (str) – Sticker set name

  • user_id (int) – User identifier

  • thumb (filelike object) –

Returns

On success, True is returned.

Return type

bool

set_update_listener(func: Awaitable)#

Update listener is a function that gets any update.

Parameters

func (Awaitable) – function that should get update.

Example on asynchronous update listeners.#
async def update_listener(new_messages):
    for message in new_messages:
        print(message.text) # Prints message text

bot.set_update_listener(update_listener)
Returns

None

async set_webhook(url: Optional[str] = None, certificate: Optional[Union[str, Any]] = None, max_connections: Optional[int] = None, allowed_updates: Optional[List[str]] = None, ip_address: Optional[str] = None, drop_pending_updates: Optional[bool] = None, timeout: Optional[int] = None, secret_token: Optional[str] = None) bool#

Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success.

If you’d like to make sure that the webhook was set by you, you can specify secret data in the parameter secret_token. If specified, the request will contain a header “X-Telegram-Bot-Api-Secret-Token” with the secret token as content.

Telegram Documentation: https://core.telegram.org/bots/api#setwebhook

Parameters
  • url (str, optional) – HTTPS URL to send updates to. Use an empty string to remove webhook integration, defaults to None

  • certificate (str, optional) – Upload your public key certificate so that the root certificate in use can be checked, defaults to None

  • max_connections (int, optional) – The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot’s server, and higher values to increase your bot’s throughput, defaults to None

  • allowed_updates (list, optional) –

    A JSON-serialized list of the update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member (default). If not specified, the previous setting will be used.

    Please note that this parameter doesn’t affect updates created before the call to the setWebhook, so unwanted updates may be received for a short period of time. Defaults to None

  • ip_address (str, optional) – The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS, defaults to None

  • drop_pending_updates (bool, optional) – Pass True to drop all pending updates, defaults to None

  • timeout (int, optional) – Timeout of a request, defaults to None

  • secret_token (str, optional) – A secret token to be sent in a header “X-Telegram-Bot-Api-Secret-Token” in every webhook request, 1-256 characters. Only characters A-Z, a-z, 0-9, _ and - are allowed. The header is useful to ensure that the request comes from a webhook set by you. Defaults to None

Returns

True on success.

Return type

bool if the request was successful.

setup_middleware(middleware: BaseMiddleware)#

Setup middleware.

Note

Take a look at the telebot.asyncio_handler_backends.BaseMiddleware section for more.

Parameters

middleware (telebot.asyncio_handler_backends.BaseMiddleware) – Middleware-class.

Returns

None

shipping_query_handler(func, **kwargs)#

Handles new incoming shipping query. Only for invoices with flexible price. As a parameter to the decorator function, it passes telebot.types.ShippingQuery object.

Parameters
  • func (function) – Function executed as a filter

  • kwargs – Optional keyword arguments(custom filters)

Returns

None

async skip_updates()#

Skip existing updates. Only last update will remain on server.

async stop_message_live_location(chat_id: Optional[Union[int, str]] = None, message_id: Optional[int] = None, inline_message_id: Optional[str] = None, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None, timeout: Optional[int] = None) Message#

Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned.

Telegram documentation: https://core.telegram.org/bots/api#stopmessagelivelocation

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • message_id (int) – Required if inline_message_id is not specified. Identifier of the message with live location to stop

  • inline_message_id (str) – Required if chat_id and message_id are not specified. Identifier of the inline message with live location to stop

  • reply_markup (telebot.types.InlineKeyboardMarkup or telebot.types.ReplyKeyboardMarkup or telebot.types.ReplyKeyboardRemove or telebot.types.ForceReply) – A JSON-serialized object for a new inline keyboard.

  • timeout (int) – Timeout in seconds for the request.

Returns

On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned.

Return type

telebot.types.Message or bool

async stop_poll(chat_id: Union[int, str], message_id: int, reply_markup: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply]] = None) Poll#

Use this method to stop a poll which was sent by the bot. On success, the stopped Poll is returned.

Telegram documentation: https://core.telegram.org/bots/api#stoppoll

Parameters
  • chat_id (int | str) – Unique identifier for the target chat or username of the target channel

  • message_id (int) – Identifier of the original message with the poll

  • reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply) – A JSON-serialized object for a new message markup.

Returns

On success, the stopped Poll is returned.

Return type

types.Poll

async unban_chat_member(chat_id: Union[int, str], user_id: int, only_if_banned: Optional[bool] = False) bool#

Use this method to unban a previously kicked user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don’t want this, use the parameter only_if_banned.

Telegram documentation: https://core.telegram.org/bots/api#unbanchatmember

Parameters
  • chat_id (int or str) – Unique identifier for the target group or username of the target supergroup or channel (in the format @username)

  • user_id (int) – Unique identifier of the target user

  • only_if_banned (bool) – Do nothing if the user is not banned

Returns

True on success

Return type

bool

async unban_chat_sender_chat(chat_id: Union[int, str], sender_chat_id: Union[int, str]) bool#

Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#unbanchatsenderchat

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • sender_chat_id (int or str) – Unique identifier of the target sender chat.

Returns

True on success.

Return type

bool

async unpin_all_chat_messages(chat_id: Union[int, str]) bool#

Use this method to unpin a all pinned messages in a supergroup chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#unpinallchatmessages

Parameters

chat_id (int or str) – Int or Str: Unique identifier for the target chat or username of the target channel (in the format @channelusername)

Returns

True on success.

Return type

bool

async unpin_chat_message(chat_id: Union[int, str], message_id: Optional[int] = None) bool#

Use this method to unpin specific pinned message in a supergroup chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.

Telegram documentation: https://core.telegram.org/bots/api#unpinchatmessage

Parameters
  • chat_id (int or str) – Unique identifier for the target chat or username of the target channel (in the format @channelusername)

  • message_id (int) – Int: Identifier of a message to unpin

Returns

True on success.

Return type

bool

async upload_sticker_file(user_id: int, png_sticker: Union[Any, str]) File#

Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.

Telegram documentation: https://core.telegram.org/bots/api#uploadstickerfile

Parameters
  • user_id (int) – User identifier of sticker set owner

  • png_sticker (filelike object) – PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px.

Returns

On success, the sent file is returned.

Return type

telebot.types.File

class telebot.async_telebot.ExceptionHandler#

Bases: object

Class for handling exceptions while Polling

handle(exception)#
class telebot.async_telebot.Handler(callback, *args, **kwargs)#

Bases: object

Class for (next step|reply) handlers

Asyncio filters#

class telebot.asyncio_filters.AdvancedCustomFilter#

Bases: ABC

Advanced Custom Filter base class. Create child class with check() method. Accepts two parameters, returns bool: True - filter passed, False - filter failed. message: Message class text: Filter value given in handler

Child classes should have .key property.

Example on creating an advanced custom filter.#
class TextStartsFilter(AdvancedCustomFilter):
    # Filter to check whether message starts with some text.
    key = 'text_startswith'

    def check(self, message, text):
        return message.text.startswith(text)
async check(message, text)#

Perform a check.

key: str = None#
class telebot.asyncio_filters.ChatFilter#

Bases: AdvancedCustomFilter

Check whether chat_id corresponds to given chat_id.

Example on using this filter:#
@bot.message_handler(chat_id=[99999])
# your function
key: str = 'chat_id'#
class telebot.asyncio_filters.ForwardFilter#

Bases: SimpleCustomFilter

Check whether message was forwarded from channel or group.

Example on using this filter:#
@bot.message_handler(is_forwarded=True)
# your function
key: str = 'is_forwarded'#
class telebot.asyncio_filters.IsAdminFilter(bot)#

Bases: SimpleCustomFilter

Check whether the user is administrator / owner of the chat.

Example on using this filter:#
@bot.message_handler(chat_types=['supergroup'], is_chat_admin=True)
# your function
key: str = 'is_chat_admin'#
class telebot.asyncio_filters.IsDigitFilter#

Bases: SimpleCustomFilter

Filter to check whether the string is made up of only digits.

Example on using this filter:#
@bot.message_handler(is_digit=True)
# your function
key: str = 'is_digit'#
class telebot.asyncio_filters.IsReplyFilter#

Bases: SimpleCustomFilter

Check whether message is a reply.

Example on using this filter:#
@bot.message_handler(is_reply=True)
# your function
key: str = 'is_reply'#
class telebot.asyncio_filters.LanguageFilter#

Bases: AdvancedCustomFilter

Check users language_code.

Example on using this filter:#
@bot.message_handler(language_code=['ru'])
# your function
key: str = 'language_code'#
class telebot.asyncio_filters.SimpleCustomFilter#

Bases: ABC

Simple Custom Filter base class. Create child class with check() method. Accepts only message, returns bool value, that is compared with given in handler.

Child classes should have .key property.

Example on creating a simple custom filter.#
class ForwardFilter(SimpleCustomFilter):
    # Check whether message was forwarded from channel or group.
    key = 'is_forwarded'

    def check(self, message):
        return message.forward_date is not None
async check(message)#

Perform a check.

key: str = None#
class telebot.asyncio_filters.StateFilter(bot)#

Bases: AdvancedCustomFilter

Filter to check state.

Example on using this filter:#
@bot.message_handler(state=1)
# your function
key: str = 'state'#
class telebot.asyncio_filters.TextContainsFilter#

Bases: AdvancedCustomFilter

Filter to check Text message. key: text

Example on using this filter:#
# Will respond if any message.text contains word 'account'
@bot.message_handler(text_contains=['account'])
# your function
key: str = 'text_contains'#
class telebot.asyncio_filters.TextFilter(equals: Optional[str] = None, contains: Optional[Union[list, tuple]] = None, starts_with: Optional[Union[str, list, tuple]] = None, ends_with: Optional[Union[str, list, tuple]] = None, ignore_case: bool = False)#

Bases: object

Advanced text filter to check (types.Message, types.CallbackQuery, types.InlineQuery, types.Poll)

example of usage is in examples/asynchronous_telebot/custom_filters/advanced_text_filter.py

Parameters
  • equals (str) – string, True if object’s text is equal to passed string

  • contains (list[str] or tuple[str]) – list[str] or tuple[str], True if any string element of iterable is in text

  • starts_with (str) – string, True if object’s text starts with passed string

  • ends_with (str) – string, True if object’s text starts with passed string

  • ignore_case (bool) – bool (default False), case insensitive

Raises

ValueError – if incorrect value for a parameter was supplied

Returns

None

class telebot.asyncio_filters.TextMatchFilter#

Bases: AdvancedCustomFilter

Filter to check Text message.

Example on using this filter:#
@bot.message_handler(text=['account'])
# your function
key: str = 'text'#
class telebot.asyncio_filters.TextStartsFilter#

Bases: AdvancedCustomFilter

Filter to check whether message starts with some text.

Example on using this filter:#
# Will work if message.text starts with 'sir'.
@bot.message_handler(text_startswith='sir')
# your function
key: str = 'text_startswith'#

Asyncio handler backends#

File with all middleware classes, states.

class telebot.asyncio_handler_backends.BaseMiddleware#

Bases: object

Base class for middleware. Your middlewares should be inherited from this class.

Set update_sensitive=True if you want to get different updates on different functions. For example, if you want to handle pre_process for message update, then you will have to create pre_process_message function, and so on. Same applies to post_process.

Example of class-based middlewares#
class MyMiddleware(BaseMiddleware):
    def __init__(self):
        self.update_sensitive = True
        self.update_types = ['message', 'edited_message']

    async def pre_process_message(self, message, data):
        # only message update here
        pass

    async def post_process_message(self, message, data, exception):
        pass # only message update here for post_process

    async def pre_process_edited_message(self, message, data):
        # only edited_message update here
        pass

    async def post_process_edited_message(self, message, data, exception):
        pass # only edited_message update here for post_process
async post_process(message, data, exception)#
async pre_process(message, data)#
update_sensitive: bool = False#
class telebot.asyncio_handler_backends.CancelUpdate#

Bases: object

Class for canceling updates. Just return instance of this class in middleware to skip update. Update will skip handler and execution of post_process in middlewares.

class telebot.asyncio_handler_backends.SkipHandler#

Bases: object

Class for skipping handlers. Just return instance of this class in middleware to skip handler. Update will go to post_process, but will skip execution of handler.

class telebot.asyncio_handler_backends.State#

Bases: object

Class representing a state.

class MyStates(StatesGroup):
    my_state = State() # returns my_state:State string.
class telebot.asyncio_handler_backends.StatesGroup#

Bases: object

Class representing common states.

class MyStates(StatesGroup):
    my_state = State() # returns my_state:State string.

Extensions#