-
Notifications
You must be signed in to change notification settings - Fork 0
Code snippets
This 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.
- Pure API
-
General code snippets
- Post a text message
- Reply to a message
- [Send a chat action ᵀᴱᴸᴱᴳᴿᴬᴹ](#send-a-chat-action------------https---coretelegramorg-bots-api-sendchataction-)
- Requesting location and contact from user
-
Message Formatting (bold, italic, code, ...)
- [Post a text message with Markdown formatting ᵀᴱᴸᴱᴳᴿᴬᴹ](#post-a-text-message-with-markdown-formatting------------https---coretelegramorg-bots-api-sendmessage-)
- [Post a text message with HTML formatting ᵀᴱᴸᴱᴳᴿᴬᴹ](#post-a-text-message-with-html-formatting------------https---coretelegramorg-bots-api-sendmessage-)
- [Message entities ᵀᴱᴸᴱᴳᴿᴬᴹ](#message-entities------------https---coretelegramorg-bots-api-messageentity-)
-
Working with files and media
- [Post an image file from disk ᵀᴱᴸᴱᴳᴿᴬᴹ](#post-an-image-file-from-disk------------https---coretelegramorg-bots-api-sendphoto-)
- [Post a voice file from disk ᵀᴱᴸᴱᴳᴿᴬᴹ](#post-a-voice-file-from-disk------------https---coretelegramorg-bots-api-sendvoice-)
- [Post a photo from a URL ᵀᴱᴸᴱᴳᴿᴬᴹ](#post-a-photo-from-a-url------------https---coretelegramorg-bots-api-sendphoto-)
- [Post an audio from disk ᵀᴱᴸᴱᴳᴿᴬᴹ](#post-an-audio-from-disk------------https---coretelegramorg-bots-api-sendaudio-)
- [Post a file from disk ᵀᴱᴸᴱᴳᴿᴬᴹ](#post-a-file-from-disk------------https---coretelegramorg-bots-api-senddocument-)
- Post an image from memory
- [Download a file ᵀᴱᴸᴱᴳᴿᴬᴹ](#download-a-file------------https---coretelegramorg-bots-api-getfile-)
-
Keyboard Menus
- [Custom Keyboards ᵀᴱᴸᴱᴳᴿᴬᴹ:](#custom-keyboards------------https---coretelegramorg-bots-keyboards--)
- Remove a custom keyboard
- Advanced snippets
- What to read next?
Table of contents generated with markdown-toc
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.
>>> updates = bot.get_updates()
>>> print([u.message.text for u in updates])
>>> updates = bot.get_updates()
>>> print([u.message.photo for u in updates if u.message.photo])
You'll always need the chat_id
>>> chat_id = bot.get_updates()[-1].message.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.
>>> bot.send_message(chat_id=chat_id, text="I'm sorry Dave I'm afraid I can't do that.")
This is a shortcut to bot.send_message
with sane defaults. Read more about it in the docs.
>>> update.message.reply_text("I'm sorry Dave I'm afraid I can't do that.")
Note: There are equivalents of this method for replying with photos, audio etc., and similar shortcuts exist throughout the library. Related PRs: #362, #420, #423
ᵀᴱᴸᴱᴳᴿᴬᴹ Use this to tell the user that something is happening on the bot's side:
>>> bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)
>>> location_keyboard = telegram.KeyboardButton(text="send_location", request_location=True)
>>> contact_keyboard = telegram.KeyboardButton(text="send_contact", request_contact=True)
>>> custom_keyboard = [[ location_keyboard, contact_keyboard ]]
>>> reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard)
>>> bot.send_Message(chat_id=chat_id,
... text="Would you mind sharing your location and contact with me?",
... reply_markup=reply_markup)
>>> bot.send_message(chat_id=chat_id,
... text="*bold* _italic_ `fixed width font` [link](http://google.com).",
... parse_mode=telegram.ParseMode.MARKDOWN)
>>> bot.send_message(chat_id=chat_id,
... text='<b>bold</b> <i>italic</i> <a href="http://google.com">link</a>.',
... parse_mode=telegram.ParseMode.HTML)
ᵀᴱᴸᴱᴳᴿᴬᴹ
To use MessageEntity, extract the entities from a Message object using get_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.
>>> entities = message.get_entities()
There are many more API methods. To read the full API documentation, visit the Telegram API documentation or the library documentation of telegram.Bot
>>> bot.send_photo(chat_id=chat_id, photo=open('tests/test.png', 'rb'))
>>> bot.send_voice(chat_id=chat_id, voice=open('tests/telegram.ogg', 'rb'))
>>> bot.send_photo(chat_id=chat_id, photo='https://telegram.org/img/t_logo.png')
>>> bot.send_audio(chat_id=chat_id, audio=open('tests/test.mp3', 'rb'))
>>> bot.send_document(chat_id=chat_id, document=open('tests/test.zip', 'rb'))
In this example, image
is a PIL (or Pillow) Image
object, but it works the same with all media types.
>>> from io import BytesIO
>>> bio = BytesIO()
>>> bio.name = 'image.jpeg'
>>> image.save(bio, 'JPEG')
>>> bio.seek(0)
>>> bot.send_photo(chat_id, photo=bio)
>>> file_id = message.voice.file_id
>>> newFile = bot.get_file(file_id)
>>> newFile.download('voice.ogg')
Note: For downloading photos, keep in mind that update.message.photo
is an array of different photo sizes. Use update.message.photo[-1]
to get the biggest size.
>>> custom_keyboard = [['top-left', 'top-right'],
... ['bottom-left', 'bottom-right']]
>>> reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard)
>>> bot.send_message(chat_id=chat_id,
... text="Custom Keyboard Test",
... reply_markup=reply_markup)
See also: Build a menu with Buttons
>>> reply_markup = telegram.ReplyKeyboardRemove()
>>> bot.send_message(chat_id=chat_id, text="I'm back.", reply_markup=reply_markup)
This decorator allows you to restrict the access of a handler to only the user_ids
specified in LIST_OF_ADMINS
.
from functools import wraps
LIST_OF_ADMINS = [12345678, 87654321]
def restricted(func):
@wraps(func)
def wrapped(bot, update, *args, **kwargs):
user_id = update.effective_user.id
if user_id not in LIST_OF_ADMINS:
print("Unauthorized access denied for {}.".format(user_id))
return
return func(bot, update, *args, **kwargs)
return wrapped
Add a @restricted
decorator on top of your handler declaration:
@restricted
def my_handler(bot, update):
pass # only accessible if `user_id` is in `LIST_OF_ADMINS`.
If you want to limit certain bot functions to group administrators, you have to test if a user is an administrator in the group in question. This however requires an extra API request, which is why it can make sense to cache this information for a certain time, especially if your bot is very busy.
This snippet requires this timeout-based cache decorator. (gist mirror)
Save the decorator to a new file named mwt.py
and add this line to your imports:
from mwt import MWT
Then, add the following decorated function to your script. You can change the timeout as required.
@MWT(timeout=60*60)
def get_admin_ids(bot, chat_id):
"""Returns a list of admin IDs for a given chat. Results are cached for 1 hour."""
return [admin.user.id for admin in bot.get_chat_administrators(chat_id)]
You can then use the function like this:
if update.message.from_user.id in get_admin_ids(bot, update.message.chat_id):
# admin only
Note: Private chats and groups with all_members_are_administrator
flag, are not covered by this snippet. Make sure you handle them.
The following handler allows you to easily restart the bot. It goes without saying that you should protect this method from access by unauthorized users, for example with the restricted decorator.
import os
import time
import sys
def restart(bot, update):
bot.send_message(update.message.chat_id, "Bot is restarting...")
time.sleep(0.2)
os.execl(sys.executable, sys.executable, *sys.argv)
You can trigger this handler with the /r
-command within Telegram, once you have added it to the dispatcher: dispatcher.add_handler(CommandHandler('r', restart))
The following code allows you to store ConversationHandler States and UserData and reloading them when you restart the bot. Store procedure is executed every 60 seconds; to change this value, you can modify the time.sleep(60)
instruction.
You should declare the two methods at the end of the main method to use python closure for accessing ConversationHandler and UserData.
import time, threading, pickle
def main():
def loadData():
try:
f = open('backup/conversations', 'rb')
conv_handler.conversations = pickle.load(f)
f.close()
f = open('backup/userdata', 'rb')
dp.user_data = pickle.load(f)
f.close()
except FileNotFoundError:
utils.logging.error("Data file not found")
except:
utils.logging.error(sys.exc_info()[0])
def saveData():
while True:
time.sleep(60)
# Before pickling
resolved = dict()
for k, v in conv_handler.conversations.items():
if isinstance(v, tuple) and len(v) is 2 and isinstance(v[1], Promise):
try:
new_state = v[1].result() # Result of async function
except:
new_state = v[0] # In case async function raised an error, fallback to old state
resolved[k] = new_state
else:
resolved[k] = v
try:
f = open('backup/conversations', 'wb+')
pickle.dump(resolved, f)
f.close()
f = open('backup/userdata', 'wb+')
pickle.dump(dp.user_data, f)
f.close()
except:
utils.logging.error(sys.exc_info()[0])
def main():
...
loadData()
threading.Thread(target=saveData).start()
If you haven't read the tutorial "Extensions – Your first Bot" yet, you might want to do it now.
- Wiki of
python-telegram-bot
© Copyright 2015-2025 – Licensed by Creative Commons
- Architecture Overview
- Builder Pattern for
Application
- Types of Handlers
- Working with Files and Media
- Exceptions, Warnings and Logging
- Concurrency in PTB
- Advanced Filters
- Storing data
- Making your bot persistent
- Adding Defaults
- Job Queue
- Arbitrary
callback_data
- Avoiding flood limits
- Webhooks
- Bot API Forward Compatiblity
- Frequently requested design patterns
- Code snippets
- Performance Optimizations
- Telegram Passport
- Bots built with PTB
- Automated Bot Tests