We read every piece of feedback, and take your input very seriously.
Include my email address so I can be contactedThis page can be read on its own to find the code snippet you need right now.
It is also a follow-up to the page Introduction to the API. If you come from there, you can leave your command line open and just try out a few of these snippets.
To fetch messages sent to your Bot, you can use the getUpdates API method.
Note: You don't have to use get_updates if you are writing your bot with the telegram.ext submodule, since telegram.ext.Updater takes care of fetching all updates for you. Read more about that here.
You'll always need the chat_id
These snippets usually apply to both ways of fetching updates. If you're using telegram.ext, you can get the chat_id in your handler callback with update.message.chat_id.
Note: In general, you can send messages to users by passing their user id as the chat_id. If the bot has a chat with the user, it will send the message to that chat.
Note: send_message method (as any of send_* methods of Bot class) returns the instance of Message class, so it can be used in code later.
This is a shortcut to bot.send_message with same defaults. Read more about it in the docs.
Note: There are equivalents of this method for replying with photos, audio etc., and similar shortcuts exist throughout the library.
ᵀᴱᴸᴱᴳᴿᴬᴹ Use this to tell the user that something is happening on the bot's side:
Alternatively, if you have several commands and don't want to repeat the above code snippet inside all commands see this wiki section on how to do that.
To catch the incoming message with the location/contact, use MessageHandler with filters.LOCATION and filters.CONTACT, respectively.
Telegram supports some formatting options for text. All the details about what is supported can be found here. Please keep in mind that you will have to escape the special characters as detailed in the documentation. PTB also offers a helper function for escaping of Markdown text. For escaping of HTML text, you can use html.escape from the standard library.
You can format text with every API method/type that has a parse_mode parameter. In addition to editing your text as described in the link above, pass one of the parse modes available through telegram.constants.ParseMode to the parse_mode parameter. Since the 5.0 update of the Bot API (version 13.1+ of PTB), you can alternatively pass a list of telegram.MessageEntities to the entities parameter.
Note: In the API 4.5 update, Telegram introduced MarkdownV2, which supports nested entities and needs other escaping than v1. Markdown V1 is referred as legacy mode by the official API docs, and you should prefer MarkdownV2. Make sure to also use reply_markdown_v2 instead of reply_markdown etc.
ᵀᴱᴸᴱᴳᴿᴬᴹ To use MessageEntity, extract the entities and their respective text from a Message object using parse_entities.
Note: This method should always be used instead of the entities attribute, since it calculates the correct substring from the message text based on UTF-16 codepoints - that is, it extracts the correct string even on when working with weird characters such as Emojis.
Consider this example which checks for presence of URLs in a message and prints them on screen.
For more narrowed use cases like extracting only Telegram message links, you might be better using ptbcontrib/extract_urls.
This is an example how to use entities to convert Telegram formatting to BBCode. In the current version it does not support nested entities.
Define parsing function:
Click to expand
Call it with:
...or for photo captions:
bbcode will contain message/caption text formatted in BBCode. urled parameter determines if URLs in text are to be processed as links or left as text.
See also: Build a menu with Buttons
The Unicode flag emoji for any country can by definition be calculated from the countries 2 letter country code. The following snippet only works in Python 3.
The 🎰 dice can take the values 1-64. Here is a dictionary that maps each value to the unique combination of symbols that produce that value:
(Source: This Gist by @Chase22)
Click to expand
Note that service messages about non-bot users joining the chat are removed from large groups. You can get the new members message by following the chatmemberbot.py example.
If you're using MessageHandlers and do not want them to respond to the channel posts automatically forwarded to the discussion group linked to your channel, you can use this filter in your MessageHandler (requires PTB v13.9+):
If you're using MessageHandlers and do not want them to respond to messages from anonymous admins, you can use this filter in your MessageHandler:
This decorator allows you to register a function as a command handler in a Flask like manner.
Add the @command_handler(command) decorator on top of your handler function:
Note: You can modify this decorator in order to register any type of handler (see Types Of Handlers). Please also note that PTB deliberately does not provide such functionality out of the box due to the reasons mentioned in #899.
This decorator allows you to restrict the access of a handler to only the user_ids specified in LIST_OF_ADMINS.
Add a @restricted decorator on top of your handler declaration:
This parametrized decorator allows you to signal different actions depending on the type of response of your bot. This way users will have similar feedback from your bot as they would from a real human.
You can decorate handler callbacks directly with @send_action(ChatAction.<Action>) or create aliases and decorate with them (more readable) .
With the above aliases, the following decorators are equivalent
All possible actions are documented here.
Often times you will find yourself in need for a menu with dynamic content. Use the following build_menu method to create a button layout with n_cols columns out of a list of buttons.
You can use the header_buttons and footer_buttons lists to put buttons in the first or last row respectively.
Replace the ... in below snippet by an appropriate argument, as indicated in the InlineKeyboardButton documentation. If you want to use KeyboardButtons, use ReplyKeyboardMarkup instead of InlineKeyboardMarkup.
Or, if you need a dynamic version, use list comprehension to generate your button_list dynamically from a list of strings:
This is especially useful if put inside a helper method like get_data_buttons to work on dynamic data and updating the menu according to user input.
To handle the callback_data, you need to set a CallbackQueryHandler.
When using a LoginUrl in an InlineKeyboardButton to authorize a user on your website via Telegram, you'll have to to check the hash of the received data to verify the data of the integrity as described here
The data JSON data will have the following form:
The following is an example implementation in Python:
Click to expand
A sample of Flask app can be found here.
The following example allows you to restart the bot from within a handler. It goes without saying that you should protect this method from access by unauthorized users - see here for some tips on this. The main magic consists of calling Application.stop_running from within a handler callback to allow for a graceful shutdown. Actually restarting the python script can then be achieved by different means.
Click to expand
Wiki of python-telegram-bot © Copyright 2015-2026 – Licensed by Creative Commons