python-telegram-bot-readthedocs-io-en-stable
python-telegram-bot-readthedocs-io-en-stable
Release 12.8
Leandro Toledo
2 Examples 3
3 Reference 5
3.1 telegram.ext package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.1.1 telegram.ext.Updater . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.1.2 telegram.ext.Dispatcher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.1.3 telegram.ext.DispatcherHandlerStop . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.1.4 telegram.ext.filters Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.1.5 telegram.ext.Job . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.1.6 telegram.ext.JobQueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.1.7 telegram.ext.MessageQueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.1.8 telegram.ext.DelayQueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.1.9 telegram.ext.CallbackContext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.1.10 telegram.ext.Defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.1.11 Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.1.12 Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
3.2 telegram package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
3.2.1 telegram.Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
3.2.2 telegram.Audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
3.2.3 telegram.Bot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
3.2.4 telegram.BotCommand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
3.2.5 telegram.CallbackQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
3.2.6 telegram.Chat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
3.2.7 telegram.ChatAction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
3.2.8 telegram.ChatMember . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
3.2.9 telegram.ChatPermissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
3.2.10 telegram.ChatPhoto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
3.2.11 telegram.constants Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
3.2.12 telegram.Contact . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
3.2.13 telegram.Dice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
3.2.14 telegram.Document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
3.2.15 telegram.error module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
3.2.16 telegram.File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
3.2.17 telegram.ForceReply . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
3.2.18 telegram.InlineKeyboardButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
3.2.19 telegram.InlineKeyboardMarkup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
3.2.20 telegram.InputFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
3.2.21 telegram.InputMedia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
3.2.22 telegram.InputMediaAnimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
i
3.2.23 telegram.InputMediaAudio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
3.2.24 telegram.InputMediaDocument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
3.2.25 telegram.InputMediaPhoto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
3.2.26 telegram.InputMediaVideo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
3.2.27 telegram.KeyboardButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
3.2.28 telegram.KeyboardButtonPollType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
3.2.29 telegram.Location . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
3.2.30 telegram.LoginUrl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
3.2.31 telegram.Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
3.2.32 telegram.MessageEntity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
3.2.33 telegram.ParseMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
3.2.34 telegram.PhotoSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
3.2.35 telegram.Poll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
3.2.36 telegram.PollAnswer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
3.2.37 telegram.PollOption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
3.2.38 telegram.ReplyKeyboardRemove . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
3.2.39 telegram.ReplyKeyboardMarkup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
3.2.40 telegram.ReplyMarkup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
3.2.41 telegram.TelegramObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
3.2.42 telegram.Update . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
3.2.43 telegram.User . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
3.2.44 telegram.UserProfilePhotos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
3.2.45 telegram.Venue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
3.2.46 telegram.Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
3.2.47 telegram.VideoNote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
3.2.48 telegram.Voice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
3.2.49 telegram.WebhookInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
3.2.50 Stickers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
3.2.51 Inline Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
3.2.52 Payments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
3.2.53 Games . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
3.2.54 Passport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
3.3 telegram.utils package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
3.3.1 telegram.utils.helpers Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
3.3.2 telegram.utils.promise.Promise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
3.3.3 telegram.utils.request.Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
3.4 Changelog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
3.4.1 Changelog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Index 259
ii
CHAPTER 1
If you’re just starting out with the library, we recommend following our “Your first Bot” tutorial that you can find
on our wiki. On our wiki you will also find guides like how to use handlers, webhooks, emoji, proxies and much
more.
1
Python Telegram Bot Documentation, Release 12.8
Examples
A great way to learn is by looking at examples. Ours can be found at our github in the examples folder.
3
Python Telegram Bot Documentation, Release 12.8
4 Chapter 2. Examples
CHAPTER 3
Reference
Below you can find a reference of all the classes and methods in python-telegram-bot. Apart from the telegram.ext
package the objects should reflect the types defined in the official telegram bot api documentation.
3.1.1 telegram.ext.Updater
5
Python Telegram Bot Documentation, Release 12.8
Type telegram.ext.JobQueue
dispatcher
Dispatcher that handles the updates and dispatches them to the handlers.
Type telegram.ext.Dispatcher
running
Indicates if the updater is running.
Type bool
persistence
Optional. The persistence class to store data that should be persistent over restarts.
Type telegram.ext.BasePersistence
use_context
Optional. True if using context based callbacks.
Type bool
Parameters
• token (str, optional) – The bot’s token given by the @BotFather.
• base_url (str, optional) – Base_url for the bot.
• base_file_url (str, optional) – Base_file_url for the bot.
• workers (int, optional) – Amount of threads in the thread pool for functions deco-
rated with @run_async (ignored if dispatcher argument is used).
• bot (telegram.Bot, optional) – A pre-initialized bot instance (ignored if dispatcher
argument is used). If a pre-initialized bot is used, it is the user’s responsibility to create
it using a Request instance with a large enough connection pool.
• dispatcher (telegram.ext.Dispatcher, optional) – A pre-initialized dis-
patcher instance. If a pre-initialized dispatcher is used, it is the user’s responsibility
to create it with proper arguments.
• private_key (bytes, optional) – Private key for decryption of telegram passport
data.
• private_key_password (bytes, optional) – Password for above private key.
• user_sig_handler (function, optional) – Takes signum, frame as posi-
tional arguments. This will be called when a signal is received, defaults are (SIGINT,
SIGTERM, SIGABRT) setable with idle.
• request_kwargs (dict, optional) – Keyword args to control the creation of a tele-
gram.utils.request.Request object (ignored if bot or dispatcher argument is used). The
request_kwargs are very useful for the advanced users who would like to control the
default timeouts and/or control the proxy used for http communication.
• use_context (bool, optional) – If set to True Use the context based callback API
(ignored if dispatcher argument is used). During the deprecation period of the old API
the default is False. New users: set this to True.
• persistence (telegram.ext.BasePersistence, optional) – The persis-
tence class to store data that should be persistent over restarts (ignored if dispatcher
argument is used).
• defaults (telegram.ext.Defaults, optional) – An object containing default
values to be used if not set explicitly in the bot methods.
Note:
6 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
Raises ValueError – If both token and bot are passed or none of them.
3.1.2 telegram.ext.Dispatcher
8 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
Parameters
• bot (telegram.Bot) – The bot object that should be passed to the handlers.
• update_queue (Queue) – The synchronized queue that will contain the updates.
• job_queue (telegram.ext.JobQueue, optional) – The telegram.ext.
JobQueue instance to pass onto handler callbacks.
• workers (int, optional) – Number of maximum concurrent worker threads for the
@run_async decorator. defaults to 4.
• persistence (telegram.ext.BasePersistence, optional) – The persis-
tence class to store data that should be persistent over restarts
• use_context (bool, optional) – If set to True Use the context based callback API.
During the deprecation period of the old API the default is False. New users: set this
to True.
add_error_handler(callback)
Registers an error handler in the Dispatcher. This handler will receive every error which happens in
your bot.
Warning: The errors handled within these handlers won’t show up in the logger, so you need to make
sure that you reraise the error.
Parameters callback (callable) – The callback function for this error handler. Will
be called when an error is raised. Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The error that happened will be present in context.error.
Note: See https://git.io/fxJuV for more info about switching to context based API.
add_handler(handler, group=0)
Register a handler.
TL;DR: Order and priority counts. 0 or 1 handlers per group will be used. End handling of update
with telegram.ext.DispatcherHandlerStop.
A handler must be an instance of a subclass of telegram.ext.Handler. All handlers are or-
ganized in groups with a numeric value. The default group is 0. All groups will be evaluated
for handling an update, but only 0 or 1 handler per group will be used. If telegram.ext.
DispatcherHandlerStop is raised from one of the handlers, no further handlers (regardless
of the group) will be called.
The priority/order of handlers is determined as follows:
• Priority of the group (lower group number == higher priority)
• The first handler in a group which should handle an update (see telegram.ext.Handler.
check_update) will be used. Other handlers from the group will not be used. The order in
which handlers were added to the group defines the priority.
Parameters
• handler (telegram.ext.Handler) – A Handler instance.
• group (int, optional) – The group identifier. Default is 0.
dispatch_error(update, error)
Dispatches an error.
Parameters
• update (str | telegram.Update | None) – The update that caused the error
Warning: If you’re using @run_async you cannot rely on adding custom attributes to
telegram.ext.CallbackContext. See its docs for more info.
Parameters
• func (callable) – The function to run in the thread.
• *args (tuple, optional) – Arguments to func.
• **kwargs (dict, optional) – Keyword arguments to func.
Returns Promise
running = None
Indicates if this dispatcher is running.
Type bool
start(ready=None)
Thread target of thread ‘dispatcher’.
Runs in background and processes the update queue.
10 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
3.1.3 telegram.ext.DispatcherHandlerStop
class telegram.ext.DispatcherHandlerStop
Bases: Exception
Raise this in handler to prevent execution any other handler (even in different group).
This module contains the Filters for use with the MessageHandler class.
class telegram.ext.filters.Filters
Bases: object
Predefined filters for use as the filter argument of telegram.ext.MessageHandler.
Examples
Use MessageHandler(Filters.video, callback_method) to filter all video messages. Use
MessageHandler(Filters.contact, callback_method) for all contacts. etc.
all = Filters.all
All Messages.
animation = Filters.animation
Messages that contain telegram.Animation.
audio = Filters.audio
Messages that contain telegram.Audio.
caption = Filters.caption
Messages with a caption. If a list of strings is passed, it filters messages to only allow those whose
caption is appearing in the given list.
Examples
MessageHandler(Filters.caption, callback_method)
class caption_entity(entity_type)
Bases: telegram.ext.filters.BaseFilter
Filters media messages to only allow those which have a telegram.MessageEntity where their
type matches entity_type.
Examples
Example MessageHandler(Filters.caption_entity("hashtag"),
callback_method)
Parameters entity_type – Caption Entity type to check for. All types can be found as
constants in telegram.MessageEntity.
Examples
MessageHandler(Filters.chat(-1234), callback_method)
Warning: chat_ids will give a copy of the saved chat ids as frozenset. This is to ensure
thread safety. To add/remove a chat, you should use add_usernames(), add_chat_ids(),
remove_usernames() and remove_chat_ids(). Only update the entire set by filter.
chat_ids/usernames = new_set, if you are entirely sure that it is not causing race condi-
tions, as this will complete replace the current set of allowed chats.
chat_ids
Which chat ID(s) to allow through.
Type set(int), optional
usernames
Which username(s) (without leading ‘@’) to allow through.
Type set(str), optional
allow_empty
Whether updates should be processed, if no chat is specified in chat_ids and usernames.
Type bool, optional
Parameters
• chat_id (int | List[int], optional) – Which chat ID(s) to allow through.
• username (str | List[str], optional) – Which username(s) to allow through. Lead-
ing ‘@’s in usernames will be discarded.
• allow_empty (bool, optional) – Whether updates should be processed, if no chat
is specified in chat_ids and usernames. Defaults to False
Raises RuntimeError – If chat_id and username are both present.
add_chat_ids(chat_id)
Add one or more chats to the allowed chat ids.
Parameters chat_id (int | List[int], optional) – Which chat ID(s) to allow through.
add_usernames(username)
Add one or more chats to the allowed usernames.
Parameters username (str | List[str], optional) – Which username(s) to allow
through. Leading ‘@’s in usernames will be discarded.
12 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
remove_chat_ids(chat_id)
Remove one or more chats from allowed chat ids.
Parameters chat_id (int | List[int], optional) – Which chat ID(s) to disallow
through.
remove_usernames(username)
Remove one or more chats from allowed usernames.
Parameters username (str | List[str], optional) – Which username(s) to disallow
through. Leading ‘@’s in usernames will be discarded.
command = Filters.command
Messages with a telegram.MessageEntity.BOT_COMMAND. By default only allows messages
starting with a bot command. Pass False to also allow messages that contain a bot command any-
where in the text.
Examples:
MessageHandler(Filters.command, command_at_start_callback)
MessageHandler(Filters.command(False), command_anywhere_callback)
Parameters update (bool, optional) – Whether to only allow messages that start with a
bot command. Defaults to True.
contact = Filters.contact
Messages that contain telegram.Contact.
dice = Filters.dice
Dice Messages. If an integer or a list of integers is passed, it filters messages to only allow those whose
dice value is appearing in the given list.
Examples
To allow any dice message, simply use MessageHandler(Filters.dice,
callback_method). To allow only dice with value 6, use MessageHandler(Filters.
dice(6), callback_method). To allow only dice with value 5 or 6, use
MessageHandler(Filters.dice([5, 6]), callback_method).
Parameters update (int | List[int], optional) – Which values to allow. If not specified,
will allow any dice message.
Note: Dice messages don’t have text. If you want to filter either text or dice messages, use Filters.
text | Filters.dice.
dice
Dice messages with the emoji . Passing a list of integers is supported just as for Filters.dice.
darts
Dice messages with the emoji . Passing a list of integers is supported just as for Filters.dice.
basketball
Dice messages with the emoji . Passing a list of integers is supported just as for Filters.dice.
document = Filters.document
Subset for messages containing a document/file.
Examples
Use these filters like: Filters.document.mp3, Filters.document.
mime_type("text/plain") etc. Or use just Filters.document for all document
messages.
category
This Filter filters documents by their category in the mime-type attribute
Note: This Filter only filters by the mime_type of the document, it doesn’t check the validity of
the document. The user can manipulate the mime-type of a message and send media with wrong
types that don’t fit to this handler.
Example
Filters.documents.category('audio/') filters all types of audio sent as file, for
example ‘audio/mpeg’ or ‘audio/x-wav’
application
Same as Filters.document.category("application").
audio
Same as Filters.document.category("audio").
image
Same as Filters.document.category("image").
video
Same as Filters.document.category("video").
text
Same as Filters.document.category("text").
mime_type
This Filter filters documents by their mime-type attribute
Note: This Filter only filters by the mime_type of the document, it doesn’t check the validity of
document.
The user can manipulate the mime-type of a message and send media with wrong types that don’t
fit to this handler.
Example
Filters.documents.mime_type('audio/mpeg') filters all audio in mp3 format.
apk
Same as Filters.document.mime_type("application/vnd.android.
package-archive")-
doc
Same as Filters.document.mime_type("application/msword")-
docx
Same as Filters.document.mime_type("application/vnd.
openxmlformats-officedocument.wordprocessingml.document")-
14 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
exe
Same as Filters.document.mime_type("application/
x-ms-dos-executable")-
gif
Same as Filters.document.mime_type("video/mp4")-
jpg
Same as Filters.document.mime_type("image/jpeg")-
mp3
Same as Filters.document.mime_type("audio/mpeg")-
pdf
Same as Filters.document.mime_type("application/pdf")-
py
Same as Filters.document.mime_type("text/x-python")-
svg
Same as Filters.document.mime_type("image/svg+xml")-
txt
Same as Filters.document.mime_type("text/plain")-
targz
Same as Filters.document.mime_type("application/x-compressed-tar")-
wav
Same as Filters.document.mime_type("audio/x-wav")-
xml
Same as Filters.document.mime_type("application/xml")-
zip
Same as Filters.document.mime_type("application/zip")-
class entity(entity_type)
Bases: telegram.ext.filters.BaseFilter
Filters messages to only allow those which have a telegram.MessageEntity where their type
matches entity_type.
Examples
Example MessageHandler(Filters.entity("hashtag"), callback_method)
Parameters entity_type – Entity type to check for. All types can be found as constants
in telegram.MessageEntity.
forwarded = Filters.forwarded
Messages that are forwarded.
game = Filters.game
Messages that contain telegram.Game.
group = Filters.group
Messages sent in a group chat.
invoice = Filters.invoice
Messages that contain telegram.Invoice.
class language(lang)
Bases: telegram.ext.filters.BaseFilter
Filters messages to only allow those which are from users with a certain language code.
Note: According to official telegram api documentation, not every single user has the language_code
attribute. Do not count on this filter working on all users.
Examples
MessageHandler(Filters.language("en"), callback_method)
Parameters lang (str | List[str]) – Which language code(s) to allow through. This
will be matched using .startswith meaning that ‘en’ will match both ‘en_US’ and
‘en_GB’.
location = Filters.location
Messages that contain telegram.Location.
passport_data = Filters.passport_data
Messages that contain a telegram.PassportData
photo = Filters.photo
Messages that contain telegram.PhotoSize.
poll = Filters.poll
Messages that contain a telegram.Poll.
private = Filters.private
Messages sent in a private chat.
class regex(pattern)
Bases: telegram.ext.filters.BaseFilter
Filters updates by searching for an occurrence of pattern in the message text. The re.search
function is used to determine whether an update should be filtered.
Refer to the documentation of the re module for more information.
To get the groups and groupdict matched, see telegram.ext.CallbackContext.matches.
Examples
Use MessageHandler(Filters.regex(r'help'), callback) to capture all messages
that contain the word help. You can also use MessageHandler(Filters.regex(re.
compile(r'help', re.IGNORECASE), callback) if you want your pattern to be case in-
sensitive. This approach is recommended if you need to specify flags on your pattern.
Note: Filters use the same short circuiting logic as python’s and, or and not. This means that for
example:
With a message.text of x, will only ever return the matches for the first filter, since the second one is
never evaluated.
reply = Filters.reply
Messages that are a reply to another message.
16 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
status_update = Filters.status_update
Subset for messages containing a status update.
Examples
Use these filters like: Filters.status_update.new_chat_members etc. Or use just
Filters.status_update for all status update messages.
chat_created
Messages that contain telegram.Message.group_chat_created,
telegram.Message.supergroup_chat_created or telegram.Message.
channel_chat_created.
delete_chat_photo
Messages that contain telegram.Message.delete_chat_photo.
left_chat_member
Messages that contain telegram.Message.left_chat_member.
migrate
Messages that contain telegram.Message.migrate_from_chat_id or :attr: tele-
gram.Message.migrate_from_chat_id.
new_chat_members
Messages that contain telegram.Message.new_chat_members.
new_chat_photo
Messages that contain telegram.Message.new_chat_photo.
new_chat_title
Messages that contain telegram.Message.new_chat_title.
pinned_message
Messages that contain telegram.Message.pinned_message.
sticker = Filters.sticker
Messages that contain telegram.Sticker.
successful_payment = Filters.successful_payment
Messages that confirm a telegram.SuccessfulPayment.
text = Filters.text
Text Messages. If a list of strings is passed, it filters messages to only allow those whose text is
appearing in the given list.
Examples
To allow any text message, simply use MessageHandler(Filters.text,
callback_method).
A simple usecase for passing a list is to allow only messages that were send by a custom telegram.
ReplyKeyboardMarkup:
Note:
• Dice messages don’t have text. If you want to filter either text or dice messages, use Filters.
text | Filters.dice.
• Messages containing a command are accepted by this filter. Use Filters.text &
(~Filters.command), if you want to filter only text messages without commands.
update = Filters.update
Subset for filtering the type of update.
Examples
Use these filters like: Filters.update.message or Filters.update.channel_posts
etc. Or use just Filters.update for all types.
message
Updates with telegram.Update.message
edited_message
Updates with telegram.Update.edited_message
messages
Updates with either telegram.Update.message or telegram.Update.
edited_message
channel_post
Updates with telegram.Update.channel_post
edited_channel_post
Updates with telegram.Update.edited_channel_post
channel_posts
Updates with either telegram.Update.channel_post or telegram.Update.
edited_channel_post
class user(user_id=None, username=None, allow_empty=False)
Bases: telegram.ext.filters.BaseFilter
Filters messages to allow only those which are from specified user ID.
Examples
MessageHandler(Filters.user(1234), callback_method)
Warning: user_ids will give a copy of the saved user ids as frozenset. This is to ensure
thread safety. To add/remove a user, you should use add_usernames(), add_user_ids(),
remove_usernames() and remove_user_ids(). Only update the entire set by filter.
user_ids/usernames = new_set, if you are entirely sure that it is not causing race condi-
tions, as this will complete replace the current set of allowed users.
user_ids
Which user ID(s) to allow through.
Type set(int), optional
usernames
Which username(s) (without leading ‘@’) to allow through.
Type set(str), optional
allow_empty
Whether updates should be processed, if no user is specified in user_ids and usernames.
18 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
Parameters
• user_id (int | List[int], optional) – Which user ID(s) to allow through.
• username (str | List[str], optional) – Which username(s) to allow through. Lead-
ing ‘@’s in usernames will be discarded.
• allow_empty (bool, optional) – Whether updates should be processed, if no user
is specified in user_ids and usernames. Defaults to False
Raises RuntimeError – If user_id and username are both present.
add_user_ids(user_id)
Add one or more users to the allowed user ids.
Parameters user_id (int | List[int], optional) – Which user ID(s) to allow through.
add_usernames(username)
Add one or more users to the allowed usernames.
Parameters username (str | List[str], optional) – Which username(s) to allow
through. Leading ‘@’s in usernames will be discarded.
remove_user_ids(user_id)
Remove one or more users from allowed user ids.
Parameters user_id (int | List[int], optional) – Which user ID(s) to disallow
through.
remove_usernames(username)
Remove one or more users from allowed usernames.
Parameters username (str | List[str], optional) – Which username(s) to disallow
through. Leading ‘@’s in usernames will be discarded.
venue = Filters.venue
Messages that contain telegram.Venue.
video = Filters.video
Messages that contain telegram.Video.
video_note = Filters.video_note
Messages that contain telegram.VideoNote.
voice = Filters.voice
Messages that contain telegram.Voice.
class telegram.ext.filters.BaseFilter
Bases: abc.ABC
Base class for all Message Filters.
Subclassing from this class filters to be combined using bitwise operators:
And:
Or:
Not:
>>> ~ Filters.command
Note: Filters use the same short circuiting logic as python’s and, or and not. This means that for example:
With a message.text of x, will only ever return the matches for the first filter, since the second one is never
evaluated.
If you want to create your own filters create a class inheriting from this class and implement a filter method
that returns a boolean: True if the message should be handled, False otherwise. Note that the filters work
only as class instances, not actual class objects (so remember to initialize your filter classes).
By default the filters name (what will get printed when converted to a string for display) will be the class
name. If you want to overwrite this assign a better name to the name class variable.
name
Name for this filter. Defaults to the type of filter.
Type str
update_filter
Whether this filter should work on update. If False it will run the filter on update.
effective_message`. Default is False.
Type bool
data_filter
Whether this filter is a data filter. A data filter should return a dict with lists. The dict will be merged
with telegram.ext.CallbackContext’s internal dict in most cases (depends on the handler).
Type bool
filter(update)
This method must be overwritten.
Note: If update_filter is false then the first argument is message and of type telegram.
Message.
class telegram.ext.filters.InvertedFilter(f )
Bases: telegram.ext.filters.BaseFilter
Represents a filter that has been inverted.
Parameters f – The filter to invert.
filter(update)
This method must be overwritten.
Note: If update_filter is false then the first argument is message and of type telegram.
Message.
20 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
Note: If update_filter is false then the first argument is message and of type telegram.
Message.
3.1.5 telegram.ext.Job
Parameters
• callback (callable) – The callback function that should be executed by the new
job. Callback signature for context based API:
def callback(CallbackContext)
a context.job is the telegram.ext.Job instance. It can be used to access its
job.context or change it to a repeating job.
days
Optional. Defines on which days of the week the job should run.
Type Tuple[int]
enabled
Whether this job is enabled.
Type bool
interval
Optional. The interval in which the job will run.
Type int | float | datetime.timedelta
interval_seconds
The interval for this job in seconds.
Type int
job_queue
Optional. The JobQueue this job belongs to.
Type telegram.ext.JobQueue
next_t
Datetime for the next job execution. Datetime is localized according to tzinfo. If job is removed or
already ran it equals to None.
Type datetime.datetime
removed
Whether this job is due to be removed.
Type bool
repeat
Optional. If this job should periodically execute its callback function.
Type bool
22 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
run(dispatcher)
Executes the callback function.
schedule_removal()
Schedules this job for removal from the JobQueue. It will be removed without executing its callback
function again.
3.1.6 telegram.ext.JobQueue
class telegram.ext.JobQueue(bot=None)
Bases: object
This class allows you to periodically perform tasks with the bot.
_queue
The queue that holds the Jobs.
Type PriorityQueue
bot
The bot instance that should be passed to the jobs. DEPRECATED: Use set_dispatcher instead.
Type telegram.Bot
get_jobs_by_name(name)
Returns a tuple of jobs with the given name that are currently in the JobQueue
jobs()
Returns a tuple of all jobs that are currently in the JobQueue.
run_daily(callback, time, days=(0, 1, 2, 3, 4, 5, 6), context=None, name=None)
Creates a new Job that runs on a daily basis and adds it to the queue.
Parameters
• callback (callable) – The callback function that should be executed by the new
job. Callback signature for context based API:
def callback(CallbackContext)
context.job is the telegram.ext.Job instance. It can be used to access its
job.context or change it to a repeating job.
• time (datetime.time) – Time of day at which the job should run. If the timezone
(time.tzinfo) is None, UTC will be assumed. time.tzinfo will implicitly
define Job.tzinfo.
• days (Tuple[int], optional) – Defines on which days of the week the job should run.
Defaults to EVERY_DAY
• context (object, optional) – Additional data needed for the callback function.
Can be accessed through job.context in the callback. Defaults to None.
• name (str, optional) – The name of the new job. Defaults to callback.
__name__.
Returns The new Job instance that has been added to the job queue.
Return type telegram.ext.Job
Note: Daily is just an alias for “24 Hours”. That means that if DST changes during that interval, the
job might not run at the time one would expect. It is always recommended to pin servers to UTC time,
then time related behaviour can always be expected.
Parameters
• callback (callable) – The callback function that should be executed by the new
job. Callback signature for context based API:
def callback(CallbackContext)
context.job is the telegram.ext.Job instance. It can be used to access its
job.context or change it to a repeating job.
• when (datetime.time) – Time of day at which the job should run. If the timezone
(when.tzinfo) is None, UTC will be assumed. This will also implicitly define
Job.tzinfo.
• day (int) – Defines the day of the month whereby the job would run. It should be
within the range of 1 and 31, inclusive.
• context (object, optional) – Additional data needed for the callback function.
Can be accessed through job.context in the callback. Defaults to None.
• name (str, optional) – The name of the new job. Defaults to callback.
__name__.
• day_is_strict (bool, optional) – If False and day > month.days, will pick the
last day in the month. Defaults to True.
Returns The new Job instance that has been added to the job queue.
Return type telegram.ext.Job
run_once(callback, when, context=None, name=None)
Creates a new Job that runs once and adds it to the queue.
Parameters
• callback (callable) – The callback function that should be executed by the new
job. Callback signature for context based API:
def callback(CallbackContext)
context.job is the telegram.ext.Job instance. It can be used to access its
job.context or change it to a repeating job.
• when (int | float | datetime.timedelta | datetime.datetime |
datetime.time) – Time in or at which the job should run. This parameter will
be interpreted depending on its type.
– int or float will be interpreted as “seconds from now” in which the job should
run.
– datetime.timedelta will be interpreted as “time from now” in which the job
should run.
– datetime.datetime will be interpreted as a specific date and time at which
the job should run. If the timezone (datetime.tzinfo) is None, UTC will be
assumed.
– datetime.time will be interpreted as a specific time of day at which the job
should run. This could be either today or, if the time has already passed, tomorrow.
If the timezone (time.tzinfo) is None, UTC will be assumed.
If when is datetime.datetime or datetime.time type then when.tzinfo
will define Job.tzinfo. Otherwise UTC will be assumed.
• context (object, optional) – Additional data needed for the callback function.
Can be accessed through job.context in the callback. Defaults to None.
• name (str, optional) – The name of the new job. Defaults to callback.
__name__.
24 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
Returns The new Job instance that has been added to the job queue.
Return type telegram.ext.Job
run_repeating(callback, interval, first=None, context=None, name=None)
Creates a new Job that runs at specified intervals and adds it to the queue.
Parameters
• callback (callable) – The callback function that should be executed by the new
job. Callback signature for context based API:
def callback(CallbackContext)
context.job is the telegram.ext.Job instance. It can be used to access its
job.context or change it to a repeating job.
• interval (int | float | datetime.timedelta) – The interval in which the
job will run. If it is an int or a float, it will be interpreted as seconds.
• first (int | float | datetime.timedelta | datetime.datetime |
datetime.time, optional) – Time in or at which the job should run. This pa-
rameter will be interpreted depending on its type.
– int or float will be interpreted as “seconds from now” in which the job should
run.
– datetime.timedelta will be interpreted as “time from now” in which the job
should run.
– datetime.datetime will be interpreted as a specific date and time at which
the job should run. If the timezone (datetime.tzinfo) is None, UTC will be
assumed.
– datetime.time will be interpreted as a specific time of day at which the job
should run. This could be either today or, if the time has already passed, tomorrow.
If the timezone (time.tzinfo) is None, UTC will be assumed.
If first is datetime.datetime or datetime.time type then first.
tzinfo will define Job.tzinfo. Otherwise UTC will be assumed.
Defaults to interval
• context (object, optional) – Additional data needed for the callback function.
Can be accessed through job.context in the callback. Defaults to None.
• name (str, optional) – The name of the new job. Defaults to callback.
__name__.
Returns The new Job instance that has been added to the job queue.
Return type telegram.ext.Job
Note: interval is always respected “as-is”. That means that if DST changes during that interval, the
job might not run at the time one would expect. It is always recommended to pin servers to UTC time,
then time related behaviour can always be expected.
set_dispatcher(dispatcher)
Set the dispatcher to be used by this JobQueue. Use this instead of passing a telegram.Bot to the
JobQueue, which is deprecated.
Parameters dispatcher (telegram.ext.Dispatcher) – The dispatcher.
start()
Starts the job_queue thread.
stop()
Stops the thread.
tick()
Run all jobs that are due and re-enqueue them with their interval.
3.1.7 telegram.ext.MessageQueue
26 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
3.1.8 telegram.ext.DelayQueue
Parameters
• queue (Queue, optional) – Used to pass callbacks to thread. Creates Queue implicitly
if not provided.
• burst_limit (int, optional) – Number of maximum callbacks to process per time-
window defined by time_limit_ms. Defaults to 30.
• time_limit_ms (int, optional) – Defines width of time-window used when each
processing limit is calculated. Defaults to 1000.
• exc_route (callable, optional) – A callable, accepting 1 positional argument;
used to route exceptions from processor thread to main thread; is called on Exception
subclass exceptions. If not provided, exceptions are routed through dummy handler,
which re-raises them.
• autostart (bool, optional) – If True, processor is started immediately after object’s
creation; if False, should be started manually by start method. Defaults to True.
3.1.9 telegram.ext.CallbackContext
class telegram.ext.CallbackContext(dispatcher)
This is a context object passed to the callback called by telegram.ext.Handler or by the
telegram.ext.Dispatcher in an error handler added by telegram.ext.Dispatcher.
add_error_handler or to the callback of a telegram.ext.Job.
Note: telegram.ext.Dispatcher will create a single context for an entire update. This means that
if you got 2 handlers in different groups and they both get called, they will get passed the same Callback-
Context object (of course with proper attributes like .matches differing). This allows you to add custom
attributes in a lower handler group callback, and then subsequently access those attributes in a higher han-
dler group callback. Note that the attributes on CallbackContext might change in the future, so make sure
to use a fairly unique name for the attributes.
28 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
Warning: Do not combine custom attributes and @run_async. Due to how @run_async works, it will
almost certainly execute the callbacks for an update out of order, and the attributes that you think you
added will not be present.
bot_data
Optional. A dict that can be used to keep any data in. For each update it will be the same dict.
Type dict
chat_data
Optional. A dict that can be used to keep any data in. For each update from the same chat id it will be
the same dict.
Warning: When a group chat migrates to a supergroup, its chat id will change and the
chat_data needs to be transferred. For details see our wiki page.
Type dict
user_data
Optional. A dict that can be used to keep any data in. For each update from the same user it will be
the same dict.
Type dict
matches
Optional. If the associated update originated from a regex-supported handler or had a Filters.
regex, this will contain a list of match objects for every pattern where re.search(pattern,
string) returned a match. Note that filters short circuit, so combined regex filters will not always
be evaluated.
Type List[re match object]
args
Optional. Arguments passed to a command if the associated update is handled by
telegram.ext.CommandHandler, telegram.ext.PrefixHandler or telegram.
ext.StringCommandHandler. It contains a list of the words in the text after the command,
using any whitespace string as a delimiter.
Type List[str]
error
Optional. The Telegram error that was raised. Only present when passed to a error handler registered
with telegram.ext.Dispatcher.add_error_handler.
Type telegram.TelegramError
job
The job that that originated this callback. Only present when passed to the callback of telegram.
ext.Job.
Type telegram.ext.Job
bot
The bot associated with this context.
Type telegram.Bot
dispatcher
The dispatcher associated with this context.
Type telegram.ext.Dispatcher
job_queue
The JobQueue used by the telegram.ext.Dispatcher and (usually) the telegram.ext.
Updater associated with this context.
Type telegram.ext.JobQueue
match
The first match from matches. Useful if you are only filtering using a single regex filter. Returns
None if matches is empty.
Type Regex match type
update_queue
The Queue instance used by the telegram.ext.Dispatcher and (usually) the telegram.
ext.Updater associated with this context.
Type queue.Queue
3.1.10 telegram.ext.Defaults
Parameters
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram apps
to show bold, italic, fixed-width toxt or URLs in your bot’s message.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• disable_web_page_preview (bool, optional) – Disables link previews for links
in this message.
30 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
• timeout (int | float, optional) – If this value is specified, use it as the read timeout
from the server (instead of the one specified during creation of the connection pool).
• quote (bool, opitonal) – If set to True, the reply is sent as an actual reply to the
message. If reply_to_message_id is passed in kwargs, this parameter will be
ignored. Default: True in group chats and False in private chats.
3.1.11 Handlers
telegram.ext.Handler
Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See https://git.io/fxJuV for
more info.
Parameters
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• pass_update_queue (bool, optional) – If set to True, a keyword argument called
update_queue will be passed to the callback function. It will be the Queue instance
used by the telegram.ext.Updater and telegram.ext.Dispatcher that
contains new updates which can be used to insert updates. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_job_queue (bool, optional) – If set to True, a keyword argument called
job_queue will be passed to the callback function. It will be a telegram.ext.
JobQueue instance created by the telegram.ext.Updater which can be used to
schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.
• pass_user_data (bool, optional) – If set to True, a keyword argument called
user_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_chat_data (bool, optional) – If set to True, a keyword argument called
chat_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
check_update(update)
This method is called to determine if an update should be handled by this handler instance. It should
always be overridden.
Parameters update (str | telegram.Update) – The update to be tested.
Returns Either None or False if the update should not be handled. Otherwise an object
that will be passed to handle_update and collect_additional_context
when the update gets handled.
collect_additional_context(context, update, dispatcher, check_result)
Prepares additional arguments for the context. Override if needed.
Parameters
• context (telegram.ext.CallbackContext) – The context object.
• update (telegram.Update) – The update to gather chat/user id from.
• dispatcher (telegram.ext.Dispatcher) – The calling dispatcher.
• check_result – The result (return value) from check_update.
collect_optional_args(dispatcher, update=None, check_result=None)
Prepares the optional arguments. If the handler has additional optional args, it should subclass this
method, but remember to call this super method.
DEPRECATED: This method is being replaced by new context based callbacks. Please see https:
//git.io/fxJuV for more info.
Parameters
• dispatcher (telegram.ext.Dispatcher) – The dispatcher.
• update (telegram.Update) – The update to gather chat/user id from.
• check_result – The result from check_update
handle_update(update, dispatcher, check_result, context=None)
This method is called if it was determined that an update should indeed be handled by this instance.
Calls self.callback along with its respectful arguments. To work with the telegram.ext.
ConversationHandler, this method returns the value returned from self.callback. Note
that it can be overridden if needed by the subclassing handler.
Parameters
• update (str | telegram.Update) – The update to be handled.
• dispatcher (telegram.ext.Dispatcher) – The calling dispatcher.
• check_result – The result from check_update.
32 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
telegram.ext.CallbackQueryHandler
Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See https://git.io/fxJuV for
more info.
Parameters
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update) – Incoming telegram update.
Returns bool
collect_additional_context(context, update, dispatcher, check_result)
Prepares additional arguments for the context. Override if needed.
Parameters
• context (telegram.ext.CallbackContext) – The context object.
• update (telegram.Update) – The update to gather chat/user id from.
• dispatcher (telegram.ext.Dispatcher) – The calling dispatcher.
• check_result – The result (return value) from check_update.
collect_optional_args(dispatcher, update=None, check_result=None)
Prepares the optional arguments. If the handler has additional optional args, it should subclass this
method, but remember to call this super method.
DEPRECATED: This method is being replaced by new context based callbacks. Please see https:
//git.io/fxJuV for more info.
Parameters
34 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
telegram.ext.ChosenInlineResultHandler
Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See https://git.io/fxJuV for
more info.
Parameters
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• pass_update_queue (bool, optional) – If set to True, a keyword argument called
update_queue will be passed to the callback function. It will be the Queue instance
used by the telegram.ext.Updater and telegram.ext.Dispatcher that
contains new updates which can be used to insert updates. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update) – Incoming telegram update.
Returns bool
telegram.ext.ConversationHandler
36 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
entry_points
A list of Handler objects that can trigger the start of the conversation.
Type List[telegram.ext.Handler]
states
A dict that defines the different states of conversation a user can be in and one or more associated
Handler objects that should be used in that state.
Type Dict[object, List[telegram.ext.Handler]]
fallbacks
A list of handlers that might be used if the user is in a conversation, but every handler for their current
state returned False on check_update.
Type List[telegram.ext.Handler]
allow_reentry
Determines if a user can restart a conversation with an entry point.
Type bool
per_chat
If the conversationkey should contain the Chat’s ID.
Type bool
per_user
If the conversationkey should contain the User’s ID.
Type bool
per_message
If the conversationkey should contain the Message’s ID.
Type bool
conversation_timeout
Optional. When this handler is inactive more than this timeout (in seconds), it will be automatically
ended. If this value is 0 (default), there will be no timeout. When it’s triggered, the last received update
and the corresponding context will be handled by ALL the handler’s who’s check_update method
returns True that are in the state ConversationHandler.TIMEOUT.
Type float | datetime.timedelta
name
Optional. The name for this conversationhandler. Required for persistence
Type str
persistent
Optional. If the conversations dict for this handler should be saved. Name is required and persistence
has to be set in telegram.ext.Updater
Type bool
map_to_parent
Optional. A dict that can be used to instruct a nested conversationhandler to transition into a mapped
state on its parent conversationhandler in place of a specified nested state.
Type Dict[object, object]
Parameters
• entry_points (List[telegram.ext.Handler]) – A list of Handler objects
that can trigger the start of the conversation. The first handler which check_update
method returns True will be used. If all return False, the update is not handled.
END = -1
Used as a constant to return when a conversation is ended.
Type int
TIMEOUT = -2
Used as a constant to handle state when a conversation is timed out.
Type int
WAITING = -3
Used as a constant to handle state when a conversation is still waiting on the previous @run_sync
decorated running handler to finish.
Type int
check_update(update)
Determines whether an update should be handled by this conversationhandler, and if so in which state
the conversation currently is.
Parameters update (telegram.Update) – Incoming telegram update.
Returns bool
handle_update(update, dispatcher, check_result, context=None)
Send the update to the callback for the current state and Handler
38 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
Parameters
• check_result – The result from check_update. For this handler it’s a tuple of key,
handler, and the handler’s check result.
• update (telegram.Update) – Incoming telegram update.
• dispatcher (telegram.ext.Dispatcher) – Dispatcher that originated the
Update.
telegram.ext.CommandHandler
pass_chat_data
Determines whether chat_data will be passed to the callback function.
Type bool
Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See https://git.io/fxJuV for
more info.
Parameters
• command (str | List[str]) – The command or list of commands this handler should
listen for. Limitations are the same as described here https://core.telegram.org/bots#
commands
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• filters (telegram.ext.BaseFilter, optional) – A filter inheriting from
telegram.ext.filters.BaseFilter. Standard filters can be found in
telegram.ext.filters.Filters. Filters can be combined using bitwise op-
erators (& for and, | for or, ~ for not).
• allow_edited (bool, optional) – Determines whether the handler should also ac-
cept edited messages. Default is False. DEPRECATED: Edited is allowed by default.
To change this behavior use ~Filters.update.edited_message.
• pass_args (bool, optional) – Determines whether the handler should be passed the
arguments passed to the command as a keyword argument called args. It will contain
a list of strings, which is the text following the command split on single or consecutive
whitespace characters. Default is False DEPRECATED: Please switch to context
based callbacks.
• pass_update_queue (bool, optional) – If set to True, a keyword argument called
update_queue will be passed to the callback function. It will be the Queue instance
used by the telegram.ext.Updater and telegram.ext.Dispatcher that
contains new updates which can be used to insert updates. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_job_queue (bool, optional) – If set to True, a keyword argument called
job_queue will be passed to the callback function. It will be a telegram.ext.
JobQueue instance created by the telegram.ext.Updater which can be used to
schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.
• pass_user_data (bool, optional) – If set to True, a keyword argument called
user_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_chat_data (bool, optional) – If set to True, a keyword argument called
chat_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
Raises ValueError - when command is too long or has illegal chars.
40 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update) – Incoming telegram update.
Returns The list of args for the handler
Return type list
collect_additional_context(context, update, dispatcher, check_result)
Prepares additional arguments for the context. Override if needed.
Parameters
• context (telegram.ext.CallbackContext) – The context object.
• update (telegram.Update) – The update to gather chat/user id from.
• dispatcher (telegram.ext.Dispatcher) – The calling dispatcher.
• check_result – The result (return value) from check_update.
collect_optional_args(dispatcher, update=None, check_result=None)
Prepares the optional arguments. If the handler has additional optional args, it should subclass this
method, but remember to call this super method.
DEPRECATED: This method is being replaced by new context based callbacks. Please see https:
//git.io/fxJuV for more info.
Parameters
• dispatcher (telegram.ext.Dispatcher) – The dispatcher.
• update (telegram.Update) – The update to gather chat/user id from.
• check_result – The result from check_update
telegram.ext.InlineQueryHandler
Type bool
pass_groupdict
Determines whether groupdict. will be passed to the callback function.
Type bool
pass_user_data
Determines whether user_data will be passed to the callback function.
Type bool
pass_chat_data
Determines whether chat_data will be passed to the callback function.
Type bool
Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See https://git.io/fxJuV for
more info.
Parameters
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• pass_update_queue (bool, optional) – If set to True, a keyword argument called
update_queue will be passed to the callback function. It will be the Queue instance
used by the telegram.ext.Updater and telegram.ext.Dispatcher that
contains new updates which can be used to insert updates. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_job_queue (bool, optional) – If set to True, a keyword argument called
job_queue will be passed to the callback function. It will be a telegram.ext.
JobQueue instance created by the telegram.ext.Updater which can be used to
schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.
• pattern (str | Pattern, optional) – Regex pattern. If not None, re.match
is used on telegram.InlineQuery.query to determine if an update should be
handled by this handler.
• pass_groups (bool, optional) – If the callback should be passed the result of re.
match(pattern, data).groups() as a keyword argument called groups.
Default is False DEPRECATED: Please switch to context based callbacks.
• pass_groupdict (bool, optional) – If the callback should be passed the result
of re.match(pattern, data).groupdict() as a keyword argument called
groupdict. Default is False DEPRECATED: Please switch to context based call-
backs.
• pass_user_data (bool, optional) – If set to True, a keyword argument called
user_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
42 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update) – Incoming telegram update.
Returns bool
collect_additional_context(context, update, dispatcher, check_result)
Prepares additional arguments for the context. Override if needed.
Parameters
• context (telegram.ext.CallbackContext) – The context object.
• update (telegram.Update) – The update to gather chat/user id from.
• dispatcher (telegram.ext.Dispatcher) – The calling dispatcher.
• check_result – The result (return value) from check_update.
collect_optional_args(dispatcher, update=None, check_result=None)
Prepares the optional arguments. If the handler has additional optional args, it should subclass this
method, but remember to call this super method.
DEPRECATED: This method is being replaced by new context based callbacks. Please see https:
//git.io/fxJuV for more info.
Parameters
• dispatcher (telegram.ext.Dispatcher) – The dispatcher.
• update (telegram.Update) – The update to gather chat/user id from.
• check_result – The result from check_update
telegram.ext.MessageHandler
pass_user_data
Determines whether user_data will be passed to the callback function.
Type bool
pass_chat_data
Determines whether chat_data will be passed to the callback function.
Type bool
message_updates
Should “normal” message updates be handled? Default is None.
Type bool
channel_post_updates
Should channel posts updates be handled? Default is None.
Type bool
edited_updates
Should “edited” message updates be handled? Default is None.
Type bool
Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See https://git.io/fxJuV for
more info.
Parameters
• filters (telegram.ext.BaseFilter, optional) – A filter inheriting from
telegram.ext.filters.BaseFilter. Standard filters can be found in
telegram.ext.filters.Filters. Filters can be combined using bitwise op-
erators (& for and, | for or, ~ for not). Default is telegram.ext.filters.
Filters.update. This defaults to all message_type updates being: message,
edited_message, channel_post and edited_channel_post. If you don’t
want or need any of those pass ~Filters.update.* in the filter argument.
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• pass_update_queue (bool, optional) – If set to True, a keyword argument called
update_queue will be passed to the callback function. It will be the Queue instance
used by the telegram.ext.Updater and telegram.ext.Dispatcher that
contains new updates which can be used to insert updates. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_job_queue (bool, optional) – If set to True, a keyword argument called
job_queue will be passed to the callback function. It will be a telegram.ext.
JobQueue instance created by the telegram.ext.Updater which can be used to
schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.
44 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update) – Incoming telegram update.
Returns bool
collect_additional_context(context, update, dispatcher, check_result)
Prepares additional arguments for the context. Override if needed.
Parameters
• context (telegram.ext.CallbackContext) – The context object.
• update (telegram.Update) – The update to gather chat/user id from.
• dispatcher (telegram.ext.Dispatcher) – The calling dispatcher.
• check_result – The result (return value) from check_update.
telegram.ext.PollAnswerHandler
pass_chat_data
Determines whether chat_data will be passed to the callback function.
Type bool
Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See https://git.io/fxJuV for
more info.
Parameters
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• pass_update_queue (bool, optional) – If set to True, a keyword argument called
update_queue will be passed to the callback function. It will be the Queue instance
used by the telegram.ext.Updater and telegram.ext.Dispatcher that
contains new updates which can be used to insert updates. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_job_queue (bool, optional) – If set to True, a keyword argument called
job_queue will be passed to the callback function. It will be a telegram.ext.
JobQueue instance created by the telegram.ext.Updater which can be used to
schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.
• pass_user_data (bool, optional) – If set to True, a keyword argument called
user_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_chat_data (bool, optional) – If set to True, a keyword argument called
chat_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update) – Incoming telegram update.
Returns bool
telegram.ext.PollHandler
46 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
pass_update_queue
Determines whether update_queue will be passed to the callback function.
Type bool
pass_job_queue
Determines whether job_queue will be passed to the callback function.
Type bool
pass_user_data
Determines whether user_data will be passed to the callback function.
Type bool
pass_chat_data
Determines whether chat_data will be passed to the callback function.
Type bool
Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See https://git.io/fxJuV for
more info.
Parameters
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• pass_update_queue (bool, optional) – If set to True, a keyword argument called
update_queue will be passed to the callback function. It will be the Queue instance
used by the telegram.ext.Updater and telegram.ext.Dispatcher that
contains new updates which can be used to insert updates. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_job_queue (bool, optional) – If set to True, a keyword argument called
job_queue will be passed to the callback function. It will be a telegram.ext.
JobQueue instance created by the telegram.ext.Updater which can be used to
schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.
• pass_user_data (bool, optional) – If set to True, a keyword argument called
user_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_chat_data (bool, optional) – If set to True, a keyword argument called
chat_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update) – Incoming telegram update.
Returns bool
telegram.ext.PreCheckoutQueryHandler
Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See https://git.io/fxJuV for
more info.
Parameters
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• pass_update_queue (bool, optional) – If set to True, a keyword argument
called update_queue will be passed to the callback function. It will be the Queue
DEPRECATED: Please switch to context based callbacks. instance used by the
telegram.ext.Updater and telegram.ext.Dispatcher that contains new
updates which can be used to insert updates. Default is False.
• pass_job_queue (bool, optional) – If set to True, a keyword argument called
job_queue will be passed to the callback function. It will be a telegram.ext.
JobQueue instance created by the telegram.ext.Updater which can be used to
schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.
48 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update) – Incoming telegram update.
Returns bool
telegram.ext.PrefixHandler
By default the handler listens to messages as well as edited messages. To change this behavior use ~‘‘Fil-
ters.update.edited_message‘‘.
prefix
The prefix(es) that will precede command.
Type str | List[str]
command
The command or list of commands this handler should listen for.
Type str | List[str]
callback
The callback function for this handler.
Type callable
filters
Optional. Only allow updates with these Filters.
Type telegram.ext.BaseFilter
pass_args
Determines whether the handler should be passed args.
Type bool
pass_update_queue
Determines whether update_queue will be passed to the callback function.
Type bool
pass_job_queue
Determines whether job_queue will be passed to the callback function.
Type bool
pass_user_data
Determines whether user_data will be passed to the callback function.
Type bool
pass_chat_data
Determines whether chat_data will be passed to the callback function.
Type bool
Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See https://git.io/fxJuV for
more info.
Parameters
• prefix (str | List[str]) – The prefix(es) that will precede command.
• command (str | List[str]) – The command or list of commands this handler should
listen for.
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• filters (telegram.ext.BaseFilter, optional) – A filter inheriting from
telegram.ext.filters.BaseFilter. Standard filters can be found in
telegram.ext.filters.Filters. Filters can be combined using bitwise op-
erators (& for and, | for or, ~ for not).
• pass_args (bool, optional) – Determines whether the handler should be passed the
arguments passed to the command as a keyword argument called args. It will contain
a list of strings, which is the text following the command split on single or consecutive
whitespace characters. Default is False DEPRECATED: Please switch to context
based callbacks.
• pass_update_queue (bool, optional) – If set to True, a keyword argument called
update_queue will be passed to the callback function. It will be the Queue instance
used by the telegram.ext.Updater and telegram.ext.Dispatcher that
50 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
contains new updates which can be used to insert updates. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_job_queue (bool, optional) – If set to True, a keyword argument called
job_queue will be passed to the callback function. It will be a telegram.ext.
JobQueue instance created by the telegram.ext.Updater which can be used to
schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.
• pass_user_data (bool, optional) – If set to True, a keyword argument called
user_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_chat_data (bool, optional) – If set to True, a keyword argument called
chat_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update) – Incoming telegram update.
Returns The list of args for the handler
Return type list
collect_additional_context(context, update, dispatcher, check_result)
Prepares additional arguments for the context. Override if needed.
Parameters
• context (telegram.ext.CallbackContext) – The context object.
• update (telegram.Update) – The update to gather chat/user id from.
• dispatcher (telegram.ext.Dispatcher) – The calling dispatcher.
• check_result – The result (return value) from check_update.
telegram.ext.RegexHandler
pass_groupdict
Determines whether groupdict. will be passed to the callback function.
Type bool
pass_update_queue
Determines whether update_queue will be passed to the callback function.
Type bool
pass_job_queue
Determines whether job_queue will be passed to the callback function.
Type bool
pass_user_data
Determines whether user_data will be passed to the callback function.
Type bool
pass_chat_data
Determines whether chat_data will be passed to the callback function.
Type bool
Note: This handler is being deprecated. For the same usecase use: MessageHandler(Filters.
regex(r'pattern'), callback)
Parameters
• pattern (str | Pattern) – The regex pattern.
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• pass_groups (bool, optional) – If the callback should be passed the result of re.
match(pattern, data).groups() as a keyword argument called groups.
Default is False
• pass_groupdict (bool, optional) – If the callback should be passed the result
of re.match(pattern, data).groupdict() as a keyword argument called
groupdict. Default is False
• pass_update_queue (bool, optional) – If set to True, a keyword argument called
update_queue will be passed to the callback function. It will be the Queue instance
used by the telegram.ext.Updater and telegram.ext.Dispatcher that
contains new updates which can be used to insert updates. Default is False.
• pass_job_queue (bool, optional) – If set to True, a keyword argument called
job_queue will be passed to the callback function. It will be a telegram.ext.
JobQueue instance created by the telegram.ext.Updater which can be used to
schedule new jobs. Default is False.
• pass_user_data (bool, optional) – If set to True, a keyword argument called
user_data will be passed to the callback function. Default is False.
• pass_chat_data (bool, optional) – If set to True, a keyword argument called
chat_data will be passed to the callback function. Default is False.
• message_updates (bool, optional) – Should “normal” message updates be han-
dled? Default is True.
52 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
telegram.ext.ShippingQueryHandler
Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See https://git.io/fxJuV for
more info.
Parameters
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• pass_update_queue (bool, optional) – If set to True, a keyword argument called
update_queue will be passed to the callback function. It will be the Queue instance
used by the telegram.ext.Updater and telegram.ext.Dispatcher that
contains new updates which can be used to insert updates. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_job_queue (bool, optional) – If set to True, a keyword argument called
job_queue will be passed to the callback function. It will be a telegram.ext.
JobQueue instance created by the telegram.ext.Updater which can be used to
schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.
• pass_user_data (bool, optional) – If set to True, a keyword argument called
user_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_chat_data (bool, optional) – If set to True, a keyword argument called
chat_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update) – Incoming telegram update.
Returns bool
telegram.ext.StringCommandHandler
Note: This handler is not used to handle Telegram telegram.Update, but strings manually put in the
queue. For example to send messages with the bot using command line or API.
command
The command this handler should listen for.
Type str
callback
The callback function for this handler.
Type callable
pass_args
Determines whether the handler should be passed args.
Type bool
54 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
pass_update_queue
Determines whether update_queue will be passed to the callback function.
Type bool
pass_job_queue
Determines whether job_queue will be passed to the callback function.
Type bool
Parameters
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• pass_args (bool, optional) – Determines whether the handler should be passed the
arguments passed to the command as a keyword argument called args. It will contain
a list of strings, which is the text following the command split on single or consecutive
whitespace characters. Default is False DEPRECATED: Please switch to context
based callbacks.
• pass_update_queue (bool, optional) – If set to True, a keyword argument called
update_queue will be passed to the callback function. It will be the Queue instance
used by the telegram.ext.Updater and telegram.ext.Dispatcher that
contains new updates which can be used to insert updates. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_job_queue (bool, optional) – If set to True, a keyword argument
called job_queue will be passed to the callback function. It will be a
class:telegram.ext.JobQueue instance created by the telegram.ext.Updater
which can be used to schedule new jobs. Default is False. DEPRECATED: Please
switch to context based callbacks.
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (str) – An incoming command.
Returns bool
collect_additional_context(context, update, dispatcher, check_result)
Prepares additional arguments for the context. Override if needed.
Parameters
• context (telegram.ext.CallbackContext) – The context object.
• update (telegram.Update) – The update to gather chat/user id from.
• dispatcher (telegram.ext.Dispatcher) – The calling dispatcher.
• check_result – The result (return value) from check_update.
collect_optional_args(dispatcher, update=None, check_result=None)
Prepares the optional arguments. If the handler has additional optional args, it should subclass this
method, but remember to call this super method.
DEPRECATED: This method is being replaced by new context based callbacks. Please see https:
//git.io/fxJuV for more info.
Parameters
• dispatcher (telegram.ext.Dispatcher) – The dispatcher.
telegram.ext.StringRegexHandler
Note: This handler is not used to handle Telegram telegram.Update, but strings manually put in the
queue. For example to send messages with the bot using command line or API.
pattern
The regex pattern.
Type str | Pattern
callback
The callback function for this handler.
Type callable
pass_groups
Determines whether groups will be passed to the callback function.
Type bool
pass_groupdict
Determines whether groupdict. will be passed to the callback function.
Type bool
pass_update_queue
Determines whether update_queue will be passed to the callback function.
Type bool
pass_job_queue
Determines whether job_queue will be passed to the callback function.
Type bool
Parameters
• pattern (str | Pattern) – The regex pattern.
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• pass_groups (bool, optional) – If the callback should be passed the result of re.
match(pattern, data).groups() as a keyword argument called groups.
Default is False DEPRECATED: Please switch to context based callbacks.
56 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (str) – An incoming command.
Returns bool
collect_additional_context(context, update, dispatcher, check_result)
Prepares additional arguments for the context. Override if needed.
Parameters
• context (telegram.ext.CallbackContext) – The context object.
• update (telegram.Update) – The update to gather chat/user id from.
• dispatcher (telegram.ext.Dispatcher) – The calling dispatcher.
• check_result – The result (return value) from check_update.
collect_optional_args(dispatcher, update=None, check_result=None)
Prepares the optional arguments. If the handler has additional optional args, it should subclass this
method, but remember to call this super method.
DEPRECATED: This method is being replaced by new context based callbacks. Please see https:
//git.io/fxJuV for more info.
Parameters
• dispatcher (telegram.ext.Dispatcher) – The dispatcher.
• update (telegram.Update) – The update to gather chat/user id from.
• check_result – The result from check_update
telegram.ext.TypeHandler
Type callable
strict
Use type instead of isinstance. Default is False.
Type bool
pass_update_queue
Determines whether update_queue will be passed to the callback function.
Type bool
pass_job_queue
Determines whether job_queue will be passed to the callback function.
Type bool
Parameters
• type (type) – The type of updates this handler should process, as determined by
isinstance
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• strict (bool, optional) – Use type instead of isinstance. Default is False
• pass_update_queue (bool, optional) – If set to True, a keyword argument called
update_queue will be passed to the callback function. It will be the Queue instance
used by the telegram.ext.Updater and telegram.ext.Dispatcher that
contains new updates which can be used to insert updates. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_job_queue (bool, optional) – If set to True, a keyword argument called
job_queue will be passed to the callback function. It will be a telegram.ext.
JobQueue instance created by the telegram.ext.Updater which can be used to
schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update) – Incoming telegram update.
Returns bool
3.1.12 Persistence
telegram.ext.BasePersistence
58 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
Parameters
• store_user_data (bool, optional) – Whether user_data should be saved by this
persistence class. Default is True.
• store_chat_data (bool, optional) – Whether chat_data should be saved by this
persistence class. Default is True .
• store_bot_data (bool, optional) – Whether bot_data should be saved by this per-
sistence class. Default is True .
flush()
Will be called by telegram.ext.Updater upon receiving a stop signal. Gives the persistence a
chance to finish up saving or close a database connection gracefully. If this is not of any importance
just pass will be sufficient.
get_bot_data()
“Will be called by telegram.ext.Dispatcher upon creation with a persistence object. It should
return the bot_data if stored, or an empty dict.
Returns The restored bot data.
Return type defaultdict
get_chat_data()
“Will be called by telegram.ext.Dispatcher upon creation with a persistence object. It should
return the chat_data if stored, or an empty defaultdict(dict).
Returns The restored chat data.
Return type defaultdict
get_conversations(name)
“Will be called by telegram.ext.Dispatcher when a telegram.ext.
ConversationHandler is added if telegram.ext.ConversationHandler.
persistent is True. It should return the conversations for the handler with name or an
empty dict
Parameters name (str) – The handlers name.
telegram.ext.PicklePersistence
60 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
store_bot_data
Optional. Whether bot_data should be saved by this persistence class.
Type bool
single_file
Optional. When False will store 3 sperate files of filename_user_data, filename_chat_data and
filename_conversations. Default is True.
Type bool
on_flush
When True will only save to file when flush() is called and keep data in memory until that hap-
pens. When False will store data on any transaction and on call fo flush(). Default is False.
Type bool, optional
Parameters
• filename (str) – The filename for storing the pickle files. When single_file is
false this will be used as a prefix.
• store_user_data (bool, optional) – Whether user_data should be saved by this
persistence class. Default is True.
• store_chat_data (bool, optional) – Whether user_data should be saved by this
persistence class. Default is True.
• store_bot_data (bool, optional) – Whether bot_data should be saved by this per-
sistence class. Default is True .
• single_file (bool, optional) – When False will store 3 sperate files of file-
name_user_data, filename_chat_data and filename_conversations. Default is True.
• on_flush (bool, optional) – When True will only save to file when flush() is
called and keep data in memory until that happens. When False will store data on any
transaction and on call fo flush(). Default is False.
flush()
Will save all data in memory to pickle file(s).
get_bot_data()
Returns the bot_data from the pickle file if it exsists or an empty dict.
Returns The restored bot data.
Return type defaultdict
get_chat_data()
Returns the chat_data from the pickle file if it exsists or an empty defaultdict.
Returns The restored chat data.
Return type defaultdict
get_conversations(name)
Returns the conversations from the pickle file if it exsists or an empty defaultdict.
Parameters name (str) – The handlers name.
Returns The restored conversations for the handler.
Return type dict
get_user_data()
Returns the user_data from the pickle file if it exsists or an empty defaultdict.
Returns The restored user data.
Return type defaultdict
update_bot_data(data)
Will update the bot_data (if changed) and depending on on_flush save the pickle file.
Parameters data (dict) – The telegram.ext.dispatcher.bot_data.
update_chat_data(chat_id, data)
Will update the chat_data (if changed) and depending on on_flush save the pickle file.
Parameters
• chat_id (int) – The chat the data might have been changed for.
• data (dict) – The telegram.ext.dispatcher.chat_data [chat_id].
update_conversation(name, key, new_state)
Will update the conversations for the given handler and depending on on_flush save the pickle file.
Parameters
• name (str) – The handlers name.
• key (tuple) – The key the state is changed for.
• new_state (tuple | any) – The new state for the given key.
update_user_data(user_id, data)
Will update the user_data (if changed) and depending on on_flush save the pickle file.
Parameters
• user_id (int) – The user the data might have been changed for.
• data (dict) – The telegram.ext.dispatcher.user_data [user_id].
telegram.ext.DictPersistence
Parameters
• store_user_data (bool, optional) – Whether user_data should be saved by this
persistence class. Default is True.
• store_chat_data (bool, optional) – Whether user_data should be saved by this
persistence class. Default is True.
• store_bot_data (bool, optional) – Whether bot_data should be saved by this per-
sistence class. Default is True .
62 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
bot_data
The bot_data as a dict
Type dict
bot_data_json
The bot_data serialized as a JSON-string.
Type str
chat_data
The chat_data as a dict
Type dict
chat_data_json
The chat_data serialized as a JSON-string.
Type str
conversations
The conversations as a dict
Type dict
conversations_json
The conversations serialized as a JSON-string.
Type str
get_bot_data()
Returns the bot_data created from the bot_data_json or an empty dict.
Returns The restored user data.
Return type defaultdict
get_chat_data()
Returns the chat_data created from the chat_data_json or an empty defaultdict.
Returns The restored user data.
Return type defaultdict
get_conversations(name)
Returns the conversations created from the conversations_json or an empty defaultdict.
Returns The restored user data.
Return type defaultdict
get_user_data()
Returns the user_data created from the user_data_json or an empty defaultdict.
Returns The restored user data.
Return type defaultdict
update_bot_data(data)
Will update the bot_data (if changed).
3.2.1 telegram.Animation
64 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
height
Video height as defined by sender.
Type int
duration
Duration of the video in seconds as defined by sender.
Type int
thumb
Optional. Animation thumbnail as defined by sender.
Type telegram.PhotoSize
file_name
Optional. Original animation filename as defined by sender.
Type str
mime_type
Optional. MIME type of the file as defined by sender.
Type str
file_size
Optional. File size.
Type int
bot
Optional. The Bot to use for instance methods.
Type telegram.Bot
Parameters
• file_id (str) – Identifier for this file, which can be used to download or reuse the
file.
• file_unique_id (str) – Unique and the same over time and for different bots file
identifier.
• width (int) – Video width as defined by sender.
• height (int) – Video height as defined by sender.
• duration (int) – Duration of the video in seconds as defined by sender.
• thumb (telegram.PhotoSize, optional) – Animation thumbnail as defined by
sender.
• file_name (str, optional) – Original animation filename as defined by sender.
• mime_type (str, optional) – MIME type of the file as defined by sender.
• file_size (int, optional) – File size.
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.
get_file(timeout=None, **kwargs)
Convenience wrapper over telegram.Bot.get_file
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns telegram.File
Raises telegram.TelegramError
3.2.2 telegram.Audio
Parameters
• file_id (str) – Identifier for this file, which can be used to download or reuse the
file.
• file_unique_id (str) – Unique and the same over time and for different bots file
identifier.
• duration (int) – Duration of the audio in seconds as defined by sender.
66 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
get_file(timeout=None, **kwargs)
Convenience wrapper over telegram.Bot.get_file
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns telegram.File
Raises telegram.TelegramError
3.2.3 telegram.Bot
Warning: As of API 4.7 png_sticker is an optional argument and therefore the order of the
arguments had to be changed. Use keyword arguments to make sure that the arguments are passed
correctly.
Note: The png_sticker and tgs_sticker argument can be either a file_id, an URL or a file from disk
open(filename, 'rb')
Parameters
• user_id (int) – User identifier of created sticker set owner.
• name (str) – Sticker set name.
• png_sticker (str | filelike object, optional) – 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 | filelike object, optional) – TGS animation with the sticker,
uploaded using multipart/form-data. See https://core.telegram.org/animated_stickers#
technical-requirements for technical requirements
• emojis (str) – One or more emoji corresponding to the sticker.
• mask_position (telegram.MaskPosition, optional) – Position where the
mask should be placed on faces.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, True is returned.
Return type bool
Raises telegram.TelegramError
68 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
the user can be redirected to the specified Game URL. For this option to work, you must first cre-
ate a game for your bot via BotFather and accept the terms. Otherwise, you may use links like
t.me/your_bot?start=XXXX that open your bot with a parameter.
Parameters
• callback_query_id (str) – Unique identifier for the query to be answered.
• text (str, optional) – Text of the notification. If not specified, nothing will be
shown to the user, 0-200 characters.
• show_alert (bool, optional) – 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, optional) – 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. Otherwise, you may use links like t.me/your_bot?start=XXXX that open
your bot with a parameter.
• cache_time (int, optional) – The maximum amount of time in seconds that the
result of the callback query may be cached client-side. Defaults to 0.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns bool On success, True is returned.
Raises telegram.TelegramError
answer_inline_query(inline_query_id, results, cache_time=300,
is_personal=None, next_offset=None, switch_pm_text=None,
switch_pm_parameter=None, timeout=None, **kwargs)
Use this method to send answers to an inline query. No more than 50 results per query are allowed.
Parameters
• inline_query_id (str) – Unique identifier for the answered query.
• results (List[telegram.InlineQueryResult) – A list of results for the in-
line query.
• cache_time (int, optional) – The maximum amount of time in seconds that the
result of the inline query may be cached on the server. Defaults to 300.
• is_personal (bool, optional) – Pass True, if results may be cached on the server
side only for the user that sent the query. By default, results may be returned to any
user who sends the same query.
• next_offset (str, optional) – Pass the offset that a client should send in the next
query with the same text to receive more results. Pass an empty string if there are no
more results or if you don’t support pagination. Offset length can’t exceed 64 bytes.
• switch_pm_text (str, optional) – If passed, clients will display a button with
specified text that switches the user to a private chat with the bot and sends the bot a
start message with the parameter switch_pm_parameter.
• switch_pm_parameter (str, optional) – 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.
• timeout (int | float, optional) – If this value is specified, use it as he read timeout
from the server (instead of the one specified during creation of the connection pool).
• **kwargs (dict) – Arbitrary keyword arguments.
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.
Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
Parameters
• pre_checkout_query_id (str) – Unique identifier for the query to be an-
swered.
• 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, optional) – 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.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, True is returned.
Return type bool
Raises telegram.TelegramError
70 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
Warning: As of API 4.7 png_sticker is an optional argument and therefore the order of the
arguments had to be changed. Use keyword arguments to make sure that the arguments are passed
correctly.
Note: The png_sticker and tgs_sticker argument can be either a file_id, an URL or a file from disk
open(filename, 'rb')
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.
• png_sticker (str | filelike object, optional) – 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 | filelike object, optional) – TGS animation with the sticker,
uploaded using multipart/form-data. See https://core.telegram.org/animated_stickers#
technical-requirements for technical requirements
• emojis (str) – One or more emoji corresponding to the sticker.
• contains_masks (bool, optional) – Pass True, if a set of mask stickers should be
created.
• mask_position (telegram.MaskPosition, optional) – Position where the
mask should be placed on faces.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, True is returned.
Return type bool
Raises telegram.TelegramError
72 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
in the chat for this to work and must have the appropriate admin rights. Use the field telegram.
Chat.can_set_sticker_set optionally returned in get_chat requests to check if the bot can
use this method.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
supergroup (in the format @supergroupusername).
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, True is returned.
Return type bool
delete_message(chat_id, message_id, timeout=None, **kwargs)
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.
Parameters
• chat_id (int | 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 | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, True is returned.
Return type bool
Raises telegram.TelegramError
Raises telegram.TelegramError
delete_webhook(timeout=None, **kwargs)
Use this method to remove webhook integration if you decide to switch back to getUpdates. Requires
no parameters.
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns bool On success, True is returned.
Raises telegram.TelegramError
editMessageCaption(chat_id=None, message_id=None, inline_message_id=None, cap-
tion=None, reply_markup=None, timeout=None, parse_mode=None,
**kwargs)
Alias for edit_message_caption
editMessageLiveLocation(chat_id=None, message_id=None, inline_message_id=None,
latitude=None, longitude=None, location=None, re-
ply_markup=None, timeout=None, **kwargs)
Alias for edit_message_live_location
editMessageMedia(chat_id=None, message_id=None, inline_message_id=None, media=None,
reply_markup=None, timeout=None, **kwargs)
Alias for edit_message_media
editMessageReplyMarkup(chat_id=None, message_id=None, inline_message_id=None, re-
ply_markup=None, timeout=None, **kwargs)
Alias for edit_message_reply_markup
editMessageText(text, chat_id=None, message_id=None, inline_message_id=None,
parse_mode=None, disable_web_page_preview=None, reply_markup=None,
timeout=None, **kwargs)
Alias for edit_message_text
edit_message_caption(chat_id=None, message_id=None, inline_message_id=None, cap-
tion=None, reply_markup=None, timeout=None, parse_mode=None,
**kwargs)
Use this method to edit captions of messages sent by the bot or via the bot (for inline bots).
Parameters
• chat_id (int | str, optional) – 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, optional) – Required if inline_message_id is not specified. Iden-
tifier of the message to edit.
• inline_message_id (str, optional) – Required if chat_id and message_id are
not specified. Identifier of the inline message.
• caption (str, optional) – New caption of the message, 0-1024 characters after
entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See
the constants in telegram.ParseMode for the available modes.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – A JSON-
serialized object for an inline keyboard.
74 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, if edited message is sent by the bot, the edited Message is returned,
otherwise True is returned.
Return type telegram.Message
Raises telegram.TelegramError
edit_message_live_location(chat_id=None, message_id=None, in-
line_message_id=None, latitude=None, longitude=None,
location=None, reply_markup=None, timeout=None,
**kwargs)
Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A
location can be edited until its live_period expires or editing is explicitly disabled by a call to
stop_message_live_location.
Parameters
• chat_id (int | str, optional) – 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, optional) – Required if inline_message_id is not specified. Iden-
tifier of the message to edit.
• inline_message_id (str, optional) – Required if chat_id and message_id are
not specified. Identifier of the inline message.
• latitude (float, optional) – Latitude of location.
• longitude (float, optional) – Longitude of location.
• location (telegram.Location, optional) – The location to send.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – A JSON-
serialized object for a new inline keyboard.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
Returns On success, if edited message is sent by the bot, the edited Message is returned,
otherwise True is returned.
Return type telegram.Message
76 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• from_chat_id (int | str) – Unique identifier for the chat where the original
message was sent (or channel username in the format @channelusername).
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• message_id (int) – Message identifier in the chat specified in from_chat_id.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type telegram.Message
Raises telegram.TelegramError
getChat(chat_id, timeout=None, **kwargs)
Alias for get_chat
getChatAdministrators(chat_id, timeout=None, **kwargs)
Alias for get_chat_administrators
getChatMember(chat_id, user_id, timeout=None, **kwargs)
Alias for get_chat_member
getChatMembersCount(chat_id, timeout=None, **kwargs)
Alias for get_chat_members_count
getFile(file_id, timeout=None, **kwargs)
Alias for get_file
getGameHighScores(user_id, chat_id=None, message_id=None, inline_message_id=None,
timeout=None, **kwargs)
Alias for get_game_high_scores
getMe(timeout=None, **kwargs)
Alias for get_me
getMyCommands(timeout=None, **kwargs)
Alias for get_my_commands
getStickerSet(name, timeout=None, **kwargs)
Alias for get_sticker_set
getUpdates(offset=None, limit=100, timeout=0, read_latency=2.0, allowed_updates=None,
**kwargs)
Alias for get_updates
getUserProfilePhotos(user_id, offset=None, limit=100, timeout=None, **kwargs)
Alias for get_user_profile_photos
getWebhookInfo(timeout=None, **kwargs)
Alias for get_webhook_info
get_chat(chat_id, timeout=None, **kwargs)
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.).
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
78 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns telegram.Chat
Raises telegram.TelegramError
get_chat_administrators(chat_id, timeout=None, **kwargs)
Use this method to get a list of administrators in a chat.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, returns a list of ChatMember objects that contains information about
all chat administrators except other bots. If the chat is a group or a supergroup and no
administrators were appointed, only the creator will be returned.
Return type List[telegram.ChatMember]
Raises telegram.TelegramError
get_chat_member(chat_id, user_id, timeout=None, **kwargs)
Use this method to get information about a member of a chat.
Parameters
• chat_id (int | 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.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns telegram.ChatMember
Raises telegram.TelegramError
get_chat_members_count(chat_id, timeout=None, **kwargs)
Use this method to get the number of members in a chat.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns Number of members in the chat.
Return type int
Raises telegram.TelegramError
Note: This function may not preserve the original file name and MIME type. You should save the
file’s MIME type and name (if available) when the File object is received.
Parameters
• file_id (str | telegram.Animation | telegram.Audio | telegram.
ChatPhoto | telegram.Document | telegram.PhotoSize | telegram.
Sticker | telegram.Video | telegram.VideoNote | telegram.Voice)
– Either the file identifier or an object that has a file_id attribute to get file information
about.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns telegram.File
Raises telegram.TelegramError
80 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
Raises telegram.TelegramError
get_my_commands(timeout=None, **kwargs)
Use this method to get the current list of the bot’s commands.
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the commands set for the bot
Return type List[telegram.BotCommand]
Raises telegram.TelegramError
get_sticker_set(name, timeout=None, **kwargs)
Use this method to get a sticker set.
Parameters
• name (str) – Name of the sticker set.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns telegram.StickerSet
Raises telegram.TelegramError
get_updates(offset=None, limit=100, timeout=0, read_latency=2.0, allowed_updates=None,
**kwargs)
Use this method to receive incoming updates using long polling.
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 be-
tween 1-100 are accepted. Defaults to 100.
• timeout (int, optional) – Timeout in seconds for long polling. Defaults to 0, i.e.
usual short polling. Should be positive, short polling should be used for testing pur-
poses only.
• allowed_updates (List[str]), optional) – A JSON-serialized list the types
of updates you want your bot to receive. For example, specify [“message”,
“edited_channel_post”, “callback_query”] to only receive updates of these types. See
telegram.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. 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.
• **kwargs (dict) – Arbitrary keyword arguments.
Note:
Returns List[telegram.Update]
Raises telegram.TelegramError
82 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• until_date (int | datetime.datetime, optional) – 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.
• **kwargs (dict) – Arbitrary keyword arguments.
Returns bool On success, True is returned.
Raises telegram.TelegramError
last_name
Optional. Bot’s last name.
Type str
leaveChat(chat_id, timeout=None, **kwargs)
Alias for leave_chat
leave_chat(chat_id, timeout=None, **kwargs)
Use this method for your bot to leave a group, supergroup or channel.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns bool On success, True is returned.
Raises telegram.TelegramError
link
Convenience property. Returns the t.me link of the bot.
Type str
name
Bot’s @username.
Type str
pinChatMessage(chat_id, message_id, disable_notification=None, timeout=None, **kwargs)
Alias for pin_chat_message
pin_chat_message(chat_id, message_id, disable_notification=None, timeout=None,
**kwargs)
Use this method to pin a message in a group, a supergroup, or a channel. The bot must be an adminis-
trator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup
or ‘can_edit_messages’ admin right in the channel.
Parameters
• chat_id (int | 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, optional) – Pass True, if it is not necessary to
send a notification to all group members about the new pinned message. Notifications
are always disabled in channels.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments
Returns On success, True is returned.
Return type bool
Raises telegram.TelegramError
promoteChatMember(chat_id, user_id, can_change_info=None, can_post_messages=None,
can_edit_messages=None, can_delete_messages=None,
can_invite_users=None, can_restrict_members=None,
can_pin_messages=None, can_promote_members=None, timeout=None,
**kwargs)
Alias for promote_chat_member
promote_chat_member(chat_id, user_id, can_change_info=None, can_post_messages=None,
can_edit_messages=None, can_delete_messages=None,
can_invite_users=None, can_restrict_members=None,
can_pin_messages=None, can_promote_members=None, time-
out=None, **kwargs)
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.
Parameters
• chat_id (int | 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.
• can_change_info (bool, optional) – Pass True, if the administrator can change
chat title, photo and other settings.
• can_post_messages (bool, optional) – Pass True, if the administrator can create
channel posts, channels only.
• can_edit_messages (bool, optional) – Pass True, if the administrator can edit
messages of other users, channels only.
• can_delete_messages (bool, optional) – Pass True, if the administrator can
delete messages of other users.
• can_invite_users (bool, optional) – Pass True, if the administrator can invite
new users to the chat.
• can_restrict_members (bool, optional) – Pass True, if the administrator can
restrict, ban or unban chat members.
• can_pin_messages (bool, optional) – Pass True, if the administrator can pin
messages, supergroups only.
• can_promote_members (bool, optional) – 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).
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments
Returns On success, True is returned.
84 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
Note: Since Bot API 4.4, restrict_chat_member takes the new user permissions in a single
argument of type telegram.ChatPermissions. The old way of passing parameters will not
keep working forever.
Parameters
• chat_id (int | 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.
• until_date (int | datetime.datetime, optional) – 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.
• permissions (telegram.ChatPermissions) – New user permissions.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments
Returns On success, True is returned.
Return type bool
Raises telegram.TelegramError
86 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
Note: The audio argument can be either a file_id, an URL or a file from disk open(filename,
'rb')
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• audio (str | filelike object | telegram.Audio) – 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. Lastly you can pass an existing telegram.
Audio object to send.
• caption (str, optional) – Audio caption, 0-1024 characters after entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See
the constants in telegram.ParseMode for the available modes.
• duration (int, optional) – Duration of sent audio in seconds.
• performer (str, optional) – Performer.
• title (str, optional) – Track name.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup (telegram.ReplyMarkup, optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• thumb (filelike object, optional) – Thumbnail of the file sent; can be ignored if thumb-
nail 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.
• timeout (int | float, optional) – Send file timeout (default: 20 seconds).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type telegram.Message
Raises telegram.TelegramError
88 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
Note: You can either supply contact or phone_number and first_name with optionally
last_name and optionally vcard.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• phone_number (str, optional) – Contact’s phone number.
• first_name (str, optional) – Contact’s first name.
• last_name (str, optional) – Contact’s last name.
• vcard (str, optional) – Additional data about the contact in the form of a vCard,
0-2048 bytes.
• contact (telegram.Contact, optional) – The contact to send.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup (telegram.ReplyMarkup, optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type telegram.Message
Raises telegram.TelegramError
Parameters
• chat_id (int | str) – Unique identifier for the target private chat.
• emoji (str, optional) – Emoji on which the dice throw animation is based. Cur-
rently, must be one of “”, “” or “”. Dice can have values 1-6 for “” and “”, and values
1-5 for “” . Defaults to “”
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup (telegram.ReplyMarkup, optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type telegram.Message
Raises telegram.TelegramError
send_document(chat_id, document, filename=None, caption=None, disable_notification=False,
reply_to_message_id=None, reply_markup=None, timeout=20,
parse_mode=None, thumb=None, **kwargs)
Use this method to send general files.
Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the
future.
Note: The document argument can be either a file_id, an URL or a file from disk open(filename,
'rb')
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• document (str | filelike object | telegram.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. Lastly you can pass an existing telegram.
Document object to send.
• filename (str, optional) – File name that shows in telegram message (it is useful
when you send file generated by temp module, for example). Undocumented.
• caption (str, optional) – Document caption (may also be used when resending
documents by file_id), 0-1024 characters after entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See
the constants in telegram.ParseMode for the available modes.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
90 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
92 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• latitude (float, optional) – Latitude of location.
• longitude (float, optional) – Longitude of location.
• location (telegram.Location, optional) – The location to send.
• live_period (int, optional) – Period in seconds for which the location will be
updated, should be between 60 and 86400.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup (telegram.ReplyMarkup, optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type telegram.Message
Raises telegram.TelegramError
Note: The photo argument can be either a file_id, an URL or a file from disk open(filename,
'rb')
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• photo (str | filelike object | telegram.PhotoSize) – 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
94 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
a new photo using multipart/form-data. Lastly you can pass an existing telegram.
PhotoSize object to send.
• caption (str, optional) – Photo caption (may also be used when resending photos
by file_id), 0-1024 characters after entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See
the constants in telegram.ParseMode for the available modes.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup (telegram.ReplyMarkup, optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – Send file timeout (default: 20 seconds).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type telegram.Message
Raises telegram.TelegramError
Note: The sticker argument can be either a file_id, an URL or a file from disk open(filename,
'rb')
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• sticker (str | filelike object telegram.Sticker) – 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. Lastly you can pass an existing telegram.
Sticker object to send.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup (telegram.ReplyMarkup, optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – Send file timeout (default: 20 seconds).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type telegram.Message
Raises telegram.TelegramError
96 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
Note: You can either supply venue, or latitude, longitude, title and address and
optionally foursquare_id and optionally foursquare_type.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• latitude (float, optional) – Latitude of venue.
• longitude (float, optional) – Longitude of venue.
• title (str, optional) – Name of the venue.
• address (str, optional) – Address of the venue.
• foursquare_id (str, optional) – Foursquare identifier of the venue.
• foursquare_type (str, optional) – Foursquare type of the venue, if
known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium”
or “food/icecream”.)
• venue (telegram.Venue, optional) – The venue to send.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup (telegram.ReplyMarkup, optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type telegram.Message
Raises telegram.TelegramError
Note: The video argument can be either a file_id, an URL or a file from disk open(filename,
'rb')
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• video (str | filelike object | telegram.Video) – Video file to send. Pass a file_id
as String to send an video file that exists on the Telegram servers (recommended), pass
an HTTP URL as a String for Telegram to get an video file from the Internet, or upload
a new one using multipart/form-data. Lastly you can pass an existing telegram.
Video object to send.
• duration (int, optional) – Duration of sent video in seconds.
• width (int, optional) – Video width.
• height (int, optional) – Video height.
• caption (str, optional) – Video caption (may also be used when resending videos
by file_id), 0-1024 characters after entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See
the constants in telegram.ParseMode for the available modes.
• supports_streaming (bool, optional) – Pass True, if the uploaded video is
suitable for streaming.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup (telegram.ReplyMarkup, optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• thumb (filelike object, optional) – Thumbnail of the file sent; can be ignored if thumb-
nail 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.
• timeout (int | float, optional) – Send file timeout (default: 20 seconds).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type telegram.Message
Raises telegram.TelegramError
Note: The video_note argument can be either a file_id or a file from disk open(filename,
'rb')
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
98 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.8
Note: The voice argument can be either a file_id, an URL or a file from disk open(filename,
'rb')
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• voice (str | filelike object | telegram.Voice) – Voice file to send. Pass a file_id
as String to send an voice file that exists on the Telegram servers (recommended), pass
an HTTP URL as a String for Telegram to get an voice file from the Internet, or upload
a new one using multipart/form-data. Lastly you can pass an existing telegram.
Voice object to send.
• caption (str, optional) – Voice message caption, 0-1024 characters after entities
parsing.
Parameters
• chat_id (int | 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 administrator.
• custom_title (str) – emoji are not allowed.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments
Returns On success, True is returned.
Return type bool
Raises telegram.TelegramError
set_chat_description(chat_id, description, timeout=None, **kwargs)
Use this method to change the description of a group, 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.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• description (str) – New chat description, 0-255 characters.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments
Returns On success, True is returned.
Return type bool
Raises telegram.TelegramError
set_chat_permissions(chat_id, permissions, timeout=None, **kwargs)
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.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
supergroup (in the format @supergroupusername).
• permissions (telegram.ChatPermissions) – New default chat permis-
sions.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments
Returns On success, True is returned.
Return type bool
Raises telegram.TelegramError
Parameters
• user_id (int) – User identifier
• errors (List[PassportElementError]) – A JSON-serialized array describing
the errors.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, True is returned.
Return type bool
Raises telegram.TelegramError
set_sticker_position_in_set(sticker, position, timeout=None, **kwargs)
Use this method to move a sticker in a set created by the bot to a specific position.
Parameters
• sticker (str) – File identifier of the sticker.
• position (int) – New sticker position in the set, zero-based.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, True is returned.
Return type bool
Raises telegram.TelegramError
set_sticker_set_thumb(name, user_id, thumb=None, timeout=None, **kwargs)
Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated
sticker sets only.
Note: The thumb can be either a file_id, an URL or a file from disk open(filename, 'rb')
Parameters
• name (str) – Sticker set name
• user_id (int) – User identifier of created sticker set owner.
• thumb (str | filelike object, optional) – A PNG image with the thumbnail, must
• up to 128 kilobytes in size and have width and height
exactly 100px, or a TGS (be) –
• with the thumbnail up to 32 kilobytes in size; see
(animation) –
• https – //core.telegram.org/animated_stickers#technical-requirements for animated
sticker
• requirements. Pass a file_id as a String to send a file
that already exists (technical) –
• the Telegram servers, pass an HTTP URL as a String for
Telegram to get a file from (on) –
Note: The certificate argument should be a file from disk open(filename, 'rb').
Parameters
• url (str) – HTTPS url to send updates to. Use an empty string to remove webhook
integration.
• certificate (filelike) – Upload your public key certificate so that the root
certificate in use can be checked. See our self-signed guide for details. (https://goo.gl/
rw7w6Y)
• max_connections (int, optional) – 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 (List[str], optional) – A JSON-serialized list the types
of updates you want your bot to receive. For example, specify [“message”,
“edited_channel_post”, “callback_query”] to only receive updates of these types. See
telegram.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. Please note that this parameter doesn’t affect updates created
before the call to the set_webhook, so unwanted updates may be received for a short
period of time.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Note:
1. You will not be able to receive updates using get_updates for as long as an outgoing webhook is
set up.
2. To use a self-signed certificate, you need to upload your public key certificate using certificate
parameter. Please upload as InputFile, sending a String will not work.
3. Ports currently supported for Webhooks: 443, 80, 88, 8443.
If you’re having any trouble setting up webhooks, please check out this guide to Webhooks.
Note: The png_sticker argument can be either a file_id, an URL or a file from disk
open(filename, 'rb')
Parameters
• user_id (int) – User identifier of sticker file owner.
• png_sticker (str | 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.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns The uploaded File
Return type telegram.File
Raises telegram.TelegramError
username
Bot’s username.
Type str
3.2.4 telegram.BotCommand
Parameters
• command (str) – Text of the command, 1-32 characters. Can contain only lowercase
English letters, digits and underscores.
• description (str) – Description of the command, 3-256 characters.
3.2.5 telegram.CallbackQuery
Note:
• In Python from is a reserved word, use from_user instead.
id
Unique identifier for this query.
Type str
from_user
Sender.
Type telegram.User
chat_instance
Global identifier, uniquely corresponding to the chat to which the message with the callback button
was sent.
Type str
message
Optional. Message with the callback button that originated the query.
Type telegram.Message
data
Optional. Data associated with the callback button.
Type str
inline_message_id
Optional. Identifier of the message sent via the bot in inline mode, that originated the query.
Type str
game_short_name
Optional. Short name of a Game to be returned.
Type str
bot
The Bot to use for instance methods.
Type telegram.Bot, optional
Parameters
• id (str) – Unique identifier for this query.
• from_user (telegram.User) – Sender.
• chat_instance (str) – Global identifier, uniquely corresponding to the chat to
which the message with the callback button was sent. Useful for high scores in games.
• message (telegram.Message, optional) – Message with the callback button that
originated the query. Note that message content and message date will not be available
if the message is too old.
• data (str, optional) – Data associated with the callback button. Be aware that a bad
client can send arbitrary data in this field.
• inline_message_id (str, optional) – Identifier of the message sent via the bot in
inline mode, that originated the query.
• game_short_name (str, optional) – Short name of a Game to be returned, serves
as the unique identifier for the game
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
Note: After the user presses an inline button, Telegram clients will display a progress bar until you call
answer. It is, therefore, necessary to react by calling telegram.Bot.answer_callback_query
even if no notification to the user is needed (e.g., without specifying any of the optional parameters).
answer(*args, **kwargs)
Shortcut for:
bot.edit_message_caption(caption=caption,
chat_id=update.callback_query.message.chat_id,
message_id=update.callback_query.message.message_id,
*args, **kwargs)
or:
bot.edit_message_caption(caption=caption
inline_message_id=update.callback_query.inline_
˓→message_id,
*args, **kwargs)
Returns On success, if edited message is sent by the bot, the edited Message is returned,
otherwise True is returned.
Return type telegram.Message
bot.edit_message_replyMarkup(chat_id=update.callback_query.message.chat_id,
message_id=update.callback_query.message.
˓→message_id,
reply_markup=reply_markup,
*args, **kwargs)
or:
bot.edit_message_reply_markup(inline_message_id=update.callback_query.
˓→inline_message_id,
reply_markup=reply_markup,
*args, **kwargs)
Returns On success, if edited message is sent by the bot, the edited Message is returned,
otherwise True is returned.
Return type telegram.Message
bot.edit_message_text(text, chat_id=update.callback_query.message.chat_id,
message_id=update.callback_query.message.message_id,
*args, **kwargs)
or:
bot.edit_message_text(text, inline_message_id=update.callback_query.inline_
˓→message_id,
*args, **kwargs)
Returns On success, if edited message is sent by the bot, the edited Message is returned,
otherwise True is returned.
Return type telegram.Message
3.2.6 telegram.Chat
Type str
pinned_message
Optional. Pinned message, for supergroups. Returned only in get_chat.
Type telegram.Message
permissions
Optional. Default chat member permissions, for groups and supergroups. Returned only in getChat.
Type telegram.ChatPermission
slow_mode_delay
Optional. For supergroups, the minimum allowed delay between consecutive messages sent by each
unpriviledged user. Returned only in getChat.
Type int
sticker_set_name
Optional. For supergroups, name of Group sticker set.
Type str
can_set_sticker_set
Optional. True, if the bot can change group the sticker set.
Type bool
Parameters
• id (int) – Unique identifier for this chat. This number may be greater than 32 bits and
some programming languages may have difficulty/silent defects in interpreting it. But it
is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe
for storing this identifier.
• type (str) – Type of chat, can be either ‘private’, ‘group’, ‘supergroup’ or ‘channel’.
• title (str, optional) – Title, for supergroups, channels and group chats.
• username (str, optional) – Username, for private chats, supergroups and channels if
available.
• first_name (str, optional) – First name of the other party in a private chat.
• last_name (str, optional) – Last name of the other party in a private chat.
• photo (telegram.ChatPhoto, optional) – Chat photo. Returned only in getChat.
• description (str, optional) – Description, for groups, supergroups and channel
chats. Returned only in get_chat.
• invite_link (str, optional) – Chat invite link, for supergroups and channel chats.
Returned only in get_chat.
• pinned_message (telegram.Message, optional) – Pinned message, for super-
groups. Returned only in get_chat.
• permissions (telegram.ChatPermission) – Optional. Default chat member
permissions, for groups and supergroups. Returned only in getChat.
• slow_mode_delay (int, optional) – For supergroups, the minimum allowed de-
lay between consecutive messages sent by each unpriviledged user. Returned only in
getChat.
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
• sticker_set_name (str, optional) – For supergroups, name of Group sticker set.
Returned only in get_chat.
• can_set_sticker_set (bool, optional) – True, if the bot can change group the
sticker set. Returned only in get_chat.
CHANNEL = 'channel'
‘channel’
Type str
GROUP = 'group'
‘group’
Type str
PRIVATE = 'private'
‘private’
Type str
SUPERGROUP = 'supergroup'
‘supergroup’
Type str
get_administrators(*args, **kwargs)
Shortcut for:
get_member(*args, **kwargs)
Shortcut for:
Returns telegram.ChatMember
get_members_count(*args, **kwargs)
Shortcut for:
Returns int
kick_member(*args, **kwargs)
Shortcut for:
Note: This method will only work if the All Members Are Admins setting is off in the target group.
Otherwise members may only be removed by the group’s creator or by the member that added them.
leave(*args, **kwargs)
Shortcut for:
link
Convenience property. If the chat has a username, returns a t.me link of the chat.
Type str
send_action(*args, **kwargs)
Shortcut for:
send_animation(*args, **kwargs)
Shortcut for:
send_photo(*args, **kwargs)
Shortcut for:
bot.set_chat_administrator_custom_title(update.message.chat.id, *args,
˓→**kwargs)
3.2.7 telegram.ChatAction
class telegram.ChatAction
Bases: object
Helper class to provide constants for different chatactions.
FIND_LOCATION = 'find_location'
‘find_location’
Type str
RECORD_AUDIO = 'record_audio'
‘record_audio’
Type str
RECORD_VIDEO = 'record_video'
‘record_video’
Type str
RECORD_VIDEO_NOTE = 'record_video_note'
‘record_video_note’
Type str
TYPING = 'typing'
‘typing’
Type str
UPLOAD_AUDIO = 'upload_audio'
‘upload_audio’
Type str
UPLOAD_DOCUMENT = 'upload_document'
‘upload_document’
Type str
UPLOAD_PHOTO = 'upload_photo'
‘upload_photo’
Type str
UPLOAD_VIDEO = 'upload_video'
‘upload_video’
Type str
UPLOAD_VIDEO_NOTE = 'upload_video_note'
‘upload_video_note’
Type str
3.2.8 telegram.ChatMember
Type bool
can_invite_users
Optional. If the user can invite new users to the chat.
Type bool
can_restrict_members
Optional. If the administrator can restrict, ban or unban chat members.
Type bool
can_pin_messages
Optional. If the user can pin messages.
Type bool
can_promote_members
Optional. If the administrator can add new administrators.
Type bool
is_member
Optional. Restricted only. True, if the user is a member of the chat at the moment of the request.
Type bool
can_send_messages
Optional. If the user can send text messages, contacts, locations and venues.
Type bool
can_send_media_messages
Optional. If the user can send media messages, implies can_send_messages.
Type bool
can_send_polls
Optional. True, if the user is allowed to send polls.
Type bool
can_send_other_messages
Optional. If the user can send animations, games, stickers and use inline bots, implies
can_send_media_messages.
Type bool
can_add_web_page_previews
Optional. If user may add web page previews to his messages, implies can_send_media_messages
Type bool
Parameters
• user (telegram.User) – Information about the user.
• status (str) – The member’s status in the chat. Can be ‘creator’, ‘administrator’,
‘member’, ‘restricted’, ‘left’ or ‘kicked’.
• custom_title (str, optional) – Owner and administrators only. Custom title for
this user.
• until_date (datetime.datetime, optional) – Restricted and kicked only. Date
when restrictions will be lifted for this user.
• can_be_edited (bool, optional) – Administrators only. True, if the bot is allowed
to edit administrator privileges of that user.
• can_change_info (bool, optional) – Administrators and restricted only. True, if
the user can change the chat title, photo and other settings.
ADMINISTRATOR = 'administrator'
‘administrator’
Type str
CREATOR = 'creator'
‘creator’
Type str
KICKED = 'kicked'
‘kicked’
Type str
LEFT = 'left'
‘left’
Type str
MEMBER = 'member'
‘member’
Type str
RESTRICTED = 'restricted'
‘restricted’
Type str
3.2.9 telegram.ChatPermissions
Note: Though not stated explicitly in the offical docs, Telegram changes not only the permissions that
are set, but also sets all the others to False. However, since not documented, this behaviour may change
unbeknown to PTB.
can_send_messages
Optional. True, if the user is allowed to send text messages, contacts, locations and venues.
Type bool
can_send_media_messages
Optional. True, if the user is allowed to send audios, documents, photos, videos, video notes and voice
notes, implies can_send_messages.
Type bool
can_send_polls
Optional. True, if the user is allowed to send polls, implies can_send_messages.
Type bool
can_send_other_messages
Optional. True, if the user is allowed to send animations, games, stickers and use inline bots, implies
can_send_media_messages.
Type bool
can_add_web_page_previews
Optional. True, if the user is allowed to add web page previews to their messages, implies
can_send_media_messages.
Type bool
can_change_info
Optional. True, if the user is allowed to change the chat title, photo and other settings. Ignored in
public supergroups.
Type bool
can_invite_users
Optional. True, if the user is allowed to invite new users to the chat.
Type bool
can_pin_messages
Optional. True, if the user is allowed to pin messages. Ignored in public supergroups.
Type bool
Parameters
3.2.10 telegram.ChatPhoto
Parameters
• small_file_id (str) – Unique file identifier of small (160x160) chat photo. This
file_id can be used only for photo download and only for as long as the photo is not
changed.
get_big_file(timeout=None, **kwargs)
Convenience wrapper over telegram.Bot.get_file for getting the big (640x640) chat photo
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns telegram.File
Raises telegram.TelegramError
get_small_file(timeout=None, **kwargs)
Convenience wrapper over telegram.Bot.get_file for getting the small (160x160) chat photo
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns telegram.File
Raises telegram.TelegramError
Type int
telegram.constants.MAX_FILESIZE_UPLOAD
In bytes (50MB)
Type int
telegram.constants.MAX_PHOTOSIZE_UPLOAD
In bytes (10MB)
Type int
telegram.constants.MAX_MESSAGES_PER_SECOND_PER_CHAT
1. Telegram may allow short bursts that go over this limit, but eventually you’ll begin receiving 429 errors.
Type int
telegram.constants.MAX_MESSAGES_PER_SECOND
30
Type int
telegram.constants.MAX_MESSAGES_PER_MINUTE_PER_GROUP
20
Type int
telegram.constants.MAX_INLINE_QUERY_RESULTS
50
Type int
The following constant have been found by experimentation:
telegram.constants.MAX_MESSAGE_ENTITIES
100 (Beyond this cap telegram will simply ignore further formatting styles)
Type int
3.2.12 telegram.Contact
Type str
Parameters
• phone_number (str) – Contact’s phone number.
• first_name (str) – Contact’s first name.
• last_name (str, optional) – Contact’s last name.
• user_id (int, optional) – Contact’s user identifier in Telegram.
• vcard (str, optional) – Additional data about the contact in the form of a vCard.
• **kwargs (dict) – Arbitrary keyword arguments.
3.2.13 telegram.Dice
Note: If emoji is “”, a value of 6 currently represents a bullseye, while a value of 1 indicates that the
dartboard was missed. However, this behaviour is undocumented and might be changed by Telegram.
If emoji is “”, a value of 4 or 5 currently score a basket, while a value of 1 to 3 indicates that the basket
was missed. However, this behaviour is undocumented and might be changed by Telegram.
value
Value of the dice.
Type int
emoji
Emoji on which the dice throw animation is based.
Type str
Parameters
• value (int) – Value of the dice. 1-6 for dice and darts, 1-5 for basketball.
• emoji (str) – Emoji on which the dice throw animation is based.
3.2.14 telegram.Document
Parameters
• file_id (str) – Identifier for this file, which can be used to download or reuse the
file.
• file_unique_id (str) – Unique and the same over time and for different bots file
identifier.
• thumb (telegram.PhotoSize, optional) – Document thumbnail as defined by
sender.
• file_name (str, optional) – Original filename as defined by sender.
• mime_type (str, optional) – MIME type of the file as defined by sender.
• file_size (int, optional) – File size.
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.
get_file(timeout=None, **kwargs)
Convenience wrapper over telegram.Bot.get_file
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns telegram.File
Raises telegram.TelegramError
3.2.16 telegram.File
file_id
Unique identifier for this file.
Type str
file_unique_id
Unique identifier for this file, which is supposed to be the same over time and for different bots. Can’t
be used to download or reuse the file.
Type str
file_size
Optional. File size.
Type str
file_path
Optional. File path. Use download to get the file.
Type str
Parameters
• file_id (str) – Identifier for this file, which can be used to download or reuse the
file.
• file_unique_id (str) – Unique and the same over time and for different bots file
identifier.
• file_size (int, optional) – Optional. File size, if known.
• file_path (str, optional) – File path. Use download to get the file.
• bot (telegram.Bot, optional) – Bot to use with shortcut method.
• **kwargs (dict) – Arbitrary keyword arguments.
Note: If you obtain an instance of this class from telegram.PassportFile.get_file, then it will
automatically be decrypted as it downloads when you call download().
Parameters
• custom_path (str, optional) – Custom path.
• out (io.BufferedWriter, optional) – A file-like object. Must be opened for
writing in binary mode, if applicable.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
Returns The same object as out if specified. Otherwise, returns the filename downloaded
to.
Return type str | io.BufferedWriter
Raises ValueError – If both custom_path and out are passed.
download_as_bytearray(buf=None)
Download this file and return it as a bytearray.
Parameters buf (bytearray, optional) – Extend the given bytearray with the down-
loaded data.
Returns The same object as buf if it was specified. Otherwise a newly allocated
bytearray.
Return type bytearray
3.2.17 telegram.ForceReply
Parameters
• selective (bool, optional) – Use this parameter if you want to force reply from
specific users only. Targets:
1) users that are @mentioned in the text of the Message object
2) if the bot’s message is a reply (has reply_to_message_id), sender of the original mes-
sage.
• **kwargs (dict) – Arbitrary keyword arguments.
3.2.18 telegram.InlineKeyboardButton
Note: You must use exactly one of the optional fields. Mind that callback_game is not working as
expected. Putting a game short name in it might, but is not guaranteed to work.
text
Label text on the button.
Type str
url
Optional. HTTP or tg:// url to be opened when button is pressed.
Type str
login_url
authorize the user. Can be used as a replacement for the Telegram Login Widget.
Type telegram.LoginUrl
callback_data
Optional. Data to be sent in a callback query to the bot when button is pressed, UTF-8 1-64 bytes.
Type str
switch_inline_query
Optional. Will prompt the user to select one of their chats, open that chat and insert the bot’s username
and the specified inline query in the input field. Can be empty, in which case just the bot’s username
will be inserted.
Type str
switch_inline_query_current_chat
Optional. Will insert the bot’s username and the specified inline query in the current chat’s input field.
Can be empty, in which case just the bot’s username will be inserted.
Type str
callback_game
Optional. Description of the game that will be launched when the user presses the button.
Type telegram.CallbackGame
pay
Optional. Specify True, to send a Pay button.
Type bool
Parameters
• text (str) – Label text on the button.
• url (str) – HTTP or tg:// url to be opened when button is pressed.
• login_url (telegram.LoginUrl, optional) – authorize the user. Can be used as
a replacement for the Telegram Login Widget.
• callback_data (str, optional) – Data to be sent in a callback query to the bot
when button is pressed, UTF-8 1-64 bytes.
• switch_inline_query (str, optional) – If set, pressing the button will prompt
the user to select one of their chats, open that chat and insert the bot’s username and
the specified inline query in the input field. Can be empty, in which case just the bot’s
username will be inserted. This offers an easy way for users to start using your bot in
inline mode when they are currently in a private chat with it. Especially useful when
combined with switch_pm* actions - in this case the user will be automatically returned
to the chat they switched from, skipping the chat selection screen.
• switch_inline_query_current_chat (str, optional) – If set, pressing the
button will insert the bot’s username and the specified inline query in the current chat’s
input field. Can be empty, in which case only the bot’s username will be inserted. This
offers a quick way for the user to open your bot in inline mode in the same chat - good
for selecting something from multiple options.
• callback_game (telegram.CallbackGame, optional) – Description of the
game that will be launched when the user presses the button. This type of button must
always be the first button in the first row.
• pay (bool, optional) – Specify True, to send a Pay button. This type of button must
always be the first button in the first row.
• **kwargs (dict) – Arbitrary keyword arguments.
3.2.19 telegram.InlineKeyboardMarkup
Parameters
• inline_keyboard (List[List[telegram.InlineKeyboardButton]]) – Ar-
ray of button rows, each represented by an Array of InlineKeyboardButton objects.
• **kwargs (dict) – Arbitrary keyword arguments.
3.2.20 telegram.InputFile
input_file_content
The binaray content of the file to send.
Type bytes
filename
Optional, Filename for the file to be sent.
Type str
attach
Optional, attach id for sending multiple files.
Type str
Parameters
• obj (File handler) – An open file descriptor.
• filename (str, optional) – Filename for this InputFile.
• attach (bool, optional) – Whether this should be send as one file or is part of a
collection of files.
Raises TelegramError
static is_image(stream)
Check if the content file is an image by analyzing its headers.
Parameters stream (str) – A str representing the content of a file.
Returns The str mime-type of an image.
Return type str
3.2.21 telegram.InputMedia
class telegram.InputMedia
Bases: telegram.base.TelegramObject
Base class for Telegram InputMedia Objects.
See telegram.InputMediaAnimation, telegram.InputMediaAudio, telegram.
InputMediaDocument, telegram.InputMediaPhoto and telegram.InputMediaVideo
for detailed use.
3.2.22 telegram.InputMediaAnimation
Type str
parse_mode
Optional. The parse mode to use for text formatting.
Type str
thumb
Optional. Thumbnail of the file to send.
Type telegram.InputFile
width
Optional. Animation width.
Type int
height
Optional. Animation height.
Type int
duration
Optional. Animation duration.
Type int
Parameters
• media (str | filelike object | telegram.Animation) – File to send. Pass a file_id
to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for
Telegram to get a file from the Internet. Lastly you can pass an existing telegram.
Animation object to send.
• thumb (filelike object, optional) – Thumbnail of the file sent; can be ignored if thumb-
nail 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.
• caption (str, optional) – Caption of the animation to be sent, 0-1024 characters
after entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.ParseMode for the available modes.
• width (int, optional) – Animation width.
• height (int, optional) – Animation height.
• duration (int, optional) – Animation duration.
Note: When using a telegram.Animation for the media attribute. It will take the width, height and
duration from that video, unless otherwise specified with the optional arguments.
3.2.23 telegram.InputMediaAudio
type
audio.
Type str
media
Audio file to send.
Type str | telegram.InputFile
caption
Optional. Caption of the document to be sent.
Type str
parse_mode
Optional. The parse mode to use for text formatting.
Type str
duration
Duration of the audio in seconds.
Type int
performer
Optional. Performer of the audio as defined by sender or by audio tags.
Type str
title
Optional. Title of the audio as defined by sender or by audio tags.
Type str
thumb
Optional. Thumbnail of the file to send.
Type telegram.InputFile
Parameters
• media (str | filelike object | telegram.Audio) – File to send. Pass a file_id to
send a file that exists on the Telegram servers (recommended), pass an HTTP URL for
Telegram to get a file from the Internet. Lastly you can pass an existing telegram.
Document object to send.
• caption (str, optional) – Caption of the audio to be sent, 0-1024 characters after
entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.ParseMode for the available modes.
• duration (int) – Duration of the audio in seconds as defined by sender.
• performer (str, optional) – Performer of the audio as defined by sender or by audio
tags.
• title (str, optional) – Title of the audio as defined by sender or by audio tags.
• thumb (filelike object, optional) – Thumbnail of the file sent; can be ignored if thumb-
nail 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.
Note: When using a telegram.Audio for the media attribute. It will take the duration, performer and
title from that video, unless otherwise specified with the optional arguments.
3.2.24 telegram.InputMediaDocument
Parameters
• media (str | filelike object | telegram.Document) – File to send. Pass a file_id to
send a file that exists on the Telegram servers (recommended), pass an HTTP URL for
Telegram to get a file from the Internet. Lastly you can pass an existing telegram.
Document object to send.
• caption (str, optional) – Caption of the document to be sent, 0-1024 characters after
entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.ParseMode for the available modes.
• thumb (filelike object, optional) – Thumbnail of the file sent; can be ignored if thumb-
nail 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.
3.2.25 telegram.InputMediaPhoto
Parameters
• media (str | filelike object | telegram.PhotoSize) – File to send. Pass a file_id
to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for
Telegram to get a file from the Internet. Lastly you can pass an existing telegram.
PhotoSize object to send.
• caption (str, optional) – Caption of the photo to be sent, 0-1024 characters after
entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.ParseMode for the available modes.
3.2.26 telegram.InputMediaVideo
Type int
height
Optional. Video height.
Type int
duration
Optional. Video duration.
Type int
supports_streaming
Optional. Pass True, if the uploaded video is suitable for streaming.
Type bool
thumb
Optional. Thumbnail of the file to send.
Type telegram.InputFile
Parameters
• media (str | filelike object | telegram.Video) – File to send. Pass a file_id to
send a file that exists on the Telegram servers (recommended), pass an HTTP URL for
Telegram to get a file from the Internet. Lastly you can pass an existing telegram.
Video object to send.
• caption (str, optional) – Caption of the video to be sent, 0-1024 characters after
entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.ParseMode for the available modes.
• width (int, optional) – Video width.
• height (int, optional) – Video height.
• duration (int, optional) – Video duration.
• supports_streaming (bool, optional) – Pass True, if the uploaded video is suit-
able for streaming.
• thumb (filelike object, optional) – Thumbnail of the file sent; can be ignored if thumb-
nail 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.
Note: When using a telegram.Video for the media attribute. It will take the width, height and
duration from that video, unless otherwise specified with the optional arguments.
3.2.27 telegram.KeyboardButton
text
Text of the button.
Type str
request_contact
Optional. If the user’s phone number will be sent.
Type bool
request_location
Optional. If the user’s current location will be sent.
Type bool
request_poll
Optional. If the user should create a poll.
Type KeyboardButtonPollType
Parameters
• text (str) – Text of the button. If none of the optional fields are used, it will be sent
to the bot as a message when the button is pressed.
• request_contact (bool, optional) – If True, the user’s phone number will be sent
as a contact when the button is pressed. Available in private chats only.
• request_location (bool, optional) – If True, the user’s current location will be
sent when the button is pressed. Available in private chats only.
• request_poll (KeyboardButtonPollType, optional) – If specified, the user
will be asked to create a poll and send it to the bot when the button is pressed. Available
in private chats only.
Note: request_contact and request_location options will only work in Telegram versions
released after 9 April, 2016. Older clients will ignore them.
request_poll option will only work in Telegram versions released after 23 January, 2020. Older clients
will receive unsupported message.
3.2.28 telegram.KeyboardButtonPollType
class telegram.KeyboardButtonPollType(type=None)
Bases: telegram.base.TelegramObject
This object represents type of a poll, which is allowed to be created and sent when the corresponding button
is pressed.
type
Optional. If telegram.Poll.QUIZ is passed, the user will be allowed to create only polls in the
quiz mode. If telegram.Poll.REGULAR is passed, only regular polls will be allowed. Otherwise,
the user will be allowed to create a poll of any type.
Type str
3.2.29 telegram.Location
Parameters
• longitude (float) – Longitude as defined by sender.
• latitude (float) – Latitude as defined by sender.
• **kwargs (dict) – Arbitrary keyword arguments.
3.2.30 telegram.LoginUrl
Parameters
• url (str) – An HTTP URL to be opened with user authorization data added to the
query string when the button is pressed. If the user refuses to provide authorization data,
the original URL without information about the user will be opened. The data added is
the same as described in Receiving authorization data. NOTE: You must always check
the hash of the received data to verify the authentication and the integrity of the data as
described in Checking authorization.
3.2.31 telegram.Message
Note:
• In Python from is a reserved word, use from_user instead.
message_id
Unique message identifier inside this chat.
Type int
from_user
Optional. Sender.
Type telegram.User
date
Date the message was sent.
Type datetime.datetime
chat
Conversation the message belongs to.
Type telegram.Chat
forward_from
Optional. Sender of the original message.
Type telegram.User
forward_from_chat
Optional. Information about the original channel.
Type telegram.Chat
forward_from_message_id
Optional. Identifier of the original message in the channel.
Type int
forward_date
Optional. Date the original message was sent.
Type datetime.datetime
reply_to_message
Optional. The original message.
Type telegram.Message
edit_date
Optional. Date the message was last edited.
Type datetime.datetime
media_group_id
Optional. The unique identifier of a media message group this message belongs to.
Type str
text
Optional. The actual UTF-8 text of the message.
Type str
entities
Optional. Special entities like usernames, URLs, bot commands, etc. that appear in the text. See
Message.parse_entity and parse_entities methods for how to use properly.
Type List[telegram.MessageEntity]
caption_entities
Optional. Special entities like usernames, URLs, bot commands, etc. that appear in the caption. See
Message.parse_caption_entity and parse_caption_entities methods for how to
use properly.
Type List[telegram.MessageEntity]
audio
Optional. Information about the file.
Type telegram.Audio
document
Optional. Information about the file.
Type telegram.Document
animation
For backward compatibility, when this field is set, the document field will also be set.
Type telegram.Animation
game
Optional. Information about the game.
Type telegram.Game
photo
Optional. Available sizes of the photo.
Type List[telegram.PhotoSize]
sticker
Optional. Information about the sticker.
Type telegram.Sticker
video
Optional. Information about the video.
Type telegram.Video
voice
Optional. Information about the file.
Type telegram.Voice
video_note
Optional. Information about the video message.
Type telegram.VideoNote
new_chat_members
Optional. Information about new members to the chat. (the bot itself may be one of these members).
Type List[telegram.User]
caption
Optional. Caption for the document, photo or video, 0-1024 characters.
Type str
contact
Optional. Information about the contact.
Type telegram.Contact
location
Optional. Information about the location.
Type telegram.Location
venue
Optional. Information about the venue.
Type telegram.Venue
left_chat_member
Optional. Information about the user that left the group. (this member may be the bot itself).
Type telegram.User
new_chat_title
Optional. A chat title was changed to this value.
Type str
new_chat_photo
Optional. A chat photo was changed to this value.
Type List[telegram.PhotoSize]
delete_chat_photo
Optional. The chat photo was deleted.
Type bool
group_chat_created
Optional. The group has been created.
Type bool
supergroup_chat_created
Optional. The supergroup has been created.
Type bool
channel_chat_created
Optional. The channel has been created.
Type bool
migrate_to_chat_id
Optional. The group has been migrated to a supergroup with the specified identifier.
Type int
migrate_from_chat_id
Optional. The supergroup has been migrated from a group with the specified identifier.
Type int
pinned_message
Optional. Specified message was pinned.
Type telegram.message
invoice
Optional. Information about the invoice.
Type telegram.Invoice
successful_payment
Optional. Information about the payment.
Type telegram.SuccessfulPayment
connected_website
Optional. The domain name of the website on which the user has logged in.
Type str
forward_signature
Optional. Signature of the post author for messages forwarded from channels.
Type str
forward_sender_name
Optional. Sender’s name for messages forwarded from users who disallow adding a link to their
account in forwarded messages.
Type str
author_signature
Optional. Signature of the post author for messages in channels.
Type str
passport_data
Optional. Telegram Passport data.
Type telegram.PassportData
poll
Optional. Message is a native poll, information about the poll.
Type telegram.Poll
dice
Optional. Message is a dice.
Type telegram.Dice
via_bot
Optional. Bot through which the message was sent.
Type telegram.User
reply_markup
Optional. Inline keyboard attached to the message.
Type telegram.InlineKeyboardMarkup
bot
Optional. The Bot to use for instance methods.
Type telegram.Bot
default_quote
Optional. Default setting for the quote parameter of the reply_text and friends.
Type bool
Parameters
• message_id (int) – Unique message identifier inside this chat.
• from_user (telegram.User, optional) – Sender, can be empty for messages sent
to channels.
• date (datetime.datetime) – Date the message was sent in Unix time. Converted
to datetime.datetime.
• chat (telegram.Chat) – Conversation the message belongs to.
• forward_from (telegram.User, optional) – For forwarded messages, sender of
the original message.
• forward_from_chat (telegram.Chat, optional) – For messages forwarded
from a channel, information about the original channel.
• forward_from_message_id (int, optional) – For forwarded channel posts, iden-
tifier of the original message in the channel.
• forward_sender_name (str, optional) – Sender’s name for messages forwarded
from users who disallow adding a link to their account in forwarded messages.
• forward_date (datetime.datetime, optional) – For forwarded messages, date
the original message was sent in Unix time. Converted to datetime.datetime.
• reply_to_message (telegram.Message, optional) – For replies, the origi-
nal message. Note that the Message object in this field will not contain further
reply_to_message fields even if it itself is a reply.
• edit_date (datetime.datetime, optional) – Date the message was last edited
in Unix time. Converted to datetime.datetime.
• media_group_id (str, optional) – The unique identifier of a media message group
this message belongs to.
• text (str, optional) – For text messages, the actual UTF-8 text of
the message, 0-4096 characters. Also found as telegram.constants.
MAX_MESSAGE_LENGTH.
• entities (List[telegram.MessageEntity], optional) – For text messages,
special entities like usernames, URLs, bot commands, etc. that appear in the text. See
attr:parse_entity and attr:parse_entities methods for how to use properly.
• caption_entities (List[telegram.MessageEntity]) – Optional. For Mes-
sages with a Caption. Special entities like usernames, URLs, bot commands,
etc. that appear in the caption. See Message.parse_caption_entity and
parse_caption_entities methods for how to use properly.
• audio (telegram.Audio, optional) – Message is an audio file, information about
the file.
smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for
storing this identifier.
• migrate_from_chat_id (int, optional) – The supergroup has been migrated
from a group with the specified identifier. This number may be greater than 32 bits
and some programming languages may have difficulty/silent defects in interpreting it.
But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type
are safe for storing this identifier.
• pinned_message (telegram.message, optional) – Specified message was
pinned. Note that the Message object in this field will not contain further
reply_to_message fields even if it is itself a reply.
• invoice (telegram.Invoice, optional) – Message is an invoice for a payment,
information about the invoice.
• successful_payment (telegram.SuccessfulPayment, optional) – Mes-
sage is a service message about a successful payment, information about the payment.
• connected_website (str, optional) – The domain name of the website on which
the user has logged in.
• forward_signature (str, optional) – Signature of the post author for messages
forwarded from channels.
• author_signature (str, optional) – Signature of the post author for messages in
channels.
• passport_data (telegram.PassportData, optional) – Telegram Passport
data.
• poll (telegram.Poll, optional) – Message is a native poll, information about the
poll.
• dice (telegram.Dice, optional) – Message is a dice with random value from 1 to
6.
• via_bot (telegram.User, optional) – Message was sent through an inline bot.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline key-
board attached to the message. login_url buttons are represented as ordinary url buttons.
• default_quote (bool, optional) – Default setting for the quote parameter of the
reply_text and friends.
caption_html
Creates an HTML-formatted string from the markup entities found in the message’s caption.
Use this if you want to retrieve the message caption with the caption entities formatted as HTML in
the same way the original message was formatted.
Returns Message caption with captionentities formatted as HTML.
Return type str
caption_html_urled
Creates an HTML-formatted string from the markup entities found in the message’s caption.
Use this if you want to retrieve the message caption with the caption entities formatted as HTML. This
also formats telegram.MessageEntity.URL as a hyperlink.
Returns Message caption with caption entities formatted as HTML.
Return type str
caption_markdown
Creates an Markdown-formatted string from the markup entities found in the message’s caption using
telegram.ParseMode.MARKDOWN .
Use this if you want to retrieve the message caption with the caption entities formatted as Markdown
in the same way the original message was formatted.
Returns Message caption with caption entities formatted as Markdown.
Return type str
caption_markdown_urled
Creates an Markdown-formatted string from the markup entities found in the message’s caption using
telegram.ParseMode.MARKDOWN .
Use this if you want to retrieve the message caption with the caption entities formatted as Markdown.
This also formats telegram.MessageEntity.URL as a hyperlink.
Returns Message caption with caption entities formatted as Markdown.
Return type str
caption_markdown_v2
Creates an Markdown-formatted string from the markup entities found in the message’s caption using
telegram.ParseMode.MARKDOWN_V2.
Use this if you want to retrieve the message caption with the caption entities formatted as Markdown
in the same way the original message was formatted.
Returns Message caption with caption entities formatted as Markdown.
Return type str
caption_markdown_v2_urled
Creates an Markdown-formatted string from the markup entities found in the message’s caption using
telegram.ParseMode.MARKDOWN_V2.
Use this if you want to retrieve the message caption with the caption entities formatted as Markdown.
This also formats telegram.MessageEntity.URL as a hyperlink.
Returns Message caption with caption entities formatted as Markdown.
Return type str
chat_id
Shortcut for telegram.Chat.id for chat.
Type int
delete(*args, **kwargs)
Shortcut for:
bot.delete_message(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
edit_caption(*args, **kwargs)
Shortcut for:
bot.edit_message_caption(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
Note: You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods)
or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and
might be changed by Telegram.
bot.edit_message_media(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
Note: You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods)
or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and
might be changed by Telegram.
edit_reply_markup(*args, **kwargs)
Shortcut for:
bot.edit_message_reply_markup(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
Note: You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods)
or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and
might be changed by Telegram.
edit_text(*args, **kwargs)
Shortcut for:
bot.edit_message_text(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
Note: You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods)
or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and
might be changed by Telegram.
effective_attachment
telegram.Audio or telegram.Contact or telegram.Document or telegram.
Animation or telegram.Game or telegram.Invoice or telegram.
Location or List[telegram.PhotoSize] or telegram.Sticker or telegram.
SuccessfulPayment or telegram.Venue or telegram.Video or telegram.
VideoNote or telegram.Voice: The attachment that this message was sent with. May
be None if no attachment was sent.
forward(chat_id, *args, **kwargs)
Shortcut for:
bot.forward_message(chat_id=chat_id,
from_chat_id=update.message.chat_id,
message_id=update.message.message_id,
*args,
**kwargs)
link
Convenience property. If the chat of the message is not a private chat or normal group, returns a t.me
link of the message.
Type str
parse_caption_entities(types=None)
Returns a dict that maps telegram.MessageEntity to str. It contains entities from this
message’s caption filtered by their telegram.MessageEntity.type attribute as the key, and
the text that each entity belongs to as the value of the dict.
Note: This method should always be used instead of the caption_entities attribute,
since it calculates the correct substring from the message text based on UTF-16 codepoints. See
parse_entity for more info.
parse_caption_entity(entity)
Returns the text from a given telegram.MessageEntity.
Note: This method is present because Telegram calculates the offset and length in UTF-16 code-
point pairs, which some versions of Python don’t handle automatically. (That is, you can’t just slice
Message.caption with the offset and length.)
parse_entities(types=None)
Returns a dict that maps telegram.MessageEntity to str. It contains entities from this
message filtered by their telegram.MessageEntity.type attribute as the key, and the text that
each entity belongs to as the value of the dict.
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. See parse_entity for more
info.
parse_entity(entity)
Returns the text from a given telegram.MessageEntity.
Note: This method is present because Telegram calculates the offset and length in UTF-16 code-
point pairs, which some versions of Python don’t handle automatically. (That is, you can’t just slice
Message.text with the offset and length.)
reply_animation(*args, **kwargs)
Shortcut for:
Keyword Arguments quote (bool, optional) – If set to True, the animation is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type telegram.Message
reply_audio(*args, **kwargs)
Shortcut for:
Keyword Arguments quote (bool, optional) – If set to True, the audio is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
reply_contact(*args, **kwargs)
Shortcut for:
Keyword Arguments quote (bool, optional) – If set to True, the contact is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type telegram.Message
reply_dice(*args, **kwargs)
Shortcut for:
Keyword Arguments quote (bool, optional) – If set to True, the dice is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type telegram.Message
reply_document(*args, **kwargs)
Shortcut for:
Keyword Arguments quote (bool, optional) – If set to True, the document is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type telegram.Message
reply_html(*args, **kwargs)
Shortcut for:
Keyword Arguments quote (bool, optional) – If set to True, the location is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type telegram.Message
reply_markdown(*args, **kwargs)
Shortcut for:
bot.send_message(update.message.chat_id, parse_mode=ParseMode.MARKDOWN,
˓→*args,
**kwargs)
bot.send_message(update.message.chat_id, parse_mode=ParseMode.MARKDOWN_V2,
˓→*args,
**kwargs)
Keyword Arguments quote (bool, optional) – If set to True, the media group is sent
as an actual reply to this message. If reply_to_message_id is passed in kwargs,
this parameter will be ignored. Default: True in group chats and False in private
chats.
Returns An array of the sent Messages.
Return type List[telegram.Message]
Raises telegram.TelegramError
reply_photo(*args, **kwargs)
Shortcut for:
Keyword Arguments quote (bool, optional) – If set to True, the photo is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type telegram.Message
reply_poll(*args, **kwargs)
Shortcut for:
Keyword Arguments quote (bool, optional) – If set to True, the poll is sent as an ac-
tual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type telegram.Message
reply_sticker(*args, **kwargs)
Shortcut for:
Keyword Arguments quote (bool, optional) – If set to True, the sticker is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type telegram.Message
reply_text(*args, **kwargs)
Shortcut for:
Keyword Arguments quote (bool, optional) – If set to True, the message is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type telegram.Message
reply_venue(*args, **kwargs)
Shortcut for:
Keyword Arguments quote (bool, optional) – If set to True, the venue is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type telegram.Message
reply_video(*args, **kwargs)
Shortcut for:
Keyword Arguments quote (bool, optional) – If set to True, the video is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type telegram.Message
reply_video_note(*args, **kwargs)
Shortcut for:
Keyword Arguments quote (bool, optional) – If set to True, the video note is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type telegram.Message
reply_voice(*args, **kwargs)
Shortcut for:
Keyword Arguments quote (bool, optional) – If set to True, the voice note is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type telegram.Message
stop_poll(*args, **kwargs)
Shortcut for:
bot.stop_poll(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
Returns
On success, the stopped Poll with the final results is returned.
Return type telegram.Poll
text_html
Creates an HTML-formatted string from the markup entities found in the message.
Use this if you want to retrieve the message text with the entities formatted as HTML in the same way
the original message was formatted.
Returns Message text with entities formatted as HTML.
Return type str
text_html_urled
Creates an HTML-formatted string from the markup entities found in the message.
Use this if you want to retrieve the message text with the entities formatted as HTML. This also formats
telegram.MessageEntity.URL as a hyperlink.
Returns Message text with entities formatted as HTML.
Return type str
text_markdown
Creates an Markdown-formatted string from the markup entities found in the message using
telegram.ParseMode.MARKDOWN .
Use this if you want to retrieve the message text with the entities formatted as Markdown in the same
way the original message was formatted.
Returns Message text with entities formatted as Markdown.
Return type str
text_markdown_urled
Creates an Markdown-formatted string from the markup entities found in the message using
telegram.ParseMode.MARKDOWN .
Use this if you want to retrieve the message text with the entities formatted as Markdown. This also
formats telegram.MessageEntity.URL as a hyperlink.
Returns Message text with entities formatted as Markdown.
Return type str
text_markdown_v2
Creates an Markdown-formatted string from the markup entities found in the message using
telegram.ParseMode.MARKDOWN_V2.
Use this if you want to retrieve the message text with the entities formatted as Markdown in the same
way the original message was formatted.
Returns Message text with entities formatted as Markdown.
Return type str
text_markdown_v2_urled
Creates an Markdown-formatted string from the markup entities found in the message using
telegram.ParseMode.MARKDOWN_V2.
Use this if you want to retrieve the message text with the entities formatted as Markdown. This also
formats telegram.MessageEntity.URL as a hyperlink.
Returns Message text with entities formatted as Markdown.
Return type str
3.2.32 telegram.MessageEntity
Type int
length
Length of the entity in UTF-16 code units.
Type int
url
Optional. Url that will be opened after user taps on the text.
Type str
user
Optional. The mentioned user.
Type telegram.User
language
Optional. Programming language of the entity text
Type str
Parameters
• type (str) – Type of the entity. Can be mention (@username), hashtag,
bot_command, url, email, bold (bold text), italic (italic text), code (monowidth string),
pre (monowidth block), text_link (for clickable text URLs), text_mention (for users
without usernames).
• offset (int) – Offset in UTF-16 code units to the start of the entity.
• length (int) – Length of the entity in UTF-16 code units.
• url (str, optional) – For TEXT_LINK only, url that will be opened after usertaps on
the text.
• user (telegram.User, optional) – For TEXT_MENTION only, the mentioned user.
• language (str, optional) – For PRE only, the programming language of the entity
text
HASHTAG = 'hashtag'
‘hashtag’
Type str
ITALIC = 'italic'
‘italic’
Type str
MENTION = 'mention'
‘mention’
Type str
PHONE_NUMBER = 'phone_number'
‘phone_number’
Type str
PRE = 'pre'
‘pre’
Type str
STRIKETHROUGH = 'strikethrough'
‘strikethrough’
Type str
TEXT_LINK = 'text_link'
‘text_link’
Type str
TEXT_MENTION = 'text_mention'
‘text_mention’
Type str
UNDERLINE = 'underline'
‘underline’
Type str
URL = 'url'
‘url’
Type str
3.2.33 telegram.ParseMode
class telegram.ParseMode
Bases: object
This object represents a Telegram Message Parse Modes.
HTML = 'HTML'
‘HTML’
Type str
MARKDOWN = 'Markdown'
‘Markdown’
Type str
MARKDOWN_V2 = 'MarkdownV2'
‘MarkdownV2’
Type str
3.2.34 telegram.PhotoSize
Parameters
• file_id (str) – Identifier for this file, which can be used to download or reuse the
file.
• file_unique_id (str) – Unique and the same over time and for different bots file
identifier.
• width (int) – Photo width.
• height (int) – Photo height.
• file_size (int, optional) – File size.
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.
get_file(timeout=None, **kwargs)
Convenience wrapper over telegram.Bot.get_file
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns telegram.File
Raises telegram.TelegramError
3.2.35 telegram.Poll
open_period
Optional. Amount of time in seconds the poll will be active after creation.
Type int
close_date
Optional. Point in time when the poll will be automatically closed.
Type datetime.datetime
Parameters
• id (str) – Unique poll identifier.
• question (str) – Poll question, 1-255 characters.
• options (List[PollOption]) – List of poll options.
• is_closed (bool) – True, if the poll is closed.
• is_anonymous (bool) – True, if the poll is anonymous.
• type (str) – Poll type, currently can be REGULAR or QUIZ.
• allows_multiple_answers (bool) – True, if the poll allows multiple answers.
• correct_option_id (int, optional) – 0-based identifier of the correct answer op-
tion. Available only for polls in the quiz mode, which are closed, or was sent (not
forwarded) by the bot or to the private chat with the bot.
• explanation (str, optional) – 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.
• explanation_entities (List[telegram.MessageEntity], optional) – Spe-
cial entities like usernames, URLs, bot commands, etc. that appear in the
explanation.
• open_period (int, optional) – Amount of time in seconds the poll will be active
after creation.
• close_date (datetime.datetime, optional) – Point in time (Unix timestamp)
when the poll will be automatically closed. Converted to datetime.datetime.
QUIZ = 'quiz'
‘quiz’
Type str
REGULAR = 'regular'
‘regular’
Type str
parse_explanation_entities(types=None)
Returns a dict that maps telegram.MessageEntity to str. It contains entities from this polls
explanation filtered by their type attribute as the key, and the text that each entity belongs to as the
value of the dict.
Note: This method should always be used instead of the explanation_entities attribute,
since it calculates the correct substring from the message text based on UTF-16 codepoints. See
parse_explanation_entity for more info.
Returns A dictionary of entities mapped to the text that belongs to them, calculated based
on UTF-16 codepoints.
Return type Dict[telegram.MessageEntity, str]
parse_explanation_entity(entity)
Returns the text from a given telegram.MessageEntity.
Note: This method is present because Telegram calculates the offset and length in UTF-16 code-
point pairs, which some versions of Python don’t handle automatically. (That is, you can’t just slice
Message.text with the offset and length.)
3.2.36 telegram.PollAnswer
Parameters
• poll_id (str) – Unique poll identifier.
• user (telegram.User) – The user, who changed the answer to the poll.
• option_ids (List[int]) – 0-based identifiers of answer options, chosen by the user.
May be empty if the user retracted their vote.
3.2.37 telegram.PollOption
voter_count
Number of users that voted for this option.
Type int
Parameters
• text (str) – Option text, 1-100 characters.
• voter_count (int) – Number of users that voted for this option.
3.2.38 telegram.ReplyKeyboardRemove
Example
A user votes in a poll, bot returns confirmation message in reply to the vote and removes the keyboard for
that user, while still showing the keyboard with poll options to users who haven’t voted yet.
Parameters
• selective (bool, optional) – Use this parameter if you want to remove the keyboard
for specific users only. Targets:
1) users that are @mentioned in the text of the Message object
2) if the bot’s message is a reply (has reply_to_message_id), sender of the original mes-
sage.
• **kwargs (dict) – Arbitrary keyword arguments.
3.2.39 telegram.ReplyKeyboardMarkup
Type bool
one_time_keyboard
Optional. Requests clients to hide the keyboard as soon as it’s been used.
Type bool
selective
Optional. Show the keyboard to specific users only.
Type bool
Example
A user requests to change the bot’s language, bot replies to the request with a keyboard to select the new
language. Other users in the group don’t see the keyboard.
Parameters
• keyboard (List[List[str | telegram.KeyboardButton]]) – Array of button
rows, each represented by an Array of telegram.KeyboardButton objects.
• resize_keyboard (bool, optional) – Requests clients to resize the keyboard ver-
tically for optimal fit (e.g., make the keyboard smaller if there are just two rows of
buttons). Defaults to false, in which case the custom keyboard is always of the same
height as the app’s standard keyboard. Defaults to False
• one_time_keyboard (bool, optional) – Requests clients to hide the keyboard as
soon as it’s been used. The keyboard will still be available, but clients will automatically
display the usual letter-keyboard in the chat - the user can press a special button in the
input field to see the custom keyboard again. Defaults to False.
• selective (bool, optional) – Use this parameter if you want to show the keyboard
to specific users only. Targets:
1) users that are @mentioned in the text of the Message object
2) if the bot’s message is a reply (has reply_to_message_id), sender of the original mes-
sage.
Defaults to False.
• **kwargs (dict) – Arbitrary keyword arguments.
ReplyKeyboardMarkup([[button]], **kwargs)
• selective (bool, optional) – Use this parameter if you want to show the keyboard
to specific users only. Targets:
1) users that are @mentioned in the text of the Message object
2) if the bot’s message is a reply (has reply_to_message_id), sender of the
original message.
Defaults to False.
• **kwargs (dict) – Arbitrary keyword arguments.
classmethod from_column(button_column, resize_keyboard=False,
one_time_keyboard=False, selective=False, **kwargs)
Shortcut for:
ReplyKeyboardMarkup([[button] for button in button_column], **kwargs)
• selective (bool, optional) – Use this parameter if you want to show the keyboard
to specific users only. Targets:
1) users that are @mentioned in the text of the Message object
2) if the bot’s message is a reply (has reply_to_message_id), sender of the
original message.
Defaults to False.
• **kwargs (dict) – Arbitrary keyword arguments.
3.2.40 telegram.ReplyMarkup
class telegram.ReplyMarkup
Bases: telegram.base.TelegramObject
Base class for Telegram ReplyMarkup Objects.
See telegram.ReplyKeyboardMarkup and telegram.InlineKeyboardMarkup for detailed
use.
3.2.41 telegram.TelegramObject
class telegram.TelegramObject
Bases: object
Base class for most telegram objects.
to_json()
Returns str
3.2.42 telegram.Update
Note: At most one of the optional parameters can be present in any given update.
update_id
The update’s unique identifier.
Type int
message
Optional. New incoming message.
Type telegram.Message
edited_message
Optional. New version of a message.
Type telegram.Message
channel_post
Optional. New incoming channel post.
Type telegram.Message
edited_channel_post
Optional. New version of a channel post.
Type telegram.Message
inline_query
Optional. New incoming inline query.
Type telegram.InlineQuery
chosen_inline_result
Optional. The result of an inline query that was chosen by a user.
Type telegram.ChosenInlineResult
callback_query
Optional. New incoming callback query.
Type telegram.CallbackQuery
shipping_query
Optional. New incoming shipping query.
Type telegram.ShippingQuery
pre_checkout_query
Optional. New incoming pre-checkout query.
Type telegram.PreCheckoutQuery
poll
Optional. New poll state. Bots receive only updates about stopped polls and polls, which are sent by
the bot
Type telegram.Poll
poll_answer
Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls
that were sent by the bot itself.
Type telegram.PollAnswer
Parameters
• update_id (int) – The update’s unique identifier. Update identifiers start from a
certain positive number and increase sequentially. This ID becomes especially handy if
you’re using Webhooks, since it allows you to ignore repeated updates or to restore the
correct update sequence, should they get out of order.
• message (telegram.Message, optional) – New incoming message of any kind -
text, photo, sticker, etc.
• edited_message (telegram.Message, optional) – New version of a message
that is known to the bot and was edited.
• channel_post (telegram.Message, optional) – New incoming channel post of
any kind - text, photo, sticker, etc.
• edited_channel_post (telegram.Message, optional) – New version of a
channel post that is known to the bot and was edited.
• inline_query (telegram.InlineQuery, optional) – New incoming inline
query.
• chosen_inline_result (telegram.ChosenInlineResult, optional) –
The result of an inline query that was chosen by a user and sent to their chat partner.
3.2.43 telegram.User
Type str
username
Optional. User’s or bot’s username.
Type str
language_code
Optional. IETF language tag of the user’s language.
Type str
can_join_groups
Optional. True, if the bot can be invited to groups. Returned only in telegram.Bot.get_me
requests.
Type str
can_read_all_group_messages
Optional. True, if privacy mode is disabled for the bot. Returned only in telegram.Bot.get_me
requests.
Type str
supports_inline_queries
Optional. True, if the bot supports inline queries. Returned only in telegram.Bot.get_me re-
quests.
Type str
bot
Optional. The Bot to use for instance methods.
Type telegram.Bot
Parameters
• id (int) – Unique identifier for this user or bot.
• is_bot (bool) – True, if this user is a bot
• first_name (str) – User’s or bot’s first name.
• last_name (str, optional) – User’s or bot’s last name.
• username (str, optional) – User’s or bot’s username.
• language_code (str, optional) – IETF language tag of the user’s language.
• can_join_groups (str, optional) – True, if the bot can be invited to groups. Re-
turned only in telegram.Bot.get_me requests.
• can_read_all_group_messages (str, optional) – True, if privacy mode is dis-
abled for the bot. Returned only in telegram.Bot.get_me requests.
• supports_inline_queries (str, optional) – True, if the bot supports inline
queries. Returned only in telegram.Bot.get_me requests.
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
link
Convenience property. If username is available, returns a t.me link of the user.
Type str
mention_html(name=None)
Parameters name (str) – The name used as a link for the user. Defaults to full_name.
Returns The inline mention for the user as HTML.
Return type str
mention_markdown(name=None)
Parameters name (str) – The name used as a link for the user. Defaults to full_name.
Returns The inline mention for the user as markdown (version 1).
Return type str
mention_markdown_v2(name=None)
Parameters name (str) – The name used as a link for the user. Defaults to full_name.
Returns The inline mention for the user as markdown (version 2).
Return type str
name
Convenience property. If available, returns the user’s username prefixed with “@”. If username
is not available, returns full_name.
Type str
send_animation(*args, **kwargs)
Shortcut for:
send_message(*args, **kwargs)
Shortcut for:
3.2.44 telegram.UserProfilePhotos
Parameters
• total_count (int) – Total number of profile pictures the target user has.
• photos (List[List[telegram.PhotoSize]]) – Requested profile pictures (in up to
4 sizes each).
3.2.45 telegram.Venue
Parameters
• location (telegram.Location) – Venue location.
• title (str) – Name of the venue.
• address (str) – Address of the venue.
• foursquare_id (str, optional) – Foursquare identifier of the venue.
• foursquare_type (str, optional) – Foursquare type of the venue. (For example,
“arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
• **kwargs (dict) – Arbitrary keyword arguments.
3.2.46 telegram.Video
Parameters
• file_id (str) – Identifier for this file, which can be used to download or reuse the
file.
• file_unique_id (str) – Unique and the same over time and for different bots file
identifier.
• width (int) – Video width as defined by sender.
• height (int) – Video height as defined by sender.
• duration (int) – Duration of the video in seconds as defined by sender.
• thumb (telegram.PhotoSize, optional) – Video thumbnail.
• mime_type (str, optional) – Mime type of a file as defined by sender.
• file_size (int, optional) – File size.
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.
get_file(timeout=None, **kwargs)
Convenience wrapper over telegram.Bot.get_file
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns telegram.File
Raises telegram.TelegramError
3.2.47 telegram.VideoNote
file_size
Optional. File size.
Type int
bot
Optional. The Bot to use for instance methods.
Type telegram.Bot
Parameters
• file_id (str) – Identifier for this file, which can be used to download or reuse the
file.
• file_unique_id (str) – Unique and the same over time and for different bots file
identifier.
• length (int) – Video width and height as defined by sender.
• duration (int) – Duration of the video in seconds as defined by sender.
• thumb (telegram.PhotoSize, optional) – Video thumbnail.
• file_size (int, optional) – File size.
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.
get_file(timeout=None, **kwargs)
Convenience wrapper over telegram.Bot.get_file
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns telegram.File
Raises telegram.TelegramError
3.2.48 telegram.Voice
mime_type
Optional. MIME type of the file as defined by sender.
Type str
file_size
Optional. File size.
Type int
bot
Optional. The Bot to use for instance methods.
Type telegram.Bot
Parameters
• file_id (str) – Identifier for this file, which can be used to download or reuse the
file.
• file_unique_id (str) – Unique and the same over time and for different bots file
identifier.
• duration (int, optional) – Duration of the audio in seconds as defined by sender.
• mime_type (str, optional) – MIME type of the file as defined by sender.
• file_size (int, optional) – File size.
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.
get_file(timeout=None, **kwargs)
Convenience wrapper over telegram.Bot.get_file
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns telegram.File
Raises telegram.TelegramError
3.2.49 telegram.WebhookInfo
pending_update_count
Number of updates awaiting delivery.
Type int
last_error_date
Optional. Unix time for the most recent error that happened.
Type int
last_error_message
Optional. Error message in human-readable format.
Type str
max_connections
Optional. Maximum allowed number of simultaneous HTTPS connections.
Type int
allowed_updates
Optional. A list of update types the bot is subscribed to.
Type List[str]
Parameters
• url (str) – Webhook URL, may be empty if webhook is not set up.
• has_custom_certificate (bool) – True, if a custom certificate was provided
for webhook certificate checks.
• pending_update_count (int) – Number of updates awaiting delivery.
• last_error_date (int, optional) – Unix time for the most recent error that hap-
pened when trying todeliver an update via webhook.
• last_error_message (str, optional) – Error message in human-readable format
for the most recent error that happened when trying to deliver an update via webhook.
• max_connections (int, optional) – Maximum allowed number of simultaneous
HTTPS connections to the webhook for update delivery.
• allowed_updates (List[str], optional) – A list of update types the bot is sub-
scribed to. Defaults to all update types.
3.2.50 Stickers
telegram.Sticker
width
Sticker width.
Type int
height
Sticker height.
Type int
is_animated
True, if the sticker is animated.
Type bool
thumb
Optional. Sticker thumbnail in the .webp or .jpg format.
Type telegram.PhotoSize
emoji
Optional. Emoji associated with the sticker.
Type str
set_name
Optional. Name of the sticker set to which the sticker belongs.
Type str
mask_position
Optional. For mask stickers, the position where the mask should be placed.
Type telegram.MaskPosition
file_size
Optional. File size.
Type int
bot
Optional. The Bot to use for instance methods.
Type telegram.Bot
Parameters
• file_id (str) – Identifier for this file, which can be used to download or reuse the
file.
• file_unique_id (str) – Unique and the same over time and for different bots file
identifier.
• width (int) – Sticker width.
• height (int) – Sticker height.
• is_animated (bool) – True, if the sticker is animated.
• thumb (telegram.PhotoSize, optional) – Sticker thumbnail in the .webp or .jpg
format.
• emoji (str, optional) – Emoji associated with the sticker
• set_name (str, optional) – Name of the sticker set to which the sticker belongs.
• mask_position (telegram.MaskPosition, optional) – For mask stickers, the
position where the mask should be placed.
• file_size (int, optional) – File size.
• (obj (**kwargs) – dict): Arbitrary keyword arguments.7
get_file(timeout=None, **kwargs)
Convenience wrapper over telegram.Bot.get_file
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns telegram.File
Raises telegram.TelegramError
telegram.StickerSet
Parameters
• name (str) – Sticker set name.
• title (str) – Sticker set title.
• is_animated (bool) – True, if the sticker set contains animated stickers.
• contains_masks (bool) – True, if the sticker set contains masks.
• stickers (List[telegram.Sticker]) – List of all set stickers.
• thumb (telegram.PhotoSize, optional) – Sticker set thumbnail in the .WEBP or
.TGS format
telegram.MaskPosition
Note: type should be one of the following: forehead, eyes, mouth or chin. You can use the classconstants
for those.
Parameters
• point (str) – The part of the face relative to which the mask should be placed.
• x_shift (float) – Shift by X-axis measured in widths of the mask scaled to the face
size, from left to right. For example, choosing -1.0 will place mask just to the left of the
default mask position.
• y_shift (float) – Shift by Y-axis measured in heights of the mask scaled to the face
size, from top to bottom. For example, 1.0 will place the mask just below the default
mask position.
• scale (float) – Mask scaling coefficient. For example, 2.0 means double size.
CHIN = 'chin'
‘chin’
Type str
EYES = 'eyes'
‘eyes’
Type str
FOREHEAD = 'forehead'
‘forehead’
Type str
MOUTH = 'mouth'
‘mouth’
Type str
telegram.InlineQuery
Note:
• In Python from is a reserved word, use from_user instead.
id
Unique identifier for this query.
Type str
from_user
Sender.
Type telegram.User
location
Optional. Sender location, only for bots that request user location.
Type telegram.Location
query
Text of the query (up to 256 characters).
Type str
offset
Offset of the results to be returned, can be controlled by the bot.
Type str
Parameters
• id (str) – Unique identifier for this query.
• from_user (telegram.User) – Sender.
• location (telegram.Location, optional) – Sender location, only for bots that
request user location.
• query (str) – Text of the query (up to 256 characters).
• offset (str) – Offset of the results to be returned, can be controlled by the bot.
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.
answer(*args, **kwargs)
Shortcut for:
Parameters
• results (List[telegram.InlineQueryResult]) – A list of results for the
inline query.
• cache_time (int, optional) – The maximum amount of time in seconds that the
result of the inline query may be cached on the server. Defaults to 300.
• is_personal (bool, optional) – Pass True, if results may be cached on the server
side only for the user that sent the query. By default, results may be returned to any
user who sends the same query.
• next_offset (str, optional) – Pass the offset that a client should send in the next
query with the same text to receive more results. Pass an empty string if there are no
more results or if you don’t support pagination. Offset length can’t exceed 64 bytes.
• switch_pm_text (str, optional) – If passed, clients will display a button with
specified text that switches the user to a private chat with the bot and sends the bot a
start message with the parameter switch_pm_parameter.
• switch_pm_parameter (str, optional) – 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.
telegram.InlineQueryResult
Parameters
• type (str) – Type of the result.
• id (str) – Unique identifier for this result, 1-64 Bytes.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InlineQueryResultArticle
title
Title of the result.
Type str
input_message_content
Content of the message to be sent.
Type telegram.InputMessageContent
reply_markup
Optional. Inline keyboard attached to the message.
Type telegram.ReplyMarkup
url
Optional. URL of the result.
Type str
hide_url
Optional. Pass True, if you don’t want the URL to be shown in the message.
Type bool
description
Optional. Short description of the result.
Type str
thumb_url
Optional. Url of the thumbnail for the result.
Type str
thumb_width
Optional. Thumbnail width.
Type int
thumb_height
Optional. Thumbnail height.
Type int
Parameters
• id (str) – Unique identifier for this result, 1-64 Bytes.
• title (str) – Title of the result.
• input_message_content (telegram.InputMessageContent) – Content
of the message to be sent.
• reply_markup (telegram.ReplyMarkup, optional) – Inline keyboard attached
to the message
• url (str, optional) – URL of the result.
• hide_url (bool, optional) – Pass True, if you don’t want the URL to be shown in
the message.
• description (str, optional) – Short description of the result.
• thumb_url (str, optional) – Url of the thumbnail for the result.
• thumb_width (int, optional) – Thumbnail width.
• thumb_height (int, optional) – Thumbnail height.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InlineQueryResultAudio
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• audio_url (str) – A valid URL for the audio file.
telegram.InlineQueryResultCachedAudio
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• audio_file_id (str) – A valid file identifier for the audio file.
• caption (str, optional) – Caption, 0-1024 characters after entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.ParseMode for the available modes.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline key-
board attached to the message.
• input_message_content (telegram.InputMessageContent, optional) –
Content of the message to be sent instead of the audio.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InlineQueryResultCachedDocument
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the file.
Type telegram.InputMessageContent
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• title (str) – Title for the result.
• document_file_id (str) – A valid file identifier for the file.
• description (str, optional) – Short description of the result.
• caption (str, optional) – Caption of the document to be sent, 0-1024 characters after
entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption.. See the
constants in telegram.ParseMode for the available modes.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline key-
board attached to the message.
• input_message_content (telegram.InputMessageContent, optional) –
Content of the message to be sent instead of the file.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InlineQueryResultCachedGif
caption
Optional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing.
Type str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.ParseMode for the available
modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the gif.
Type telegram.InputMessageContent
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• gif_file_id (str) – A valid file identifier for the GIF file.
• title (str, optional) – Title for the result.caption (str, optional):
• caption (str, optional) – Caption of the GIF file to be sent, 0-1024 characters after
entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.ParseMode for the available modes.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline key-
board attached to the message.
• input_message_content (telegram.InputMessageContent, optional) –
Content of the message to be sent instead of the gif.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InlineQueryResultCachedMpeg4Gif
mpeg4_file_id
A valid file identifier for the MP4 file.
Type str
title
Optional. Title for the result.
Type str
caption
Optional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing.
Type str
parse_mode
Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline
URLs in the media caption. See the constants in telegram.ParseMode for the available modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the MPEG-4 file.
Type telegram.InputMessageContent
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• mpeg4_file_id (str) – A valid file identifier for the MP4 file.
• title (str, optional) – Title for the result.
• caption (str, optional) – Caption of the MPEG-4 file to be sent, 0-1024 characters
after entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.ParseMode for the available modes.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline key-
board attached to the message.
• input_message_content (telegram.InputMessageContent, optional) –
Content of the message to be sent instead of the MPEG-4 file.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InlineQueryResultCachedPhoto
type
‘photo’.
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
photo_file_id
A valid file identifier of the photo.
Type str
title
Optional. Title for the result.
Type str
description
Optional. Short description of the result.
Type str
caption
Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing.
Type str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.ParseMode for the available
modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the photo.
Type telegram.InputMessageContent
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• photo_file_id (str) – A valid file identifier of the photo.
• title (str, optional) – Title for the result.
• description (str, optional) – Short description of the result.
• caption (str, optional) – Caption of the photo to be sent, 0-1024 characters after
entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.ParseMode for the available modes.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline key-
board attached to the message.
• input_message_content (telegram.InputMessageContent, optional) –
Content of the message to be sent instead of the photo.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InlineQueryResultCachedSticker
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• sticker_file_id (str) – A valid file identifier of the sticker.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline key-
board attached to the message.
• input_message_content (telegram.InputMessageContent, optional) –
Content of the message to be sent instead of the sticker.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InlineQueryResultCachedVideo
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
video_file_id
A valid file identifier for the video file.
Type str
title
Title for the result.
Type str
description
Optional. Short description of the result.
Type str
caption
Optional. Caption of the video to be sent, 0-1024 characters after entities parsing.
Type str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.ParseMode for the available
modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the video.
Type telegram.InputMessageContent
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• video_file_id (str) – A valid file identifier for the video file.
• title (str) – Title for the result.
• description (str, optional) – Short description of the result.
• caption (str, optional) – Caption of the video to be sent, 0-1024 characters after
entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.ParseMode for the available modes.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline key-
board attached to the message.
• input_message_content (telegram.InputMessageContent, optional) –
Content of the message to be sent instead of the video.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InlineQueryResultCachedVoice
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• voice_file_id (str) – A valid file identifier for the voice message.
• title (str) – Voice message title.
• caption (str, optional) – Caption, 0-1024 characters after entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.ParseMode for the available modes.
telegram.InlineQueryResultContact
Type int
thumb_height
Optional. Thumbnail height.
Type int
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• phone_number (str) – Contact’s phone number.
• first_name (str) – Contact’s first name.
• last_name (str, optional) – Contact’s last name.
• vcard (str, optional) – Additional data about the contact in the form of a vCard,
0-2048 bytes.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline key-
board attached to the message.
• input_message_content (telegram.InputMessageContent, optional) –
Content of the message to be sent instead of the contact.
• thumb_url (str, optional) – Url of the thumbnail for the result.
• thumb_width (int, optional) – Thumbnail width.
• thumb_height (int, optional) – Thumbnail height.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InlineQueryResultDocument
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.ParseMode for the available
modes.
Type str
document_url
A valid URL for the file.
Type str
mime_type
Mime type of the content of the file, either “application/pdf” or “application/zip”.
Type str
description
Optional. Short description of the result.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the file.
Type telegram.InputMessageContent
thumb_url
Optional. URL of the thumbnail (jpeg only) for the file.
Type str
thumb_width
Optional. Thumbnail width.
Type int
thumb_height
Optional. Thumbnail height.
Type int
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• title (str) – Title for the result.
• caption (str, optional) – Caption of the document to be sent, 0-1024 characters after
entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.ParseMode for the available modes.
• document_url (str) – A valid URL for the file.
• mime_type (str) – Mime type of the content of the file, either “application/pdf” or
“application/zip”.
• description (str, optional) – Short description of the result.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline key-
board attached to the message.
telegram.InlineQueryResultGame
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• game_short_name (str) – Short name of the game.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline key-
board attached to the message.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InlineQueryResultGif
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
gif_url
A valid URL for the GIF file. File size must not exceed 1MB.
Type str
gif_width
Optional. Width of the GIF.
Type int
gif_height
Optional. Height of the GIF.
Type int
gif_duration
Optional. Duration of the GIF.
Type int
thumb_url
URL of the static thumbnail for the result (jpeg or gif).
Type str
thumb_mime_type
Optional. MIME type of the thumbnail.
Type str
title
Optional. Title for the result.
Type str
caption
Optional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing.
Type str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.ParseMode for the available
modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the GIF animation.
Type telegram.InputMessageContent
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• gif_url (str) – A valid URL for the GIF file. File size must not exceed 1MB.
• gif_width (int, optional) – Width of the GIF.
telegram.InlineQueryResultLocation
reply_markup
Optional. Inline keyboard attached to the message.
Type telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the location.
Type telegram.InputMessageContent
thumb_url
Optional. Url of the thumbnail for the result.
Type str
thumb_width
Optional. Thumbnail width.
Type int
thumb_height
Optional. Thumbnail height.
Type int
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• latitude (float) – Location latitude in degrees.
• longitude (float) – Location longitude in degrees.
• title (str) – Location title.
• live_period (int, optional) – Period in seconds for which the location can be
updated, should be between 60 and 86400.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline key-
board attached to the message.
• input_message_content (telegram.InputMessageContent, optional) –
Content of the message to be sent instead of the location.
• thumb_url (str, optional) – Url of the thumbnail for the result.
• thumb_width (int, optional) – Thumbnail width.
• thumb_height (int, optional) – Thumbnail height.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InlineQueryResultMpeg4Gif
type
‘mpeg4_gif’.
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
mpeg4_url
A valid URL for the MP4 file. File size must not exceed 1MB.
Type str
mpeg4_width
Optional. Video width.
Type int
mpeg4_height
Optional. Video height.
Type int
mpeg4_duration
Optional. Video duration.
Type int
thumb_url
URL of the static thumbnail (jpeg or gif) for the result.
Type str
thumb_mime_type
Optional. MIME type of the thumbnail.
Type str
title
Optional. Title for the result.
Type str
caption
Optional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing.
Type str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.ParseMode for the available
modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the video animation.
Type telegram.InputMessageContent
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• mpeg4_url (str) – A valid URL for the MP4 file. File size must not exceed 1MB.
telegram.InlineQueryResultPhoto
Type int
title
Optional. Title for the result.
Type str
description
Optional. Short description of the result.
Type str
caption
Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing.
Type str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.ParseMode for the available
modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the photo.
Type telegram.InputMessageContent
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• photo_url (str) – A valid URL of the photo. Photo must be in jpeg format. Photo
size must not exceed 5MB.
• thumb_url (str) – URL of the thumbnail for the photo.
• photo_width (int, optional) – Width of the photo.
• photo_height (int, optional) – Height of the photo.
• title (str, optional) – Title for the result.
• description (str, optional) – Short description of the result.
• caption (str, optional) – Caption of the photo to be sent, 0-1024 characters after
entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.ParseMode for the available modes.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline key-
board attached to the message.
• input_message_content (telegram.InputMessageContent, optional) –
Content of the message to be sent instead of the photo.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InlineQueryResultVenue
thumb_width
Optional. Thumbnail width.
Type int
thumb_height
Optional. Thumbnail height.
Type int
Parameters
• id (str) – Unique identifier for this result, 1-64 Bytes.
• latitude (float) – Latitude of the venue location in degrees.
• longitude (float) – Longitude of the venue location in degrees.
• title (str) – Title of the venue.
• address (str) – Address of the venue.
• foursquare_id (str, optional) – Foursquare identifier of the venue if known.
• foursquare_type (str, optional) – Foursquare type of the venue, if
known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or
“food/icecream”.)
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline key-
board attached to the message.
• input_message_content (telegram.InputMessageContent, optional) –
Content of the message to be sent instead of the location.
• thumb_url (str, optional) – Url of the thumbnail for the result.
• thumb_width (int, optional) – Thumbnail width.
• thumb_height (int, optional) – Thumbnail height.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InlineQueryResultVideo
Note: If an InlineQueryResultVideo message contains an embedded video (e.g., YouTube), you must
replace its content using input_message_content.
type
‘video’.
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
video_url
A valid URL for the embedded video player or video file.
Type str
mime_type
Mime type of the content of video url, “text/html” or “video/mp4”.
Type str
thumb_url
URL of the thumbnail (jpeg only) for the video.
Type str
title
Title for the result.
Type str
caption
Optional. Caption of the video to be sent, 0-1024 characters after entities parsing.
Type str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.ParseMode for the available
modes.
Type str
video_width
Optional. Video width.
Type int
video_height
Optional. Video height.
Type int
video_duration
Optional. Video duration in seconds.
Type int
description
Optional. Short description of the result.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the video. This field is required if Inline-
QueryResultVideo is used to send an HTML-page as a result (e.g., a YouTube video).
Type telegram.InputMessageContent
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• video_url (str) – A valid URL for the embedded video player or video file.
• mime_type (str) – Mime type of the content of video url, “text/html” or
“video/mp4”.
• thumb_url (str) – URL of the thumbnail (jpeg only) for the video.
• title (str) – Title for the result.
• caption (str, optional) – Caption, 0-1024 characters after entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.ParseMode for the available modes.
• video_width (int, optional) – Video width.
• video_height (int, optional) – Video height.
• video_duration (int, optional) – Video duration in seconds.
• description (str, optional) – Short description of the result.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline key-
board attached to the message.
• input_message_content (telegram.InputMessageContent, optional) –
Content of the message to be sent instead of the video. This field is required if Inline-
QueryResultVideo is used to send an HTML-page as a result (e.g., a YouTube video).
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InlineQueryResultVoice
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.ParseMode for the available
modes.
Type str
voice_duration
Optional. Recording duration in seconds.
Type int
reply_markup
Optional. Inline keyboard attached to the message.
Type telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the voice recording.
Type telegram.InputMessageContent
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• voice_url (str) – A valid URL for the voice recording.
• title (str) – Recording title.
• caption (str, optional) – Caption, 0-1024 characters after entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram
apps to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.ParseMode for the available modes.
• voice_duration (int, optional) – Recording duration in seconds.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline key-
board attached to the message.
• input_message_content (telegram.InputMessageContent, optional) –
Content of the message to be sent instead of the voice recording.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InputMessageContent
class telegram.InputMessageContent
Bases: telegram.base.TelegramObject
Base class for Telegram InputMessageContent Objects.
See: telegram.InputContactMessageContent, telegram.
InputLocationMessageContent, telegram.InputTextMessageContent and
telegram.InputVenueMessageContent for more details.
telegram.InputTextMessageContent
message_text
Text of the message to be sent, 1-4096 characters after entities parsing.
Type str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in your bot’s message.
Type str
disable_web_page_preview
Optional. Disables link previews for links in the sent message.
Type bool
Parameters
• message_text (str) – Text of the message to be sent, 1-4096 characters after enti-
ties parsing. Also found as telegram.constants.MAX_MESSAGE_LENGTH.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram apps
to show bold, italic, fixed-width text or inline URLs in your bot’s message.
• disable_web_page_preview (bool, optional) – Disables link previews for links
in the sent message.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InputLocationMessageContent
Parameters
• latitude (float) – Latitude of the location in degrees.
• longitude (float) – Longitude of the location in degrees.
• live_period (int, optional) – Period in seconds for which the location can be
updated, should be between 60 and 86400.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InputVenueMessageContent
latitude
Latitude of the location in degrees.
Type float
longitude
Longitude of the location in degrees.
Type float
title
Name of the venue.
Type str
address
Address of the venue.
Type str
foursquare_id
Optional. Foursquare identifier of the venue, if known.
Type str
foursquare_type
Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”,
“arts_entertainment/aquarium” or “food/icecream”.)
Type str
Parameters
• latitude (float) – Latitude of the location in degrees.
• longitude (float) – Longitude of the location in degrees.
• title (str) – Name of the venue.
• address (str) – Address of the venue.
• foursquare_id (str, optional) – Foursquare identifier of the venue, if known.
• foursquare_type (str, optional) – Foursquare type of the venue, if
known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or
“food/icecream”.)
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.InputContactMessageContent
Type str
vcard
Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes.
Type str
Parameters
• phone_number (str) – Contact’s phone number.
• first_name (str) – Contact’s first name.
• last_name (str, optional) – Contact’s last name.
• vcard (str, optional) – Additional data about the contact in the form of a vCard,
0-2048 bytes.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.ChosenInlineResult
result_id
The unique identifier for the result that was chosen.
Type str
from_user
The user that chose the result.
Type telegram.User
location
Optional. Sender location.
Type telegram.Location
inline_message_id
Optional. Identifier of the sent inline message.
Type str
query
The query that was used to obtain the result.
Type str
Parameters
• result_id (str) – The unique identifier for the result that was chosen.
• from_user (telegram.User) – The user that chose the result.
• location (telegram.Location, optional) – Sender location, only for bots that
require user location.
• inline_message_id (str, optional) – Identifier of the sent inline message. Avail-
able only if there is an inline keyboard attached to the message. Will be also received in
callback queries and can be used to edit the message.
• query (str) – The query that was used to obtain the result.
• **kwargs (dict) – Arbitrary keyword arguments.
3.2.52 Payments
telegram.LabeledPrice
Parameters
• label (str) – Portion label
• amount (int) – Price of the product in the smallest units of the currency (integer, not
float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp
parameter in currencies.json, it shows the number of digits past the decimal point for
each currency (2 for the majority of currencies).
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.Invoice
Parameters
• title (str) – Product name.
• description (str) – Product description.
• start_parameter (str) – Unique bot deep-linking parameter that can be used to
generate this invoice.
• currency (str) – Three-letter ISO 4217 currency code.
• total_amount (int) – Total price in the smallest units of the currency (integer, not
float/double). For example, for a price of US$ 1.45 pass amount = 145.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.ShippingAddress
Parameters
• country_code (str) – ISO 3166-1 alpha-2 country code.
• state (str) – State, if applicable.
• city (str) – City.
• street_line1 (str) – First line for the address.
• street_line2 (str) – Second line for the address.
• post_code (str) – Address post code.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.OrderInfo
Parameters
• name (str, optional) – User name.
• phone_number (str, optional) – User’s phone number.
• email (str, optional) – User email.
• shipping_address (telegram.ShippingAddress, optional) – User ship-
ping address.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.ShippingOption
Parameters
• id (str) – Shipping option identifier.
• title (str) – Option title.
• prices (List[telegram.LabeledPrice]) – List of price portions.
telegram.SuccessfulPayment
Parameters
• currency (str) – Three-letter ISO 4217 currency code.
• total_amount (int) – Total price in the smallest units of the currency (integer, not
float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp
parameter in currencies.json, it shows the number of digits past the decimal point for
each currency (2 for the majority of currencies).
• invoice_payload (str) – Bot specified invoice payload.
• shipping_option_id (str, optional) – Identifier of the shipping option chosen
by the user.
• order_info (telegram.OrderInfo, optional) – Order info provided by the user
• telegram_payment_charge_id (str) – Telegram payment identifier.
• provider_payment_charge_id (str) – Provider payment identifier.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.ShippingQuery
Note:
• In Python from is a reserved word, use from_user instead.
id
Unique query identifier.
Type str
from_user
User who sent the query.
Type telegram.User
invoice_payload
Bot specified invoice payload.
Type str
shipping_address
User specified shipping address.
Type telegram.ShippingAddress
bot
Optional. The Bot to use for instance methods.
Type telegram.Bot
Parameters
• id (str) – Unique query identifier.
• from_user (telegram.User) – User who sent the query.
• invoice_payload (str) – Bot specified invoice payload.
• shipping_address (telegram.ShippingAddress) – User specified ship-
ping address.
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.
answer(*args, **kwargs)
Shortcut for:
Parameters
• 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 possi-
ble).
• shipping_options (List[telegram.ShippingOption], optional) – Re-
quired if ok is True. A JSON-serialized array of available shipping options.
telegram.PreCheckoutQuery
Note:
• In Python from is a reserved word, use from_user instead.
id
Unique query identifier.
Type str
from_user
User who sent the query.
Type telegram.User
currency
Three-letter ISO 4217 currency code.
Type str
total_amount
Total price in the smallest units of the currency.
Type int
invoice_payload
Bot specified invoice payload.
Type str
shipping_option_id
Optional. Identifier of the shipping option chosen by the user.
Type str
order_info
Optional. Order info provided by the user.
Type telegram.OrderInfo
bot
Optional. The Bot to use for instance methods.
Type telegram.Bot
Parameters
• id (str) – Unique query identifier.
• from_user (telegram.User) – User who sent the query.
• currency (str) – Three-letter ISO 4217 currency code
• total_amount (int) – Total price in the smallest units of the currency (integer, not
float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp
parameter in currencies.json, it shows the number of digits past the decimal point for
each currency (2 for the majority of currencies).
• invoice_payload (str) – Bot specified invoice payload.
• shipping_option_id (str, optional) – Identifier of the shipping option chosen
by the user.
• order_info (telegram.OrderInfo, optional) – Order info provided by the user.
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.
answer(*args, **kwargs)
Shortcut for:
bot.answer_pre_checkout_query(update.pre_checkout_query.id, *args,
˓→**kwargs)
Parameters
• 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, optional) – 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.
• **kwargs (dict) – Arbitrary keyword arguments.
3.2.53 Games
telegram.Game
Type str
text_entities
Optional. Special entities that appear in text, such as usernames, URLs, bot commands, etc.
Type List[telegram.MessageEntity]
animation
Optional. Animation that will be displayed in the game message in chats. Upload via BotFather.
Type telegram.Animation
Parameters
• title (str) – Title of the game.
• description (str) – Description of the game.
• photo (List[telegram.PhotoSize]) – Photo that will be displayed in the game
message in chats.
• text (str, optional) – Brief description of the game or high scores included in the
game message. Can be automatically edited to include current high scores for the game
when the bot calls set_game_score, or manually edited using edit_message_text. 0-4096
characters. Also found as telegram.constants.MAX_MESSAGE_LENGTH.
• text_entities (List[telegram.MessageEntity], optional) – Special entities
that appear in text, such as usernames, URLs, bot commands, etc.
• animation (telegram.Animation, optional) – Animation that will be displayed
in the game message in chats. Upload via BotFather.
parse_text_entities(types=None)
Returns a dict that maps telegram.MessageEntity to str. It contains entities from this
message filtered by their type attribute as the key, and the text that each entity belongs to as the value
of the dict.
Note: This method should always be used instead of the text_entities attribute, since
it calculates the correct substring from the message text based on UTF-16 codepoints. See
parse_text_entity for more info.
parse_text_entity(entity)
Returns the text from a given telegram.MessageEntity.
Note: This method is present because Telegram calculates the offset and length in UTF-16 code-
point pairs, which some versions of Python don’t handle automatically. (That is, you can’t just slice
Message.text with the offset and length.)
telegram.Callbackgame
class telegram.CallbackGame
Bases: telegram.base.TelegramObject
A placeholder, currently holds no information. Use BotFather to set up your game.
telegram.GameHighScore
Parameters
• position (int) – Position in high score table for the game.
• user (telegram.User) – User.
• score (int) – Score.
3.2.54 Passport
telegram.PassportElementError
Parameters
telegram.PassportElementErrorFile
Parameters
• type (str) – The section of the user’s Telegram Passport which has the issue, one of
“utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “tempo-
rary_registration”.
• file_hash (str) – Base64-encoded file hash.
• message (str) – Error message.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.PassportElementErrorReverseSide
Parameters
• type (str) – The section of the user’s Telegram Passport which has the issue, one of
“driver_license”, “identity_card”.
• file_hash (str) – Base64-encoded hash of the file with the reverse side of the
document.
• message (str) – Error message.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.PassportElementErrorFrontSide
Parameters
• type (str) – The section of the user’s Telegram Passport which has the issue, one of
“passport”, “driver_license”, “identity_card”, “internal_passport”.
• file_hash (str) – Base64-encoded hash of the file with the front side of the docu-
ment.
• message (str) – Error message.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.PassportElementErrorFiles
Type str
Parameters
• type (str) – The section of the user’s Telegram Passport which has the issue, one of
“utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “tempo-
rary_registration”.
• file_hashes (List[str]) – List of base64-encoded file hashes.
• message (str) – Error message.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.PassportElementErrorDataField
Parameters
• type (str) – The section of the user’s Telegram Passport which has the error, one of
“personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”,
“address”.
• field_name (str) – Name of the data field which has the error.
• data_hash (str) – Base64-encoded data hash.
• message (str) – Error message.
• **kwargs (dict) – Arbitrary keyword arguments.
telegram.Credentials
nonce
Bot-specified nonce
Type str
telegram.DataCredentials
telegram.SecureData
telegram.FileCredentials
telegram.IdDocumentData
telegram.PersonalDetails
telegram.ResidentialAddress
street_line1
First line for the address.
Type str
street_line2
Optional. Second line for the address.
Type str
city
City.
Type str
state
Optional. State.
Type str
country_code
ISO 3166-1 alpha-2 country code.
Type str
post_code
Address post code.
Type str
telegram.PassportData
Parameters
• data (List[telegram.EncryptedPassportElement]) – Array with encrypted
information about documents and other Telegram Passport elements that was shared
with the bot.
• credentials (str) – Encrypted credentials.
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.
Note: To be able to decrypt this object, you must pass your private_key to either telegram.Updater
or telegram.Bot. Decrypted data is then found in decrypted_data and the payload can be found
in decrypted_credentials’s attribute telegram.Credentials.payload.
decrypted_credentials
Lazily decrypt and return credentials that were used to decrypt the data. This object also contains
the user specified payload as decrypted_data.payload.
decrypted_data
Lazily decrypt and return information about documents and other Telegram Passport elements
which were shared with the bot.
telegram.PassportFile
Parameters
• file_id (str) – Identifier for this file, which can be used to download or reuse the
file.
• file_unique_id (str) – Unique and the same over time and for different bots file
identifier.
• file_size (int) – File size.
• file_date (int) – Unix time when the file was uploaded.
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.
get_file(timeout=None, **kwargs)
Wrapper over telegram.Bot.get_file. Will automatically assign the correct creden-
tials to the returned telegram.File if originating from telegram.PassportData.
decrypted_data.
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns telegram.File
Raises telegram.TelegramError
telegram.EncryptedPassportElement
files
Optional. Array of encrypted/decrypted files with documents provided by the user, avail-
able for “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “tempo-
rary_registration” types.
Type List[telegram.PassportFile]
front_side
Optional. Encrypted/decrypted file with the front side of the document, provided by the user. Available
for “passport”, “driver_license”, “identity_card” and “internal_passport”.
Type telegram.PassportFile
reverse_side
Optional. Encrypted/decrypted file with the reverse side of the document, provided by the user. Avail-
able for “driver_license” and “identity_card”.
Type telegram.PassportFile
selfie
Optional. Encrypted/decrypted file with the selfie of the user holding a document, provided by the
user; available for “passport”, “driver_license”, “identity_card” and “internal_passport”.
Type telegram.PassportFile
translation
Optional. Array of encrypted/decrypted files with translated versions of documents provided
by the user. Available if requested for “passport”, “driver_license”, “identity_card”, “inter-
nal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and
“temporary_registration” types.
Type List[telegram.PassportFile]
hash
Base64-encoded element hash for using in telegram.PassportElementErrorUnspecified.
Type str
bot
Optional. The Bot to use for instance methods.
Type telegram.Bot
Parameters
• type (str) – Element type. One of “personal_details”, “passport”,
“driver_license”, “identity_card”, “internal_passport”, “address”, “utility_bill”,
“bank_statement”, “rental_agreement”, “passport_registration”, “tempo-
rary_registration”, “phone_number”, “email”.
• data (telegram.PersonalDetails or telegram.IdDocument or
telegram.ResidentialAddress or str, optional) – Decrypted or encrypted
data, available for “personal_details”, “passport”, “driver_license”, “identity_card”,
“identity_passport” and “address” types.
• phone_number (str, optional) – User’s verified phone number, available only for
“phone_number” type.
• email (str, optional) – User’s verified email address, available only for “email” type.
• files (List[telegram.PassportFile], optional) – Array of en-
crypted/decrypted files with documents provided by the user, available for “util-
ity_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “tempo-
rary_registration” types.
• front_side (telegram.PassportFile, optional) – Encrypted/decrypted file
with the front side of the document, provided by the user. Available for “passport”,
“driver_license”, “identity_card” and “internal_passport”.
telegram.EncryptedCredentials
Parameters
• data (telegram.Credentials or str) – Decrypted data with unique user’s
nonce, data hashes and secrets used for EncryptedPassportElement decryption and au-
thentication or base64 encrypted data.
• hash (str) – Base64-encoded data hash for data authentication.
• secret (str) – Decrypted or encrypted secret used for decryption.
• **kwargs (dict) – Arbitrary keyword arguments.
decrypted_data
Lazily decrypt and return credentials data. This object also contains the user specified nonce as
decrypted_data.nonce.
decrypted_secret
Lazily decrypt and return secret.
Raises telegram.TelegramDecryptionError – Decryption failed. Usually due to
bad private/public key but can also suggest malformed/tampered data.
Type str
DefaultOne = DefaultValue(1)
def f(arg=DefaultOne):
if arg is DefaultOne:
print('`arg` is the default')
arg = arg.value
else:
print('`arg` was set explicitly')
print('`arg` = ' + str(arg))
This yields:
>>> f()
`arg` is the default
`arg` = 1
>>> f(1)
`arg` was set explicitly
`arg` = 1
>>> f(2)
`arg` was set explicitly
`arg` = 2
default = DefaultValue(value)
if default:
...
is equivalent to:
default = DefaultValue(value)
if value:
...
value
The value of the default argument
Type obj
telegram.utils.helpers.create_deep_linked_url(bot_username, payload=None,
group=False)
Creates a deep-linked URL for this bot_username with the specified payload. See https://core.
telegram.org/bots#deep-linking to learn more.
The payload may consist of the following characters: A-Z, a-z, 0-9, _, -
Examples
create_deep_linked_url(bot.get_me().username, "some-params")
Parameters
• bot_username (str) – The username to link to
• payload (str, optional) – Parameters to encode in the created URL
• group (bool, optional) – If True the user is prompted to select a group to add the bot
to. If False, opens a one-on-one conversation with the bot. Defaults to False.
Returns An URL to start the bot with specific parameters
Return type str
telegram.utils.helpers.decode_conversations_from_json(json_string)
Helper method to decode a conversations dict (that uses tuples as keys) from a JSON-string created with
_encode_conversations_to_json.
Parameters json_string (str) – The conversations dict as JSON string.
Returns The conversations dict after decoding
Return type dict
telegram.utils.helpers.decode_user_chat_data_from_json(data)
Helper method to decode chat or user data (that uses ints as keys) from a JSON-string.
Parameters data (str) – The user/chat_data dict as JSON string.
Returns The user/chat_data defaultdict after decoding
Return type dict
telegram.utils.helpers.effective_message_type(entity)
Extracts the type of message as a string identifier from a telegram.Message or a telegram.Update.
Parameters entity (Update | Message) –
Returns One of Message.MESSAGE_TYPES
Return type str
telegram.utils.helpers.encode_conversations_to_json(conversations)
Helper method to encode a conversations dict (that uses tuples as keys) to a JSON-serializable way. Use
_decode_conversations_from_json to decode.
Parameters conversations (dict) – The conversations dict to transofrm to JSON.
Returns The JSON-serialized conversations dict
Return type str
telegram.utils.helpers.escape_markdown(text, version=1, entity_type=None)
Helper function to escape telegram markup symbols.
Parameters
• text (str) – The text.
• version (int | str) – Use to specify the version of telegrams Markdown. Either 1
or 2. Defaults to 1.
• entity_type (str, optional) – For the entity types PRE, CODE and the link part of
TEXT_LINKS, only certain characters need to be escaped in MarkdownV2. See the
official API documentation for details. Only valid in combination with version=2,
will be ignored else.
telegram.utils.helpers.from_timestamp(unixtime, tzinfo=datetime.timezone.utc)
Converts an (integer) unix timestamp to a timezone aware datetime object. None s are left alone (i.e.
from_timestamp(None) is None).
Parameters
• unixtime (int) – integer POSIX timestamp
• tzinfo (datetime.tzinfo, optional) – The timezone, the timestamp is to be con-
verted to. Defaults to UTC.
Returns timezone aware equivalent datetime.datetime value if timestamp is not
None; else None
telegram.utils.helpers.get_signal_name(signum)
Returns the signal name of the given signal number.
telegram.utils.helpers.mention_html(user_id, name)
Parameters
• user_id (int) –
• name (str) –
Returns The inline mention for the user as html.
Return type str
telegram.utils.helpers.mention_markdown(user_id, name, version=1)
Parameters
• user_id (int) –
• name (str) –
• version (int | str) – Use to specify the version of telegrams Markdown. Either 1
or 2. Defaults to 1
3.3.2 telegram.utils.promise.Promise
pooled_function
The callable that will be called concurrently.
Type callable
args
Positional arguments for pooled_function.
Type list | tuple
kwargs
Keyword arguments for pooled_function.
Type dict
done
Is set when the result is available.
Type threading.Event
exception
The exception raised by pooled_function or None if no exception has been raised (yet).
result(timeout=None)
Return the result of the Promise.
Parameters timeout (float, optional) – Maximum time in seconds to wait for the result
to be calculated. None means indefinite. Default is None.
Returns Returns the return value of pooled_function or None if the timeout ex-
pires.
Raises Any exception raised by pooled_function.
run()
Calls the pooled_function callable.
3.3.3 telegram.utils.request.Request
3.4 Changelog
3.4.1 Changelog
Version 12.8
Released 2020-06-22
Major Changes:
• Remove Python 2 support (#1715)
• Bot API 4.9 support (#1980)
• IDs/Usernames of Filters.user and Filters.chat can now be updated (#1757)
Minor changes, CI improvements, doc fixes or bug fixes:
• Update contribution guide and stale bot (#1937)
• Remove NullHandlers (#1913)
• Improve and expand examples (#1943, #1995, #1983, #1997)
Version 12.7
Released 2020-05-02
Major Changes:
• Bot API 4.8 support. Note: The Dice object now has a second positional argument emoji. This is
relevant, if you instantiate Dice objects manually. (#1917)
New Features:
• New method run_mothly for the JobQueue (#1705)
• Job.next_t now gives the datetime of the jobs next execution (#1685)
Minor changes, CI improvements, doc fixes or bug fixes:
• Added tzinfo argument to helpers.from_timestamp (#1621)
• Stabalize CI (#1919, #1931)
• Use ABCs @abstractmethod instead of raising NotImplementedError for Handler,
BasePersistence and BaseFilter (#1905)
• Doc fixes (#1914, #1902, #1910)
Version 12.6.1
Released 2020-04-11
Bug fixes:
• Fix serialization of reply_markup in media messages (#1889)
Version 12.6
Released 2020-04-10
Major Changes:
• Bot API 4.7 support. Note: In Bot.create_new_sticker_set and Bot.
add_sticker_to_set, the order of the parameters had be changed, as the png_sticker parameter
is now optional. (#1858)
Minor changes, CI improvements or bug fixes:
• Add tests for swtich_inline_query(_current_chat) with empty string (#1635)
• Doc fixes (#1854, #1874, #1884)
• Update issue templates (#1880)
• Favor concrete types over “Iterable” (#1882)
• Pass last valid CallbackContext to TIMEOUT handlers of ConversationHandler (#1826)
• Tweak handling of persistence and update persistence after job calls (#1827)
• Use checkout@v2 for GitHub actions (#1887)
Version 12.5.1
Released 2020-03-30
Minor changes, doc fixes or bug fixes:
• Add missing docs for PollHandler and PollAnswerHandler (#1853)
• Fix wording in Filters docs (#1855)
• Reorder tests to make them more stable (#1835)
• Make ConversationHandler attributes immutable (#1756)
• Make PrefixHandler attributes command and prefix editable (#1636)
• Fix UTC as default tzinfo for Job (#1696)
Version 12.5
Released 2020-03-29
New Features:
• Bot.link gives the t.me link of the bot (#1770)
Major Changes:
• Bot API 4.5 and 4.6 support. (#1508, #1723)
Minor changes, CI improvements or bug fixes:
• Remove legacy CI files (#1783, #1791)
• Update pre-commit config file (#1787)
• Remove builtin names (#1792)
• CI improvements (#1808, #1848)
• Support Python 3.8 (#1614, #1824)
• Use stale bot for auto closing stale issues (#1820, #1829, #1840)
• Doc fixes (#1778, #1818)
• Fix typo in edit_message_media (#1779)
• In examples, answer CallbackQueries and use edit_message_text shortcut (#1721)
• Revert accidental change in vendored urllib3 (#1775)
Version 12.4.2
Released 2020-02-10
Bug Fixes
• Pass correct parse_mode to InlineResults if bot.defaults is None (#1763)
• Make sure PP can read files that dont have bot_data (#1760)
Version 12.4.1
Released 2020-02-08
This is a quick release for #1744 which was accidently left out of v12.4.0 though mentioned in the release notes.
Version 12.4.0
Released 2020-02-08
New features:
• Set default values for arguments appearing repeatedly. We also have a wiki page for the new defaults.
(#1490)
• Store data in CallbackContext.bot_data to access it in every callback. Also persists. (#1325)
• Filters.poll allows only messages containing a poll (#1673)
Major changes:
• Filters.text now accepts messages that start with a slash, because CommandHandler checks for
MessageEntity.BOT_COMMAND since v12. This might lead to your MessageHandlers receiving more
updates than before (#1680).
• Filters.command new checks for MessageEntity.BOT_COMMAND instead of just a leading slash.
Also by Filters.command(False) you can now filters for messages containing a command anywhere
in the text (#1744).
Minor changes, CI improvements or bug fixes:
• Add disptacher argument to Updater to allow passing a customized Dispatcher (#1484)
• Add missing names for Filters (#1632)
• Documentation fixes (#1624, #1647, #1669, #1703, #1718, #1734, #1740, #1642, #1739, #1746)
• CI improvements (#1716, #1731, #1738, #1748, #1749, #1750, #1752)
• Fix spelling issue for encode_conversations_to_json (#1661)
• Remove double assignement of Dispatcher.job_queue (#1698)
• Expose dispatcher as property for CallbackContext (#1684)
• Fix None check in JobQueue._put() (#1707)
• Log datetimes correctly in JobQueue (#1714)
• Fix false Message.link creation for private groups (#1741)
• Add option --with-upstream-urllib3 to setup.py to allow using non-vendored version (#1725)
• Fix persistence for nested ConversationHandlers (#1679)
• Improve handling of non-decodable server responses (#1623)
• Fix download for files without file_path (#1591)
• test_webhook_invalid_posts is now considered flaky and retried on failure (#1758)
Version 12.3.0
Released 2020-01-11
New features:
• Filters.caption allows only messages with caption (#1631).
• Filter for exact messages/captions with new capability of Filters.text and Filters.caption. Especially useful
in combination with ReplyKeyboardMarkup. (#1631).
Major changes:
• Fix inconsistent handling of naive datetimes (#1506).
Minor changes, CI improvements or bug fixes:
Version 12.2.0
Released 2019-10-14
New features:
• Nested ConversationHandlers (#1512).
Minor changes, CI improvments or bug fixes:
• Fix CI failures due to non-backward compat attrs depndency (#1540).
• travis.yaml: TEST_OFFICIAL removed from allowed_failures.
• Fix typos in examples (#1537).
• Fix Bot.to_dict to use proper first_name (#1525).
• Refactor test_commandhandler.py (#1408).
• Add Python 3.8 (RC version) to Travis testing matrix (#1543).
• test_bot.py: Add to_dict test (#1544).
• Flake config moved into setup.cfg (#1546).
Version 12.1.1
Released 2019-09-18
Hot fix release
Fixed regression in the vendored urllib3 (#1517).
Version 12.1.0
Released 2019-09-13
Major changes:
• Bot API 4.4 support (#1464, #1510)
• Add get_file method to Animation & ChatPhoto. Add, get_small_file & get_big_file methods to ChatPhoto
(#1489)
• Tools for deep linking (#1049)
Minor changes and/or bug fixes:
• Documentation fixes (#1500, #1499)
• Improved examples (#1502)
Version 12.0.0
Released 2019-08-29
Well. . . This felt like decades. But here we are with a new release.
Expect minor releases soon (mainly complete Bot API 4.4 support)
Major and/or breaking changes:
• Context based callbacks
• Persistence
• PrefixHandler added (Handler overhaul)
• Deprecation of RegexHandler and edited_messages, channel_post, etc. arguments (Filter overhaul)
• Various ConversationHandler changes and fixes
• Bot API 4.1, 4.2, 4.3 support
• Python 3.4 is no longer supported
• Error Handler now handles all types of exceptions (#1485)
• Return UTC from from_timestamp() (#1485)
See the wiki page at https://git.io/fxJuV for a detailed guide on how to migrate from version 11 to version
12.
Persistence (#1017)
• CommandHandler now only triggers on actual commands as defined by telegram servers (everything that
the clients mark as a tabable link).
• PrefixHandler can be used if you need to trigger on prefixes (like all messages starting with a “/” (old
CommandHandler behaviour) or even custom prefixes like “#” or “!”).
• RegexHandler is deprecated and should be replaced with a MessageHandler with a regex filter.
• Use update filters to filter update types instead of arguments (message_updates, channel_post_updates and
edited_updates) on the handlers.
• Completely remove allow_edited argument - it has been deprecated for a while.
• data_filters now exist which allows filters that return data into the callback function. This is how the regex
filter is implemented.
• All this means that it no longer possible to use a list of filters in a handler. Use bitwise operators instead!
ConversationHandler
Internal improvements
• Finally fix our CI builds mostly (too many commits and PRs to list)
• Use multiple bots for CI to improve testing times significantly.
• Allow pypy to fail in CI.
• Remove the last CamelCase CheckUpdate methods from the handlers we missed earlier.
• test_official is now executed in a different job
Version 11.1.0
Released 2018-09-01
Fixes and updates for Telegram Passport: (#1198)
• Fix passport decryption failing at random times
• Added support for middle names.
• Added support for translations for documents
• Add errors for translations for documents
• Added support for requesting names in the language of the user’s country of residence
• Replaced the payload parameter with the new parameter nonce
• Add hash to EncryptedPassportElement
Version 11.0.0
Released 2018-08-29
Fully support Bot API version 4.0! (also some bugfixes :))
Telegram Passport (#1174):
• Add full support for telegram passport.
Version 10.1.0
Released 2018-05-02
Fixes changing previous behaviour:
• Add urllib3 fix for socks5h support (#1085)
• Fix send_sticker() timeout=20 (#1088)
Fixes:
• Add a caption_entity filter for filtering caption entities (#1068)
• Inputfile encode filenames (#1086)
• InputFile: Fix proper naming of file when reading from subprocess.PIPE (#1079)
• Remove pytest-catchlog from requirements (#1099)
• Documentation fixes (#1061, #1078, #1081, #1096)
Version 10.0.2
Released 2018-04-17
Important fix:
• Handle utf8 decoding errors (#1076)
New features:
• Added Filter.regex (#1028)
• Filters for Category and file types (#1046)
• Added video note filter (#1067)
Fixes:
• Fix in telegram.Message (#1042)
• Make chat_id a positional argument inside shortcut methods of Chat and User classes (#1050)
• Make Bot.full_name return a unicode object. (#1063)
• CommandHandler faster check (#1074)
• Correct documentation of Dispatcher.add_handler (#1071)
• Various small fixes to documentation.
Version 10.0.1
Released 2018-03-05
Fixes:
• Fix conversationhandler timeout (PR #1032)
• Add missing docs utils (PR #912)
Version 10.0.0
Released 2018-03-02
Non backward compatabile changes and changed defaults
• JobQueue: Remove deprecated prevent_autostart & put() (PR #1012)
• Bot, Updater: Remove deprecated network_delay (PR #1012)
• Remove deprecated Message.new_chat_member (PR #1012)
• Retry bootstrap phase indefinitely (by default) on network errors (PR #1018)
New Features
• Support v3.6 API (PR #1006)
Version 9.0.0
Released 2017-12-08
Breaking changes (possibly)
• Drop support for python 3.3 (PR #930)
New Features
• Support Bot API 3.5 (PR #920)
Changes
• Fix race condition in dispatcher start/stop (#887)
• Log error trace if there is no error handler registered (#694)
• Update examples with consistent string formatting (#870)
• Various changes and improvements to the docs.
Version 8.1.1
Released 2017-10-15
• Fix Commandhandler crashing on single character messages (PR #873).
Version 8.1.0
Released 2017-10-14
New features - Support Bot API 3.4 (PR #865).
Changes - MessageHandler & RegexHandler now consider channel_updates. - Fix command not recognized if it
is directly followed by a newline (PR #869). - Removed Bot._message_wrapper (PR #822). - Unitests are now
also running on AppVeyor (Windows VM). - Various unitest improvements. - Documentation fixes.
Version 8.0.0
Released 2017-09-01
New features
• Fully support Bot Api 3.3 (PR #806).
• DispatcherHandlerStop (see docs).
• Regression fix for text_html & text_markdown (PR #777).
• Added effective_attachment to message (PR #766).
Non backward compatible changes
• Removed Botan support from the library (PR #776).
• Fully support Bot Api 3.3 (PR #806).
• Remove de_json() (PR #789).
Changes
• Sane defaults for tcp socket options on linux (PR #754).
• Add RESTRICTED as constant to ChatMember (PR #761).
• Add rich comparison to CallbackQuery (PR #764).
• Fix get_game_high_scores (PR #771).
• Warn on small con_pool_size during custom initalization of Updater (PR #793).
• Catch exceptions in error handlerfor errors that happen during polling (PR #810).
• For testing we switched to pytest (PR #788).
• Lots of small improvements to our tests and documentation.
Version 7.0.1
Released 2017-07-28
• Fix TypeError exception in RegexHandler (PR #751).
• Small documentation fix (PR #749).
Version 7.0.0
Released 2017-07-25
• Fully support Bot API 3.2.
• New filters for handling messages from specific chat/user id (PR #677).
• Add the possibility to add objects as arguments to send_* methods (PR #742).
• Fixed download of URLs with UTF-8 chars in path (PR #688).
Pre-version 7.0
2017-06-18
Released 6.1.0
• Fully support Bot API 3.0
• Add more fine-grained filters for status updates
• Bug fixes and other improvements
2017-05-29
Released 6.0.3
• Faulty PyPI release
2017-05-29
Released 6.0.2
• Avoid confusion with user’s urllib3 by renaming vendored urllib3 to ptb_urllib3
2017-05-19
Released 6.0.1
• Add support for User.language_code
• Fix Message.text_html and Message.text_markdown for messages with emoji
2017-05-19
Released 6.0.0
• Add support for Bot API 2.3.1
• Add support for deleteMessage API method
• New, simpler API for JobQueue - https://github.com/python-telegram-bot/python-telegram-bot/pull/484
• Download files into file-like objects - https://github.com/python-telegram-bot/python-telegram-bot/pull/
459
• Use vendor urllib3 to address issues with timeouts - The default timeout for messages is now 5 seconds.
For sending media, the default timeout is now 20 seconds.
• String attributes that are not set are now None by default, instead of empty strings
• Add text_markdown and text_html properties to Message - https://github.com/
python-telegram-bot/python-telegram-bot/pull/507
• PEP8 improvements
2015-07-08
Released 1.1
• PyPi package now available
2015-07-08
Released 1.0
• Initial checkin of python-telegram-bot
t
telegram.constants, 122
telegram.error, 126
telegram.ext.filters, 11
telegram.utils.helpers, 230
257
Python Telegram Bot Documentation, Release 12.8
259
Python Telegram Bot Documentation, Release 12.8
gram.InlineQueryResultCachedAudio at- C
tribute), 183 callback (telegram.ext.CallbackQueryHandler at-
audio_url (telegram.InlineQueryResultAudio tribute), 33
attribute), 182 callback (telegram.ext.ChosenInlineResultHandler
author_signature (telegram.Message attribute), attribute), 35
142 callback (telegram.ext.CommandHandler attribute),
39
B callback (telegram.ext.Handler attribute), 31
BadRequest, 126 callback (telegram.ext.InlineQueryHandler at-
bank_statement (telegram.SecureData attribute), tribute), 41
223 callback (telegram.ext.Job attribute), 21
BaseFilter (class in telegram.ext.filters), 19 callback (telegram.ext.MessageHandler attribute),
BasePersistence (class in telegram.ext), 58 43
BASKETBALL (telegram.Dice attribute), 124 callback (telegram.ext.PollAnswerHandler at-
basketball (telegram.ext.filters.Filters attribute), tribute), 45
13 callback (telegram.ext.PollHandler attribute), 46
big_file_id (telegram.ChatPhoto attribute), 121 callback (telegram.ext.PreCheckoutQueryHandler
big_file_unique_id (telegram.ChatPhoto attribute), 48
attribute), 121 callback (telegram.ext.PrefixHandler attribute), 49
birth_date (telegram.PersonalDetails attribute), callback (telegram.ext.RegexHandler attribute), 51
224 callback (telegram.ext.ShippingQueryHandler at-
BOLD (telegram.MessageEntity attribute), 155 tribute), 53
Bot (class in telegram), 67 callback (telegram.ext.StringCommandHandler at-
bot (telegram.Animation attribute), 65 tribute), 54
bot (telegram.Audio attribute), 66 callback (telegram.ext.StringRegexHandler at-
bot (telegram.CallbackQuery attribute), 109 tribute), 56
bot (telegram.Document attribute), 125 callback (telegram.ext.TypeHandler attribute), 57
bot (telegram.EncryptedPassportElement attribute), callback_data (telegram.InlineKeyboardButton
228 attribute), 129
bot (telegram.ext.CallbackContext attribute), 29 callback_game (telegram.InlineKeyboardButton
bot (telegram.ext.Dispatcher attribute), 8 attribute), 129
bot (telegram.ext.JobQueue attribute), 23 callback_query (telegram.Update attribute), 165
bot (telegram.ext.Updater attribute), 5 CallbackContext (class in telegram.ext), 28
bot (telegram.Message attribute), 143 CallbackGame (class in telegram), 218
bot (telegram.PassportData attribute), 225 CallbackQuery (class in telegram), 108
bot (telegram.PassportFile attribute), 226 CallbackQueryHandler (class in telegram.ext),
bot (telegram.PhotoSize attribute), 157 33
bot (telegram.PreCheckoutQuery attribute), 215 can_add_web_page_previews (tele-
bot (telegram.ShippingQuery attribute), 214 gram.ChatMember attribute), 118
bot (telegram.Sticker attribute), 176 can_add_web_page_previews (tele-
bot (telegram.User attribute), 167 gram.ChatPermissions attribute), 120
bot (telegram.Video attribute), 171 can_be_edited (telegram.ChatMember attribute),
bot (telegram.VideoNote attribute), 173 117
bot (telegram.Voice attribute), 174 can_change_info (telegram.ChatMember at-
BOT_COMMAND (telegram.MessageEntity attribute), tribute), 117
155 can_change_info (telegram.ChatPermissions at-
bot_data (telegram.ext.CallbackContext attribute), tribute), 120
29 can_delete_messages (telegram.ChatMember
bot_data (telegram.ext.DictPersistence attribute), 63 attribute), 117
bot_data (telegram.ext.Dispatcher attribute), 8 can_edit_messages (telegram.ChatMember at-
bot_data_json (telegram.ext.DictPersistence at- tribute), 117
tribute), 63 can_invite_users (telegram.ChatMember at-
bot_username (telegram.LoginUrl attribute), 138 tribute), 118
BotCommand (class in telegram), 108 can_invite_users (telegram.ChatPermissions at-
burst_limit (telegram.ext.DelayQueue attribute), tribute), 120
27 can_join_groups (telegram.Bot attribute), 71
can_join_groups (telegram.User attribute), 167
260 Index
Python Telegram Bot Documentation, Release 12.8
Index 261
Python Telegram Bot Documentation, Release 12.8
262 Index
Python Telegram Bot Documentation, Release 12.8
Index 263
Python Telegram Bot Documentation, Release 12.8
264 Index
Python Telegram Bot Documentation, Release 12.8
Index 265
Python Telegram Bot Documentation, Release 12.8
266 Index
Python Telegram Bot Documentation, Release 12.8
Index 267
Python Telegram Bot Documentation, Release 12.8
268 Index
Python Telegram Bot Documentation, Release 12.8
Index 269
Python Telegram Bot Documentation, Release 12.8
M message (telegram.PassportElementErrorFiles
map_to_parent (telegram.ext.ConversationHandler attribute), 220
attribute), 37 message (telegram.PassportElementErrorFrontSide
MARKDOWN (telegram.ParseMode attribute), 156 attribute), 220
MARKDOWN_V2 (telegram.ParseMode attribute), 156 message (telegram.PassportElementErrorReverseSide
mask_position (telegram.Sticker attribute), 176 attribute), 219
MaskPosition (class in telegram), 178 message (telegram.Update attribute), 164
match (telegram.ext.CallbackContext attribute), 30 message_id (telegram.Message attribute), 139
matches (telegram.ext.CallbackContext attribute), 29 message_text (telegram.InputTextMessageContent
MAX_CAPTION_LENGTH (in module tele- attribute), 206
gram.constants), 122 message_updates (telegram.ext.MessageHandler
max_connections (telegram.WebhookInfo at- attribute), 44
tribute), 175 MessageEntity (class in telegram), 154
MAX_FILESIZE_DOWNLOAD (in module tele- MessageHandler (class in telegram.ext), 43
gram.constants), 122 MessageQueue (class in telegram.ext), 26
MAX_FILESIZE_UPLOAD (in module tele- messages (telegram.ext.filters.Filters attribute), 18
gram.constants), 123 middle_name (telegram.PersonalDetails attribute),
MAX_INLINE_QUERY_RESULTS (in module tele- 224
gram.constants), 123 middle_name_native (telegram.PersonalDetails
MAX_MESSAGE_ENTITIES (in module tele- attribute), 224
gram.constants), 123 migrate (telegram.ext.filters.Filters attribute), 17
MAX_MESSAGE_LENGTH (in module tele- migrate_from_chat_id (telegram.Message at-
gram.constants), 122 tribute), 142
MAX_MESSAGES_PER_MINUTE_PER_GROUP (in migrate_to_chat_id (telegram.Message at-
module telegram.constants), 123 tribute), 142
MAX_MESSAGES_PER_SECOND (in module tele- mime_type (telegram.Animation attribute), 65
gram.constants), 123 mime_type (telegram.Audio attribute), 66
MAX_MESSAGES_PER_SECOND_PER_CHAT (in mime_type (telegram.Document attribute), 125
module telegram.constants), 123 mime_type (telegram.ext.filters.Filters attribute), 14
MAX_PHOTOSIZE_UPLOAD (in module tele- mime_type (telegram.InlineQueryResultDocument
gram.constants), 123 attribute), 194
media (telegram.InputMediaAnimation attribute), 131 mime_type (telegram.InlineQueryResultVideo
media (telegram.InputMediaAudio attribute), 133 attribute), 204
media (telegram.InputMediaDocument attribute), 134 mime_type (telegram.Video attribute), 171
media (telegram.InputMediaPhoto attribute), 135 mime_type (telegram.Voice attribute), 173
media (telegram.InputMediaVideo attribute), 135 MOUTH (telegram.MaskPosition attribute), 178
media_group_id (telegram.Message attribute), 140 mp3 (telegram.ext.filters.Filters attribute), 15
MEMBER (telegram.ChatMember attribute), 119 mpeg4_duration (tele-
MENTION (telegram.MessageEntity attribute), 156 gram.InlineQueryResultMpeg4Gif attribute),
mention_html() (in module tele- 199
gram.utils.helpers), 232 mpeg4_file_id (tele-
mention_html() (telegram.User method), 168 gram.InlineQueryResultCachedMpeg4Gif
mention_markdown() (in module tele- attribute), 187
gram.utils.helpers), 232 mpeg4_height (tele-
mention_markdown() (telegram.User method), gram.InlineQueryResultMpeg4Gif attribute),
168 199
mention_markdown_v2() (telegram.User mpeg4_url (telegram.InlineQueryResultMpeg4Gif
method), 168 attribute), 199
MergedFilter (class in telegram.ext.filters), 21 mpeg4_width (tele-
Message (class in telegram), 139 gram.InlineQueryResultMpeg4Gif attribute),
message (telegram.CallbackQuery attribute), 109 199
message (telegram.ext.filters.Filters attribute), 18
message (telegram.PassportElementError attribute),
N
218 name (telegram.Bot attribute), 83
message (telegram.PassportElementErrorDataField name (telegram.ext.ConversationHandler attribute), 37
attribute), 221 name (telegram.ext.DelayQueue attribute), 27
message (telegram.PassportElementErrorFile at- name (telegram.ext.filters.BaseFilter attribute), 20
tribute), 219 name (telegram.ext.Job attribute), 21
270 Index
Python Telegram Bot Documentation, Release 12.8
Index 271
Python Telegram Bot Documentation, Release 12.8
272 Index
Python Telegram Bot Documentation, Release 12.8
31 attribute), 182
pass_user_data (tele- performer (telegram.InputMediaAudio attribute),
gram.ext.InlineQueryHandler attribute), 133
42 permissions (telegram.Chat attribute), 112
pass_user_data (telegram.ext.MessageHandler persistence (telegram.ext.Dispatcher attribute), 8
attribute), 43 persistence (telegram.ext.Updater attribute), 6
pass_user_data (telegram.ext.PollAnswerHandler persistent (telegram.ext.ConversationHandler at-
attribute), 45 tribute), 37
pass_user_data (telegram.ext.PollHandler at- personal_details (telegram.SecureData at-
tribute), 47 tribute), 222
pass_user_data (tele- PersonalDetails (class in telegram), 224
gram.ext.PreCheckoutQueryHandler at- phone_number (telegram.Contact attribute), 123
tribute), 48 phone_number (tele-
pass_user_data (telegram.ext.PrefixHandler at- gram.EncryptedPassportElement attribute),
tribute), 50 227
pass_user_data (telegram.ext.RegexHandler at- phone_number (telegram.InlineQueryResultContact
tribute), 52 attribute), 192
pass_user_data (tele- phone_number (tele-
gram.ext.ShippingQueryHandler attribute), gram.InputContactMessageContent at-
53 tribute), 208
passport (telegram.SecureData attribute), 222 PHONE_NUMBER (telegram.MessageEntity attribute),
passport_data (telegram.ext.filters.Filters at- 156
tribute), 16 phone_number (telegram.OrderInfo attribute), 212
passport_data (telegram.Message attribute), 142 photo (telegram.Chat attribute), 111
passport_registration (telegram.SecureData photo (telegram.ext.filters.Filters attribute), 16
attribute), 223 photo (telegram.Game attribute), 216
PassportData (class in telegram), 225 photo (telegram.Message attribute), 140
PassportElementError (class in telegram), 218 photo_file_id (tele-
PassportElementErrorDataField (class in gram.InlineQueryResultCachedPhoto at-
telegram), 221 tribute), 188
PassportElementErrorFile (class in tele- photo_height (telegram.InlineQueryResultPhoto
gram), 219 attribute), 200
PassportElementErrorFiles (class in tele- photo_url (telegram.InlineQueryResultPhoto
gram), 220 attribute), 200
PassportElementErrorFrontSide (class in photo_width (telegram.InlineQueryResultPhoto at-
telegram), 220 tribute), 200
PassportElementErrorReverseSide (class in photos (telegram.UserProfilePhotos attribute), 170
telegram), 219 PhotoSize (class in telegram), 157
PassportFile (class in telegram), 226 PicklePersistence (class in telegram.ext), 60
pattern (telegram.ext.CallbackQueryHandler pin_chat_message() (telegram.Bot method), 83
attribute), 33 pinChatMessage() (telegram.Bot method), 83
pattern (telegram.ext.InlineQueryHandler at- pinned_message (telegram.Chat attribute), 112
tribute), 41 pinned_message (telegram.ext.filters.Filters
pattern (telegram.ext.RegexHandler attribute), 51 attribute), 17
pattern (telegram.ext.StringRegexHandler at- pinned_message (telegram.Message attribute), 142
tribute), 56 point (telegram.MaskPosition attribute), 178
pay (telegram.InlineKeyboardButton attribute), 129 Poll (class in telegram), 158
pdf (telegram.ext.filters.Filters attribute), 15 poll (telegram.ext.filters.Filters attribute), 16
pending_update_count (telegram.WebhookInfo poll (telegram.Message attribute), 142
attribute), 174 poll (telegram.Update attribute), 165
per_chat (telegram.ext.ConversationHandler at- poll_answer (telegram.Update attribute), 165
tribute), 37 poll_id (telegram.PollAnswer attribute), 160
per_message (telegram.ext.ConversationHandler PollAnswer (class in telegram), 160
attribute), 37 PollAnswerHandler (class in telegram.ext), 45
per_user (telegram.ext.ConversationHandler at- PollHandler (class in telegram.ext), 46
tribute), 37 PollOption (class in telegram), 160
performer (telegram.Audio attribute), 66 pooled_function (telegram.utils.promise.Promise
performer (telegram.InlineQueryResultAudio attribute), 233
Index 273
Python Telegram Bot Documentation, Release 12.8
274 Index
Python Telegram Bot Documentation, Release 12.8
Index 275
Python Telegram Bot Documentation, Release 12.8
276 Index
Python Telegram Bot Documentation, Release 12.8
Index 277
Python Telegram Bot Documentation, Release 12.8
278 Index
Python Telegram Bot Documentation, Release 12.8
Index 279
Python Telegram Bot Documentation, Release 12.8
280 Index