Python Telegram Bot Readthedocs Io en Stable
Python Telegram Bot Readthedocs Io en Stable
Release 13.5
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.1.4 telegram.ext.CallbackContext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.1.5 telegram.ext.Defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.1.6 telegram.ext.Job . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.1.7 telegram.ext.JobQueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.1.8 telegram.ext.MessageQueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.1.9 telegram.ext.DelayQueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.1.10 Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.1.11 Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
3.1.12 utils . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
3.2 telegram package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
3.2.1 telegram.Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
3.2.2 telegram.Audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
3.2.3 telegram.Bot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
3.2.4 telegram.BotCommand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
3.2.5 telegram.CallbackQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
3.2.6 telegram.Chat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
3.2.7 telegram.ChatAction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
3.2.8 telegram.ChatInviteLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
3.2.9 telegram.ChatLocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
3.2.10 telegram.ChatMember . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
3.2.11 telegram.ChatMemberUpdated . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
3.2.12 telegram.ChatPermissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
3.2.13 telegram.ChatPhoto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
3.2.14 telegram.constants Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
3.2.15 telegram.Contact . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
3.2.16 telegram.Dice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
3.2.17 telegram.Document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
3.2.18 telegram.error module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
3.2.19 telegram.File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
3.2.20 telegram.ForceReply . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
3.2.21 telegram.InlineKeyboardButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
3.2.22 telegram.InlineKeyboardMarkup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
3.2.23 telegram.InputFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
3.2.24 telegram.InputMedia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
3.2.25 telegram.InputMediaAnimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
i
3.2.26 telegram.InputMediaAudio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
3.2.27 telegram.InputMediaDocument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
3.2.28 telegram.InputMediaPhoto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
3.2.29 telegram.InputMediaVideo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
3.2.30 telegram.KeyboardButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
3.2.31 telegram.KeyboardButtonPollType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
3.2.32 telegram.Location . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
3.2.33 telegram.LoginUrl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
3.2.34 telegram.Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
3.2.35 telegram.MessageAutoDeleteTimerChanged . . . . . . . . . . . . . . . . . . . . . . . . 209
3.2.36 telegram.MessageId . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
3.2.37 telegram.MessageEntity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
3.2.38 telegram.ParseMode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
3.2.39 telegram.PhotoSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
3.2.40 telegram.Poll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
3.2.41 telegram.PollAnswer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
3.2.42 telegram.PollOption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
3.2.43 telegram.ProximityAlertTriggered . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
3.2.44 telegram.ReplyKeyboardRemove . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
3.2.45 telegram.ReplyKeyboardMarkup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
3.2.46 telegram.ReplyMarkup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
3.2.47 telegram.TelegramObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
3.2.48 telegram.Update . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
3.2.49 telegram.User . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
3.2.50 telegram.UserProfilePhotos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
3.2.51 telegram.Venue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
3.2.52 telegram.Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
3.2.53 telegram.VideoNote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
3.2.54 telegram.Voice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
3.2.55 telegram.VoiceChatStarted . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
3.2.56 telegram.VoiceChatEnded . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
3.2.57 telegram.VoiceChatScheduled . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
3.2.58 telegram.VoiceChatParticipantsInvited . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
3.2.59 telegram.WebhookInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
3.2.60 Stickers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
3.2.61 Inline Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
3.2.62 Payments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
3.2.63 Games . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
3.2.64 Passport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
3.2.65 utils . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
3.3 Changelog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
3.3.1 Changelog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Index 339
ii
CHAPTER
ONE
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 13.5
TWO
EXAMPLES
A great way to learn is by looking at examples. Ours can be found in our examples folder on Github.
3
python-telegram-bot Documentation, Release 13.5
4 Chapter 2. Examples
CHAPTER
THREE
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
Note:
• You must supply either a bot or a token argument.
• If you supply a bot, you will need to pass defaults to both the bot and the telegram.ext.
Updater.
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.
5
python-telegram-bot Documentation, Release 13.5
bot
The bot used with this Updater.
Type telegram.Bot
user_sig_handler
Optional. Function to be called when a signal is received.
Type function
update_queue
Queue for the updates.
Type Queue
job_queue
Jobqueue for the updater.
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
6 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
Note: Due to an incompatibility of the Tornado library PTB uses for the webhook with Python 3.8+
on Windows machines, PTB will attempt to set the event loop to asyncio.SelectorEventLoop
and raise an exception, if an incompatible event loop has already been specified. See this thread for
more details. To suppress the exception, set force_event_loop to True.
Parameters
• listen (str, optional) – IP-Address to listen on. Default 127.0.0.1.
• port (int, optional) – Port the bot should be listening on. Default 80.
• url_path (str, optional) – Path inside url.
• cert (str, optional) – Path to the SSL certificate file.
• key (str, optional) – Path to the SSL key file.
• drop_pending_updates (bool, optional) – Whether to clean any pending up-
dates on Telegram servers before actually starting to poll. Default is False.
New in version 13.4.
• clean (bool, optional) – Alias for drop_pending_updates.
Deprecated since version 13.4: Use drop_pending_updates instead.
• bootstrap_retries (int, optional) – Whether the bootstrapping phase of the
telegram.ext.Updater will retry on failures on the Telegram server.
– < 0 - retry indefinitely (default)
– 0 - no retries
– > 0 - retry up to X times
• webhook_url (str, optional) – Explicitly specify the webhook url. Useful behind
NAT, reverse proxy, etc. Default is derived from listen, port & url_path.
• ip_address (str, optional) – Passed to telegram.Bot.set_webhook().
New in version 13.4.
• allowed_updates (List[str], optional) – Passed to telegram.Bot.
set_webhook().
• force_event_loop (bool, optional) – Force using the current event loop. See
above note for details. Defaults to False
Returns The update queue that can be filled from the main thread.
Return type Queue
stop()
Stops the polling/webhook thread, the dispatcher and the job queue.
3.1.2 telegram.ext.Dispatcher
8 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
• use_context (bool, optional) – If set to True uses the context based callback API
(ignored if dispatcher argument is used). Defaults to True. New users: set this to
True.
bot
The bot object that should be passed to the handlers.
Type telegram.Bot
update_queue
The synchronized queue that will contain the updates.
Type Queue
job_queue
Optional. The telegram.ext.JobQueue instance to pass onto handler callbacks.
Type telegram.ext.JobQueue
workers
Number of maximum concurrent worker threads for the @run_async decorator and
run_async().
Type int, optional
user_data
A dictionary handlers can use to store data for the user.
Type defaultdict
chat_data
A dictionary handlers can use to store data for the chat.
Type defaultdict
bot_data
A dictionary handlers can use to store data for the bot.
Type dict
persistence
Optional. The persistence class to store data that should be persistent over restarts.
Type telegram.ext.BasePersistence
add_error_handler(callback, run_async=False)
Registers an error handler in the Dispatcher. This handler will receive every error which happens in
your bot.
Note: Attempts to add the same callback multiple times will be ignored.
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: object, context: CallbackContext)
The error that happened will be present in context.error.
• run_async (bool, optional) – Whether this handlers callback should be run asyn-
chronously using run_async(). Defaults to False.
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.
10 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
Note: If the update is handled by least one synchronously running handlers (i.e.
run_async=False), update_persistence() is called once after all handlers synchronous
handlers are done. Each asynchronously running handler will trigger update_persistence()
on its own.
remove_error_handler(callback)
Removes an error handler.
Parameters callback (callable) – The error handler to remove.
remove_handler(handler, group=0)
Remove a handler from the specified group.
Parameters
• handler (telegram.ext.Handler) – A Handler instance.
• group (object, optional) – The group identifier. Default is 0.
run_async(func, *args, update=None, **kwargs)
Queue a function (with given args/kwargs) to be run asynchronously. Exceptions raised by the function
will be handled by the error handlers registered with add_error_handler().
Warning:
• If you’re using @run_async/run_async() you cannot rely on adding custom attributes
to telegram.ext.CallbackContext. See its docs for more info.
• Calling a function through run_async() from within an error handler can lead to an
infinite error handling loop.
Parameters
• func (callable) – The function to run in the thread.
• *args (tuple, optional) – Arguments to func.
• update (telegram.Update | object, optional) – The update associated with
the functions call. If passed, it will be available in the error handlers, in case an
exception is raised by func.
• **kwargs (dict, optional) – Keyword arguments to func.
Returns Promise
running
Indicates if this dispatcher is running.
Type bool
start(ready=None)
Thread target of thread ‘dispatcher’.
Runs in background and processes the update queue.
Parameters ready (threading.Event, optional) – If specified, the event will be set
once the dispatcher is ready.
stop()
Stops the thread.
update_persistence(update=None)
Update user_data, chat_data and bot_data in persistence.
Parameters
• update (telegram.Update, optional) – The update to process. If passed, only
the
• user_data and chat_data will be updated. (corresponding) –
3.1.3 telegram.ext.DispatcherHandlerStop
class telegram.ext.DispatcherHandlerStop(state=None)
Bases: Exception
Raise this in handler to prevent execution of any other handler (even in different group).
In order to use this exception in a telegram.ext.ConversationHandler, pass the optional state
parameter instead of returning the next state:
state
Optional. The next state of the conversation.
Type object
3.1.4 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.
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.
12 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
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 error that was raised. Only present when passed to a error handler registered with
telegram.ext.Dispatcher.add_error_handler.
Type Exception
async_args
Optional. Positional arguments of the function that raised the error. Only present when the raising
function was run asynchronously using telegram.ext.Dispatcher.run_async().
Type List[object]
async_kwargs
Optional. Keyword arguments of the function that raised the error. Only present when the raising
function was run asynchronously using telegram.ext.Dispatcher.run_async().
Type Dict[str, object]
job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Job.
Type telegram.ext.Job
property bot
The bot associated with this context.
Type telegram.Bot
property dispatcher
The dispatcher associated with this context.
Type telegram.ext.Dispatcher
property job_queue
The JobQueue used by the telegram.ext.Dispatcher and (usually) the telegram.ext.
Updater associated with this context.
Type telegram.ext.JobQueue
property 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
property 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.5 telegram.ext.Defaults
14 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
Type str
disable_notification
Optional. Sends the message silently. Users will receive a notification with no sound.
Type bool
disable_web_page_preview
Optional. Disables link previews for links in this message.
Type bool
allow_sending_without_reply
Optional. Pass True, if the message should be sent even if the specified replied-to message is not
found.
Type bool
timeout
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).
Type int | float
quote
Optional. 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.
Type bool
tzinfo
A timezone to be used for all date(time) objects appearing throughout PTB.
Type tzinfo
run_async
Optional. Default setting for the run_async parameter of handlers and error handlers registered
through Dispatcher.add_handler() and Dispatcher.add_error_handler().
Type bool
3.1.6 telegram.ext.Job
Note:
• All attributes and instance methods of job are also directly available as attributes/methods of the
corresponding telegram.ext.Job object.
• Two instances of telegram.ext.Job are considered equal, if their corresponding job attributes
have the same id.
• If job isn’t passed on initialization, it must be set manually afterwards for this telegram.ext.
Job to be useful.
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.
• 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__.
• job_queue (telegram.ext.JobQueue, optional) – The JobQueue this job be-
longs to. Only optional for backward compatibility with JobQueue.put().
• job (apscheduler.job.Job, optional) – The APS Job this job is a wrapper for.
callback
The callback function that should be executed by the new job.
Type callable
context
Optional. Additional data needed for the callback function.
Type object
name
Optional. The name of the new job.
Type str
job_queue
Optional. The JobQueue this job belongs to.
Type telegram.ext.JobQueue
job
Optional. The APS Job this job is a wrapper for.
Type apscheduler.job.Job
property enabled
Whether this job is enabled.
Type bool
property 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
property removed
Whether this job is due to be removed.
Type bool
run(dispatcher)
Executes the callback function independently of the jobs schedule.
schedule_removal()
Schedules this job for removal from the JobQueue. It will be removed without executing its callback
function again.
16 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
3.1.7 telegram.ext.JobQueue
class telegram.ext.JobQueue
Bases: object
This class allows you to periodically perform tasks with the bot. It is a convenience wrapper for the AP-
Scheduler library.
scheduler
The APScheduler
Type apscheduler.schedulers.background.BackgroundScheduler
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 all pending/scheduled jobs with the given name that are currently in the JobQueue
jobs()
Returns a tuple of all pending/scheduled jobs that are currently in the JobQueue.
run_custom(callback, job_kwargs, context=None, name=None)
Creates a new customly defined Job.
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.
• job_kwargs (dict) – Arbitrary keyword arguments. Used as arguments for
scheduler.add_job.
• 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
run_daily(callback, time, days=(0, 1, 2, 3, 4, 5, 6), context=None, name=None,
job_kwargs=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, the default timezone of the bot will be used.
• days (Tuple[int], optional) – Defines on which days of the week the job should run
(where 0-6 correspond to monday - sunday). 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__.
• job_kwargs (dict, optional) – Arbitrary keyword arguments to pass to the
scheduler.add_job().
Returns The new Job instance that has been added to the job queue.
Return type telegram.ext.Job
Note: For a note about DST, please see the documentation of APScheduler.
18 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
– 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, the default
timezone of the bot will be used.
– 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, the default timezone of the bot will be
used.
• 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__.
• job_kwargs (dict, optional) – Arbitrary keyword arguments to pass to the
scheduler.add_job().
Returns The new Job instance that has been added to the job queue.
Return type telegram.ext.Job
run_repeating(callback, interval, first=None, last=None, context=None, name=None,
job_kwargs=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, the default
timezone of the bot will be used.
– 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, the default timezone of the bot will be
used.
Defaults to interval
• last (int | float | datetime.timedelta | datetime.datetime |
datetime.time, optional) – Latest possible time for the job to run. This parameter
will be interpreted depending on its type. See first for details.
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.
3.1.8 telegram.ext.MessageQueue
20 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
3.1.9 telegram.ext.DelayQueue
• 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 ob-
ject’s creation; if False, should be started manually by start method. Defaults to
True.
• name (str, optional) – Thread’s name. Defaults to 'DelayQueue-N', where N is
sequential number of object created.
burst_limit
Number of maximum callbacks to process per time-window.
Type int
time_limit
Defines width of time-window used when each processing limit is calculated.
Type int
exc_route
A callable, accepting 1 positional argument; used to route exceptions from processor thread to main
thread;
Type callable
name
Thread’s name.
Type str
__call__(func, *args, **kwargs)
Used to process callbacks in throughput-limiting thread through queue.
Parameters
• func (callable) – The actual function (or any callable) that is processed through
queue.
• *args (list) – Variable-length func arguments.
• **kwargs (dict) – Arbitrary keyword-arguments to func.
__init__(queue=None, burst_limit=30, time_limit_ms=1000, exc_route=None, autostart=True,
name=None)
This constructor should always be called with keyword arguments. Arguments are:
group should be None; reserved for future extension when a ThreadGroup class is implemented.
target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is
called.
name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N
is a small decimal number.
args is the argument tuple for the target invocation. Defaults to ().
kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.
22 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
If a subclass overrides the constructor, it must make sure to invoke the base class constructor
(Thread.__init__()) before doing anything else to the thread.
run()
Do not use the method except for unthreaded testing purposes, the method normally is automatically
called by autostart argument.
stop(timeout=None)
Used to gently stop processor and shutdown its thread.
Parameters timeout (float) – Indicates maximum time to wait for processor to stop
and its thread to exit. If timeout exceeds and processor has not stopped, method silently
returns. is_alive could be used afterwards to check the actual status. timeout set
to None, blocks until processor is shut down. Defaults to None.
3.1.10 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.
Warning: When setting run_async to True, you cannot rely on adding custom attributes to
telegram.ext.CallbackContext. See its docs 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.
callback
The callback function for this handler.
Type callable
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
run_async
Determines whether the callback will run asynchronously.
Type bool
abstract check_update(update)
This method is called to determine if an update should be handled by this handler instance. It should
always be overridden.
Note: Custom updates types can be handled by the dispatcher. Therefore, an implementation of this
method should always check the type of update.
24 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
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.
Warning: When setting run_async to True, you cannot rely on adding custom attributes to
telegram.ext.CallbackContext. See its docs 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.CallbackQuery.data 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.
• 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.
• run_async (bool) – Determines whether the callback will run asynchronously. De-
faults to False.
callback
The callback function for this handler.
Type callable
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
pattern
Optional. Regex pattern to test telegram.CallbackQuery.data against.
Type str | Pattern
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
26 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
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
run_async
Determines whether the callback will run asynchronously.
Type bool
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update | object) – Incoming 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.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.
Warning: When setting run_async to True, you cannot rely on adding custom attributes to
telegram.ext.CallbackContext. See its docs 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.
• run_async (bool) – Determines whether the callback will run asynchronously. De-
faults to False.
callback
The callback function for this handler.
Type callable
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
run_async
Determines whether the callback will run asynchronously.
Type bool
28 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update | object) – Incoming update.
Returns bool
telegram.ext.ChatMemberHandler
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.
Warning: When setting run_async to True, you cannot rely on adding custom attributes to
telegram.ext.CallbackContext. See its docs 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.
• chat_member_types (int, optional) – Pass one of MY_CHAT_MEMBER,
CHAT_MEMBER or ANY_CHAT_MEMBER to specify if this handler should han-
dle only updates with telegram.Update.my_chat_member, telegram.
Update.chat_member or both. Defaults to MY_CHAT_MEMBER.
• 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.
callback
The callback function for this handler.
Type callable
chat_member_types
Specifies if this handler should handle only updates with telegram.Update.
my_chat_member, telegram.Update.chat_member or both.
Type int, optional
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
run_async
Determines whether the callback will run asynchronously.
Type bool
ANY_CHAT_MEMBER: ClassVar[int] = 1
Used as a constant to handle bot telegram.Update.my_chat_member and telegram.
Update.chat_member.
Type int
CHAT_MEMBER: ClassVar[int] = 0
Used as a constant to handle only telegram.Update.chat_member.
Type int
MY_CHAT_MEMBER: ClassVar[int] = -1
Used as a constant to handle only telegram.Update.my_chat_member.
Type int
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update | object) – Incoming update.
Returns bool
30 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
telegram.ext.CommandHandler
Note:
• CommandHandler does not handle (edited) channel posts.
• 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.
Warning: When setting run_async to True, you cannot rely on adding custom attributes to
telegram.ext.CallbackContext. See its docs for more info.
Parameters
• command (telegram.utils.types.SLT[str]) – The command or list of com-
mands 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.
command
The command or list of commands this handler should listen for. Limitations are the same as described
here https://core.telegram.org/bots#commands
Type telegram.utils.types.SLT[str]
callback
The callback function for this handler.
Type callable
filters
Optional. Only allow updates with these Filters.
Type telegram.ext.BaseFilter
allow_edited
Determines whether the handler should also accept edited messages.
Type bool
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.
32 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
Type bool
run_async
Determines whether the callback will run asynchronously.
Type bool
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update | object) – Incoming 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.ConversationHandler
The first collection, a list named entry_points, is used to initiate the conversation, for example with
a telegram.ext.CommandHandler or telegram.ext.MessageHandler.
The second collection, a dict named states, contains the different conversation steps and one or more
associated handlers that should be used if the user sends a message when the conversation with them
is currently in that state. Here you can also define a state for TIMEOUT to define the behavior when
conversation_timeout is exceeded, and a state for WAITING to define behavior when a new update
is received while the previous @run_async decorated handler is not finished.
The third collection, a list named fallbacks, is used if the user is currently in a conversation but the
state has either no associated handler or the handler that is associated to the state is inappropriate for the
update, for example if the update contains a command, but a regular text message is expected. You could
use this for a /cancel command or to let the user know their message was not recognized.
To change the state of conversation, the callback function of a handler must return the new state after
responding to the user. If it does not return anything (returning None by default), the state will not
change. If an entry point callback function returns None, the conversation ends immediately after the
execution of this callback function. To end the conversation, the callback function must return END
or -1. To handle the conversation timeout, use handler TIMEOUT or -2. Finally, telegram.ext.
DispatcherHandlerStop can be used in conversations as described in the corresponding documenta-
tion.
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.
• states (Dict[object, List[telegram.ext.Handler]]) – A dict that de-
fines the different states of conversation a user can be in and one or more associ-
ated Handler objects that should be used in that state. The first handler which
check_update method returns True will be used.
• fallbacks (List[telegram.ext.Handler]) – 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. The first handler which check_update method returns
True will be used. If all return False, the update is not handled.
• allow_reentry (bool, optional) – If set to True, a user that is currently in a
conversation can restart the conversation by triggering one of the entry points.
• per_chat (bool, optional) – If the conversationkey should contain the Chat’s ID.
Default is True.
• per_user (bool, optional) – If the conversationkey should contain the User’s ID.
Default is True.
• per_message (bool, optional) – If the conversationkey should contain the Mes-
sage’s ID. Default is False.
• conversation_timeout (float | datetime.timedelta, optional) – When
this handler is inactive more than this timeout (in seconds), it will be automati-
cally ended. If this value is 0 or None (default), there will be no timeout. The
34 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
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.
• name (str, optional) – The name for this conversationhandler. Required for persis-
tence.
• persistent (bool, optional) – If the conversations dict for this handler should be
saved. Name is required and persistence has to be set in telegram.ext.Updater
• map_to_parent (Dict[object, object], 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.
• run_async (bool, optional) – Pass True to override the Handler.run_async
setting of all handlers (in entry_points, states and fallbacks).
Note: If set to True, you should not pass a handler instance, that needs to be run
synchronously in another context.
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 up-
date 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]
run_async
If True, will override the Handler.run_async setting of all internal handlers on initialization.
New in version 13.2.
Type bool
END: ClassVar[int] = -1
Used as a constant to return when a conversation is ended.
Type int
TIMEOUT: ClassVar[int] = -2
Used as a constant to handle state when a conversation is timed out.
Type int
WAITING: ClassVar[int] = -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 | object) – Incoming update.
Returns bool
handle_update(update, dispatcher, check_result, context=None)
Send the update to the callback for the current state and Handler
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.
• context (telegram.ext.CallbackContext, optional) – The context as pro-
vided by the dispatcher.
36 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
telegram.ext.InlineQueryHandler
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.
Warning:
• When setting run_async to True, you cannot rely on adding custom attributes to telegram.
ext.CallbackContext. See its docs for more info.
• telegram.InlineQuery.chat_type will not be set for inline queries from secret chats
and may not be set for inline queries coming from third-party clients. These updates won’t be
handled, if chat_types is passed.
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.
• chat_types (List[str], optional) – List of allowed chat types. If passed, will only
handle inline queries with the appropriate telegram.InlineQuery.chat_type.
New in version 13.5.
• 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.
• 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.
• run_async (bool) – Determines whether the callback will run asynchronously. De-
faults to False.
callback
The callback function for this handler.
Type callable
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
pattern
Optional. Regex pattern to test telegram.InlineQuery.query against.
Type str | Pattern
chat_types
List of allowed chat types.
New in version 13.5.
Type List[str], optional
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_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
run_async
Determines whether the callback will run asynchronously.
38 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
Type bool
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update | object) – Incoming 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
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.
Warning: When setting run_async to True, you cannot rely on adding custom attributes to
telegram.ext.CallbackContext. See its docs for more info.
Parameters
• filters (telegram.ext.BaseFilter, optional) – A filter inheriting from
telegram.ext.filters.BaseFilter. Standard filters can be found in
filters
Only allow updates with these Filters. See telegram.ext.filters for a full list of all available
filters.
Type Filter
callback
The callback function for this handler.
Type callable
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.
40 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
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
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
run_async
Determines whether the callback will run asynchronously.
Type bool
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update | object) – Incoming 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.filters Module
This module contains the Filters for use with the MessageHandler class.
class telegram.ext.filters.BaseFilter
Bases: abc.ABC
Base class for all Filters.
Filters subclassing from this class can combined using bitwise operators:
And:
Or:
Exclusive 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 message.text == 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 either MessageFilter or
UpdateFilter 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
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
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.
42 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
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.MessageFilter
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.
class caption_regex(pattern)
Bases: telegram.ext.filters.MessageFilter
Filters updates by searching for an occurrence of pattern in the message caption.
This filter works similarly to Filters.regex, with the only exception being that it applies to the
message caption instead of the text.
Examples
Use MessageHandler(Filters.photo & Filters.caption_regex(r'help'),
callback) to capture all photos with caption containing the word ‘help’.
Note: This filter will not work on simple text messages, but only on media with caption.
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.
Parameters
• chat_id (telegram.utils.types.SLT[int], optional) – Which chat ID(s)
to allow through.
• username (telegram.utils.types.SLT[str], optional) – Which user-
name(s) to allow through. Leading '@' 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.
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
add_chat_ids(chat_id)
Add one or more chats to the allowed chat ids.
Parameters chat_id (telegram.utils.types.SLT[int], optional) – Which
chat ID(s) to allow through.
add_usernames(username)
Add one or more chats to the allowed usernames.
Parameters username (telegram.utils.types.SLT[str], optional) –
Which username(s) to allow through. Leading '@' s in usernames will be discarded.
get_chat_or_user(message)
remove_chat_ids(chat_id)
Remove one or more chats from allowed chat ids.
Parameters chat_id (telegram.utils.types.SLT[int], optional) – Which
chat ID(s) to disallow through.
remove_usernames(username)
Remove one or more chats from allowed usernames.
Parameters username (telegram.utils.types.SLT[str], optional) –
Which username(s) to disallow through. Leading '@' s in usernames will be
discarded.
chat_type = Filters.chat_type
Subset for filtering the type of chat.
Examples
Use these filters like: Filters.chat_type.channel or Filters.chat_type.
supergroup etc. Or use just Filters.chat_type for all chat types.
44 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
channel
Updates from channel
group
Updates from group
supergroup
Updates from supergroup
groups
Updates from group or supergroup
private
Updates sent in private chat
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).
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.
football
Dice messages with the emoji . Passing a list of integers is supported just as for Filters.dice.
slot_machine
Dice messages with the emoji . Passing a list of integers is supported just as for Filters.dice.
bowling
Dice messages with the emoji . Passing a list of integers is supported just as for Filters.dice.
New in version 13.4.
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
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.document.category('audio/') filters all types of audio sent as file, for ex-
ample ‘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
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
46 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
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").
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").
file_extension
This filter filters documents by their file ending/extension.
Note:
• This Filter only filters by the file ending/extension of the document, it doesn’t check the
validity of document.
• The user can manipulate the file extension of a document and send media with wrong types
that don’t fit to this handler.
• Case insensitive by default, you may change this with the flag case_sensitive=True.
• Extension should be passed without leading dot unless it’s a part of the extension.
• Pass None to filter files with no extension, i.e. without a dot in the filename.
Example
class entity(entity_type)
Bases: telegram.ext.filters.MessageFilter
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.
class forwarded_from(chat_id=None, username=None, allow_empty=False)
Bases: telegram.ext.filters.Filters._ChatUserBaseFilter
Filters messages to allow only those which are forwarded from the specified chat ID(s) or
username(s) based on telegram.Message.forward_from and telegram.Message.
forward_from_chat.
New in version 13.5.
Examples
MessageHandler(Filters.forwarded_from(chat_id=1234),
callback_method)
Note: When a user has disallowed adding a link to their account while forwarding their messages,
this filter will not work since both telegram.Message.forwarded_from and telegram.
Message.forwarded_from_chat are None. However, this behaviour is undocumented and
might be changed by Telegram.
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.
Parameters
• chat_id (telegram.utils.types.SLT[int], optional) – Which chat/user
ID(s) to allow through.
48 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
chat_ids
Which chat/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 chat is specified in chat_ids and usernames.
Type bool, optional
add_chat_ids(chat_id)
Add one or more chats to the allowed chat ids.
Parameters chat_id (telegram.utils.types.SLT[int], optional) – Which
chat/user ID(s) to allow through.
add_usernames(username)
Add one or more chats to the allowed usernames.
Parameters username (telegram.utils.types.SLT[str], optional) –
Which username(s) to allow through. Leading '@' s in usernames will be discarded.
get_chat_or_user(message)
remove_chat_ids(chat_id)
Remove one or more chats from allowed chat ids.
Parameters chat_id (telegram.utils.types.SLT[int], optional) – Which
chat/user ID(s) to disallow through.
remove_usernames(username)
Remove one or more chats from allowed usernames.
Parameters username (telegram.utils.types.SLT[str], optional) –
Which username(s) to disallow through. Leading '@' s in usernames will be
discarded.
game = Filters.game
Messages that contain telegram.Game.
group = Filters.group
Messages sent in a group or a supergroup chat.
invoice = Filters.invoice
Messages that contain telegram.Invoice.
class language(lang)
Bases: telegram.ext.filters.MessageFilter
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 lan-
guage_code attribute. Do not count on this filter working on all users.
Examples
MessageHandler(Filters.language("en"), callback_method)
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.MessageFilter
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
insensitive. 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.
class sender_chat(chat_id=None, username=None, allow_empty=False)
Bases: telegram.ext.filters.Filters._ChatUserBaseFilter
50 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
Filters messages to allow only those which are from a specified sender chats chat ID or username.
Examples
• To filter for messages forwarded to a discussion group from a channel with ID -1234, use
MessageHandler(Filters.sender_chat(-1234), callback_method).
• To filter for messages of anonymous admins in a super group with username @anonymous,
use MessageHandler(Filters.sender_chat(username='anonymous'),
callback_method).
• To filter for messages forwarded to a discussion group from any channel, use
MessageHandler(Filters.sender_chat.channel, callback_method).
• To filter for messages of anonymous admins in any super group, use
MessageHandler(Filters.sender_chat.super_group, callback_method).
Note: Remember, sender_chat is also set for messages in a channel as the channel itself, so when
your bot is an admin in a channel and the linked discussion group, you would receive the message
twice (once from inside the channel, once inside the discussion group).
Warning: chat_ids will return 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.
Parameters
• chat_id (telegram.utils.types.SLT[int], optional) – Which sender
chat chat ID(s) to allow through.
• username (telegram.utils.types.SLT[str], optional) – Which sender
chat username(s) to allow through. Leading '@' s in usernames will be discarded.
• allow_empty (bool, optional) – Whether updates should be processed, if no
sender chat is specified in chat_ids and usernames. Defaults to False
Raises RuntimeError – If both chat_id and username are present.
chat_ids
Which sender chat chat ID(s) to allow through.
Type set(int), optional
usernames
Which sender chat username(s) (without leading '@') to allow through.
Type set(str), optional
allow_empty
Whether updates should be processed, if no sender chat is specified in chat_ids and
usernames.
Type bool, optional
super_group
Messages whose sender chat is a super group.
Examples
Filters.sender_chat.supergroup
channel
Messages whose sender chat is a channel.
Examples
Filters.sender_chat.channel
add_chat_ids(chat_id)
Add one or more sender chats to the allowed chat ids.
Parameters chat_id (telegram.utils.types.SLT[int], optional) – Which
sender chat ID(s) to allow through.
add_usernames(username)
Add one or more sender chats to the allowed usernames.
Parameters username (telegram.utils.types.SLT[str], optional) –
Which sender chat username(s) to allow through. Leading '@' s in usernames will be
discarded.
channel = _Channel
get_chat_or_user(message)
remove_chat_ids(chat_id)
Remove one or more sender chats from allowed chat ids.
Parameters chat_id (telegram.utils.types.SLT[int], optional) – Which
sender chat ID(s) to disallow through.
remove_usernames(username)
Remove one or more sender chats from allowed usernames.
Parameters username (telegram.utils.types.SLT[str], optional) –
Which sender chat username(s) to disallow through. Leading '@' s in usernames will
be discarded.
super_group = _SuperGroup
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.
connected_website
Messages that contain telegram.Message.connected_website.
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_to_chat_id or telegram.
Message.migrate_from_chat_id.
52 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
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.
message_auto_delete_timer_changed
Messages that contain message_auto_delete_timer_changed.
New in version 13.4.
pinned_message
Messages that contain telegram.Message.pinned_message.
proximity_alert_triggered
Messages that contain telegram.Message.proximity_alert_triggered.
voice_chat_scheduled
Messages that contain telegram.Message.voice_chat_scheduled.
New in version 13.5.
voice_chat_started
Messages that contain telegram.Message.voice_chat_started.
New in version 13.4.
voice_chat_ended
Messages that contain telegram.Message.voice_chat_ended.
New in version 13.4.
voice_chat_participants_invited
Messages that contain telegram.Message.voice_chat_participants_invited.
New in version 13.4.
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 use case for passing a list is to allow only messages that were sent 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.Filters._ChatUserBaseFilter
Filters messages to allow only those which are from specified user ID(s) or username(s).
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.
Parameters
• user_id (telegram.utils.types.SLT[int], optional) – Which user ID(s)
to allow through.
• username (telegram.utils.types.SLT[str], optional) – Which user-
name(s) to allow through. Leading '@' s in usernames will be discarded.
54 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
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.
Type bool, optional
add_user_ids(user_id)
Add one or more users to the allowed user ids.
Parameters user_id (telegram.utils.types.SLT[int], optional) – Which
user ID(s) to allow through.
add_usernames(username)
Add one or more users to the allowed usernames.
Parameters username (telegram.utils.types.SLT[str], optional) –
Which username(s) to allow through. Leading '@' s in usernames will be discarded.
get_chat_or_user(message)
remove_user_ids(user_id)
Remove one or more users from allowed user ids.
Parameters user_id (telegram.utils.types.SLT[int], optional) – Which
user ID(s) to disallow through.
remove_usernames(username)
Remove one or more users from allowed usernames.
Parameters username (telegram.utils.types.SLT[str], optional) –
Which username(s) to disallow through. Leading '@' s in usernames will be
discarded.
property user_ids
venue = Filters.venue
Messages that contain telegram.Venue.
class via_bot(bot_id=None, username=None, allow_empty=False)
Bases: telegram.ext.filters.Filters._ChatUserBaseFilter
Filters messages to allow only those which are from specified via_bot ID(s) or username(s).
Examples
MessageHandler(Filters.via_bot(1234), callback_method)
Warning: bot_ids will give a copy of the saved bot ids as frozenset. This is to ensure
thread safety. To add/remove a bot, you should use add_usernames(), add_bot_ids(),
remove_usernames() and remove_bot_ids(). Only update the entire set by filter.
bot_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 bots.
Parameters
bot_ids
Which bot 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 bot is specified in bot_ids and usernames.
Type bool, optional
add_bot_ids(bot_id)
Add one or more users to the allowed user ids.
Parameters bot_id (telegram.utils.types.SLT[int], optional) – Which
bot ID(s) to allow through.
add_usernames(username)
Add one or more users to the allowed usernames.
Parameters username (telegram.utils.types.SLT[str], optional) –
Which username(s) to allow through. Leading '@' s in usernames will be discarded.
property bot_ids
get_chat_or_user(message)
remove_bot_ids(bot_id)
Remove one or more users from allowed user ids.
Parameters bot_id (telegram.utils.types.SLT[int], optional) – Which
bot ID(s) to disallow through.
remove_usernames(username)
Remove one or more users from allowed usernames.
Parameters username (telegram.utils.types.SLT[str], optional) –
Which username(s) to disallow through. Leading '@' s in usernames will be
discarded.
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.InvertedFilter(f )
Bases: telegram.ext.filters.UpdateFilter
Represents a filter that has been inverted.
Parameters f – The filter to invert.
filter(update)
This method must be overwritten.
Parameters update (telegram.Update) – The update that is tested.
56 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
telegram.ext.PollAnswerHandler
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.
Warning: When setting run_async to True, you cannot rely on adding custom attributes to
telegram.ext.CallbackContext. See its docs 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.
58 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
callback
The callback function for this handler.
Type callable
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
run_async
Determines whether the callback will run asynchronously.
Type bool
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update | object) – Incoming update.
Returns bool
telegram.ext.PollHandler
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.
Warning: When setting run_async to True, you cannot rely on adding custom attributes to
telegram.ext.CallbackContext. See its docs 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.
• run_async (bool) – Determines whether the callback will run asynchronously. De-
faults to False.
callback
The callback function for this handler.
Type callable
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
run_async
Determines whether the callback will run asynchronously.
Type bool
60 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update | object) – Incoming 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.
Warning: When setting run_async to True, you cannot rely on adding custom attributes to
telegram.ext.CallbackContext. See its docs 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.
• 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.
• run_async (bool) – Determines whether the callback will run asynchronously. De-
faults to False.
callback
The callback function for this handler.
Type callable
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
run_async
Determines whether the callback will run asynchronously.
Type bool
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update | object) – Incoming update.
Returns bool
telegram.ext.PrefixHandler
Examples
Single prefix and command:
62 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
By default the handler listens to messages as well as edited messages. To change this behavior use
~Filters.update.edited_message.
Note:
• PrefixHandler does not handle (edited) channel posts.
• 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.
Warning: When setting run_async to True, you cannot rely on adding custom attributes to
telegram.ext.CallbackContext. See its docs for more info.
Parameters
• prefix (telegram.utils.types.SLT[str]) – The prefix(es) that will pre-
cede command.
• command (telegram.utils.types.SLT[str]) – The command or list of com-
mands 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
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.
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
run_async
Determines whether the callback will run asynchronously.
Type bool
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update | object) – Incoming 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.
64 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
property command
The list of commands this handler should listen for.
Returns List[str]
property prefix
The prefixes that will precede command.
Returns List[str]
telegram.ext.RegexHandler
Note: This handler is being deprecated. For the same use case use: MessageHandler(Filters.
regex(r'pattern'), callback)
Warning: When setting run_async to True, you cannot rely on adding custom attributes to
telegram.ext.CallbackContext. See its docs for more info.
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.
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
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
run_async
Determines whether the callback will run asynchronously.
Type bool
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.
66 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
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.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.
Warning: When setting run_async to True, you cannot rely on adding custom attributes to
telegram.ext.CallbackContext. See its docs 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.
• run_async (bool) – Determines whether the callback will run asynchronously. De-
faults to False.
callback
The callback function for this handler.
Type callable
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
run_async
Determines whether the callback will run asynchronously.
Type bool
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (telegram.Update | object) – Incoming 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.
Warning: When setting run_async to True, you cannot rely on adding custom attributes to
telegram.ext.CallbackContext. See its docs for more info.
Parameters
• command (str) – The command 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.
68 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
• 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.
• run_async (bool) – Determines whether the callback will run asynchronously. De-
faults to False.
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
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
run_async
Determines whether the callback will run asynchronously.
Type bool
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (object) – The incoming 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.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.
Warning: When setting run_async to True, you cannot rely on adding custom attributes to
telegram.ext.CallbackContext. See its docs for more info.
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.
• 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_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.
70 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
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
run_async
Determines whether the callback will run asynchronously.
Type bool
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (object) – The incoming 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.TypeHandler
Warning: When setting run_async to True, you cannot rely on adding custom attributes to
telegram.ext.CallbackContext. See its docs for more info.
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.
• run_async (bool) – Determines whether the callback will run asynchronously. De-
faults to False.
type
The type of updates this handler should process.
Type type
callback
The callback function for this handler.
Type callable
strict
Use type instead of isinstance. Default is False.
Type bool
72 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
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
run_async
Determines whether the callback will run asynchronously.
Type bool
check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (object) – Incoming update.
Returns bool
3.1.11 Persistence
telegram.ext.BasePersistence
Warning: Persistence will try to replace telegram.Bot instances by REPLACED_BOT and insert
the bot set with set_bot() upon loading of the data. This is to ensure that changes to the bot apply
to the saved objects, too. If you change the bots token, this may lead to e.g. Chat not found errors.
For the limitations on replacing bots see replace_bot() and insert_bot().
Note: replace_bot() and insert_bot() are used independently of the implementation of the
update/get_*() methods, i.e. you don’t need to worry about it while implementing a custom persis-
tence subclass.
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 .
store_user_data
Optional, Whether user_data should be saved by this persistence class.
Type bool
store_chat_data
Optional. Whether chat_data should be saved by this persistence class.
Type bool
store_bot_data
Optional. Whether bot_data should be saved by this persistence class.
Type bool
REPLACED_BOT: ClassVar[str] = 'bot_instance_replaced_by_ptb_persistence'
Placeholder for telegram.Bot instances replaced in saved data.
Type str
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.
abstract 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 dict
abstract 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
abstract 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.
Returns The restored conversations for the handler.
Return type dict
abstract get_user_data()
Will be called by telegram.ext.Dispatcher upon creation with a persistence object. It should
return the user_data if stored, or an empty defaultdict(dict).
Returns The restored user data.
Return type defaultdict
74 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
insert_bot(obj)
Replaces all instances of REPLACED_BOT that occur within the passed object with bot. Currently,
this handles objects of type list, tuple, set, frozenset, dict, defaultdict and objects
that have a __dict__ or __slot__ attribute, excluding objects that can’t be copied with copy.copy.
Parameters obj (object) – The object
Returns Copy of the object with Bot instances inserted.
Return type obj
classmethod replace_bot(obj)
Replaces all instances of telegram.Bot that occur within the passed object with REPLACED_BOT.
Currently, this handles objects of type list, tuple, set, frozenset, dict, defaultdict and
objects that have a __dict__ or __slot__ attribute, excluding objects that can’t be copied with
copy.copy.
Parameters obj (object) – The object
Returns Copy of the object with Bot instances replaced.
Return type obj
set_bot(bot)
Set the Bot to be used by this persistence instance.
Parameters bot (telegram.Bot) – The bot.
abstract update_bot_data(data)
Will be called by the telegram.ext.Dispatcher after a handler has handled an update.
Parameters data (dict) – The telegram.ext.dispatcher.bot_data .
abstract update_chat_data(chat_id, data)
Will be called by the telegram.ext.Dispatcher after a handler has handled an update.
Parameters
• chat_id (int) – The chat the data might have been changed for.
• data (dict) – The telegram.ext.dispatcher.chat_data [chat_id].
abstract update_conversation(name, key, new_state)
Will be called when a telegram.ext.ConversationHandler.update_state is called.
This allows the storage of the new state in the persistence.
Parameters
• name (str) – The handler’s name.
• key (tuple) – The key the state is changed for.
• new_state (tuple | any) – The new state for the given key.
abstract update_user_data(user_id, data)
Will be called by the telegram.ext.Dispatcher after a handler has handled an update.
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.PicklePersistence
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 separate 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 to flush(). Default is False.
filename
The filename for storing the pickle files. When single_file is False this will be used as a prefix.
Type str
store_user_data
Optional. Whether user_data should be saved by this persistence class.
Type bool
store_chat_data
Optional. Whether user_data should be saved by this persistence class.
Type bool
store_bot_data
Optional. Whether bot_data should be saved by this persistence class.
Type bool
single_file
Optional. When False will store 3 separate 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 to flush(). Default is False.
Type bool, optional
76 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
flush()
Will save all data in memory to pickle file(s).
get_bot_data()
Returns the bot_data from the pickle file if it exists or an empty dict.
Returns The restored bot data.
Return type dict
get_chat_data()
Returns the chat_data from the pickle file if it exists 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 dict.
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 exists or an empty defaultdict.
Returns The restored user data.
Return type defaultdict
update_bot_data(data)
Will update the bot_data 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 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 handler’s 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 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
Note: This class does not implement a flush() method, meaning that data managed by
DictPersistence is in-memory only and will be lost when the bot shuts down. This is, because
DictPersistence is mainly intended as starting point for custom persistence classes that need to JSON-
serialize the stored data before writing them to file/database.
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 .
• user_data_json (str, optional) – Json string that will be used to reconstruct
user_data on creating this persistence. Default is "".
• chat_data_json (str, optional) – Json string that will be used to reconstruct
chat_data on creating this persistence. Default is "".
• bot_data_json (str, optional) – Json string that will be used to reconstruct
bot_data on creating this persistence. Default is "".
• conversations_json (str, optional) – Json string that will be used to reconstruct
conversation on creating this persistence. Default is "".
store_user_data
Whether user_data should be saved by this persistence class.
Type bool
store_chat_data
Whether chat_data should be saved by this persistence class.
Type bool
store_bot_data
Whether bot_data should be saved by this persistence class.
Type bool
property bot_data
The bot_data as a dict.
Type dict
78 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
property bot_data_json
The bot_data serialized as a JSON-string.
Type str
property chat_data
The chat_data as a dict.
Type dict
property chat_data_json
The chat_data serialized as a JSON-string.
Type str
property conversations
The conversations as a dict.
Type dict
property 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 bot data.
Return type dict
get_chat_data()
Returns the chat_data created from the chat_data_json or an empty defaultdict.
Returns The restored chat data.
Return type defaultdict
get_conversations(name)
Returns the conversations created from the conversations_json or an empty dict.
Returns The restored conversations data.
Return type dict
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).
Parameters data (dict) – The telegram.ext.dispatcher.bot_data.
update_chat_data(chat_id, data)
Will update the chat_data (if changed).
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.
Parameters
• name (str) – The handler’s name.
3.1.12 utils
telegram.ext.utils.promise.Promise
80 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
3.2.1 telegram.Animation
82 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
3.2.2 telegram.Audio
mime_type
Optional. MIME type of the file as defined by sender.
Type str
file_size
Optional. File size.
Type int
thumb
Optional. Thumbnail of the album cover to which the music file belongs.
Type telegram.PhotoSize
bot
Optional. The Bot to use for instance methods.
Type telegram.Bot
get_file(timeout=None, api_kwargs=None)
Convenience wrapper over telegram.Bot.get_file
For the documentation of the arguments, please see telegram.Bot.get_file().
Returns telegram.File
Raises telegram.error.TelegramError –
3.2.3 telegram.Bot
Note: Most bot methods have the argument api_kwargs which allows to pass arbitrary keywords to the
Telegram API. This can be used to access new features of the API before they were incorporated into PTB.
However, this is not guaranteed to work, i.e. it will fail for passing files.
Parameters
• token (str) – Bot’s unique authentication.
• base_url (str, optional) – Telegram Bot API service URL.
• base_file_url (str, optional) – Telegram Bot API file URL.
• request (telegram.utils.request.Request, optional) – Pre initialized
telegram.utils.request.Request.
• private_key (bytes, optional) – Private key for decryption of telegram passport
data.
• private_key_password (bytes, optional) – Password for above private key.
• defaults (telegram.ext.Defaults, optional) – An object containing default
values to be used if not set explicitly in the bot methods.
84 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
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 | bytes | pathlib.Path, 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.
Changed in version 13.2: Accept bytes as input.
• tgs_sticker (str | filelike object | bytes | pathlib.Path, optional) – TGS
animation with the sticker, uploaded using multipart/form-data. See https://core.
telegram.org/animated_stickers#technical-requirements for technical requirements.
Changed in version 13.2: Accept bytes as input.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, True is returned.
Return type bool
Raises telegram.error.TelegramError –
Warning: In most use cases current_offset should not be passed manually. Instead
of calling this method directly, use the shortcut telegram.InlineQuery.answer() with
auto_pagination=True, which will take care of passing the correct value.
Parameters
• inline_query_id (str) – Unique identifier for the answered query.
• results (List[telegram.InlineQueryResult] | Callable) – A list of results
for the inline query. In case current_offset is passed, results may also be
a callable that accepts the current page index starting from 0. It must return either a
list of telegram.InlineQueryResult instances or None if there are no more
results.
86 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
• 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.
• current_offset (str, optional) – The telegram.InlineQuery.offset
of the inline query to answer. If passed, PTB will automatically take care of the pag-
ination for you, i.e. pass the correct next_offset and truncate the results list/get
the results from the callable you passed.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
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.
88 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
close(timeout=None)
Use this method to close the bot instance before moving it from one local server to another. You need
to delete the webhook before calling this method to ensure that the bot isn’t launched again after server
restart. The method will return error 429 in the first 10 minutes after the bot is launched.
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).
Returns On success
Return type True
Raises telegram.error.TelegramError –
property commands
Bot’s commands.
Type List[BotCommand]
copyMessage(chat_id, from_chat_id, message_id, caption=None, parse_mode=None, cap-
tion_entities=None, disable_notification=None, reply_to_message_id=None,
allow_sending_without_reply=None, reply_markup=None, timeout=None,
api_kwargs=None)
Alias for copy_message()
copy_message(chat_id, from_chat_id, message_id, caption=None, parse_mode=None, cap-
tion_entities=None, disable_notification=None, reply_to_message_id=None,
allow_sending_without_reply=None, reply_markup=None, timeout=None,
api_kwargs=None)
Use this method to copy messages of any kind. Service messages and invoice messages can’t be
copied. The method is analogous to the method forward_message(), but the copied message
doesn’t have a link to the original message.
Parameters
• 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).
• message_id (int) – Message identifier in the chat specified in from_chat_id.
• caption (str, optional) – New caption for media, 0-1024 characters after entities
parsing. If not specified, the original caption is kept.
• parse_mode (str, optional) – Mode for parsing entities in the new caption. See
the constants in telegram.ParseMode for the available modes.
• caption_entities (telegram.utils.types.SLT[MessageEntity])
– List of special entities that appear in the new caption, which can be specified in-
stead of parse_mode
• 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.
• allow_sending_without_reply (bool, optional) – Pass True, if the mes-
sage should be sent even if the specified replied-to message is not found.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success
Return type telegram.MessageId
Raises telegram.error.TelegramError –
createChatInviteLink(chat_id, expire_date=None, member_limit=None, timeout=None,
api_kwargs=None)
Alias for create_chat_invite_link
createNewStickerSet(user_id, name, title, emojis, png_sticker=None, contains_masks=None,
mask_position=None, timeout=20, tgs_sticker=None,
api_kwargs=None)
Alias for create_new_sticker_set()
create_chat_invite_link(chat_id, expire_date=None, member_limit=None, timeout=None,
api_kwargs=None)
Use this method to create an additional invite link for a chat. The bot must be an administrator in the
chat for this to work and must have the appropriate admin rights. The link can be revoked using the
method revoke_chat_invite_link().
New in version 13.4.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• expire_date (int | datetime.datetime, optional) – Date when the link will
expire. For timezone naive datetime.datetime objects, the default timezone of
the bot will be used.
• member_limit (int, optional) – Maximum number of users that can be members
of the chat simultaneously after joining the chat via this invite link; 1-99999.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns telegram.ChatInviteLink
Raises telegram.error.TelegramError –
create_new_sticker_set(user_id, name, title, emojis, png_sticker=None, con-
tains_masks=None, mask_position=None, timeout=20,
tgs_sticker=None, api_kwargs=None)
Use this method to create new sticker set owned by a user. The bot will be able to edit the created
sticker set. You must use exactly one of the fields png_sticker or tgs_sticker.
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.
90 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
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 | bytes | pathlib.Path, 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.
Changed in version 13.2: Accept bytes as input.
• tgs_sticker (str | filelike object | bytes | pathlib.Path, optional) – TGS
animation with the sticker, uploaded using multipart/form-data. See https://core.
telegram.org/animated_stickers#technical-requirements for technical requirements.
Changed in version 13.2: Accept bytes as input.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, True is returned.
Return type bool
Raises telegram.error.TelegramError –
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.
92 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, True is returned.
Return type bool
Raises telegram.error.TelegramError –
94 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
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.
• horizontal_accuracy (float, optional) – The radius of uncertainty for the
location, measured in meters; 0-1500.
• heading (int, optional) – Direction in which the user is moving, in degrees. Must
be between 1 and 360 if specified.
• proximity_alert_radius (int, optional) – Maximum distance for proximity
alerts about approaching another chat member, in meters. Must be between 1 and
100000 if specified.
• 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).
96 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, if edited message is not an inline message, the edited message is re-
turned, otherwise True is returned.
Return type telegram.Message
Raises telegram.error.TelegramError –
edit_message_text(text, chat_id=None, message_id=None, inline_message_id=None,
parse_mode=None, disable_web_page_preview=None, re-
ply_markup=None, timeout=None, api_kwargs=None, entities=None)
Use this method to edit text and game messages.
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.
• text (str) – New text of the message, 1-4096 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 your bot’s message. See
the constants in telegram.ParseMode for the available modes.
• entities (List[telegram.MessageEntity], optional) – List of special enti-
ties that appear in message text, which can be specified instead of parse_mode.
• disable_web_page_preview (bool, optional) – Disables link previews for
links in this message.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – A JSON-
serialized object for an 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, if edited message is not an inline message, the edited message is re-
turned, otherwise True is returned.
Return type telegram.Message
Raises telegram.error.TelegramError –
exportChatInviteLink(chat_id, timeout=None, api_kwargs=None)
Alias for export_chat_invite_link()
export_chat_invite_link(chat_id, timeout=None, api_kwargs=None)
Use this method to generate a new primary invite link for a chat; any previously generated link is
revoked. 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).
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Note: Each administrator in a chat generates their own invite links. Bots can’t use invite links
generated by other administrators. If you want your bot to work with invite links, it will need to
generate its own link using export_chat_invite_link() or by calling the get_chat()
method. If your bot needs to generate a new primary invite link replacing its previous one, use
export_chat_invite_link again.
property first_name
Bot’s first name.
Type str
forwardMessage(chat_id, from_chat_id, message_id, disable_notification=None, timeout=None,
api_kwargs=None)
Alias for forward_message()
forward_message(chat_id, from_chat_id, message_id, disable_notification=None, time-
out=None, api_kwargs=None)
Use this method to forward messages of any kind. Service messages can’t be forwarded.
Parameters
• 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).
• message_id (int) – Message identifier in the chat specified in from_chat_id.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, the sent Message is returned.
Return type telegram.Message
Raises telegram.error.TelegramError –
getChat(chat_id, timeout=None, api_kwargs=None)
Alias for get_chat()
getChatAdministrators(chat_id, timeout=None, api_kwargs=None)
Alias for get_chat_administrators()
98 Chapter 3. Reference
python-telegram-bot Documentation, Release 13.5
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.error.TelegramError –
get_chat_member(chat_id, user_id, timeout=None, api_kwargs=None)
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
supergroup or 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns telegram.ChatMember
Raises telegram.error.TelegramError –
get_chat_members_count(chat_id, timeout=None, api_kwargs=None)
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
supergroup or 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns Number of members in the chat.
Return type int
Raises telegram.error.TelegramError –
get_file(file_id, timeout=None, api_kwargs=None)
Use this method to get basic info about a file and prepare it for downloading. For the moment, bots
can download files of up to 20MB in size. The file can then be downloaded with telegram.File.
download(). It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a
new one can be requested by calling get_file again.
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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns telegram.File
Raises telegram.error.TelegramError –
Note:
1. This method will not work if an outgoing webhook is set up.
2. In order to avoid getting duplicate updates, recalculate offset after each server response.
3. To take full advantage of this library take a look at telegram.ext.Updater
Returns List[telegram.Update]
Raises telegram.error.TelegramError –
• 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. Applied for
supergroups and channels only. For timezone naive datetime.datetime objects,
the default timezone of the bot will be used.
• revoke_messages (bool, optional) – Pass True to delete all messages from
the chat for the user that is being removed. If False, the user will be able to see
messages in the group that were sent before the user was removed. Always True for
supergroups and channels.
New in version 13.4.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, True is returned.
Return type bool
Raises telegram.error.TelegramError –
property last_name
Optional. Bot’s last name.
Type str
leaveChat(chat_id, timeout=None, api_kwargs=None)
Alias for leave_chat()
leave_chat(chat_id, timeout=None, api_kwargs=None)
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
supergroup or 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, True is returned.
Return type bool
Raises telegram.error.TelegramError –
property link
Convenience property. Returns the t.me link of the bot.
Type str
logOut(timeout=None)
Alias for log_out()
log_out(timeout=None)
Use this method to log out from the cloud Bot API server before launching the bot locally. You must
log out the bot before running it locally, otherwise there is no guarantee that the bot will receive
updates. After a successful call, you can immediately log in on a local server, but will not be able to
log in back to the cloud Bot API server for 10 minutes.
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).
Returns On success
Return type True
Raises telegram.error.TelegramError –
property name
Bot’s @username.
Type str
pinChatMessage(chat_id, message_id, disable_notification=None, timeout=None,
api_kwargs=None)
Alias for pin_chat_message()
pin_chat_message(chat_id, message_id, disable_notification=None, timeout=None,
api_kwargs=None)
Use this method to add a message to the list of pinned messages in a chat. If the chat is not a private
chat, the bot must be an administrator in the chat for this to work and must have the telegram.
ChatMember.can_pin_messages admin right in a supergroup or telegram.ChatMember.
can_edit_messages admin right in a 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 chat members about the new pinned message. Notifications
are always disabled in channels and private chats.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, True is returned.
Return type bool
Raises telegram.error.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,
api_kwargs=None, is_anonymous=None, can_manage_chat=None,
can_manage_voice_chats=None)
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,
timeout=None, api_kwargs=None, is_anonymous=None,
can_manage_chat=None, can_manage_voice_chats=None)
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
channel (in the format @channelusername).
• user_id (int) – Unique identifier of the target user.
• is_anonymous (bool, optional) – Pass True, if the administrator’s presence in
the chat is hidden.
• can_manage_chat (bool, optional) – Pass True, if the administrator can access
the chat event log, chat statistics, message statistics in channels, see channel members,
see anonymous administrators in supergroups and ignore slow mode. Implied by any
other administrator privilege.
New in version 13.4.
• can_manage_voice_chats (bool, optional) – Pass True, if the administrator
can manage voice chats.
New in version 13.4.
• 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 cre-
ate channel posts, channels only.
• can_edit_messages (bool, optional) – Pass True, if the administrator can edit
messages of other users and can pin messages, 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, True is returned.
Return type bool
Raises telegram.error.TelegramError –
restrictChatMember(chat_id, user_id, permissions, until_date=None, timeout=None,
api_kwargs=None)
Alias for restrict_chat_member()
restrict_chat_member(chat_id, user_id, permissions, until_date=None, timeout=None,
api_kwargs=None)
Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup
for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to
lift restrictions from a user.
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. For
timezone naive datetime.datetime objects, the default timezone of the bot will
be used.
• permissions (telegram.ChatPermissions) – A JSON-serialized object
for 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, True is returned.
Return type bool
Raises telegram.error.TelegramError –
Note: thumb will be ignored for small files, for which Telegram can easily generate thumb nails.
However, this behaviour is undocumented and might be changed by Telegram.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• animation (str | filelike object | bytes | pathlib.Path | telegram.
Animation) – Animation to send. Pass a file_id as String to send an animation
that exists on the Telegram servers (recommended), pass an HTTP URL as a String
for Telegram to get an animation from the Internet, or upload a new animation us-
ing multipart/form-data. Lastly you can pass an existing telegram.Animation
object to send.
Changed in version 13.2: Accept bytes as input.
• filename (str, optional) – Custom file name for the animation, when uploading
a new file. Convenience parameter, useful e.g. when sending files generated by the
tempfile module.
New in version 13.1.
• duration (int, optional) – Duration of sent animation in seconds.
• width (int, optional) – Animation width.
• height (int, optional) – Animation height.
• thumb (filelike object | bytes | pathlib.Path, optional) – Thumbnail of the file
sent; can be ignored if thumbnail generation for the file is supported server-side. The
thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail’s
width and height should not exceed 320. Ignored if the file is not uploaded using
multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new
file.
Changed in version 13.2: Accept bytes as input.
• caption (str, optional) – Animation caption (may also be used when resending
animations 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.
• caption_entities (List[telegram.MessageEntity], optional) – List of
special entities that appear in message text, which can be specified instead of
parse_mode.
• 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.
• allow_sending_without_reply (bool, optional) – Pass True, if the mes-
sage should be sent even if the specified replied-to message is not found.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, the sent Message is returned.
Return type telegram.Message
Raises telegram.error.TelegramError –
Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
For sending voice messages, use the send_voice() method instead.
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 | bytes | pathlib.Path | 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.
Changed in version 13.2: Accept bytes as input.
• filename (str, optional) – Custom file name for the audio, when uploading a
new file. Convenience parameter, useful e.g. when sending files generated by the
tempfile module.
New in version 13.1.
• 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.
• caption_entities (List[telegram.MessageEntity], optional) – List of
special entities that appear in message text, which can be specified instead of
parse_mode.
• 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.
• allow_sending_without_reply (bool, optional) – Pass True, if the mes-
sage should be sent even if the specified replied-to message is not found.
• 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 | bytes | pathlib.Path, optional) – Thumbnail of the file
sent; can be ignored if thumbnail generation for the file is supported server-side. The
thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail’s
width and height should not exceed 320. Ignored if the file is not uploaded using
multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new
file.
Changed in version 13.2: Accept bytes as input.
• timeout (int | float, optional) – Send file timeout (default: 20 seconds).
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.
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 | bytes | pathlib.Path | 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.
Changed in version 13.2: Accept bytes as input.
• filename (str, optional) – Custom file name for the document, when uploading
a new file. Convenience parameter, useful e.g. when sending files generated by the
tempfile module.
• caption (str, optional) – Document caption (may also be used when resending
documents by file_id), 0-1024 characters after entities parsing.
• disable_content_type_detection (bool, optional) – Disables automatic
server-side content type detection for files uploaded using multipart/form-data.
• 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.
• caption_entities (List[telegram.MessageEntity], optional) – List of
special entities that appear in message text, which can be specified instead of
parse_mode.
• 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.
• allow_sending_without_reply (bool, optional) – Pass True, if the mes-
sage should be sent even if the specified replied-to message is not found.
• 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 | bytes | pathlib.Path, optional) – Thumbnail of the file
sent; can be ignored if thumbnail generation for the file is supported server-side. The
thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail’s
width and height should not exceed 320. Ignored if the file is not uploaded using
multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new
file.
Changed in version 13.2: Accept bytes as input.
• timeout (int | float, optional) – Send file timeout (default: 20 seconds).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, the sent Message is returned.
Warning: As of API 5.2 start_parameter 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.
Changed in version 13.5: As of Bot API 5.2, the parameter start_parameter is optional.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• title (str) – Product name, 1-32 characters.
• is_flexible (bool, optional) – Pass True, if the final price depends on the ship-
ping method.
• 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.
• allow_sending_without_reply (bool, optional) – Pass True, if the mes-
sage should be sent even if the specified replied-to message is not found.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – A JSON-
serialized object for an inline keyboard. If empty, one ‘Pay total price’ button will be
shown. If not empty, the first button must be a Pay button.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, the sent Message is returned.
Return type telegram.Message
Raises telegram.error.TelegramError –
send_location(chat_id, latitude=None, longitude=None, disable_notification=None,
reply_to_message_id=None, reply_markup=None, timeout=None,
location=None, live_period=None, api_kwargs=None, horizon-
tal_accuracy=None, heading=None, proximity_alert_radius=None, al-
low_sending_without_reply=None)
Use this method to send point on the map.
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.
• horizontal_accuracy (int, optional) – The radius of uncertainty for the loca-
tion, measured in meters; 0-1500.
• live_period (int, optional) – Period in seconds for which the location will be
updated, should be between 60 and 86400.
• heading (int, optional) – For live locations, a direction in which the user is moving,
in degrees. Must be between 1 and 360 if specified.
• proximity_alert_radius (int, optional) – For live locations, a maximum
distance for proximity alerts about approaching another chat member, in meters. Must
be between 1 and 100000 if specified.
• 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.
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 | bytes | pathlib.Path | 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 a new photo using multipart/form-data.
Lastly you can pass an existing telegram.PhotoSize object to send.
Changed in version 13.2: Accept bytes as input.
• filename (str, optional) – Custom file name for the photo, when uploading a
new file. Convenience parameter, useful e.g. when sending files generated by the
tempfile module.
New in version 13.1.
• caption (str, optional) – Photo caption (may also be used when resending photos
by file_id), 0-1024 characters after entities parsing.
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 | bytes | pathlib.Path | 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.
Changed in version 13.2: Accept bytes as input.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
Note:
• You can either supply venue, or latitude, longitude, title and address and op-
tionally foursquare_id and foursquare_type or optionally google_place_id and
google_place_type.
• Foursquare details and Google Pace details are mutually exclusive. However, this behaviour is
undocumented and might be changed by Telegram.
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”.)
• google_place_id (str, optional) – Google Places identifier of the venue.
• google_place_type (str, optional) – Google Places type of the venue. (See
supported types.)
• venue (telegram.Venue, optional) – The venue to send.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
Note:
• The video argument can be either a file_id, an URL or a file from disk open(filename,
'rb')
• thumb will be ignored for small video files, for which Telegram can easily generate thumb nails.
However, this behaviour is undocumented and might be changed by Telegram.
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 | bytes | pathlib.Path | 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.
Changed in version 13.2: Accept bytes as input.
• filename (str, optional) – Custom file name for the video, when uploading a
new file. Convenience parameter, useful e.g. when sending files generated by the
tempfile module.
New in version 13.1.
• 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.
• caption_entities (List[telegram.MessageEntity], optional) – List of
special entities that appear in message text, which can be specified instead of
parse_mode.
• 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.
• allow_sending_without_reply (bool, optional) – Pass True, if the mes-
sage should be sent even if the specified replied-to message is not found.
• 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 | bytes | pathlib.Path, optional) – Thumbnail of the file
sent; can be ignored if thumbnail generation for the file is supported server-side. The
thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail’s
width and height should not exceed 320. Ignored if the file is not uploaded using
multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new
file.
Changed in version 13.2: Accept bytes as input.
• timeout (int | float, optional) – Send file timeout (default: 20 seconds).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, the sent Message is returned.
Return type telegram.Message
Raises telegram.error.TelegramError –
Note:
• The video_note argument can be either a file_id or a file from disk open(filename, 'rb')
• thumb will be ignored for small video files, for which Telegram can easily generate thumb nails.
However, this behaviour is undocumented and might be changed by Telegram.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
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 | bytes | pathlib.Path | 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.
Changed in version 13.2: Accept bytes as input.
• filename (str, optional) – Custom file name for the voice, when uploading a
new file. Convenience parameter, useful e.g. when sending files generated by the
tempfile module.
New in version 13.1.
• caption (str, optional) – Voice message 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.
• caption_entities (List[telegram.MessageEntity], optional) – List of
special entities that appear in message text, which can be specified instead of
parse_mode.
• duration (int, optional) – Duration of the voice message in seconds.
• 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.
• allow_sending_without_reply (bool, optional) – Pass True, if the mes-
sage should be sent even if the specified replied-to message is not found.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, the sent Message is returned.
Return type telegram.Message
Raises telegram.error.TelegramError –
• sticker_set_name (str) – Name of the sticker set to be set as the group 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, True is returned.
Return type bool
set_chat_title(chat_id, title, timeout=None, api_kwargs=None)
Use this method to change the title of a chat. Titles can’t be changed for private chats. The bot must
be an administrator in the chat for this to work and must have the appropriate admin rights.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• title (str) – New chat title, 1-255 characters.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, True is returned.
Return type bool
Raises telegram.error.TelegramError –
set_game_score(user_id, score, chat_id=None, message_id=None, inline_message_id=None,
force=None, disable_edit_message=None, timeout=None, api_kwargs=None)
Use this method to set the score of the specified user in a game.
Parameters
• user_id (int) – User identifier.
• score (int) – New score, must be non-negative.
• force (bool, optional) – Pass True, if the high score is allowed to decrease. This
can be useful when fixing mistakes or banning cheaters.
• disable_edit_message (bool, optional) – Pass True, if the game message
should not be automatically edited to include the current scoreboard.
• chat_id (int | str, optional) – Required if inline_message_id is not specified.
Unique identifier for the target chat.
• message_id (int, optional) – Required if inline_message_id is not specified. Iden-
tifier of the sent message.
• inline_message_id (str, optional) – Required if chat_id and message_id are
not specified. Identifier of the inline message.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns The edited message, or if the message wasn’t sent by the bot , True.
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 | bytes | pathlib.Path, optional) – A PNG image
with the thumbnail, must be up to 128 kilobytes in size and have width and height
exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size;
see https://core.telegram.org/animated_stickers#technical-requirements for animated
sticker technical requirements. 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. Animated
sticker set thumbnail can’t be uploaded via HTTP URL.
Changed in version 13.2: Accept bytes as input.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, True is returned.
Return type bool
Raises telegram.error.TelegramError –
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)
• ip_address (str, optional) – The fixed IP address which will be used to send
webhook requests instead of the IP address resolved through DNS.
• 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 except telegram.Update.chat_member (default). If
not specified, the previous setting will be used. Please note that this parameter doesn’t
affect updates created before the call to the set_webhook, so unwanted updates may
be received for a short period of time.
• drop_pending_updates (bool, optional) – Pass True to drop all pending up-
dates.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Note:
1. You will not be able to receive updates using get_updates() for 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.
• chat_id (int | str) – Unique identifier for the target chat or username of the target
supergroup or channel (in the format @channelusername).
• user_id (int) – Unique identifier of the target user.
• only_if_banned (bool, optional) – Do nothing if the user is not banned.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns bool On success, True is returned.
Raises telegram.error.TelegramError –
unpinAllChatMessages(chat_id, timeout=None, api_kwargs=None)
Alias for unpin_all_chat_messages()
unpinChatMessage(chat_id, timeout=None, api_kwargs=None, message_id=None)
Alias for unpin_chat_message()
unpin_all_chat_messages(chat_id, timeout=None, api_kwargs=None)
Use this method to clear the list of pinned messages in a chat. If the chat is not a private chat,
the bot must be an administrator in the chat for this to work and must have the telegram.
ChatMember.can_pin_messages admin right in a supergroup or telegram.ChatMember.
can_edit_messages admin right in a 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, True is returned.
Return type bool
Raises telegram.error.TelegramError –
unpin_chat_message(chat_id, timeout=None, api_kwargs=None, message_id=None)
Use this method to remove a message from the list of pinned messages in a chat. If the chat is
not a private chat, the bot must be an administrator in the chat for this to work and must have the
telegram.ChatMember.can_pin_messages admin right in a supergroup or telegram.
ChatMember.can_edit_messages admin right in a 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, optional) – Identifier of a message to unpin. If not specified, the
most recent pinned message (by sending date) will be unpinned.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, True is returned.
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 | bytes | pathlib.Path) – 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.
Changed in version 13.2: Accept bytes as input.
• 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).
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the
Telegram API.
Returns On success, the uploaded File is returned.
Return type telegram.File
Raises telegram.error.TelegramError –
property username
Bot’s username.
Type str
3.2.4 telegram.BotCommand
Type str
3.2.5 telegram.CallbackQuery
Note:
• In Python from is a reserved word, use from_user instead.
• Exactly one of the fields data or game_short_name will be present.
• After the user presses an inline button, Telegram clients will display a progress bar un-
til 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).
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.
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
MAX_ANSWER_TEXT_LENGTH: ClassVar[int] = 200
telegram.constants.MAX_ANSWER_CALLBACK_QUERY_TEXT_LENGTH
New in version 13.2.
answer(text=None, show_alert=False, url=None, cache_time=None, timeout=None,
api_kwargs=None)
Shortcut for:
update.callback_query.message.copy(
chat_id,
from_chat_id=update.message.chat_id,
message_id=update.message.message_id,
*args,
**kwargs)
delete_message(timeout=None, api_kwargs=None)
Shortcut for:
update.callback_query.message.delete(*args, **kwargs)
or:
bot.edit_message_caption(caption=caption
inline_message_id=update.callback_query.inline_
˓→message_id,
*args, **kwargs)
update.callback_query.message.edit_live_location(*args, **kwargs)
or:
bot.edit_message_live_location(
inline_message_id=update.callback_query.inline_message_id,
*args, **kwargs
)
update.callback_query.message.edit_media(*args, **kwargs)
or:
bot.edit_message_media(inline_message_id=update.callback_query.inline_
˓→message_id,
*args, **kwargs)
update.callback_query.message.edit_reply_markup(
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
)
or:
bot.edit_message_text(text, inline_message_id=update.callback_query.inline_
˓→message_id,
*args, **kwargs)
update.callback_query.message.get_game_high_score(*args, **kwargs)
or:
bot.get_game_high_scores(inline_message_id=update.callback_query.inline_
˓→message_id,
*args, **kwargs)
Returns List[telegram.GameHighScore]
pin_message(disable_notification=None, timeout=None, api_kwargs=None)
Shortcut for:
bot.pin_chat_message(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
update.callback_query.message.set_game_score(*args, **kwargs)
or:
bot.set_game_score(inline_message_id=update.callback_query.inline_message_
˓→id,
*args, **kwargs)
update.callback_query.message.stop_live_location(*args, **kwargs)
or:
bot.stop_message_live_location(
inline_message_id=update.callback_query.inline_message_id,
*args, **kwargs
)
bot.unpin_chat_message(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
3.2.6 telegram.Chat
Type telegram.Message
permissions
Optional. Default chat member permissions, for groups and supergroups. Returned only in
telegram.Bot.get_chat().
Type telegram.ChatPermissions
slow_mode_delay
Optional. For supergroups, the minimum allowed delay between consecutive messages sent by each
unprivileged user. Returned only in telegram.Bot.get_chat().
Type int
message_auto_delete_time
Optional. The time after which all messages sent to the chat will be automatically deleted; in seconds.
Returned only in telegram.Bot.get_chat().
New in version 13.4.
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
linked_chat_id
Optional. Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and
vice versa; for supergroups and channel chats. Returned only in telegram.Bot.get_chat().
Type int
location
Optional. For supergroups, the location to which the supergroup is connected. Returned only in
telegram.Bot.get_chat().
Type telegram.ChatLocation
CHANNEL: ClassVar[str] = 'channel'
telegram.constants.CHAT_CHANNEL
GROUP: ClassVar[str] = 'group'
telegram.constants.CHAT_GROUP
PRIVATE: ClassVar[str] = 'private'
telegram.constants.CHAT_PRIVATE
SENDER: ClassVar[str] = 'sender'
telegram.constants.CHAT_SENDER
New in version 13.5.
SUPERGROUP: ClassVar[str] = 'supergroup'
telegram.constants.CHAT_SUPERGROUP
copy_message(chat_id, message_id, caption=None, parse_mode=None, cap-
tion_entities=None, disable_notification=None, reply_to_message_id=None,
allow_sending_without_reply=None, reply_markup=None, timeout=None,
api_kwargs=None)
Shortcut for:
bot.copy_message(from_chat_id=update.effective_chat.id, *args, **kwargs)
bot.create_chat_invite_link(chat_id=update.effective_chat.id, *args,
˓→**kwargs)
bot.edit_chat_invite_link(chat_id=update.effective_chat.id, *args,
˓→**kwargs)
bot.export_chat_invite_link(chat_id=update.effective_chat.id, *args,
˓→**kwargs)
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(timeout=None, api_kwargs=None)
Shortcut for:
bot.pin_chat_message(chat_id=update.effective_chat.id,
*args,
**kwargs)
bot.revoke_chat_invite_link(chat_id=update.effective_chat.id, *args,
˓→**kwargs)
Warning: As of API 5.2 start_parameter 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.
Changed in version 13.5: As of Bot API 5.2, the parameter start_parameter is optional.
Returns On success, instance representing the message posted.
Return type telegram.Message
send_location(latitude=None, longitude=None, disable_notification=None, re-
ply_to_message_id=None, reply_markup=None, timeout=None,
location=None, live_period=None, api_kwargs=None, horizon-
tal_accuracy=None, heading=None, proximity_alert_radius=None, al-
low_sending_without_reply=None)
Shortcut for:
bot.set_chat_administrator_custom_title(update.effective_chat.id, *args,
˓→**kwargs)
bot.unpin_all_chat_messages(chat_id=update.effective_chat.id,
*args,
**kwargs)
bot.unpin_chat_message(chat_id=update.effective_chat.id,
*args,
**kwargs)
3.2.7 telegram.ChatAction
class telegram.ChatAction
Bases: object
Helper class to provide constants for different chat actions.
FIND_LOCATION: ClassVar[str] = 'find_location'
telegram.constants.CHATACTION_FIND_LOCATION
RECORD_AUDIO: ClassVar[str] = 'record_audio'
telegram.constants.CHATACTION_RECORD_AUDIO
Deprecated since version 13.5: Deprecated by Telegram. Use RECORD_VOICE instead, as backwards
compatibility is not guaranteed by Telegram.
RECORD_VIDEO: ClassVar[str] = 'record_video'
telegram.constants.CHATACTION_RECORD_VIDEO
RECORD_VIDEO_NOTE: ClassVar[str] = 'record_video_note'
telegram.constants.CHATACTION_RECORD_VIDEO_NOTE
RECORD_VOICE: ClassVar[str] = 'record_voice'
telegram.constants.CHATACTION_RECORD_VOICE
New in version 13.5.
TYPING: ClassVar[str] = 'typing'
telegram.constants.CHATACTION_TYPING
UPLOAD_AUDIO: ClassVar[str] = 'upload_audio'
telegram.constants.CHATACTION_UPLOAD_AUDIO
Deprecated since version 13.5: Deprecated by Telegram. Use UPLOAD_VOICE instead, as backwards
compatibility is not guaranteed by Telegram.
UPLOAD_DOCUMENT: ClassVar[str] = 'upload_document'
telegram.constants.CHATACTION_UPLOAD_DOCUMENT
UPLOAD_PHOTO: ClassVar[str] = 'upload_photo'
telegram.constants.CHATACTION_UPLOAD_PHOTO
UPLOAD_VIDEO: ClassVar[str] = 'upload_video'
telegram.constants.CHATACTION_UPLOAD_VIDEO
UPLOAD_VIDEO_NOTE: ClassVar[str] = 'upload_video_note'
telegram.constants.CHATACTION_UPLOAD_VIDEO_NOTE
UPLOAD_VOICE: ClassVar[str] = 'upload_voice'
telegram.constants.CHATACTION_UPLOAD_VOICE
New in version 13.5.
3.2.8 telegram.ChatInviteLink
3.2.9 telegram.ChatLocation
address
Location address, as defined by the chat owner
Type str
3.2.10 telegram.ChatMember
can_manage_voice_chats
Optional. if the administrator can manage voice chats.
New in version 13.4.
Type bool
can_change_info
Optional. If the user can change the chat title, photo and other settings.
Type bool
can_post_messages
Optional. If the administrator can post in the channel.
Type bool
can_edit_messages
Optional. If the administrator can edit messages of other users.
Type bool
can_delete_messages
Optional. If the administrator can delete messages of other users.
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
ADMINISTRATOR: ClassVar[str] = 'administrator'
telegram.constants.CHATMEMBER_ADMINISTRATOR
CREATOR: ClassVar[str] = 'creator'
telegram.constants.CHATMEMBER_CREATOR
KICKED: ClassVar[str] = 'kicked'
telegram.constants.CHATMEMBER_KICKED
LEFT: ClassVar[str] = 'left'
telegram.constants.CHATMEMBER_LEFT
MEMBER: ClassVar[str] = 'member'
telegram.constants.CHATMEMBER_MEMBER
RESTRICTED: ClassVar[str] = 'restricted'
telegram.constants.CHATMEMBER_RESTRICTED
3.2.11 telegram.ChatMemberUpdated
Parameters
• chat (telegram.Chat) – Chat the user belongs to.
• from_user (telegram.User) – Performer of the action, which resulted in the
change.
• date (datetime.datetime) – Date the change was done in Unix time. Converted
to datetime.datetime.
• old_chat_member (telegram.ChatMember) – Previous information about the
chat member.
• new_chat_member (telegram.ChatMember) – New information about the chat
member.
• invite_link (telegram.ChatInviteLink, optional) – Chat invite link,
which was used by the user to join the chat. For joining by invite link events only.
chat
Chat the user belongs to.
Type telegram.Chat
from_user
Performer of the action, which resulted in the change.
Type telegram.User
date
Date the change was done in Unix time. Converted to datetime.datetime.
Type datetime.datetime
old_chat_member
Previous information about the chat member.
Type telegram.ChatMember
new_chat_member
New information about the chat member.
Type telegram.ChatMember
invite_link
Optional. Chat invite link, which was used by the user to join the chat.
Type telegram.ChatInviteLink
difference()
Computes the difference between old_chat_member and new_chat_member.
Example
>>> chat_member_updated.difference()
{'custom_title': ('old title', 'new title')}
3.2.12 telegram.ChatPermissions
Note: Though not stated explicitly in the official 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.
Parameters
• can_send_messages (bool, optional) – True, if the user is allowed to send text
messages, contacts, locations and venues.
• can_send_media_messages (bool, optional) – True, if the user is allowed
to send audios, documents, photos, videos, video notes and voice notes, implies
can_send_messages.
• can_send_polls (bool, optional) – True, if the user is allowed to send polls,
implies can_send_messages.
• can_send_other_messages (bool, optional) – True, if the user is al-
lowed to send animations, games, stickers and use inline bots, implies
can_send_media_messages.
• can_add_web_page_previews (bool, optional) – True, if the user is allowed
to add web page previews to their messages, implies can_send_media_messages.
• can_change_info (bool, optional) – True, if the user is allowed to change the
chat title, photo and other settings. Ignored in public supergroups.
• can_invite_users (bool, optional) – True, if the user is allowed to invite new
users to the chat.
• can_pin_messages (bool, optional) – True, if the user is allowed to pin mes-
sages. Ignored in public supergroups.
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
3.2.13 telegram.ChatPhoto
get_small_file(timeout=None, api_kwargs=None)
Convenience wrapper over telegram.Bot.get_file for getting the small (160x160) chat photo
For the documentation of the arguments, please see telegram.Bot.get_file().
Returns telegram.File
Raises telegram.error.TelegramError –
Type int
telegram.constants.MAX_ANSWER_CALLBACK_QUERY_TEXT_LENGTH
200
New in version 13.2.
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
telegram.constants.ANONYMOUS_ADMIN_ID
1087968824 (User id in groups for anonymous admin)
Type int
telegram.constants.SERVICE_CHAT_ID
777000 (Telegram service chat, that also acts as sender of channel posts forwarded to discussion groups)
Type int
The following constants are related to specific classes and are also available as attributes of those classes:
telegram.Chat:
telegram.constants.CHAT_PRIVATE
'private'
Type str
telegram.constants.CHAT_GROUP
'group'
Type str
telegram.constants.CHAT_SUPERGROUP
'supergroup'
Type str
telegram.constants.CHAT_CHANNEL
'channel'
Type str
telegram.constants.CHAT_SENDER
'sender'. Only relevant for telegram.InlineQuery.chat_type.
New in version 13.5.
Type str
telegram.ChatAction:
telegram.constants.CHATACTION_FIND_LOCATION
'find_location'
Type str
telegram.constants.CHATACTION_RECORD_AUDIO
'record_audio'
Deprecated since version 13.5: Deprecated by Telegram. Use CHATACTION_RECORD_VOICE instead.
Type str
telegram.constants.CHATACTION_RECORD_VOICE
'record_voice'
New in version 13.5.
Type str
telegram.constants.CHATACTION_RECORD_VIDEO
'record_video'
Type str
telegram.constants.CHATACTION_RECORD_VIDEO_NOTE
'record_video_note'
Type str
telegram.constants.CHATACTION_TYPING
'typing'
Type str
telegram.constants.CHATACTION_UPLOAD_AUDIO
'upload_audio'
Deprecated since version 13.5: Deprecated by Telegram. Use CHATACTION_UPLOAD_VOICE instead.
Type str
telegram.constants.CHATACTION_UPLOAD_VOICE
'upload_voice'
New in version 13.5.
Type str
telegram.constants.CHATACTION_UPLOAD_DOCUMENT
'upload_document'
Type str
telegram.constants.CHATACTION_UPLOAD_PHOTO
'upload_photo'
Type str
telegram.constants.CHATACTION_UPLOAD_VIDEO
'upload_video'
Type str
telegram.constants.CHATACTION_UPLOAD_VIDEO_NOTE
'upload_video_note'
Type str
telegram.ChatMember:
telegram.constants.CHATMEMBER_ADMINISTRATOR
'administrator'
Type str
telegram.constants.CHATMEMBER_CREATOR
'creator'
Type str
telegram.constants.CHATMEMBER_KICKED
'kicked'
Type str
telegram.constants.CHATMEMBER_LEFT
'left'
Type str
telegram.constants.CHATMEMBER_MEMBER
'member'
Type str
telegram.constants.CHATMEMBER_RESTRICTED
'restricted'
Type str
telegram.Dice:
telegram.constants.DICE_DICE
''
Type str
telegram.constants.DICE_DARTS
''
Type str
telegram.constants.DICE_BASKETBALL
''
Type str
telegram.constants.DICE_FOOTBALL
''
Type str
telegram.constants.DICE_SLOT_MACHINE
''
Type str
telegram.constants.DICE_BOWLING
''
New in version 13.4.
Type str
telegram.constants.DICE_ALL_EMOJI
List of all supported base emoji.
Changed in version 13.4: Added DICE_BOWLING
Type List[str]
telegram.MessageEntity:
telegram.constants.MESSAGEENTITY_MENTION
'mention'
Type str
telegram.constants.MESSAGEENTITY_HASHTAG
'hashtag'
Type str
telegram.constants.MESSAGEENTITY_CASHTAG
'cashtag'
Type str
telegram.constants.MESSAGEENTITY_PHONE_NUMBER
'phone_number'
Type str
telegram.constants.MESSAGEENTITY_BOT_COMMAND
'bot_command'
Type str
telegram.constants.MESSAGEENTITY_URL
'url'
Type str
telegram.constants.MESSAGEENTITY_EMAIL
'email'
Type str
telegram.constants.MESSAGEENTITY_BOLD
'bold'
Type str
telegram.constants.MESSAGEENTITY_ITALIC
'italic'
Type str
telegram.constants.MESSAGEENTITY_CODE
'code'
Type str
telegram.constants.MESSAGEENTITY_PRE
'pre'
Type str
telegram.constants.MESSAGEENTITY_TEXT_LINK
'text_link'
Type str
telegram.constants.MESSAGEENTITY_TEXT_MENTION
'text_mention'
Type str
telegram.constants.MESSAGEENTITY_UNDERLINE
'underline'
Type str
telegram.constants.MESSAGEENTITY_STRIKETHROUGH
'strikethrough'
Type str
telegram.constants.MESSAGEENTITY_ALL_TYPES
List of all the types of message entity.
Type List[str]
telegram.ParseMode:
telegram.constants.PARSEMODE_MARKDOWN
'Markdown'
Type str
telegram.constants.PARSEMODE_MARKDOWN_V2
'MarkdownV2'
Type str
telegram.constants.PARSEMODE_HTML
'HTML'
Type str
telegram.Poll:
telegram.constants.POLL_REGULAR
'regular'
Type str
telegram.constants.POLL_QUIZ
'quiz'
Type str
telegram.constants.MAX_POLL_QUESTION_LENGTH
300
Type int
telegram.constants.MAX_POLL_OPTION_LENGTH
100
Type int
telegram.MaskPosition:
telegram.constants.STICKER_FOREHEAD
'forehead'
Type str
telegram.constants.STICKER_EYES
'eyes'
Type str
telegram.constants.STICKER_MOUTH
'mouth'
Type str
telegram.constants.STICKER_CHIN
'chin'
Type str
telegram.Update:
telegram.constants.UPDATE_MESSAGE
'message'
New in version 13.5.
Type str
telegram.constants.UPDATE_EDITED_MESSAGE
'edited_message'
New in version 13.5.
Type str
telegram.constants.UPDATE_CHANNEL_POST
'channel_post'
New in version 13.5.
Type str
telegram.constants.UPDATE_EDITED_CHANNEL_POST
'edited_channel_post'
New in version 13.5.
Type str
telegram.constants.UPDATE_INLINE_QUERY
'inline_query'
New in version 13.5.
Type str
telegram.constants.UPDATE_CHOSEN_INLINE_RESULT
'chosen_inline_result'
New in version 13.5.
Type str
telegram.constants.UPDATE_CALLBACK_QUERY
'callback_query'
New in version 13.5.
Type str
telegram.constants.UPDATE_SHIPPING_QUERY
'shipping_query'
New in version 13.5.
Type str
telegram.constants.UPDATE_PRE_CHECKOUT_QUERY
'pre_checkout_query'
New in version 13.5.
Type str
telegram.constants.UPDATE_POLL
'poll'
New in version 13.5.
Type str
telegram.constants.UPDATE_POLL_ANSWER
'poll_answer'
New in version 13.5.
Type str
telegram.constants.UPDATE_MY_CHAT_MEMBER
'my_chat_member'
New in version 13.5.
Type str
telegram.constants.UPDATE_CHAT_MEMBER
'chat_member'
New in version 13.5.
Type str
telegram.constants.UPDATE_ALL_TYPES
List of all update types.
New in version 13.5.
Type List[str]
3.2.15 telegram.Contact
3.2.16 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.
If emoji is “”, a value of 4 to 5 currently scores a goal, while a value of 1 to 3 indicates that the goal was
missed. However, this behaviour is undocumented and might be changed by Telegram.
If emoji is “”, a value of 6 knocks all the pins, while a value of 1 means all the pins were missed. However,
this behaviour is undocumented and might be changed by Telegram.
If emoji is “”, each value corresponds to a unique combination of symbols, which can be found at our
wiki. However, this behaviour is undocumented and might be changed by Telegram.
Parameters
• value (int) – Value of the dice. 1-6 for dice, darts and bowling balls, 1-5 for basket-
ball and football/soccer ball, 1-64 for slot machine.
• emoji (str) – Emoji on which the dice throw animation is based.
value
Value of the dice.
Type int
emoji
Emoji on which the dice throw animation is based.
Type str
ALL_EMOJI: ClassVar[List[str]] = ['', '', '', '', '', '']
telegram.constants.DICE_ALL_EMOJI
BASKETBALL: ClassVar[str] = ''
telegram.constants.DICE_BASKETBALL
BOWLING: ClassVar[str] = ''
telegram.constants.DICE_BOWLING
New in version 13.4.
DARTS: ClassVar[str] = ''
telegram.constants.DICE_DARTS
DICE: ClassVar[str] = ''
telegram.constants.DICE_DICE
FOOTBALL: ClassVar[str] = ''
telegram.constants.DICE_FOOTBALL
SLOT_MACHINE: ClassVar[str] = ''
telegram.constants.DICE_SLOT_MACHINE
3.2.17 telegram.Document
Returns telegram.File
Raises telegram.error.TelegramError –
3.2.19 telegram.File
Note:
• Maximum file size to download is 20 MB.
• 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
• file_id (str) – Identifier for this file, which can be used to download or reuse the
file.
• file_unique_id (str) – 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.
• 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.
file_id
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
download(custom_path=None, out=None, timeout=None)
Download this file. By default, the file is saved in the current working directory with its original
filename as reported by Telegram. If the file has no filename, it the file ID will be used as filename. If
a custom_path is supplied, it will be saved to that path instead. If out is defined, the file contents
will be saved to that object using the out.write method.
Note:
• custom_path and out are mutually exclusive.
• If neither custom_path nor out is provided and file_path is the path of a local file (which
is the case when a Bot API Server is running in local mode), this method will just return the path.
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 or the file path of the local file.
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.20 telegram.ForceReply
3.2.21 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.
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) – An HTTP URL used to automati-
cally 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.
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
Optional. An HTTP URL used to automatically 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
3.2.22 telegram.InlineKeyboardMarkup
InlineKeyboardMarkup([[button]], **kwargs)
InlineKeyboardMarkup([button_row], **kwargs)
3.2.23 telegram.InputFile
3.2.24 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.25 telegram.InputMediaAnimation
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.
Parameters
• media (str | filelike object | bytes | pathlib.Path | telegram.Animation)
– File to send. Pass a file_id to send a file that exists on the Telegram servers (recom-
mended), pass an HTTP URL for Telegram to get a file from the Internet. Lastly you
can pass an existing telegram.Animation object to send.
Changed in version 13.2: Accept bytes as input.
• filename (str, optional) – Custom file name for the animation, when uploading
a new file. Convenience parameter, useful e.g. when sending files generated by the
tempfile module.
New in version 13.1.
• thumb (filelike object | bytes | pathlib.Path, optional) – Thumbnail of the file
sent; can be ignored if thumbnail generation for the file is supported server-side. The
thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail’s
width and height should not exceed 320. Ignored if the file is not uploaded using
multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new
file.
Changed in version 13.2: Accept bytes as input.
• 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.
• caption_entities (List[telegram.MessageEntity], optional) – List of
special entities that appear in the caption, which can be specified instead of parse_mode.
• width (int, optional) – Animation width.
• height (int, optional) – Animation height.
• duration (int, optional) – Animation duration.
type
animation.
Type str
media
Animation 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
caption_entities
Optional. List of special entities that appear in the caption.
Type List[telegram.MessageEntity]
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
3.2.26 telegram.InputMediaAudio
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.
Parameters
• media (str | filelike object | bytes | pathlib.Path | 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.Audio object to send.
Changed in version 13.2: Accept bytes as input.
• filename (str, optional) – Custom file name for the audio, when uploading a
new file. Convenience parameter, useful e.g. when sending files generated by the
tempfile module.
New in version 13.1.
• 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.
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
caption_entities
Optional. List of special entities that appear in the caption.
Type List[telegram.MessageEntity]
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
3.2.27 telegram.InputMediaDocument
caption_entities
Optional. List of special entities that appear in the caption.
Type List[telegram.MessageEntity]
thumb
Optional. Thumbnail of the file to send.
Type telegram.InputFile
disable_content_type_detection
Optional. Disables automatic server-side content type detection for files uploaded using
multipart/form-data. Always true, if the document is sent as part of an album.
Type bool
3.2.28 telegram.InputMediaPhoto
caption_entities
Optional. List of special entities that appear in the caption.
Type List[telegram.MessageEntity]
3.2.29 telegram.InputMediaVideo
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.
• thumb will be ignored for small video files, for which Telegram can easily generate thumb nails.
However, this behaviour is undocumented and might be changed by Telegram.
Parameters
• media (str | filelike object | bytes | pathlib.Path | 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.
Changed in version 13.2: Accept bytes as input.
• filename (str, optional) – Custom file name for the video, when uploading a
new file. Convenience parameter, useful e.g. when sending files generated by the
tempfile module.
New in version 13.1.
• 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.
• caption_entities (List[telegram.MessageEntity], optional) – List of
special entities that appear in the caption, which can be specified instead of parse_mode.
• 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 | bytes | pathlib.Path, optional) – Thumbnail of the file
sent; can be ignored if thumbnail generation for the file is supported server-side. The
thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail’s
width and height should not exceed 320. Ignored if the file is not uploaded using
multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new
file.
Changed in version 13.2: Accept bytes as input.
type
video.
Type str
media
Video 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
caption_entities
Optional. List of special entities that appear in the caption.
Type List[telegram.MessageEntity]
width
Optional. Video width.
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
3.2.30 telegram.KeyboardButton
Note:
• Optional fields are mutually exclusive.
• request_contact and request_location options will only work in Telegram versions re-
leased 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.
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.
text
Text of the button.
Type str
request_contact
Optional. The user’s phone number will be sent.
Type bool
request_location
Optional. The user’s current location will be sent.
Type bool
request_poll
Optional. If the user should create a poll.
Type KeyboardButtonPollType
3.2.31 telegram.KeyboardButtonPollType
3.2.32 telegram.Location
3.2.33 telegram.LoginUrl
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
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
• forward_text (str, optional) – New text of the button in forwarded messages.
• bot_username (str, optional) – Username of a bot, which will be used for user
authorization. See Setting up a bot for more details. If not specified, the current bot’s
username will be assumed. The url’s domain must be the same as the domain linked
with the bot. See Linking your domain to the bot for more details.
• request_write_access (bool, optional) – Pass True to request the permission
for your bot to send messages to the user.
url
An HTTP URL to be opened with user authorization data.
Type str
forward_text
Optional. New text of the button in forwarded messages.
Type str
bot_username
Optional. Username of a bot, which will be used for user authorization.
Type str
request_write_access
Optional. Pass True to request the permission for your bot to send messages to the user.
Type bool
3.2.34 telegram.Message
Parameters
• message_id (int) – Unique message identifier inside this chat.
• from_user (telegram.User, optional) – Sender, empty for messages sent to
channels.
• sender_chat (telegram.Chat, optional) – Sender of the message, sent on behalf
of a chat. The channel itself for channel messages. The supergroup itself for messages
from anonymous group administrators. The linked channel for messages automatically
forwarded to the discussion group.
• 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 channels or from anonymous administrators, information about the original sender
chat.
• 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.
message_id
Unique message identifier inside this chat.
Type int
from_user
Optional. Sender.
Type telegram.User
sender_chat
Optional. Sender of the message, sent on behalf of a chat. The channel itself for channel messages.
The supergroup itself for messages from anonymous group administrators. The linked channel for
messages automatically forwarded to the discussion group.
Type telegram.Chat
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. For messages forwarded from channels or from anonymous administrators, information
about the original sender chat.
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. For replies, the original message. Note that the Message object in this field will not contain
further reply_to_message fields even if it itself is a reply.
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
message_auto_delete_timer_changed
Optional. Service message: auto-delete timer settings changed in the chat.
New in version 13.4.
Type telegram.MessageAutoDeleteTimerChanged
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, or the custom title of an anonymous
group administrator.
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
proximity_alert_triggered
Optional. Service message. A user in the chat triggered another user’s proximity alert while sharing
Live Location.
Type telegram.ProximityAlertTriggered
voice_chat_scheduled
Optional. Service message: voice chat scheduled.
New in version 13.5.
Type telegram.VoiceChatScheduled
voice_chat_started
Optional. Service message: voice chat started.
New in version 13.4.
Type telegram.VoiceChatStarted
voice_chat_ended
Optional. Service message: voice chat ended.
New in version 13.4.
Type telegram.VoiceChatEnded
voice_chat_participants_invited
Optional. Service message: new participants invited to a voice chat.
New in version 13.4.
Type telegram.VoiceChatParticipantsInvited
reply_markup
Optional. Inline keyboard attached to the message.
Type telegram.InlineKeyboardMarkup
bot
Optional. The Bot to use for instance methods.
Type telegram.Bot
property 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 caption entities formatted as HTML.
Return type str
property 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
property 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.
property 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.
property 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
property 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
property chat_id
Shortcut for telegram.Chat.id for chat.
Type int
bot.copy_message(chat_id=chat_id,
from_chat_id=update.effective_message.chat_id,
message_id=update.effective_message.message_id,
*args,
**kwargs)
bot.delete_message(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
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.
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_live_location(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.
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_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.
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_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.
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(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.
Returns On success, if edited message is sent by the bot, the edited Message is returned,
otherwise True is returned.
Return type telegram.Message
property 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, disable_notification=None, timeout=None, api_kwargs=None)
Shortcut for:
bot.forward_message(chat_id=chat_id,
from_chat_id=update.effective_message.chat_id,
message_id=update.effective_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.
Returns List[telegram.GameHighScore]
property 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.)
bot.pin_chat_message(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
bot.copy_message(chat_id=message.chat.id,
from_chat_id=from_chat_id,
message_id=message_id,
*args,
**kwargs)
Parameters 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(document, filename=None, caption=None, disable_notification=None,
reply_to_message_id=None, reply_markup=None, timeout=20,
parse_mode=None, thumb=None, api_kwargs=None, dis-
able_content_type_detection=None, allow_sending_without_reply=None,
caption_entities=None, quote=None)
Shortcut for:
bot.send_message(
update.effective_message.chat_id,
parse_mode=ParseMode.HTML,
*args,
**kwargs,
)
Warning: As of API 5.2 start_parameter 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.
bot.send_message(
update.effective_message.chat_id,
parse_mode=ParseMode.MARKDOWN,
*args,
(continues on next page)
Parameters 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
bot.send_message(
update.effective_message.chat_id,
parse_mode=ParseMode.MARKDOWN_V2,
*args,
**kwargs,
)
Parameters 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(latitude=None, longitude=None, title=None, address=None,
foursquare_id=None, disable_notification=None, reply_to_message_id=None,
reply_markup=None, timeout=None, venue=None, foursquare_type=None,
api_kwargs=None, google_place_id=None, google_place_type=None, al-
low_sending_without_reply=None, quote=None)
Shortcut for:
bot.set_game_score(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.
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.stop_message_live_location(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.
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.stop_poll(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
property 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.
property 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
property 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
unpin(timeout=None, api_kwargs=None)
Shortcut for:
bot.unpin_chat_message(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)
3.2.35 telegram.MessageAutoDeleteTimerChanged
class telegram.MessageAutoDeleteTimerChanged(message_auto_delete_time,
**_kwargs)
Bases: telegram.base.TelegramObject
This object represents a service message about a change in auto-delete timer settings.
Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if
their message_auto_delete_time is equal.
New in version 13.4.
Parameters
• message_auto_delete_time (int) – New auto-delete time for messages in the
chat.
• **kwargs (dict) – Arbitrary keyword arguments.
message_auto_delete_time
New auto-delete time for messages in the chat.
Type int
3.2.36 telegram.MessageId
3.2.37 telegram.MessageEntity
language
Optional. Programming language of the entity text.
Type str
ALL_TYPES: ClassVar[List[str]] = ['mention', 'hashtag', 'cashtag', 'phone_number', '
telegram.constants.MESSAGEENTITY_ALL_TYPES
List of all the types
BOLD: ClassVar[str] = 'bold'
telegram.constants.MESSAGEENTITY_BOLD
BOT_COMMAND: ClassVar[str] = 'bot_command'
telegram.constants.MESSAGEENTITY_BOT_COMMAND
CASHTAG: ClassVar[str] = 'cashtag'
telegram.constants.MESSAGEENTITY_CASHTAG
CODE: ClassVar[str] = 'code'
telegram.constants.MESSAGEENTITY_CODE
EMAIL: ClassVar[str] = 'email'
telegram.constants.MESSAGEENTITY_EMAIL
HASHTAG: ClassVar[str] = 'hashtag'
telegram.constants.MESSAGEENTITY_HASHTAG
ITALIC: ClassVar[str] = 'italic'
telegram.constants.MESSAGEENTITY_ITALIC
MENTION: ClassVar[str] = 'mention'
telegram.constants.MESSAGEENTITY_MENTION
PHONE_NUMBER: ClassVar[str] = 'phone_number'
telegram.constants.MESSAGEENTITY_PHONE_NUMBER
PRE: ClassVar[str] = 'pre'
telegram.constants.MESSAGEENTITY_PRE
STRIKETHROUGH: ClassVar[str] = 'strikethrough'
telegram.constants.MESSAGEENTITY_STRIKETHROUGH
TEXT_LINK: ClassVar[str] = 'text_link'
telegram.constants.MESSAGEENTITY_TEXT_LINK
TEXT_MENTION: ClassVar[str] = 'text_mention'
telegram.constants.MESSAGEENTITY_TEXT_MENTION
UNDERLINE: ClassVar[str] = 'underline'
telegram.constants.MESSAGEENTITY_UNDERLINE
URL: ClassVar[str] = 'url'
telegram.constants.MESSAGEENTITY_URL
3.2.38 telegram.ParseMode
class telegram.ParseMode
Bases: object
This object represents a Telegram Message Parse Modes.
HTML: ClassVar[str] = 'HTML'
telegram.constants.PARSEMODE_HTML
MARKDOWN: ClassVar[str] = 'Markdown'
telegram.constants.PARSEMODE_MARKDOWN
Note: MARKDOWN is a legacy mode, retained by Telegram for backward compatibility. You should
use MARKDOWN_V2 instead.
3.2.39 telegram.PhotoSize
get_file(timeout=None, api_kwargs=None)
Convenience wrapper over telegram.Bot.get_file
For the documentation of the arguments, please see telegram.Bot.get_file().
Returns telegram.File
Raises telegram.error.TelegramError –
3.2.40 telegram.Poll
Type str
explanation_entities
Optional. Special entities like usernames, URLs, bot commands, etc. that appear in the
explanation.
Type List[telegram.MessageEntity]
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-300 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.
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.
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.41 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.42 telegram.PollOption
3.2.43 telegram.ProximityAlertTriggered
3.2.44 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.
Note: User will not be able to summon this keyboard; if you want to hide the keyboard from sight but keep
it accessible, use telegram.ReplyKeyboardMarkup.one_time_keyboard.
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 telegram.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.
remove_keyboard
Requests clients to remove the custom keyboard.
Type True
selective
Optional. Use this parameter if you want to remove the keyboard for specific users only.
Type bool
3.2.45 telegram.ReplyKeyboardMarkup
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
Array of button rows.
Type List[List[telegram.KeyboardButton | str]]
resize_keyboard
Optional. Requests clients to resize the keyboard.
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
classmethod from_button(button, resize_keyboard=False, one_time_keyboard=False, selec-
tive=False, **kwargs)
Shortcut for:
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.46 telegram.ReplyMarkup
class telegram.ReplyMarkup
Bases: telegram.base.TelegramObject
Base class for Telegram ReplyMarkup Objects.
See telegram.InlineKeyboardMarkup, telegram.ReplyKeyboardMarkup, telegram.
ReplyKeyboardRemove and telegram.ForceReply for detailed use.
3.2.47 telegram.TelegramObject
class telegram.TelegramObject
Bases: object
Base class for most telegram objects.
to_json()
Returns str
3.2.48 telegram.Update
Note: At most one of the optional parameters can be present in any given update.
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. If there are no new updates
for at least a week, then identifier of the next update will be chosen randomly instead of
sequentially.
• message (telegram.Message, optional) – New incoming message of any kind -
text, photo, sticker, etc.
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
my_chat_member
Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received
only when the bot is blocked or unblocked by the user.
New in version 13.4.
Type telegram.ChatMemberUpdated
chat_member
Optional. A chat member’s status was updated in a chat. The bot must be an
administrator in the chat and must explicitly specify 'chat_member' in the list of
'allowed_updates' to receive these updates (see telegram.Bot.get_updates(),
telegram.Bot.set_webhook(), telegram.ext.Updater.start_polling() and
telegram.ext.Updater.start_webhook()).
New in version 13.4.
Type telegram.ChatMemberUpdated
ALL_TYPES = ['message', 'edited_message', 'channel_post', 'edited_channel_post', 'in
telegram.constants.UPDATE_ALL_TYPES
New in version 13.5.
CALLBACK_QUERY = 'callback_query'
telegram.constants.UPDATE_CALLBACK_QUERY
New in version 13.5.
CHANNEL_POST = 'channel_post'
telegram.constants.UPDATE_CHANNEL_POST
New in version 13.5.
CHAT_MEMBER = 'chat_member'
telegram.constants.UPDATE_CHAT_MEMBER
New in version 13.5.
CHOSEN_INLINE_RESULT = 'chosen_inline_result'
telegram.constants.UPDATE_CHOSEN_INLINE_RESULT
New in version 13.5.
EDITED_CHANNEL_POST = 'edited_channel_post'
telegram.constants.UPDATE_EDITED_CHANNEL_POST
New in version 13.5.
EDITED_MESSAGE = 'edited_message'
telegram.constants.UPDATE_EDITED_MESSAGE
New in version 13.5.
INLINE_QUERY = 'inline_query'
telegram.constants.UPDATE_INLINE_QUERY
New in version 13.5.
MESSAGE = 'message'
telegram.constants.UPDATE_MESSAGE
New in version 13.5.
MY_CHAT_MEMBER = 'my_chat_member'
telegram.constants.UPDATE_MY_CHAT_MEMBER
New in version 13.5.
POLL = 'poll'
telegram.constants.UPDATE_POLL
New in version 13.5.
POLL_ANSWER = 'poll_answer'
telegram.constants.UPDATE_POLL_ANSWER
New in version 13.5.
PRE_CHECKOUT_QUERY = 'pre_checkout_query'
telegram.constants.UPDATE_PRE_CHECKOUT_QUERY
New in version 13.5.
SHIPPING_QUERY = 'shipping_query'
telegram.constants.UPDATE_SHIPPING_QUERY
New in version 13.5.
classmethod de_json(data, bot)
property effective_chat
The chat that this update was sent in, no matter what kind of update this is. Will be None
for inline_query, chosen_inline_result, callback_query from inline messages,
shipping_query, pre_checkout_query, poll and poll_answer.
Type telegram.Chat
property effective_message
The message included in this update, no matter what kind of update this is. Will be None
for inline_query, chosen_inline_result, callback_query from inline messages,
shipping_query, pre_checkout_query, poll and poll_answer.
Type telegram.Message
property effective_user
The user that sent this update, no matter what kind of update this is. Will be None for
channel_post and poll.
Type telegram.User
3.2.49 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
requests.
Type str
bot
Optional. The Bot to use for instance methods.
Type telegram.Bot
copy_message(chat_id, message_id, caption=None, parse_mode=None, cap-
tion_entities=None, disable_notification=None, reply_to_message_id=None,
allow_sending_without_reply=None, reply_markup=None, timeout=None,
api_kwargs=None)
Shortcut for:
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
property name
Convenience property. If available, returns the user’s username prefixed with “@”. If username
is not available, returns full_name.
Type str
pin_message(message_id, disable_notification=None, timeout=None, api_kwargs=None)
Shortcut for:
bot.pin_chat_message(chat_id=update.effective_user.id,
*args,
**kwargs)
Warning: As of API 5.2 start_parameter 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.
Changed in version 13.5: As of Bot API 5.2, the parameter start_parameter is optional.
Returns On success, instance representing the message posted.
Return type telegram.Message
send_location(latitude=None, longitude=None, disable_notification=None, re-
ply_to_message_id=None, reply_markup=None, timeout=None,
location=None, live_period=None, api_kwargs=None, horizon-
tal_accuracy=None, heading=None, proximity_alert_radius=None, al-
low_sending_without_reply=None)
Shortcut for:
bot.unpin_all_chat_messages(chat_id=update.effective_user.id,
*args,
**kwargs)
3.2.50 telegram.UserProfilePhotos
3.2.51 telegram.Venue
Note: Foursquare details and Google Pace details are mutually exclusive. However, this behaviour is
undocumented and might be changed by Telegram.
Parameters
• location (telegram.Location) – Venue location.
• title (str) – Name of the venue.
• address (str) – Address of the venue.
location
Venue location.
Type telegram.Location
title
Name of the venue.
Type str
address
Address of the venue.
Type str
foursquare_id
Optional. Foursquare identifier of the venue.
Type str
foursquare_type
Optional. Foursquare type of the venue.
Type str
google_place_id
Optional. Google Places identifier of the venue.
Type str
google_place_type
Optional. Google Places type of the venue.
Type str
3.2.52 telegram.Video
Raises telegram.error.TelegramError –
3.2.53 telegram.VideoNote
get_file(timeout=None, api_kwargs=None)
Convenience wrapper over telegram.Bot.get_file
For the documentation of the arguments, please see telegram.Bot.get_file().
Returns telegram.File
Raises telegram.error.TelegramError –
3.2.54 telegram.Voice
get_file(timeout=None, api_kwargs=None)
Convenience wrapper over telegram.Bot.get_file
For the documentation of the arguments, please see telegram.Bot.get_file().
Returns telegram.File
Raises telegram.error.TelegramError –
3.2.55 telegram.VoiceChatStarted
class telegram.VoiceChatStarted(**_kwargs)
Bases: telegram.base.TelegramObject
This object represents a service message about a voice chat started in the chat. Currently holds no informa-
tion.
New in version 13.4.
3.2.56 telegram.VoiceChatEnded
3.2.57 telegram.VoiceChatScheduled
3.2.58 telegram.VoiceChatParticipantsInvited
3.2.59 telegram.WebhookInfo
has_custom_certificate
If a custom certificate was provided for webhook.
Type bool
pending_update_count
Number of updates awaiting delivery.
Type int
ip_address
Optional. Currently used webhook IP address.
Type str
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. Defaults to all update types, except
telegram.Update.chat_member.
Type List[str]
3.2.60 Stickers
telegram.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.
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
• (obj (**kwargs) – dict): Arbitrary keyword arguments.
file_id
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
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
get_file(timeout=None, api_kwargs=None)
Convenience wrapper over telegram.Bot.get_file
For the documentation of the arguments, please see telegram.Bot.get_file().
Returns telegram.File
Raises telegram.error.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 class constants
for those.
Parameters
• point (str) – The part of the face relative to which the mask should be placed. One
of 'forehead', 'eyes', 'mouth', or 'chin'.
• 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.
telegram.InlineQuery
Parameters
• id (str) – Unique identifier for this query.
• from_user (telegram.User) – Sender.
• 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.
• chat_type (str, optional) – Type of the chat, from which the inline query
was sent. Can be either telegram.Chat.SENDER for a private chat with
the inline query sender, telegram.Chat.PRIVATE, telegram.Chat.GROUP,
telegram.Chat.SUPERGROUP or telegram.Chat.CHANNEL. The chat type
should be always known for requests sent from official clients and most third-party
clients, unless the request was sent from a secret chat.
New in version 13.5.
• location (telegram.Location, optional) – Sender location, only for bots that
request user location.
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.
id
Unique identifier for this query.
Type str
from_user
Sender.
Type telegram.User
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
location
Optional. Sender location, only for bots that request user location.
Type telegram.Location
chat_type
Type of the chat, from which the inline query was sent.
New in version 13.5.
Type str, optional
MAX_RESULTS: ClassVar[int] = 50
telegram.constants.MAX_INLINE_QUERY_RESULTS
New in version 13.2.
answer(results, cache_time=300, is_personal=None, next_offset=None, switch_pm_text=None,
switch_pm_parameter=None, timeout=None, current_offset=None, api_kwargs=None,
auto_pagination=False)
Shortcut for:
bot.answer_inline_query(update.inline_query.id,
*args,
current_offset=self.offset if auto_pagination else
˓→None,
**kwargs)
telegram.InlineQueryResult
Note: All URLs passed in inline query results will be available to end users and therefore must be assumed
to be public.
Parameters
• type (str) – Type of the result.
• id (str) – Unique identifier for this result, 1-64 Bytes.
• **kwargs (dict) – Arbitrary keyword arguments.
type
Type of the result.
Type str
id
Unique identifier for this result, 1-64 Bytes.
Type str
telegram.InlineQueryResultArticle
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
telegram.InlineQueryResultAudio
Type str
audio_url
A valid URL for the audio file.
Type str
title
Title.
Type str
performer
Optional. Performer.
Type str
audio_duration
Optional. Audio duration in seconds.
Type str
caption
Optional. Caption, 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
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type List[telegram.MessageEntity]
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 audio.
Type telegram.InputMessageContent
telegram.InlineQueryResultCachedAudio
telegram.InlineQueryResultCachedDocument
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
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type List[telegram.MessageEntity]
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
telegram.InlineQueryResultCachedGif
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
gif_file_id
A valid file identifier for the GIF file.
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
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type List[telegram.MessageEntity]
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
telegram.InlineQueryResultCachedMpeg4Gif
telegram.InlineQueryResultCachedPhoto
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
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type List[telegram.MessageEntity]
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
telegram.InlineQueryResultCachedSticker
Type telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the sticker.
Type telegram.InputMessageContent
telegram.InlineQueryResultCachedVideo
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
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type List[telegram.MessageEntity]
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
telegram.InlineQueryResultCachedVoice
telegram.InlineQueryResultContact
Type int
thumb_height
Optional. Thumbnail height.
Type int
telegram.InlineQueryResultDocument
title
Title for the result.
Type str
caption
Optional. Caption of the document 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
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type List[telegram.MessageEntity]
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
telegram.InlineQueryResultGame
telegram.InlineQueryResultGif
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
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type List[telegram.MessageEntity]
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
telegram.InlineQueryResultLocation
thumb_width
Optional. Thumbnail width.
Type int
thumb_height
Optional. Thumbnail height.
Type int
telegram.InlineQueryResultMpeg4Gif
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 (JPEG or GIF) or animated (MPEG4) thumbnail 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
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type List[telegram.MessageEntity]
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
telegram.InlineQueryResultPhoto
photo_width
Optional. Width of the photo.
Type int
photo_height
Optional. Height of the photo.
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
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type List[telegram.MessageEntity]
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
telegram.InlineQueryResultVenue
Note: Foursquare details and Google Pace details are mutually exclusive. However, this behaviour is
undocumented and might be changed by Telegram.
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”.)
• google_place_id (str, optional) – Google Places identifier of the venue.
• google_place_type (str, optional) – Google Places type of the venue. (See sup-
ported types.)
• 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.
type
‘venue’.
Type str
id
Unique identifier for this result, 1-64 Bytes.
Type str
latitude
Latitude of the venue location in degrees.
Type float
longitude
Longitude of the venue location in degrees.
Type float
title
Title 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.
Type str
google_place_id
Optional. Google Places identifier of the venue.
Type str
google_place_type
Optional. Google Places type of the venue.
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 venue.
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
telegram.InlineQueryResultVideo
Note: If an InlineQueryResultVideo message contains an embedded video (e.g., YouTube), you must
replace its content using input_message_content.
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.
• caption_entities (List[telegram.MessageEntity], optional) – List of
special entities that appear in the caption, which can be specified instead of
parse_mode.
• 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.
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
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type List[telegram.MessageEntity]
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
telegram.InlineQueryResultVoice
telegram.InputMessageContent
class telegram.InputMessageContent
Bases: telegram.base.TelegramObject
Base class for Telegram InputMessageContent Objects.
See: telegram.InputContactMessageContent, telegram.
InputInvoiceMessageContent, telegram.InputLocationMessageContent,
telegram.InputTextMessageContent and telegram.InputVenueMessageContent
for more details.
telegram.InputTextMessageContent
telegram.InputLocationMessageContent
telegram.InputVenueMessageContent
Note: Foursquare details and Google Pace details are mutually exclusive. However, this behaviour is
undocumented and might be changed by Telegram.
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”.)
• google_place_id (str, optional) – Google Places identifier of the venue.
• google_place_type (str, optional) – Google Places type of the venue. (See sup-
ported types.)
• **kwargs (dict) – Arbitrary keyword arguments.
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.
Type str
google_place_id
Optional. Google Places identifier of the venue.
Type str
google_place_type
Optional. Google Places type of the venue.
Type str
telegram.InputContactMessageContent
telegram.InputInvoiceMessageContent
• need_phone_number (bool, optional) – Pass True, if you require the user’s phone
number to complete the order
• need_email (bool, optional) – Pass True, if you require the user’s email address
to complete the order.
• need_shipping_address (bool, optional) – Pass True, if you require the user’s
shipping address to complete the order
• send_phone_number_to_provider (bool, optional) – Pass True, if user’s
phone number should be sent to provider.
• send_email_to_provider (bool, optional) – Pass True, if user’s email address
should be sent to provider.
• is_flexible (bool, optional) – Pass True, if the final price depends on the ship-
ping method.
• **kwargs (dict) – Arbitrary keyword arguments.
title
Product name, 1-32 characters
Type str
description
Product description, 1-255 characters
Type str
payload
Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal
processes.
Type str
provider_token
Payment provider token, obtained via @Botfather.
Type str
currency
Three-letter ISO 4217 currency code, see more on currencies
Type str
prices
Price breakdown, a JSON-serialized list of components.
Type List[telegram.LabeledPrice]
max_tip_amount
Optional. The maximum accepted amount for tips in the smallest units of the currency (integer, not
float/double).
Type int
suggested_tip_amounts
Optional. A JSON-serialized array of suggested amounts of tip in the smallest units of the currency
(integer, not float/double).
Type List[int]
provider_data
Optional. A JSON-serialized object for data about the invoice, which will be shared with the payment
provider.
Type str
photo_url
Optional. URL of the product photo for the invoice.
Type str
photo_size
Optional. Photo size.
Type int
photo_width
Optional. Photo width.
Type int
photo_height
Optional. Photo height.
Type int
need_name
Optional. Pass True, if you require the user’s full name to complete the order.
Type bool
need_phone_number
Optional. Pass True, if you require the user’s phone number to complete the order
Type bool
need_email
Optional. Pass True, if you require the user’s email address to complete the order.
Type bool
need_shipping_address
Optional. Pass True, if you require the user’s shipping address to complete the order
Type bool
send_phone_number_to_provider
Optional. Pass True, if user’s phone number should be sent to provider.
Type bool
send_email_to_provider
Optional. Pass True, if user’s email address should be sent to provider.
Type bool
is_flexible
Optional. Pass True, if the final price depends on the shipping method.
Type bool
telegram.ChosenInlineResult
Note:
• In Python from is a reserved word, use from_user instead.
• It is necessary to enable inline feedback via @Botfather in order to receive these objects in updates.
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.
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
3.2.62 Payments
telegram.LabeledPrice
amount
Price of the product in the smallest units of the currency.
Type int
telegram.Invoice
telegram.ShippingAddress
telegram.OrderInfo
telegram.ShippingOption
telegram.SuccessfulPayment
telegram.ShippingQuery
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.
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
answer(ok, shipping_options=None, error_message=None, timeout=None, api_kwargs=None)
Shortcut for:
telegram.PreCheckoutQuery
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.
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
answer(ok, error_message=None, timeout=None, api_kwargs=None)
Shortcut for:
bot.answer_pre_checkout_query(update.pre_checkout_query.id, *args,
˓→**kwargs)
3.2.63 Games
telegram.Game
Type List[telegram.PhotoSize]
text
Optional. Brief description of the game or high scores included in the game message. Can be au-
tomatically edited to include current high scores for the game when the bot calls telegram.Bot.
set_game_score(), or manually edited using telegram.Bot.edit_message_text().
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
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
3.2.64 Passport
telegram.PassportElementError
type
The section of the user’s Telegram Passport which has the error.
Type str
message
Error message.
Type str
telegram.PassportElementErrorFile
telegram.PassportElementErrorFiles
telegram.PassportElementErrorReverseSide
telegram.PassportElementErrorFrontSide
telegram.PassportElementErrorDataField
type
The section of the user’s Telegram Passport which has the error, one of "personal_details",
"passport", "driver_license", "identity_card", "internal_passport",
"address".
Type str
field_name
Name of the data field which has the error.
Type str
data_hash
Base64-encoded data hash.
Type str
message
Error message.
Type str
telegram.PassportElementErrorSelfie
telegram.PassportElementErrorTranslationFile
telegram.PassportElementErrorTranslationFiles
telegram.PassportElementErrorUnspecified
telegram.Credentials
telegram.DataCredentials
telegram.SecureData
telegram.SecureValue
translation
Credentials for an encrypted translation of the document. Available for “passport”, “driver_license”,
“identity_card”, “internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “pass-
port_registration” and “temporary_registration”.
Type List[telegram.FileCredentials], optional
files
Credentials for encrypted files. Available for “utility_bill”, “bank_statement”, “rental_agreement”,
“passport_registration” and “temporary_registration” types.
Type List[telegram.FileCredentials], optional
telegram.FileCredentials
telegram.IdDocumentData
telegram.PersonalDetails
telegram.ResidentialAddress
telegram.PassportData
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.
Parameters
• data (List[telegram.EncryptedPassportElement]) – Array with encrypted
information about documents and other Telegram Passport elements that was shared
with the bot.
• credentials (telegram.EncryptedCredentials)) – Encrypted creden-
tials.
• bot (telegram.Bot, optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.
data
Array with encrypted information about documents and other Telegram Passport elements that was
shared with the bot.
Type List[telegram.EncryptedPassportElement]
credentials
Encrypted credentials.
Type telegram.EncryptedCredentials
bot
The Bot to use for instance methods.
Type telegram.Bot, optional
property 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.
property decrypted_data
Lazily decrypt and return information about documents and other Telegram Passport elements
which were shared with the bot.
telegram.PassportFile
Type str
file_size
File size.
Type int
file_date
Unix time when the file was uploaded.
Type int
bot
Optional. The Bot to use for instance methods.
Type telegram.Bot
get_file(timeout=None, api_kwargs=None)
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.
For the documentation of the arguments, please see telegram.Bot.get_file().
Returns telegram.File
Raises telegram.error.TelegramError –
telegram.EncryptedPassportElement
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 | telegram.IdDocument |
telegram.ResidentialAddress | 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.
type
Element type. One of “personal_details”, “passport”, “driver_license”, “identity_card”,
“internal_passport”, “address”, “utility_bill”, “bank_statement”, “rental_agreement”, “pass-
port_registration”, “temporary_registration”, “phone_number”, “email”.
Type str
data
Optional. Decrypted or encrypted data, available for “personal_details”, “passport”, “driver_license”,
“identity_card”, “identity_passport” and “address” types.
Type telegram.PersonalDetails | telegram.IdDocument | telegram.
ResidentialAddress | str
phone_number
Optional. User’s verified phone number, available only for “phone_number” type.
Type str
email
Optional. User’s verified email address, available only for “email” type.
Type str
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
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.
data
Decrypted data with unique user’s nonce, data hashes and secrets used for EncryptedPassportElement
decryption and authentication or base64 encrypted data.
Type telegram.Credentials or str
hash
Base64-encoded data hash for data authentication.
Type str
secret
Decrypted or encrypted secret used for decryption.
Type str
property decrypted_data
Lazily decrypt and return credentials data. This object also contains the user specified nonce as
decrypted_data.nonce.
property 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
3.2.65 utils
telegram.utils.helpers Module
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(f'`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:
...
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
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 (telegram.Update | telegram.Message) – The update or
message to extract from.
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 transform 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=<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.
Parameters
• file_input (str | bytes | filelike object | Telegram media object) – The input to
parse.
• tg_type (type, optional) – The Telegram media type the input can be. E.g.
telegram.Animation.
• attach (bool, optional) – Whether this file should be send as one file or is part of a
collection of files. Only relevant in case an telegram.InputFile is returned.
• filename (str, optional) – The filename. Only relevant in case an telegram.
InputFile is returned.
Returns The parsed input or the untouched file_input, in case it’s no valid file input.
Return type str | telegram.InputFile | object
telegram.utils.helpers.to_float_timestamp(time_object, reference_timestamp=None,
tzinfo=None)
Converts a given time object to a float POSIX timestamp. Used to convert different time specifications to a
common format. The time object can be relative (i.e. indicate a time increment, or a time of day) or absolute.
object objects from the datetime module that are timezone-naive will be assumed to be in UTC, if bot
is not passed or bot.defaults is None.
Parameters
• time_object (int | float | datetime.timedelta | datetime.datetime
| datetime.time) – Time value to convert. The semantics of this parameter will
depend on its type:
– int or float will be interpreted as “seconds from reference_t”
– datetime.timedelta will be interpreted as “time increment from
reference_t”
– datetime.datetime will be interpreted as an absolute date/time value
– datetime.time will be interpreted as a specific time of day
• reference_timestamp (float, optional) – POSIX timestamp that indicates the
absolute time from which relative calculations are to be performed (e.g. when t is given
as an int, indicating “seconds from reference_t”). Defaults to now (the time at
which this function is called).
If t is given as an absolute representation of date & time (i.e. a datetime.
datetime object), reference_timestamp is not relevant and so its value should
be None. If this is not the case, a ValueError will be raised.
• tzinfo (pytz.BaseTzInfo, optional) – If t is a naive object from the datetime
module, it will be interpreted as this timezone. Defaults to pytz.utc.
Returns
The return value depends on the type of argument t. If t is given as a time increment (i.e. as
a int, float or datetime.timedelta), then the return value will be reference_t
+ t.
Else if it is given as an absolute date/time value (i.e. a datetime.datetime object), the
equivalent value as a POSIX timestamp will be returned.
Finally, if it is a time of the day without date (i.e. a datetime.time object), the return
value is the nearest future occurrence of that time of day.
Return type float | None
Raises
• TypeError – If t’s type is not one of those described above.
• ValueError – If t is a datetime.datetime and reference_timestamp is
not None.
telegram.utils.helpers.to_timestamp(dt_obj, reference_timestamp=None, tzinfo=None)
Wrapper over to_float_timestamp() which returns an integer (the float value truncated down to the
nearest integer).
See the documentation for to_float_timestamp() for more details.
telegram.utils.promise.Promise
class telegram.utils.promise.Promise
Shortcut for telegram.ext.utils.promise.Promise.
Deprecated since version 13.2: Use telegram.ext.utils.promise.Promise instead.
telegram.utils.request.Request
retrieve(url, timeout=None)
Retrieve the contents of a file by its URL.
Parameters
• url (str) – The web location we want to retrieve.
• timeout (int | float) – 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).
telegram.utils.types Module
3.3 Changelog
3.3.1 Changelog
Version 13.5
Released 2021-04-30
Major Changes:
Version 13.4.1
Released 2021-03-14
Hot fix release:
• Fixed a bug in setup.py (#2431)
Version 13.4
Released 2021-03-14
Major Changes:
• Full support of Bot API 5.1 (#2424)
Minor changes, CI improvements, doc fixes and type hinting:
• Improve Updater.set_webhook (#2419)
• Doc Fixes (#2404)
• Type Hinting Fixes (#2425)
• Update pre-commit Settings (#2415)
• Fix Logging for Vendored urllib3 (#2427)
• Stabilize Tests (#2409)
Version 13.3
Released 2021-02-19
Major Changes:
• Make cryptography Dependency Optional & Refactor Some Tests (#2386, #2370)
• Deprecate MessageQueue (#2393)
Bug Fixes:
• Refactor Defaults Integration (#2363)
• Add Missing telegram.SecureValue to init and Docs (#2398)
Minor changes:
• Doc Fixes (#2359)
Version 13.2
Released 2021-02-02
Major Changes:
• Introduce python-telegram-bot-raw (#2324)
• Explicit Signatures for Shortcuts (#2240)
New Features:
• Add Missing Shortcuts to Message (#2330)
• Rich Comparison for Bot (#2320)
• Add run_async Parameter to ConversationHandler (#2292)
• Add New Shortcuts to Chat (#2291)
• Add New Constant MAX_ANSWER_CALLBACK_QUERY_TEXT_LENGTH (#2282)
• Allow Passing Custom Filename For All Media (#2249)
• Handle Bytes as File Input (#2233)
Bug Fixes:
• Fix Escaping in Nested Entities in Message Properties (#2312)
• Adjust Calling of Dispatcher.update_persistence (#2285)
• Add quote kwarg to Message.reply_copy (#2232)
• ConversationHandler: Docs & edited_channel_post behavior (#2339)
Minor changes, CI improvements, doc fixes and type hinting:
• Doc Fixes (#2253, #2225)
• Reduce Usage of typing.Any (#2321)
• Extend Deeplinking Example (#2335)
• Add pyupgrade to pre-commit Hooks (#2301)
• Add PR Template (#2299)
• Drop Nightly Tests & Update Badges (#2323)
• Update Copyright (#2289, #2287)
• Change Order of Class DocStrings (#2256)
Version 13.1
Released 2020-11-29
Major Changes:
• Full support of Bot API 5.0 (#2181, #2186, #2190, #2189, #2183, #2184, #2188, #2185, #2192, #2196,
#2193, #2223, #2199, #2187, #2147, #2205)
New Features:
• Add Defaults.run_async (#2210)
• Improve and Expand CallbackQuery Shortcuts (#2172)
• Add XOR Filters and make Filters.name a Property (#2179)
• Add Filters.document.file_extension (#2169)
• Add Filters.caption_regex (#2163)
• Add Filters.chat_type (#2128)
• Handle Non-Binary File Input (#2202)
Bug Fixes:
• Improve Handling of Custom Objects in BasePersistence.insert/replace_bot (#2151)
• Fix bugs in replace/insert_bot (#2218)
Minor changes, CI improvements, doc fixes and type hinting:
• Improve Type hinting (#2204, #2118, #2167, #2136)
• Doc Fixes & Extensions (#2201, #2161)
• Use F-Strings Where Possible (#2222)
• Rename kwargs to _kwargs where possible (#2182)
• Comply with PEP561 (#2168)
• Improve Code Quality (#2131)
• Switch Code Formatting to Black (#2122, #2159, #2158)
• Update Wheel Settings (#2142)
• Update timerbot.py to v13.0 (#2149)
• Overhaul Constants (#2137)
• Add Python 3.9 to Test Matrix (#2132)
• Switch Codecov to GitHub Action (#2127)
• Specify Required pytz Version (#2121)
Version 13.0
Released 2020-10-07
For a detailed guide on how to migrate from v12 to v13, see this wiki page.
Major Changes:
• Deprecate old-style callbacks, i.e. set use_context=True by default (#2050)
• Refactor Handling of Message VS Update Filters (#2032)
• Deprecate Message.default_quote (#1965)
• Refactor persistence of Bot instances (#1994)
• Refactor JobQueue (#1981)
• Refactor handling of kwargs in Bot methods (#1924)
• Refactor Dispatcher.run_async, deprecating the @run_async decorator (#2051)
New Features:
• Type Hinting (#1920)
• Automatic Pagination for answer_inline_query (#2072)
• Defaults.tzinfo (#2042)
• Extend rich comparison of objects (#1724)
• Add Filters.via_bot (#2009)
• Add missing shortcuts (#2043)
• Allow DispatcherHandlerStop in ConversationHandler (#2059)
• Make Errors picklable (#2106)
Minor changes, CI improvements, doc fixes or bug fixes:
• Fix Webhook not working on Windows with Python 3.8+ (#2067)
• Fix setting thumbs with send_media_group (#2093)
• Make MessageHandler filter for Filters.update first (#2085)
• Fix PicklePersistence.flush() with only bot_data (#2017)
• Add test for clean argument of Updater.start_polling/webhook (#2002)
• Doc fixes, refinements and additions (#2005, #2008, #2089, #2094, #2090)
• CI fixes (#2018, #2061)
• Refine pollbot.py example (#2047)
• Refine Filters in examples (#2027)
• Rename echobot examples (#2025)
• Use Lock-Bot to lock old threads (#2048, #2052, #2049, #2053)
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)
• Doc fixes (#1940, #1962)
• Add User.send_poll() shortcut (#1968)
• Ignore private attributes en TelegramObject.to_dict() (#1989)
• Stabilize CI (#2000)
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)
• Added tzinfo argument to helpers.from_timestamp. It now returns an timezone aware ob-
ject. This is relevant for Message.{date,forward_date,edit_date}, Poll.close_date
and ChatMember.until_date (#1621)
New Features:
• New method run_monthly 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:
• 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)
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)
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:
• Documentation fixes (#1558, #1569, #1579, #1572, #1566, #1577, #1656).
• Add mutex protection on ConversationHandler (#1533).
• Add MAX_PHOTOSIZE_UPLOAD constant (#1560).
• Add args and kwargs to Message.forward() (#1574).
• Transfer to GitHub Actions CI (#1555, #1556, #1605, #1606, #1607, #1612, #1615, #1645).
• Fix deprecation warning with Py3.8 by vendored urllib3 (#1618).
• Simplify assignements for optional arguments (#1600)
• Allow private groups for Message.link (#1619).
• Fix wrong signature call for ConversationHandler.TIMEOUT handlers (#1653).
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.
– New types: PassportData, PassportFile, EncryptedPassportElement, EncryptedCredentials,
PassportElementError, PassportElementErrorDataField, PassportElementErrorFrontSide, Pass-
portElementErrorReverseSide, PassportElementErrorSelfie, PassportElementErrorFile and Pass-
portElementErrorFiles.
– New bot method: set_passport_data_errors
– New filter: Filters.passport_data
– Field passport_data field on Message
– PassportData can be easily decrypted.
– PassportFiles are automatically decrypted if originating from decrypted PassportData.
• See new passportbot.py example for details on how to use, or go to our telegram passport wiki page for
more info
• NOTE: Passport decryption requires new dependency cryptography.
Inputfile rework (#1184):
• Change how Inputfile is handled internally
• This allows support for specifying the thumbnails of photos and videos using the thumb= argument in the
different send_ methods.
• Also allows Bot.send_media_group to actually finally send more than one media.
• Add thumb to Audio, Video and Videonote
• Add Bot.edit_message_media together with InputMediaAnimation, InputMediaAudio, and inputMedi-
aDocument.
Other Bot API 4.0 changes:
• Add forusquare_type to Venue, InlineQueryResultVenue, InputVenueMessageContent, and
Bot.send_venue. (#1170)
• Add vCard support by adding vcard field to Contact, InlineQueryResultContact, InputContactMessageCon-
tent, and Bot.send_contact. (#1166)
• Support new message entities: CASHTAG and PHONE_NUMBER. (#1179)
– Cashtag seems to be things like $USD and $GBP, but it seems telegram doesn’t currently send
them to bots.
– Phone number also seems to have limited support for now
• Add Bot.send_animation, add width, height, and duration to Animation, and add Filters.animation. (#1172)
Non Bot API 4.0 changes:
• Minor integer comparison fix (#1147)
• Fix Filters.regex failing on non-text message (#1158)
• Fix ProcessLookupError if process finishes before we kill it (#1126)
• Add t.me links for User, Chat and Message if available and update User.mention_* (#1092)
• Fix mention_markdown/html on py2 (#1112)
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)
• User.full_name convinience property (PR #949)
• Add send_phone_number_to_provider and send_email_to_provider arguments to send_invoice (PR #986)
• Bot: Add shortcut methods reply_{markdown,html} (PR #827)
• Bot: Add shortcut method reply_media_group (PR #994)
• Added utils.helpers.effective_message_type (PR #826)
• Bot.get_file now allows passing a file in addition to file_id (PR #963)
• Add .get_file() to Audio, Document, PhotoSize, Sticker, Video, VideoNote and Voice (PR #963)
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).
• Fixed URL parsing for Message text properties (PR #689).
• Fixed args dispatching in MessageQueue’s decorator (PR #705).
• Fixed regression preventing IPv6 only hosts from connnecting to Telegram servers (Issue #720).
• ConvesationHandler - check if a user exist before using it (PR #699).
• Removed deprecated telegram.Emoji.
• Removed deprecated Botan import from utils (Botan is still available through contrib).
• Removed deprecated ReplyKeyboardHide.
• Removed deprecated edit_message argument of bot.set_game_score.
• Internal restructure of files.
• Improved documentation.
• Improved unitests.
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
• Fix bug where commands sent by Telegram Web would not be recognized (thanks to @shelomentsevd)
• Add option to skip old updates on bot startup
• Send files from BufferedReader
2016-02-28
Released 3.3
• Inline bots
• Send any file by URL
• Specialized exceptions: Unauthorized, InvalidToken, NetworkError and TimedOut
• Integration for botan.io (thanks to @ollmer)
• HTML Parsemode (thanks to @jlmadurga)
• Bugfixes and under-the-hood improvements
Very special thanks to Noam Meltzer (@tsnoam) for all of his work!
2016-01-09
Released 3.3b1
• Implement inline bots (beta)
2016-01-05
Released 3.2.0
• Introducing JobQueue (original author: @franciscod)
• Streamlining all exceptions to TelegramError (Special thanks to @tsnoam)
• Proper locking of Updater and Dispatcher start and stop methods
• Small bugfixes
2015-12-29
Released 3.1.2
• Fix custom path for file downloads
• Don’t stop the dispatcher thread on uncaught errors in handlers
2015-12-21
Released 3.1.1
• Fix a bug where asynchronous handlers could not have additional arguments
• Add groups and groupdict as additional arguments for regex-based handlers
2015-12-16
Released 3.1.0
• The chat-field in Message is now of type Chat. (API update Oct 8 2015)
• Message now contains the optional fields supergroup_chat_created, migrate_to_chat_id,
migrate_from_chat_id and channel_chat_created. (API update Nov 2015)
2015-12-08
Released 3.0.0
• Introducing the Updater and Dispatcher classes
2015-11-11
Released 2.9.2
2015-09-05
Released 2.8.1
• Fix regression on Telegram objects with thumb properties
2015-09-04
Released 2.8
• TelegramError when chat_id is empty for send* methods
• setWebhook now supports sending self-signed certificate
• Huge redesign of existing Telegram classes
• Added support for PyPy
• Added docstring for existing classes
2015-08-19
Released 2.7.1
• Fixed JSON serialization for message
2015-08-17
Released 2.7
• Added support for Voice object and sendVoice method
• Due backward compatibility performer or/and title will be required for sendAudio
• Fixed JSON serialization when forwarded message
2015-08-15
Released 2.6.1
• Fixed parsing image header issue on < Python 2.7.3
2015-08-14
Released 2.6.0
• Depreciation of require_authentication and clearCredentials methods
• Giving AUTHORS the proper credits for their contribution for this project
• Message.date and Message.forward_date are now datetime objects
2015-08-12
Released 2.5.3
• telegram.Bot now supports to be unpickled
2015-08-11
Released 2.5.2
• New changes from Telegram Bot API have been applied
• telegram.Bot now supports to be pickled
• Return empty str instead None when message.text is empty
2015-08-10
Released 2.5.1
• Moved from GPLv2 to LGPLv3
2015-08-09
Released 2.5
t
telegram.constants, 161
telegram.error, 171
telegram.ext.filters, 41
telegram.utils.helpers, 305
telegram.utils.types, 311
337
python-telegram-bot Documentation, Release 13.5
339
python-telegram-bot Documentation, Release 13.5
340 Index
python-telegram-bot Documentation, Release 13.5
Index 341
python-telegram-bot Documentation, Release 13.5
342 Index
python-telegram-bot Documentation, Release 13.5
Index 343
python-telegram-bot Documentation, Release 13.5
344 Index
python-telegram-bot Documentation, Release 13.5
Index 345
python-telegram-bot Documentation, Release 13.5
346 Index
python-telegram-bot Documentation, Release 13.5
Index 347
python-telegram-bot Documentation, Release 13.5
348 Index
python-telegram-bot Documentation, Release 13.5
Index 349
python-telegram-bot Documentation, Release 13.5
350 Index
python-telegram-bot Documentation, Release 13.5
Index 351
python-telegram-bot Documentation, Release 13.5
352 Index
python-telegram-bot Documentation, Release 13.5
Index 353
python-telegram-bot Documentation, Release 13.5
354 Index
python-telegram-bot Documentation, Release 13.5
Index 355
python-telegram-bot Documentation, Release 13.5
356 Index
python-telegram-bot Documentation, Release 13.5
Index 357
python-telegram-bot Documentation, Release 13.5
358 Index
python-telegram-bot Documentation, Release 13.5
Index 359
python-telegram-bot Documentation, Release 13.5
360 Index
python-telegram-bot Documentation, Release 13.5
Index 361
python-telegram-bot Documentation, Release 13.5
362 Index
python-telegram-bot Documentation, Release 13.5
Index 363
python-telegram-bot Documentation, Release 13.5
364 Index
python-telegram-bot Documentation, Release 13.5
Index 365
python-telegram-bot Documentation, Release 13.5
366 Index
python-telegram-bot Documentation, Release 13.5
W
WAITING (telegram.ext.ConversationHandler at-
tribute), 36
watcher (telegram.ProximityAlertTriggered at-
tribute), 216
wav (telegram.ext.filters.Filters attribute), 47
WebhookInfo (class in telegram), 237
Index 367