0% found this document useful (0 votes)
46 views254 pages

Docs Python Telegram Bot Org en v12.1.1

Uploaded by

kizitowit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views254 pages

Docs Python Telegram Bot Org en v12.1.1

Uploaded by

kizitowit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Telegram Bot Documentation

Release 12.1.1

Leandro Toledo

Dec 31, 2020


Contents

1 Guides and tutorials 1

2 Examples 3

3 Reference 5
3.1 [Link] package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.1.1 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.1.2 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.1.3 [Link] Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.1.4 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.1.5 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.1.6 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.1.7 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.1.8 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.1.9 Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.1.10 Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.2 telegram package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.2.1 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.2.2 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
3.2.3 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
3.2.4 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
3.2.5 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
3.2.6 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
3.2.7 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
3.2.8 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
3.2.9 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
3.2.10 [Link] Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
3.2.11 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
3.2.12 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
3.2.13 [Link] module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
3.2.14 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
3.2.15 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
3.2.16 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
3.2.17 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
3.2.18 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
3.2.19 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
3.2.20 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
3.2.21 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
3.2.22 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
3.2.23 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
3.2.24 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

i
3.2.25 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
3.2.26 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
3.2.27 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
3.2.28 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
3.2.29 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
3.2.30 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
3.2.31 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
3.2.32 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
3.2.33 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
3.2.34 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
3.2.35 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
3.2.36 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
3.2.37 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
3.2.38 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
3.2.39 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
3.2.40 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
3.2.41 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
3.2.42 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
3.2.43 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
3.2.44 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
3.2.45 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
3.2.46 Stickers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
3.2.47 Inline Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
3.2.48 Payments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
3.2.49 Games . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
3.2.50 Passport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
3.3 [Link] package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
3.3.1 [Link] Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
3.3.2 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
3.3.3 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
3.4 Changelog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
3.4.1 Changelog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211

Python Module Index 229

Index 231

ii
CHAPTER 1

Guides and tutorials

If you’re just starting out with the library, we recommend following our “Your first Bot” tutorial that you can find
on our wiki. On our wiki you will also find guides like how to use handlers, webhooks, emoji, proxies and much
more.

1
Python Telegram Bot Documentation, Release 12.1.1

2 Chapter 1. Guides and tutorials


CHAPTER 2

Examples

A great way to learn is by looking at examples. Ours can be found at our github in the examples folder.

3
Python Telegram Bot Documentation, Release 12.1.1

4 Chapter 2. Examples
CHAPTER 3

Reference

Below you can find a reference of all the classes and methods in python-telegram-bot. Apart from the [Link]
package the objects should reflect the types defined in the official telegram bot api documentation.

3.1 [Link] package

3.1.1 [Link]

class [Link](token=None, base_url=None, workers=4, bot=None,


private_key=None, private_key_password=None,
user_sig_handler=None, request_kwargs=None, persis-
tence=None, use_context=False)
Bases: object
This class, which employs the [Link], provides a frontend to [Link]
to the programmer, so they can focus on coding the bot. Its purpose is to receive the updates from Telegram
and to deliver them to said dispatcher. It also runs in a separate thread, so the user can interact with the bot,
for example on the command line. The dispatcher supports handlers for different kinds of data: Updates
from Telegram, basic text commands and even arbitrary types. The updater can be started as a polling
service or, for production, use a webhook to receive updates. This is achieved using the WebhookServer
and WebhookHandler classes.
bot
The bot used with this Updater.
Type [Link]
user_sig_handler
signals the updater will respond to.
Type signal
update_queue
Queue for the updates.
Type Queue
job_queue
Jobqueue for the updater.

5
Python Telegram Bot Documentation, Release 12.1.1

Type [Link]
dispatcher
Dispatcher that handles the updates and dispatches them to the handlers.
Type [Link]
running
Indicates if the updater is running.
Type bool
persistence
Optional. The persistence class to store data that should be persistent over restarts.
Type [Link]
use_context
True if using context based callbacks.
Type bool, optional

Parameters
• token (str, optional) – The bot’s token given by the @BotFather.
• base_url (str, optional) – Base_url for the bot.
• workers (int, optional) – Amount of threads in the thread pool for functions deco-
rated with @run_async.
• bot ([Link], optional) – A pre-initialized bot instance. 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.
• private_key (bytes, optional) – Private key for decryption of telegram passport
data.
• private_key_password (bytes, optional) – Password for above private key.
• user_sig_handler (function, optional) – Takes signum, frame as posi-
tional arguments. This will be called when a signal is received, defaults are (SIGINT,
SIGTERM, SIGABRT) setable with idle.
• request_kwargs (dict, optional) – Keyword args to control the creation of
a [Link] object (ignored if bot argument is used). The re-
quest_kwargs are very useful for the advanced users who would like to control the
default timeouts and/or control the proxy used for http communication.
• use_context (bool, optional) – If set to True Use the context based callback API.
During the deprecation period of the old API the default is False. New users: set this
to True.
• persistence ([Link], optional) – The persis-
tence class to store data that should be persistent over restarts.

Note: You must supply either a bot or a token argument.

Raises ValueError – If both token and bot are passed or none of them.

idle(stop_signals=(<[Link]: 2>, <[Link]: 15>, <[Link]: 6>))


Blocks until one of the signals are received and stops the updater.
Parameters stop_signals (iterable) – Iterable containing signals from the signal
module that should be subscribed to. [Link]() will be called on receiving one of
those signals. Defaults to (SIGINT, SIGTERM, SIGABRT).

6 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

start_polling(poll_interval=0.0, timeout=10, clean=False, bootstrap_retries=-1,


read_latency=2.0, allowed_updates=None)
Starts polling updates from Telegram.
Parameters
• poll_interval (float, optional) – Time to wait between polling updates from
Telegram in seconds. Default is 0.0.
• timeout (float, optional) – Passed to [Link].get_updates.
• clean (bool, optional) – Whether to clean any pending updates on Telegram servers
before actually starting to poll. Default is False.
• bootstrap_retries (int, optional) – Whether the bootstrapping phase of the
Updater will retry on failures on the Telegram server.
– < 0 - retry indefinitely (default)
– 0 - no retries
– > 0 - retry up to X times
• allowed_updates (List[str], optional) – Passed to [Link].
get_updates.
• read_latency (float | int, optional) – Grace time in seconds for receiving the
reply from server. Will be added to the timeout value and used as the read timeout
from server (Default: 2).
Returns The update queue that can be filled from the main thread.
Return type Queue
start_webhook(listen=’[Link]’, port=80, url_path=”, cert=None, key=None, clean=False,
bootstrap_retries=0, webhook_url=None, allowed_updates=None)
Starts a small http server to listen for updates via webhook. If cert and key are not provided, the
webhook will be started directly on [Link] so SSL can be handled by another ap-
plication. Else, the webhook will be started on [Link]
Parameters
• listen (str, optional) – IP-Address to listen on. Default [Link].
• 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.
• clean (bool, optional) – Whether to clean any pending updates on Telegram servers
before actually starting the webhook. Default is False.
• bootstrap_retries (int, optional) – Whether the bootstrapping phase of the
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.
• allowed_updates (List[str], optional) – Passed to [Link].
set_webhook.
Returns The update queue that can be filled from the main thread.

3.1. [Link] package 7


Python Telegram Bot Documentation, Release 12.1.1

Return type Queue


stop()
Stops the polling/webhook thread, the dispatcher and the job queue.

3.1.2 [Link]

class [Link](bot, update_queue, workers=4, exception_event=None,


job_queue=None, persistence=None, use_context=False)
Bases: object
This class dispatches all kinds of updates to its registered handlers.
bot
The bot object that should be passed to the handlers.
Type [Link]
update_queue
The synchronized queue that will contain the updates.
Type Queue
job_queue
Optional. The [Link] instance to pass onto handler callbacks.
Type [Link]
workers
Number of maximum concurrent worker threads for the @run_async decorator.
Type int
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
persistence
Optional. The persistence class to store data that should be persistent over restarts
Type [Link]

Parameters
• bot ([Link]) – The bot object that should be passed to the handlers.
• update_queue (Queue) – The synchronized queue that will contain the updates.
• job_queue ([Link], optional) – The [Link].
JobQueue instance to pass onto handler callbacks.
• workers (int, optional) – Number of maximum concurrent worker threads for the
@run_async decorator. defaults to 4.
• persistence ([Link], optional) – The persis-
tence class to store data that should be persistent over restarts
• use_context (bool, optional) – If set to True Use the context based callback API.
During the deprecation period of the old API the default is False. New users: set this
to True.

8 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

add_error_handler(callback)
Registers an error handler in the Dispatcher. This handler will receive every error which happens in
your bot.
Warning: The errors handled within these handlers won’t show up in the logger, so you need to make
sure that you reraise the error.
Parameters callback (callable) – The callback function for this error handler. Will
be called when an error is raised. Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The error that happened will be present in [Link].

Note: See [Link] 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.
A handler must be an instance of a subclass of [Link]. 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 [Link].
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 [Link].
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 ([Link]) – A Handler instance.
• group (int, optional) – The group identifier. Default is 0.

dispatch_error(update, error)
Dispatches an error.
Parameters
• update (str | [Link] | None) – The update that caused the error
• error (Exception) – The error that was raised.
error_handlers = None
A list of errorHandlers.
Type List[callable]
classmethod get_instance()
Get the singleton instance of this class.
Returns [Link]
Raises RuntimeError
groups = None
A list with all groups.
Type List[int]

3.1. [Link] package 9


Python Telegram Bot Documentation, Release 12.1.1

handlers = None
Holds the handlers per group.
Type Dict[int, List[[Link]]]
process_update(update)
Processes a single update.
Parameters update (str | [Link] | [Link]) –
The update to process.
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 ([Link]) – A Handler instance.
• group (object, optional) – The group identifier. Default is 0.
run_async(func, *args, **kwargs)
Queue a function (with given args/kwargs) to be run asynchronously.

Warning: If you’re using @run_async you cannot rely on adding custom attributes to
[Link]. See its docs for more info.

Parameters
• func (callable) – The function to run in the thread.
• *args (tuple, optional) – Arguments to func.
• **kwargs (dict, optional) – Keyword arguments to func.
Returns Promise

running = None
Indicates if this dispatcher is running.
Type bool
start(ready=None)
Thread target of thread ‘dispatcher’.
Runs in background and processes the update queue.
Parameters ready ([Link], optional) – If specified, the event will be set
once the dispatcher is ready.
stop()
Stops the thread.
update_persistence()
Update user_data and chat_data in persistence.
user_data = None
A dictionary handlers can use to store data for the user.
Type dict

10 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

3.1.3 [Link] Module

This module contains the Filters for use with the MessageHandler class.
class [Link]
Bases: object
Predefined filters for use as the filter argument of [Link].

Examples
Use MessageHandler([Link], callback_method) to filter all video messages. Use
MessageHandler([Link], callback_method) for all contacts. etc.

all = [Link]
All Messages.
animation = [Link]
Messages that contain [Link].
audio = [Link]
Messages that contain [Link].
class caption_entity(entity_type)
Bases: [Link]
Filters media messages to only allow those which have a [Link] 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 [Link].

class chat(chat_id=None, username=None)


Bases: [Link]
Filters messages to allow only those which are from specified chat ID.

Examples
MessageHandler([Link](-1234), callback_method)

Parameters
• chat_id (int | List[int], optional) – Which chat ID(s) to allow through.
• username (str | List[str], optional) – Which username(s) to allow through. If
username start swith ‘@’ symbol, it will be ignored.
Raises ValueError – If chat_id and username are both present, or neither is.

command = [Link]
Messages starting with /.
contact = [Link]
Messages that contain [Link].

3.1. [Link] package 11


Python Telegram Bot Documentation, Release 12.1.1

document = [Link]
Subset for messages containing a document/file.

Examples
Use these filters like: [Link].mp3, [Link].
mime_type("text/plain") etc. Or use just [Link] for all document
messages.

category
This Filter filters documents by their category in the mime-type attribute.

Example
[Link]('audio/') filters all types of audio sent as file, for
example ‘audio/mpeg’ or ‘audio/x-wav’. The following attributes can be used as a shortcut like:
[Link]

application
audio
image
video
text
mime_type
This Filter filters documents by their mime-type attribute.

Example
[Link].mime_type('audio/mpeg') filters all audio in mp3 format. The
following attributes can be used as a shortcut like: [Link]

apk
doc
docx
exe
gif
jpg
mp3
pdf
py
svg
txt
targz
wav
xml
zip

12 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

category
This Filter filters documents by their category in the mime-type attribute

Note: This Filter only filters by the mime_type of the document, it doesn’t check the validity of
the document. The user can manipulate the mime-type of a message and send media with wrong
types that don’t fit to this handler.

Example
[Link]('audio/') filters all types of audio sent as file, for
example ‘audio/mpeg’ or ‘audio/x-wav’

application
Same as [Link]("application").
audio
Same as [Link]("audio").
image
Same as [Link]("image").
video
Same as [Link]("video").
text
Same as [Link]("text").
mime_type
This Filter filters documents by their mime-type attribute

Note: This Filter only filters by the mime_type of the document, it doesn’t check the validity of
document.
The user can manipulate the mime-type of a message and send media with wrong types that don’t
fit to this handler.

Example
[Link].mime_type('audio/mpeg') filters all audio in mp3 format.

apk
Same as [Link].mime_type("application/[Link].
package-archive")-
doc
Same as [Link].mime_type("application/msword")-
docx
Same as [Link].mime_type("application/vnd.
[Link]")-
exe
Same as [Link].mime_type("application/
x-ms-dos-executable")-
gif
Same as [Link].mime_type("video/mp4")-
jpg
Same as [Link].mime_type("image/jpeg")-

3.1. [Link] package 13


Python Telegram Bot Documentation, Release 12.1.1

mp3
Same as [Link].mime_type("audio/mpeg")-
pdf
Same as [Link].mime_type("application/pdf")-
py
Same as [Link].mime_type("text/x-python")-
svg
Same as [Link].mime_type("image/svg+xml")-
txt
Same as [Link].mime_type("text/plain")-
targz
Same as [Link].mime_type("application/x-compressed-tar")-
wav
Same as [Link].mime_type("audio/x-wav")-
xml
Same as [Link].mime_type("application/xml")-
zip
Same as [Link].mime_type("application/zip")-
class entity(entity_type)
Bases: [Link]
Filters messages to only allow those which have a [Link] where their type
matches entity_type.

Examples
Example MessageHandler([Link]("hashtag"), callback_method)

Parameters entity_type – Entity type to check for. All types can be found as constants
in [Link].

forwarded = [Link]
Messages that are forwarded.
game = [Link]
Messages that contain [Link].
group = [Link]
Messages sent in a group chat.
invoice = [Link]
Messages that contain [Link].
class language(lang)
Bases: [Link]
Filters messages to only allow those which are from users with a certain language code.

Note: According to official telegram api documentation, not every single user has the language_code
attribute. Do not count on this filter working on all users.

Examples

14 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

MessageHandler([Link]("en"), callback_method)

Parameters lang (str | List[str]) – Which language code(s) to allow through. This
will be matched using .startswith meaning that ‘en’ will match both ‘en_US’ and
‘en_GB’.

location = [Link]
Messages that contain [Link].
passport_data = Filters.passport_data
Messages that contain a [Link]
photo = [Link]
Messages that contain [Link].
private = [Link]
Messages sent in a private chat.
class regex(pattern)
Bases: [Link]
Filters updates by searching for an occurrence of pattern in the message text. The [Link]
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 [Link].

Examples
Use MessageHandler([Link](r'help'), callback) to capture all messages
that contain the word help. You can also use MessageHandler([Link](re.
compile(r'help', [Link]), callback) if you want your pattern to be case in-
sensitive. This approach is recommended if you need to specify flags on your pattern.

Note: Filters use the same short circuiting logic that pythons and, or and not. This means that for
example:

>>> [Link](r'(a?x)') | [Link](r'(b?x)')

With a [Link] of x, will only ever return the matches for the first filter, since the second one is
never evaluated.

Parameters pattern (str | Pattern) – The regex pattern.

reply = [Link]
Messages that are a reply to another message.
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 [Link].group_chat_created,

3.1. [Link] package 15


Python Telegram Bot Documentation, Release 12.1.1

[Link].supergroup_chat_created or [Link].
channel_chat_created.
delete_chat_photo
Messages that contain [Link].delete_chat_photo.
left_chat_member
Messages that contain [Link].left_chat_member.
migrate
Messages that contain [Link].migrate_from_chat_id or :attr: tele-
[Link].migrate_from_chat_id.
new_chat_members
Messages that contain [Link].new_chat_members.
new_chat_photo
Messages that contain [Link].new_chat_photo.
new_chat_title
Messages that contain [Link].new_chat_title.
pinned_message
Messages that contain [Link].pinned_message.
sticker = [Link]
Messages that contain [Link].
successful_payment = Filters.successful_payment
Messages that confirm a [Link].
text = [Link]
Text Messages.
update = _UpdateType
Subset for filtering the type of update.

Examples
Use these filters like: [Link] or [Link].channel_posts
etc. Or use just [Link] for all types.

message
Updates with [Link]
edited_message
Updates with [Link].edited_message
messages
Updates with either [Link] or [Link].
edited_message
channel_post
Updates with [Link].channel_post
edited_channel_post
Updates with [Link].edited_channel_post
channel_posts
Updates with either [Link].channel_post or [Link].
edited_channel_post
class user(user_id=None, username=None)
Bases: [Link]
Filters messages to allow only those which are from specified user ID.

16 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

Examples
MessageHandler([Link](1234), callback_method)

Parameters
• user_id (int | List[int], optional) – Which user ID(s) to allow through.
• username (str | List[str], optional) – Which username(s) to allow through. If
username starts with ‘@’ symbol, it will be ignored.
Raises ValueError – If chat_id and username are both present, or neither is.

venue = [Link]
Messages that contain [Link].
video = [Link]
Messages that contain [Link].
video_note = Filters.video_note
Messages that contain [Link].
voice = [Link]
Messages that contain [Link].
class [Link]
Bases: object
Base class for all Message Filters.
Subclassing from this class filters to be combined using bitwise operators:
And:

>>> ([Link] & [Link](MENTION))

Or:

>>> ([Link] | [Link])

Not:

>>> ~ [Link]

Also works with more than two filters:

>>> ([Link] & ([Link](URL) | [Link](TEXT_LINK)))


>>> [Link] & (~ [Link])

Note: Filters use the same short circuiting logic that pythons and, or and not. This means that for example:

>>> [Link](r'(a?x)') | [Link](r'(b?x)')

With a [Link] of x, will only ever return the matches for the first filter, since the second one is never
evaluated.

If you want to create your own filters create a class inheriting from this class and implement a filter method
that returns a boolean: True if the message should be handled, False otherwise. Note that the filters work
only as class instances, not actual class objects (so remember to initialize your filter classes).
By default the filters name (what will get printed when converted to a string for display) will be the class
name. If you want to overwrite this assign a better name to the name class variable.

3.1. [Link] package 17


Python Telegram Bot Documentation, Release 12.1.1

name
Name for this filter. Defaults to the type of filter.
Type str
update_filter
Whether this filter should work on update. If False it will run the filter on update.
effective_message`. Default is False.
Type bool
data_filter
Whether this filter is a data filter. A data filter should return a dict with lists. The dict will be merged
with [Link]’s internal dict in most cases (depends on the handler).
Type bool
filter(update)
This method must be overwritten.

Note: If update_filter is false then the first argument is message and of type telegram.
Message.

Parameters update ([Link]) – The update that is tested.


Returns dict or bool

class [Link](f )
Bases: [Link]
Represents a filter that has been inverted.
Parameters f – The filter to invert.
filter(update)
This method must be overwritten.

Note: If update_filter is false then the first argument is message and of type telegram.
Message.

Parameters update ([Link]) – The update that is tested.


Returns dict or bool

class [Link](base_filter, and_filter=None, or_filter=None)


Bases: [Link]
Represents a filter consisting of two other filters.
Parameters
• base_filter – Filter 1 of the merged filter
• and_filter – Optional filter to “and” with base_filter. Mutually exclusive with
or_filter.
• or_filter – Optional filter to “or” with base_filter. Mutually exclusive with
and_filter.
filter(update)
This method must be overwritten.

18 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

Note: If update_filter is false then the first argument is message and of type telegram.
Message.

Parameters update ([Link]) – The update that is tested.


Returns dict or bool

3.1.4 [Link]

class [Link](callback, interval=None, repeat=True, context=None, days=(0, 1, 2, 3,


4, 5, 6), name=None, job_queue=None)
Bases: object
This class encapsulates a Job.
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

Parameters
• callback (callable) – The callback function that should be executed by the new
job. It should take bot, job as parameters, where job is the [Link]
instance. It can be used to access it’s context or change it to a repeating job.
• interval (int | float | [Link], optional) – The interval in
which the job will run. If it is an int or a float, it will be interpreted as seconds. If
you don’t set this value, you must set repeat to False and specify next_t when
you put the job into the job queue.
• repeat (bool, optional) – If this job should be periodically execute its callback func-
tion (True) or only once (False). Defaults to True.
• context (object, optional) – Additional data needed for the callback function. Can
be accessed through [Link] in the callback. Defaults to None.
• name (str, optional) – The name of the new job. Defaults to callback.__name__.
• days (Tuple[int], optional) – Defines on which days of the week the job should run.
Defaults to Days.EVERY_DAY
• job_queue ([Link], optional) – The JobQueue this job be-
longs to. Only optional for backward compatibility with [Link]().

days
Optional. Defines on which days of the week the job should run.
Type Tuple[int]
enabled
Whether this job is enabled.
Type bool

3.1. [Link] package 19


Python Telegram Bot Documentation, Release 12.1.1

interval
Optional. The interval in which the job will run.
Type int | float | [Link]
interval_seconds
The interval for this job in seconds.
Type int
job_queue
Optional. The JobQueue this job belongs to.
Type [Link]
removed
Whether this job is due to be removed.
Type bool
repeat
Optional. If this job should periodically execute its callback function.
Type bool
run(dispatcher)
Executes the callback function.
schedule_removal()
Schedules this job for removal from the JobQueue. It will be removed without executing its callback
function again.

3.1.5 [Link]

class [Link](bot=None)
Bases: object
This class allows you to periodically perform tasks with the bot.
_queue
The queue that holds the Jobs.
Type PriorityQueue
bot
The bot instance that should be passed to the jobs. DEPRECATED: Use set_dispatcher instead.
Type [Link]
get_jobs_by_name(name)
Returns a tuple of jobs with the given name that are currently in the JobQueue
jobs()
Returns a tuple of all jobs that are currently in the JobQueue.
run_daily(callback, time, days=(0, 1, 2, 3, 4, 5, 6), context=None, name=None)
Creates a new Job that runs on a daily basis and adds it to the queue.
Parameters
• callback (callable) – The callback function that should be executed by the new
job. It should take bot, job as parameters, where job is the [Link].
Job instance. It can be used to access its [Link] or change it to a repeating
job.
• time ([Link]) – Time of day at which the job should run.
• days (Tuple[int], optional) – Defines on which days of the week the job should run.
Defaults to EVERY_DAY

20 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

• context (object, optional) – Additional data needed for the callback function.
Can be accessed through [Link] 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 [Link]

Notes

Daily is just an alias for “24 Hours”. That means that if DST changes during that interval, the job
might not run at the time one would expect. It is always recommended to pin servers to UTC time,
then time related behaviour can always be expected.
run_once(callback, when, context=None, name=None)
Creates a new Job that runs once and adds it to the queue.
Parameters
• callback (callable) – The callback function that should be executed by the new
job. It should take bot, job as parameters, where job is the [Link].
Job instance. It can be used to access its [Link] or change it to a repeating
job.
• when (int | float | [Link] | [Link] |
[Link]) – Time in or at which the job should run. This parameter will
be interpreted depending on its type.
– int or float will be interpreted as “seconds from now” in which the job should
run.
– [Link] will be interpreted as “time from now” in which the job
should run.
– [Link] will be interpreted as a specific date and time at which
the job should run.
– [Link] 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.
• context (object, optional) – Additional data needed for the callback function.
Can be accessed through [Link] 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 [Link]
run_repeating(callback, interval, first=None, context=None, name=None)
Creates a new Job that runs at specified intervals and adds it to the queue.
Parameters
• callback (callable) – The callback function that should be executed by the new
job. It should take bot, job as parameters, where job is the [Link].
Job instance. It can be used to access its [Link] or change it to a repeating
job.
• interval (int | float | [Link]) – The interval in which the
job will run. If it is an int or a float, it will be interpreted as seconds.

3.1. [Link] package 21


Python Telegram Bot Documentation, Release 12.1.1

• first (int | float | [Link] | [Link] |


[Link], 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.
– [Link] will be interpreted as “time from now” in which the job
should run.
– [Link] will be interpreted as a specific date and time at which
the job should run.
– [Link] 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.
Defaults to interval
• context (object, optional) – Additional data needed for the callback function.
Can be accessed through [Link] 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 [Link]

Notes

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.
start()
Starts the job_queue thread.
stop()
Stops the thread.
tick()
Run all jobs that are due and re-enqueue them with their interval.

3.1.6 [Link]

class [Link](all_burst_limit=30, all_time_limit_ms=1000,


group_burst_limit=20, group_time_limit_ms=60000,
exc_route=None, autostart=True)
Bases: object
Implements callback processing with proper delays to avoid hitting Telegram’s message limits. Contains
two DelayQueue, for group and for all messages, interconnected in delay chain. Callables are processed
through group DelayQueue, then through all DelayQueue for group-type messages. For non-group
messages, only the all DelayQueue is used.
Parameters
• all_burst_limit (int, optional) – Number of maximum all-type callbacks to
process per time-window defined by all_time_limit_ms. Defaults to 30.
• all_time_limit_ms (int, optional) – Defines width of all-type time-window used
when each processing limit is calculated. Defaults to 1000 ms.
• group_burst_limit (int, optional) – Number of maximum group-type callbacks
to process per time-window defined by group_time_limit_ms. Defaults to 20.

22 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

• group_time_limit_ms (int, optional) – Defines width of group-type time-


window used when each processing limit is calculated. Defaults to 60000 ms.
• exc_route (callable, optional) – A callable, accepting one positional argu-
ment; used to route exceptions from processor threads 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, processors are started immediately after ob-
ject’s creation; if False, should be started manually by start method. Defaults to
True.
__call__(promise, is_group_msg=False)
Processes callables in troughput-limiting queues to avoid hitting limits (specified with burst_limit
and time_limit.
Parameters
• promise (callable) – Mainly the [Link]
(see Notes for other callables), that is processed in delay queues.
• is_group_msg (bool, optional) – Defines whether promise would be processed
in group*+*all* DelayQueue``s (if set to ``True), or only through all
DelayQueue (if set to False), resulting in needed delays to avoid hitting specified
limits. Defaults to False.

Notes

Method is designed to accept [Link] as promise argument,


but other callables could be used too. For example, lambdas or simple functions could be used to wrap
original func to be called with needed args. In that case, be sure that either wrapper func does not raise
outside exceptions or the proper exc_route handler is provided.
Returns Used as promise argument.
Return type callable
__init__(all_burst_limit=30, all_time_limit_ms=1000, group_burst_limit=20,
group_time_limit_ms=60000, exc_route=None, autostart=True)
Initialize self. See help(type(self)) for accurate signature.
__weakref__
list of weak references to the object (if defined)
start()
Method is used to manually start the MessageQueue processing.
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.7 [Link]

class [Link](queue=None, burst_limit=30, time_limit_ms=1000,


exc_route=None, autostart=True, name=None)
Bases: [Link]
Processes callbacks from queue with specified throughput limits. Creates a separate thread to process call-
backs with delays.

3.1. [Link] package 23


Python Telegram Bot Documentation, Release 12.1.1

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

Parameters
• queue (Queue, optional) – Used to pass callbacks to thread. Creates Queue implicitly
if not provided.
• burst_limit (int, optional) – Number of maximum callbacks to process per time-
window defined by time_limit_ms. Defaults to 30.
• time_limit_ms (int, optional) – Defines width of time-window used when each
processing limit is calculated. Defaults to 1000.
• exc_route (callable, optional) – A callable, accepting 1 positional argument;
used to route exceptions from processor thread to main thread; is called on Exception
subclass exceptions. If not provided, exceptions are routed through dummy handler,
which re-raises them.
• autostart (bool, optional) – If True, processor is started immediately after object’s
creation; if False, should be started manually by start method. Defaults to True.
• name (str, optional) – Thread’s name. Defaults to 'DelayQueue-N', where N is
sequential number of object created.

__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 {}.

24 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

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.8 [Link]

class [Link](dispatcher)
This is a context object passed to the callback called by [Link] or by the
[Link] in an error handler added by [Link].
add_error_handler or to the callback of a [Link].

Note: [Link] 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.

Warning: Do not combine custom attributes and @run_async. Due to how @run_async works, it will
almost certainly execute the callbacks for an update out of order, and the attributes that you think you
added will not be present.

chat_data
A dict that can be used to keep any data in. For each update from the same chat it will be the same
dict.
Type dict, optional
user_data
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, optional
matches
If the associated update originated from a regex-supported handler or had a [Link], this
will contain a list of match objects for every pattern where [Link](pattern, string)
returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.
Type List[re match object], optional
args
Arguments passed to a command if the associated update is handled by telegram.
[Link], [Link] or [Link].
StringCommandHandler. It contains a list of the words in the text after the command,
using any whitespace string as a delimiter.
Type List[str], optional

3.1. [Link] package 25


Python Telegram Bot Documentation, Release 12.1.1

error
The Telegram error that was raised. Only present when passed to a error handler registered with
[Link].add_error_handler.
Type [Link], optional
job
The job that that originated this callback. Only present when passed to the callback of telegram.
[Link].
Type [Link]
bot
The bot associated with this context.
Type [Link]
job_queue
The JobQueue used by the [Link] and (usually) the [Link].
Updater associated with this context.
Type [Link]
match
The first match from matches. Useful if you are only filtering using a single regex filter. Returns
None if matches is empty.
Type Regex match type
update_queue
The Queue instance used by the [Link] and (usually) the telegram.
[Link] associated with this context.
Type [Link]

3.1.9 Handlers

[Link]

class [Link](callback, pass_update_queue=False, pass_job_queue=False,


pass_user_data=False, pass_chat_data=False)
Bases: object
The base class for all update handlers. Create custom handlers by inheriting from it.
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.

26 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

Type bool

Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See [Link] 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
[Link].
• 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 [Link] and [Link] 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 [Link].
JobQueue instance created by the [Link] which can be used to
schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.
• pass_user_data (bool, optional) – If set to True, a keyword argument called
user_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_chat_data (bool, optional) – If set to True, a keyword argument called
chat_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.

check_update(update)
This method is called to determine if an update should be handled by this handler instance. It should
always be overridden.
Parameters update (str | [Link]) – The update to be tested.
Returns Either None or False if the update should not be handled. Otherwise an object
that will be passed to handle_update and collect_additional_context
when the update gets handled.
collect_additional_context(context, update, dispatcher, check_result)
Prepares additional arguments for the context. Override if needed.
Parameters
• context ([Link]) – The context object.
• update ([Link]) – The update to gather chat/user id from.
• dispatcher ([Link]) – The calling dispatcher.
• check_result – The result (return value) from check_update.

3.1. [Link] package 27


Python Telegram Bot Documentation, Release 12.1.1

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:
//[Link]/fxJuV for more info.
Parameters
• dispatcher ([Link]) – The dispatcher.
• update ([Link]) – The update to gather chat/user id from.
• check_result – The result from check_update
handle_update(update, dispatcher, check_result, context=None)
This method is called if it was determined that an update should indeed be handled by this instance.
Calls [Link] along with its respectful arguments. To work with the [Link].
ConversationHandler, this method returns the value returned from [Link]. Note
that it can be overridden if needed by the subclassing handler.
Parameters
• update (str | [Link]) – The update to be handled.
• dispatcher ([Link]) – The calling dispatcher.
• check_result – The result from check_update.

[Link]

class [Link](callback, pass_update_queue=False,


pass_job_queue=False, pat-
tern=None, pass_groups=False,
pass_groupdict=False, pass_user_data=False,
pass_chat_data=False)
Bases: [Link]
Handler class to handle Telegram callback queries. Optionally based on a regex.
Read the documentation of the re module for more information.
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 [Link] 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.

28 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

Type bool
pass_user_data
Determines whether user_data will be passed to the callback function.
Type bool
pass_chat_data
Determines whether chat_data will be passed to the callback function.
Type bool

Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See [Link] 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
[Link].
• 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 [Link] and [Link] 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 [Link].
JobQueue instance created by the [Link] 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, [Link] is used
on [Link] 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 [Link](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.

3.1. [Link] package 29


Python Telegram Bot Documentation, Release 12.1.1

check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update ([Link]) – Incoming telegram update.
Returns bool
collect_additional_context(context, update, dispatcher, check_result)
Prepares additional arguments for the context. Override if needed.
Parameters
• context ([Link]) – The context object.
• update ([Link]) – The update to gather chat/user id from.
• dispatcher ([Link]) – 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:
//[Link]/fxJuV for more info.
Parameters
• dispatcher ([Link]) – The dispatcher.
• update ([Link]) – The update to gather chat/user id from.
• check_result – The result from check_update

[Link]

class [Link](callback, pass_update_queue=False,


pass_job_queue=False,
pass_user_data=False,
pass_chat_data=False)
Bases: [Link]
Handler class to handle Telegram updates that contain a chosen inline result.
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

30 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

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 [Link] 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
[Link].
• 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 [Link] and [Link] 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 [Link].
JobQueue instance created by the [Link] which can be used to
schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.
• pass_user_data (bool, optional) – If set to True, a keyword argument called
user_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_chat_data (bool, optional) – If set to True, a keyword argument called
chat_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.

check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update ([Link]) – Incoming telegram update.
Returns bool

[Link]

class [Link](entry_points, states, fallbacks, al-


low_reentry=False, per_chat=True,
per_user=True, per_message=False, con-
versation_timeout=None, name=None, persis-
tent=False)
Bases: [Link]
A handler to hold a conversation with a single user by managing four collections of other handlers. Note that
neither posts in Telegram Channels, nor group interactions with multiple users are managed by instances of
this class.
The first collection, a list named entry_points, is used to initiate the conversation, for example with
a [Link] or [Link].

3.1. [Link] package 31


Python Telegram Bot Documentation, Release 12.1.1

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.
entry_points
A list of Handler objects that can trigger the start of the conversation.
Type List[[Link]]
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[[Link]]]
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[[Link]]
allow_reentry
Determines if a user can restart a conversation with an entry point.
Type bool
per_chat
If the conversationkey should contain the Chat’s ID.
Type bool
per_user
If the conversationkey should contain the User’s ID.
Type bool
per_message
If the conversationkey should contain the Message’s ID.
Type bool
conversation_timeout
Optional. When this handler is inactive more than this timeout (in seconds), it will be automatically
ended. If this value is 0 (default), there will be no timeout. When it’s triggered, the last received
update will be handled by ALL the handler’s who’s check_update method returns True that are in the
state [Link].
Type float`|:obj:`[Link]
name
Optional. The name for this conversationhandler. Required for persistence
Type str

32 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

persistent
Optional. If the conversations dict for this handler should be saved. Name is required and persistence
has to be set in [Link]
Type bool

Parameters
• entry_points (List[[Link]]) – 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[[Link]]]) – 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[[Link]]) – 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 | [Link], optional) – When
this handler is inactive more than this timeout (in seconds), it will be automatically
ended. If this value is 0 or None (default), there will be no timeout. The last received
update will be handled by ALL the handler’s who’s check_update method returns True
that are in the state [Link].
• 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 [Link]
Raises ValueError

END = -1
Used as a constant to return when a conversation is ended.
Type int
TIMEOUT = -2
Used as a constant to handle state when a conversation is timed out.
Type int
WAITING = -3
Used as a constant to handle state when a conversation is still waiting on the previous @run_sync
decorated running handler to finish.
Type int
check_update(update)
Determines whether an update should be handled by this conversationhandler, and if so in which state
the conversation currently is.

3.1. [Link] package 33


Python Telegram Bot Documentation, Release 12.1.1

Parameters update ([Link]) – Incoming telegram update.


Returns bool
handle_update(update, dispatcher, check_result, context=None)
Send the update to the callback for the current state and Handler
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 ([Link]) – Incoming telegram update.
• dispatcher ([Link]) – Dispatcher that originated the
Update.
persistence = None
The persistence used to store conversations. Set by dispatcher
Type [Link]

[Link]

class [Link](command, callback, filters=None, allow_edited=None,


pass_args=False, pass_update_queue=False,
pass_job_queue=False, pass_user_data=False,
pass_chat_data=False)
Bases: [Link]
Handler class to handle Telegram commands.
Commands are Telegram messages that start with /, optionally followed by an @ and the bot’s name
and/or some additional text. The handler will add a list to the CallbackContext named
[Link]. It will contain a list of strings, which is the text following the command
split on single or consecutive whitespace characters.
By default the handler listens to messages as well as edited messages. To change this behavior use
~[Link].edited_message in the filter argument.
command
The command or list of commands this handler should listen for. Limitations are the same as described
here [Link]
Type str | List[str]
callback
The callback function for this handler.
Type callable
filters
Optional. Only allow updates with these Filters.
Type [Link]
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.

34 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

Type bool
pass_job_queue
Determines whether job_queue will be passed to the callback function.
Type bool
pass_user_data
Determines whether user_data will be passed to the callback function.
Type bool
pass_chat_data
Determines whether chat_data will be passed to the callback function.
Type bool

Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See [Link] for
more info.

Parameters
• command (str | List[str]) – The command or list of commands this handler should
listen for. Limitations are the same as described here [Link]
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
[Link].
• filters ([Link], optional) – A filter inheriting from
[Link]. Standard filters can be found in
[Link]. 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 ~[Link].edited_message.
• pass_args (bool, optional) – Determines whether the handler should be passed the
arguments passed to the command as a keyword argument called args. It will contain
a list of strings, which is the text following the command split on single or consecutive
whitespace characters. Default is False DEPRECATED: Please switch to context
based callbacks.
• pass_update_queue (bool, optional) – If set to True, a keyword argument called
update_queue will be passed to the callback function. It will be the Queue instance
used by the [Link] and [Link] 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 [Link].
JobQueue instance created by the [Link] which can be used to
schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.

3.1. [Link] package 35


Python Telegram Bot Documentation, Release 12.1.1

• pass_user_data (bool, optional) – If set to True, a keyword argument called


user_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_chat_data (bool, optional) – If set to True, a keyword argument called
chat_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
Raises ValueError - when command is too long or has illegal chars.

check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update ([Link]) – Incoming telegram update.
Returns The list of args for the handler
Return type list
collect_additional_context(context, update, dispatcher, check_result)
Prepares additional arguments for the context. Override if needed.
Parameters
• context ([Link]) – The context object.
• update ([Link]) – The update to gather chat/user id from.
• dispatcher ([Link]) – 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:
//[Link]/fxJuV for more info.
Parameters
• dispatcher ([Link]) – The dispatcher.
• update ([Link]) – The update to gather chat/user id from.
• check_result – The result from check_update

[Link]

class [Link](callback, pass_update_queue=False,


pass_job_queue=False, pattern=None,
pass_groups=False, pass_groupdict=False,
pass_user_data=False, pass_chat_data=False)
Bases: [Link]
Handler class to handle Telegram inline queries. Optionally based on a regex. Read the documentation of
the re module for more information.
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

36 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

pass_job_queue
Determines whether job_queue will be passed to the callback function.
Type bool
pattern
Optional. Regex pattern to test [Link] 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
pass_user_data
Determines whether user_data will be passed to the callback function.
Type bool
pass_chat_data
Determines whether chat_data will be passed to the callback function.
Type bool

Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See [Link] 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
[Link].
• 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 [Link] and [Link] 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 [Link].
JobQueue instance created by the [Link] 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, [Link]
is used on [Link] to determine if an update should be
handled by this handler.

3.1. [Link] package 37


Python Telegram Bot Documentation, Release 12.1.1

• 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 [Link](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.

check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update ([Link]) – Incoming telegram update.
Returns bool
collect_additional_context(context, update, dispatcher, check_result)
Prepares additional arguments for the context. Override if needed.
Parameters
• context ([Link]) – The context object.
• update ([Link]) – The update to gather chat/user id from.
• dispatcher ([Link]) – 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:
//[Link]/fxJuV for more info.
Parameters
• dispatcher ([Link]) – The dispatcher.
• update ([Link]) – The update to gather chat/user id from.
• check_result – The result from check_update

[Link]

class [Link](filters, callback, pass_update_queue=False,


pass_job_queue=False, pass_user_data=False,
pass_chat_data=False, message_updates=None,
channel_post_updates=None, edited_updates=None)
Bases: [Link]
Handler class to handle telegram messages. They might contain text, media or status updates.
filters
Only allow updates with these Filters. See [Link] for a full list of all available
filters.
Type Filter

38 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

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
message_updates
Should “normal” message updates be handled? Default is None.
Type bool
channel_post_updates
Should channel posts updates be handled? Default is None.
Type bool
edited_updates
Should “edited” message updates be handled? Default is None.
Type bool

Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See [Link] for
more info.

Parameters
• filters ([Link], optional) – A filter inheriting from
[Link]. Standard filters can be found in
[Link]. Filters can be combined using bitwise op-
erators (& for and, | for or, ~ for not). Default is [Link].
[Link]. This defaults to all message_type updates being: message,
edited_message, channel_post and edited_channel_post. If you don’t
want or need any of those pass ~[Link].* in the filter argument.
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
[Link].

3.1. [Link] package 39


Python Telegram Bot Documentation, Release 12.1.1

• 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 [Link] and [Link] 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 [Link].
JobQueue instance created by the [Link] 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.
• message_updates (bool, optional) – Should “normal” message updates be han-
dled? Default is None. DEPRECATED: Please switch to filters for update filtering.
• channel_post_updates (bool, optional) – Should channel posts updates be han-
dled? Default is None. DEPRECATED: Please switch to filters for update filtering.
• edited_updates (bool, optional) – Should “edited” message updates be handled?
Default is None. DEPRECATED: Please switch to filters for update filtering.
Raises ValueError

check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update ([Link]) – Incoming telegram update.
Returns bool
collect_additional_context(context, update, dispatcher, check_result)
Prepares additional arguments for the context. Override if needed.
Parameters
• context ([Link]) – The context object.
• update ([Link]) – The update to gather chat/user id from.
• dispatcher ([Link]) – The calling dispatcher.
• check_result – The result (return value) from check_update.

[Link]

class [Link](callback, pass_update_queue=False,


pass_job_queue=False,
pass_user_data=False,
pass_chat_data=False)
Bases: [Link]
Handler class to handle Telegram PreCheckout callback queries.
callback
The callback function for this handler.
Type callable

40 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

pass_update_queue
Determines whether update_queue will be passed to the callback function.
Type bool
pass_job_queue
Determines whether job_queue will be passed to the callback function.
Type bool
pass_user_data
Determines whether user_data will be passed to the callback function.
Type bool
pass_chat_data
Determines whether chat_data will be passed to the callback function.
Type bool

Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See [Link] 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
[Link].
• 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
[Link] and [Link] 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 [Link].
JobQueue instance created by the [Link] which can be used to
schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.
• pass_user_data (bool, optional) – If set to True, a keyword argument called
user_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_chat_data (bool, optional) – If set to True, a keyword argument called
chat_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.

check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update ([Link]) – Incoming telegram update.
Returns bool

3.1. [Link] package 41


Python Telegram Bot Documentation, Release 12.1.1

[Link]

class [Link](prefix, command, callback, filters=None,


pass_args=False, pass_update_queue=False,
pass_job_queue=False, pass_user_data=False,
pass_chat_data=False)
Bases: [Link]
Handler class to handle custom prefix commands
This is a intermediate handler between MessageHandler and CommandHandler. It supports con-
figurable commands with the same options as CommandHandler. It will respond to every combination of
prefix and command. It will add a list to the CallbackContext named CallbackContext.
args. It will contain a list of strings, which is the text following the command split on single or consecutive
whitespace characters.
Examples:

Single prefix and command:

PrefixHandler('!', 'test', callback) will respond to '!test'.

Multiple prefixes, single command:

PrefixHandler(['!', '#'], 'test', callback) will respond to '!test' and


'#test'.

Miltiple prefixes and commands:

PrefixHandler(['!', '#'], ['test', 'help`], callback) will respond to '!


˓→test',
'#test', '!help' and '#help'.

By default the handler listens to messages as well as edited messages. To change this behavior use ~‘‘Fil-
[Link].edited_message‘‘.
prefix
The prefix(es) that will precede command.
Type str | List[str]
command
The command or list of commands this handler should listen for.
Type str | List[str]
callback
The callback function for this handler.
Type callable
filters
Optional. Only allow updates with these Filters.
Type [Link]
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.

42 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

Type bool
pass_user_data
Determines whether user_data will be passed to the callback function.
Type bool
pass_chat_data
Determines whether chat_data will be passed to the callback function.
Type bool

Note: pass_user_data and pass_chat_data determine whether a dict you can use to keep any
data in will be sent to the callback function. Related to either the user or the chat that the update was
sent in. For each update from the same user or in the same chat, it will be the same dict.
Note that this is DEPRECATED, and you should use context based callbacks. See [Link] for
more info.

Parameters
• prefix (str | List[str]) – The prefix(es) that will precede command.
• command (str | List[str]) – The command or list of commands this handler should
listen for.
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
[Link].
• filters ([Link], optional) – A filter inheriting from
[Link]. Standard filters can be found in
[Link]. 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 [Link] and [Link] 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 [Link].
JobQueue instance created by the [Link] 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.

3.1. [Link] package 43


Python Telegram Bot Documentation, Release 12.1.1

check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update ([Link]) – Incoming telegram update.
Returns The list of args for the handler
Return type list
collect_additional_context(context, update, dispatcher, check_result)
Prepares additional arguments for the context. Override if needed.
Parameters
• context ([Link]) – The context object.
• update ([Link]) – The update to gather chat/user id from.
• dispatcher ([Link]) – The calling dispatcher.
• check_result – The result (return value) from check_update.

[Link]

class [Link](pattern, callback, pass_groups=False,


pass_groupdict=False, pass_update_queue=False,
pass_job_queue=False, pass_user_data=False,
pass_chat_data=False, allow_edited=False, mes-
sage_updates=True, channel_post_updates=False,
edited_updates=False)
Bases: [Link]
Handler class to handle Telegram updates based on a regex.
It uses a regular expression to check text messages. Read the documentation of the re module for more
information. The [Link] function is used to determine if an update should be handled by this handler.
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.

44 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

Type bool
pass_chat_data
Determines whether chat_data will be passed to the callback function.
Type bool

Note: This handler is being deprecated. For the same usecase use: MessageHandler(Filters.
regex(r'pattern'), callback)

Parameters
• pattern (str | Pattern) – The regex pattern.
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
[Link].
• 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 [Link](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 [Link] and [Link] 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 [Link].
JobQueue instance created by the [Link] which can be used to
schedule new jobs. Default is False.
• pass_user_data (bool, optional) – If set to True, a keyword argument called
user_data will be passed to the callback function. Default is False.
• pass_chat_data (bool, optional) – If set to True, a keyword argument called
chat_data will be passed to the callback function. Default is False.
• message_updates (bool, optional) – Should “normal” message updates be han-
dled? Default is True.
• channel_post_updates (bool, optional) – Should channel posts updates be han-
dled? Default is True.
• edited_updates (bool, optional) – Should “edited” message updates be handled?
Default is False.
Raises ValueError

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:
//[Link]/fxJuV for more info.
Parameters

3.1. [Link] package 45


Python Telegram Bot Documentation, Release 12.1.1

• dispatcher ([Link]) – The dispatcher.


• update ([Link]) – The update to gather chat/user id from.
• check_result – The result from check_update

[Link]

class [Link](callback, pass_update_queue=False,


pass_job_queue=False,
pass_user_data=False,
pass_chat_data=False)
Bases: [Link]
Handler class to handle Telegram shipping callback queries.
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

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 [Link] 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
[Link].
• 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 [Link] and [Link] that
contains new updates which can be used to insert updates. Default is False. DEPRE-
CATED: Please switch to context based callbacks.

46 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

• 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 [Link].
JobQueue instance created by the [Link] which can be used to
schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.
• pass_user_data (bool, optional) – If set to True, a keyword argument called
user_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.
• pass_chat_data (bool, optional) – If set to True, a keyword argument called
chat_data will be passed to the callback function. Default is False. DEPRE-
CATED: Please switch to context based callbacks.

check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update ([Link]) – Incoming telegram update.
Returns bool

[Link]

class [Link](command, callback, pass_args=False,


pass_update_queue=False,
pass_job_queue=False)
Bases: [Link]
Handler class to handle string commands. Commands are string updates that start with /.

Note: This handler is not used to handle Telegram [Link], but strings manually put in the
queue. For example to send messages with the bot using command line or API.

command
The command this handler should listen for.
Type str
callback
The callback function for this handler.
Type callable
pass_args
Determines whether the handler should be passed args.
Type bool
pass_update_queue
Determines whether update_queue will be passed to the callback function.
Type bool
pass_job_queue
Determines whether job_queue will be passed to the callback function.
Type bool

Parameters
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)

3.1. [Link] package 47


Python Telegram Bot Documentation, Release 12.1.1

The return value of the callback is usually ignored except for the special case of
[Link].
• 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 [Link] and [Link] 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:[Link] instance created by the [Link]
which can be used to schedule new jobs. Default is False. DEPRECATED: Please
switch to context based callbacks.

check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (str) – An incoming command.
Returns bool
collect_additional_context(context, update, dispatcher, check_result)
Prepares additional arguments for the context. Override if needed.
Parameters
• context ([Link]) – The context object.
• update ([Link]) – The update to gather chat/user id from.
• dispatcher ([Link]) – 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:
//[Link]/fxJuV for more info.
Parameters
• dispatcher ([Link]) – The dispatcher.
• update ([Link]) – The update to gather chat/user id from.
• check_result – The result from check_update

[Link]

class [Link](pattern, callback, pass_groups=False,


pass_groupdict=False,
pass_update_queue=False,
pass_job_queue=False)
Bases: [Link]
Handler class to handle string updates based on a regex which checks the update content.

48 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

Read the documentation of the re module for more information. The [Link] function is used to
determine if an update should be handled by this handler.

Note: This handler is not used to handle Telegram [Link], but strings manually put in the
queue. For example to send messages with the bot using command line or API.

pattern
The regex pattern.
Type str | Pattern
callback
The callback function for this handler.
Type callable
pass_groups
Determines whether groups will be passed to the callback function.
Type bool
pass_groupdict
Determines whether groupdict. will be passed to the callback function.
Type bool
pass_update_queue
Determines whether update_queue will be passed to the callback function.
Type bool
pass_job_queue
Determines whether job_queue will be passed to the callback function.
Type bool

Parameters
• pattern (str | Pattern) – The regex pattern.
• callback (callable) – The callback function for this handler. Will be called when
check_update has determined that an update should be processed by this handler.
Callback signature for context based API:
def callback(update: Update, context: CallbackContext)
The return value of the callback is usually ignored except for the special case of
[Link].
• 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 [Link](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 [Link] and [Link] 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 [Link].
JobQueue instance created by the [Link] which can be used to

3.1. [Link] package 49


Python Telegram Bot Documentation, Release 12.1.1

schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.

check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update (str) – An incoming command.
Returns bool
collect_additional_context(context, update, dispatcher, check_result)
Prepares additional arguments for the context. Override if needed.
Parameters
• context ([Link]) – The context object.
• update ([Link]) – The update to gather chat/user id from.
• dispatcher ([Link]) – 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:
//[Link]/fxJuV for more info.
Parameters
• dispatcher ([Link]) – The dispatcher.
• update ([Link]) – The update to gather chat/user id from.
• check_result – The result from check_update

[Link]

class [Link](type, callback, strict=False, pass_update_queue=False,


pass_job_queue=False)
Bases: [Link]
Handler class to handle updates of custom types.
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
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

50 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

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
[Link].
• 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 [Link] and [Link] 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 [Link].
JobQueue instance created by the [Link] which can be used to
schedule new jobs. Default is False. DEPRECATED: Please switch to context based
callbacks.

check_update(update)
Determines whether an update should be passed to this handlers callback.
Parameters update ([Link]) – Incoming telegram update.
Returns bool

3.1.10 Persistence

[Link]

class [Link](store_user_data=True, store_chat_data=True)


Bases: object
Interface class for adding persistence to your bot. Subclass this object for different implementations of a
persistent bot.
All relevant methods must be overwritten. This means:
• If store_chat_data is True you must overwrite get_chat_data() and
update_chat_data().
• If store_user_data is True you must overwrite get_user_data() and
update_user_data().
• If you want to store conversation data with [Link], you must
overwrite get_conversations() and update_conversation().
• flush() will be called when the bot is shutdown.
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

3.1. [Link] package 51


Python Telegram Bot Documentation, Release 12.1.1

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 .

flush()
Will be called by [Link] upon receiving a stop signal. Gives the persistence a
chance to finish up saving or close a database connection gracefully. If this is not of any importance
just pass will be sufficient.
get_chat_data()
“Will be called by [Link] upon creation with a persistence object. It should
return the chat_data if stored, or an empty defaultdict(dict).
Returns The restored chat data.
Return type defaultdict
get_conversations(name)
“Will be called by [Link] when a [Link].
ConversationHandler is added if [Link].
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
get_user_data()
“Will be called by [Link] 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
update_chat_data(chat_id, data)
Will be called by the [Link] after a handler has handled an update.
Parameters
• chat_id (int) – The chat the data might have been changed for.
• data (dict) – The [Link].chat_data [user_id].
update_conversation(name, key, new_state)
Will be called when a [Link].update_state is called.
this allows the storeage of the new state in the persistence.
Parameters
• name (str) – The handlers name.
• key (tuple) – The key the state is changed for.
• new_state (tuple | any) – The new state for the given key.
update_user_data(user_id, data)
Will be called by the [Link] after a handler has handled an update.
Parameters
• user_id (int) – The user the data might have been changed for.
• data (dict) – The [Link].user_data [user_id].

52 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

[Link]

class [Link](filename, store_user_data=True,


store_chat_data=True, single_file=True,
on_flush=False)
Bases: [Link]
Using python’s builtin pickle for making you bot persistent.
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
single_file
Optional. When False will store 3 sperate files of filename_user_data, filename_chat_data and
filename_conversations. Default is True.
Type bool
on_flush
When True will only save to file when flush() is called and keep data in memory until that hap-
pens. When False will store data on any transaction and on call fo flush(). Default is False.
Type bool, optional

Parameters
• filename (str) – The filename for storing the pickle files. When single_file is
false this will be used as a prefix.
• store_user_data (bool, optional) – Whether user_data should be saved by this
persistence class. Default is True.
• store_chat_data (bool, optional) – Whether user_data should be saved by this
persistence class. Default is True.
• single_file (bool, optional) – When False will store 3 sperate files of file-
name_user_data, filename_chat_data and filename_conversations. Default is True.
• on_flush (bool, optional) – When True will only save to file when flush() is
called and keep data in memory until that happens. When False will store data on any
transaction and on call fo flush(). Default is False.

flush()
Will save all data in memory to pickle file(s).
get_chat_data()
Returns the chat_data from the pickle file if it exsists or an empty defaultdict.
Returns The restored chat data.
Return type defaultdict
get_conversations(name)
Returns the conversations from the pickle file if it exsists or an empty defaultdict.
Parameters name (str) – The handlers name.

3.1. [Link] package 53


Python Telegram Bot Documentation, Release 12.1.1

Returns The restored conversations for the handler.


Return type dict
get_user_data()
Returns the user_data from the pickle file if it exsists or an empty defaultdict.
Returns The restored user data.
Return type defaultdict
update_chat_data(chat_id, data)
Will update the chat_data (if changed) and depending on on_flush save the pickle file.
Parameters
• chat_id (int) – The chat the data might have been changed for.
• data (dict) – The [Link].chat_data [chat_id].
update_conversation(name, key, new_state)
Will update the conversations for the given handler and depending on on_flush save the pickle file.
Parameters
• name (str) – The handlers name.
• key (tuple) – The key the state is changed for.
• new_state (tuple | any) – The new state for the given key.
update_user_data(user_id, data)
Will update the user_data (if changed) and depending on on_flush save the pickle file.
Parameters
• user_id (int) – The user the data might have been changed for.
• data (dict) – The [Link].user_data [user_id].

[Link]

class [Link](store_user_data=True, store_chat_data=True,


user_data_json=”, chat_data_json=”, conversa-
tions_json=”)
Bases: [Link]
Using python’s dicts and json for making you bot persistent.
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

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.
• user_data_json (str, optional) – Json string that will be used to reconstruct
user_data on creating this persistence. Default is "".

54 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

• chat_data_json (str, optional) – Json string that will be used to reconstruct


chat_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 "".

chat_data
The chat_data as a dict
Type dict
chat_data_json
The chat_data serialized as a JSON-string.
Type str
conversations
The conversations as a dict
Type dict
conversations_json
The conversations serialized as a JSON-string.
Type str
get_chat_data()
Returns the chat_data created from the chat_data_json or an empty defaultdict.
Returns The restored user data.
Return type defaultdict
get_conversations(name)
Returns the conversations created from the conversations_json or an empty defaultdict.
Returns The restored user data.
Return type defaultdict
get_user_data()
Returns the user_data created from the user_data_json or an empty defaultdict.
Returns The restored user data.
Return type defaultdict
update_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 [Link].chat_data [chat_id].
update_conversation(name, key, new_state)
Will update the conversations for the given handler.
Parameters
• name (str) – The handlers name.
• key (tuple) – The key the state is changed for.
• new_state (tuple | any) – The new state for the given key.
update_user_data(user_id, data)
Will update the user_data (if changed).
Parameters
• user_id (int) – The user the data might have been changed for.

3.1. [Link] package 55


Python Telegram Bot Documentation, Release 12.1.1

• data (dict) – The [Link].user_data [user_id].


user_data
The user_data as a dict
Type dict
user_data_json
The user_data serialized as a JSON-string.
Type str

3.2 telegram package

3.2.1 [Link]

class [Link](file_id, width, height, duration, thumb=None, file_name=None,


mime_type=None, file_size=None, bot=None, **kwargs)
Bases: [Link]
This object represents an animation file to be displayed in the message containing a game.
file_id
Unique file identifier.
Type str
width
Video width as defined by sender.
Type int
height
Video height as defined by sender.
Type int
duration
Duration of the video in seconds as defined by sender.
Type int
thumb
Optional. Animation thumbnail as defined by sender.
Type [Link]
file_name
Optional. Original animation filename as defined by sender.
Type str
mime_type
Optional. MIME type of the file as defined by sender.
Type str
file_size
Optional. File size.
Type int
bot
Optional. The Bot to use for instance methods.
Type [Link]

Parameters

56 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

• file_id (str) – Unique file identifier.


• width (int) – Video width as defined by sender.
• height (int) – Video height as defined by sender.
• duration (int) – Duration of the video in seconds as defined by sender.
• thumb ([Link], optional) – Animation thumbnail as defined by
sender.
• file_name (str, optional) – Original animation filename as defined by sender.
• mime_type (str, optional) – MIME type of the file as defined by sender.
• file_size (int, optional) – File size.
• bot ([Link], optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.

get_file(timeout=None, **kwargs)
Convenience wrapper over [Link].get_file
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
Raises [Link]

3.2.2 [Link]

class [Link](file_id, duration, performer=None, title=None, mime_type=None,


file_size=None, thumb=None, bot=None, **kwargs)
Bases: [Link]
This object represents an audio file to be treated as music by the Telegram clients.
file_id
Unique identifier for this file.
Type str
duration
Duration of the audio in seconds.
Type int
performer
Optional. Performer of the audio as defined by sender or by audio tags.
Type str
title
Optional. Title of the audio as defined by sender or by audio tags.
Type str
mime_type
Optional. MIME type of the file as defined by sender.
Type str

3.2. telegram package 57


Python Telegram Bot Documentation, Release 12.1.1

file_size
Optional. File size.
Type int
thumb
Optional. Thumbnail of the album cover to which the music file belongs
Type [Link]
bot
Optional. The Bot to use for instance methods.
Type [Link]

Parameters
• file_id (str) – Unique identifier for this file.
• duration (int) – Duration of the audio in seconds as defined by sender.
• performer (str, optional) – Performer of the audio as defined by sender or by audio
tags.
• title (str, optional) – Title of the audio as defined by sender or by audio tags.
• mime_type (str, optional) – MIME type of the file as defined by sender.
• file_size (int, optional) – File size.
• thumb ([Link], optional) – Thumbnail of the album cover to which
the music file belongs
• bot ([Link], optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.

get_file(timeout=None, **kwargs)
Convenience wrapper over [Link].get_file
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
Raises [Link]

3.2.3 [Link]

class [Link](token, base_url=None, base_file_url=None, request=None, pri-


vate_key=None, private_key_password=None)
Bases: [Link]
This object represents a Telegram Bot.
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 ([Link], optional) – Pre initialized
[Link].

58 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

• private_key (bytes, optional) – Private key for decryption of telegram passport


data.
• private_key_password (bytes, optional) – Password for above private key.
addStickerToSet(user_id, name, png_sticker, emojis, mask_position=None, timeout=20,
**kwargs)
Alias for add_sticker_to_set
add_sticker_to_set(user_id, name, png_sticker, emojis, mask_position=None, timeout=20,
**kwargs)
Use this method to add a new sticker to a set created by the bot.

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 created sticker set owner.
• name (str) – Sticker set name.
• png_sticker (str | filelike object) – Png image with the sticker, must be up to
512 kilobytes in size, dimensions must not exceed 512px, and either width or height
must be exactly 512px. 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.
• emojis (str) – One or more emoji corresponding to the sticker.
• mask_position ([Link], optional) – Position where the
mask should beplaced on faces.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, True is returned.
Return type bool
Raises [Link]

answerCallbackQuery(callback_query_id, text=None, show_alert=False, url=None,


cache_time=None, timeout=None, **kwargs)
Alias for answer_callback_query
answerInlineQuery(inline_query_id, results, cache_time=300, is_personal=None,
next_offset=None, switch_pm_text=None, switch_pm_parameter=None,
timeout=None, **kwargs)
Alias for answer_inline_query
answerPreCheckoutQuery(pre_checkout_query_id, ok, error_message=None, timeout=None,
**kwargs)
Alias for answer_pre_checkout_query
answerShippingQuery(shipping_query_id, ok, shipping_options=None, error_message=None,
timeout=None, **kwargs)
Alias for answer_shipping_query
answer_callback_query(callback_query_id, text=None, show_alert=False, url=None,
cache_time=None, timeout=None, **kwargs)
Use this method to send answers to callback queries sent from inline keyboards. The answer will
be displayed to the user as a notification at the top of the chat screen or as an alert. Alternatively,

3.2. telegram package 59


Python Telegram Bot Documentation, Release 12.1.1

the user can be redirected to the specified Game URL. For this option to work, you must first cre-
ate a game for your bot via BotFather and accept the terms. Otherwise, you may use links like
[Link]/your_bot?start=XXXX that open your bot with a parameter.
Parameters
• callback_query_id (str) – Unique identifier for the query to be answered.
• text (str, optional) – Text of the notification. If not specified, nothing will be
shown to the user, 0-200 characters.
• show_alert (bool, optional) – If true, an alert will be shown by the client instead
of a notification at the top of the chat screen. Defaults to false.
• url (str, optional) – URL that will be opened by the user’s client. If you have
created a Game and accepted the conditions via @Botfather, specify the URL that
opens your game - note that this will only work if the query comes from a callback
game button. Otherwise, you may use links like [Link]/your_bot?start=XXXX that open
your bot with a parameter.
• cache_time (int, optional) – The maximum amount of time in seconds that the
result of the callback query may be cached client-side. Defaults to 0.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns bool On success, True is returned.
Raises [Link]
answer_inline_query(inline_query_id, results, cache_time=300,
is_personal=None, next_offset=None, switch_pm_text=None,
switch_pm_parameter=None, timeout=None, **kwargs)
Use this method to send answers to an inline query. No more than 50 results per query are allowed.
Parameters
• inline_query_id (str) – Unique identifier for the answered query.
• results (List[[Link]) – A list of results for the in-
line query.
• cache_time (int, optional) – The maximum amount of time in seconds that the
result of the inline query may be cached on the server. Defaults to 300.
• is_personal (bool, optional) – Pass True, if results may be cached on the server
side only for the user that sent the query. By default, results may be returned to any
user who sends the same query.
• next_offset (str, optional) – Pass the offset that a client should send in the next
query with the same text to receive more results. Pass an empty string if there are no
more results or if you don’t support pagination. Offset length can’t exceed 64 bytes.
• switch_pm_text (str, optional) – If passed, clients will display a button with
specified text that switches the user to a private chat with the bot and sends the bot a
start message with the parameter switch_pm_parameter.
• switch_pm_parameter (str, optional) – Deep-linking parameter for the /start
message sent to the bot when user presses the switch button. 1-64 characters, only
A-Z, a-z, 0-9, _ and - are allowed.
• timeout (int | float, optional) – If this value is specified, use it as he read timeout
from the server (instead of the one specified during creation of the connection pool).
• **kwargs (dict) – Arbitrary keyword arguments.

60 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

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.

Returns bool On success, True is returned.


Raises [Link]

answer_pre_checkout_query(pre_checkout_query_id, ok, error_message=None, time-


out=None, **kwargs)
Once the user has confirmed their payment and shipping details, the Bot API sends the final confirma-
tion in the form of an Update with the field pre_checkout_query. Use this method to respond to such
pre-checkout queries.

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

Parameters
• pre_checkout_query_id (str) – Unique identifier for the query to be an-
swered.
• ok (bool) – Specify True if everything is alright (goods are available, etc.) and the
bot is ready to proceed with the order. Use False if there are any problems.
• error_message (str, optional) – Required if ok is False. Error message in human
readable form that explains the reason for failure to proceed with the checkout (e.g.
“Sorry, somebody just bought the last of our amazing black T-shirts while you were
busy filling out your payment details. Please choose a different color or garment!”).
Telegram will display this message to the user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, True is returned.
Return type bool
Raises [Link]

answer_shipping_query(shipping_query_id, ok, shipping_options=None, er-


ror_message=None, timeout=None, **kwargs)
If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the
Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to
shipping queries.
Parameters
• shipping_query_id (str) – Unique identifier for the query to be answered.
• ok (bool) – Specify True if delivery to the specified address is possible and False if
there are any problems (for example, if delivery to the specified address is not possi-
ble).

3.2. telegram package 61


Python Telegram Bot Documentation, Release 12.1.1

• shipping_options (List[[Link]]) – Required if ok is


True. A JSON-serialized array of available shipping options.
• error_message (str, optional) – Required if ok is False. Error message in human
readable form that explains why it is impossible to complete the order (e.g. “Sorry,
delivery to your desired address is unavailable”). Telegram will display this message
to the user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns bool; On success, True is returned.
Raises [Link]
createNewStickerSet(user_id, name, title, png_sticker, emojis, contains_masks=None,
mask_position=None, timeout=20, **kwargs)
Alias for create_new_sticker_set
create_new_sticker_set(user_id, name, title, png_sticker, emojis, contains_masks=None,
mask_position=None, timeout=20, **kwargs)
Use this method to create new sticker set owned by a user.
The bot will be able to edit the created sticker set.

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 created sticker set owner.
• name (str) – Short name of sticker set, to be used in [Link]/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) – 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.
• 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 ([Link], optional) – Position where the
mask should be placed on faces.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, True is returned.
Return type bool
Raises [Link]

62 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

deleteChatPhoto(chat_id, timeout=None, **kwargs)


Alias for delete_chat_photo
deleteChatStickerSet(chat_id, timeout=None, **kwargs)
Alias for delete_chat_sticker_set
deleteMessage(chat_id, message_id, timeout=None, **kwargs)
Alias for delete_message
deleteStickerFromSet(sticker, timeout=None, **kwargs)
Alias for delete_sticker_from_set
deleteWebhook(timeout=None, **kwargs)
Alias for delete_webhook
delete_chat_photo(chat_id, timeout=None, **kwargs)
Use this method to delete a chat photo. Photos can’t be changed for private chats. The bot must be an
administrator in the chat for this to work and must have the appropriate admin rights.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments

Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are
Admins’ setting is off in the target group.

Returns Returns True on success.


Return type bool
Raises [Link]

delete_chat_sticker_set(chat_id, timeout=None, **kwargs)


Use this method to delete a group sticker set from a supergroup. The bot must be an administrator
in the chat for this to work and must have the appropriate admin rights. Use the field telegram.
Chat.can_set_sticker_set optionally returned in get_chat requests to check if the bot can
use this method.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
supergroup (in the format @supergroupusername).
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns True on success.
Return type bool
delete_message(chat_id, message_id, timeout=None, **kwargs)
Use this method to delete a message, including service messages, with the following limitations:
• A message can only be deleted if it was sent less than 48 hours ago.
• Bots can delete outgoing messages in private chats, groups, and supergroups.

3.2. telegram package 63


Python Telegram Bot Documentation, Release 12.1.1

• Bots can delete incoming messages in private chats.


• Bots granted can_post_messages permissions can delete outgoing messages in channels.
• If the bot is an administrator of a group, it can delete any message there.
• If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any
message there.

Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• message_id (int) – Identifier of the message to delete.
• timeout (int | float, optional) – If this value is specified, use it as
• read timeout (the) – from the server (instead of the one specified during creation
of the connection pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, True is returned.
Return type bool
Raises [Link]

delete_sticker_from_set(sticker, timeout=None, **kwargs)


Use this method to delete a sticker from a set created by the bot.
Parameters
• sticker (str) – File identifier of the sticker.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, True is returned.
Return type bool
Raises [Link]
delete_webhook(timeout=None, **kwargs)
Use this method to remove webhook integration if you decide to switch back to getUpdates. Requires
no parameters.
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns bool On success, True is returned.
Raises [Link]
editMessageCaption(chat_id=None, message_id=None, inline_message_id=None, cap-
tion=None, reply_markup=None, timeout=None, parse_mode=None,
**kwargs)
Alias for edit_message_caption

64 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

editMessageLiveLocation(chat_id=None, message_id=None, inline_message_id=None,


latitude=None, longitude=None, location=None, re-
ply_markup=None, timeout=None, **kwargs)
Alias for edit_message_live_location
editMessageMedia(chat_id=None, message_id=None, inline_message_id=None, media=None,
reply_markup=None, timeout=None, **kwargs)
Alias for edit_message_media
editMessageReplyMarkup(chat_id=None, message_id=None, inline_message_id=None, re-
ply_markup=None, timeout=None, **kwargs)
Alias for edit_message_reply_markup
editMessageText(text, chat_id=None, message_id=None, inline_message_id=None,
parse_mode=None, disable_web_page_preview=None, reply_markup=None,
timeout=None, **kwargs)
Alias for edit_message_text
edit_message_caption(chat_id=None, message_id=None, inline_message_id=None, cap-
tion=None, reply_markup=None, timeout=None, parse_mode=None,
**kwargs)
Use this method to edit captions of messages sent by the bot or via the bot (for inline bots).
Parameters
• chat_id (int | str) – 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 sent message.
• inline_message_id (str, optional) – Required if chat_id and message_id are
not specified. Identifier of the inline message.
• caption (str, optional) – New caption of the message.
• 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 [Link] for the available modes.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, if edited message is sent by the bot, the edited Message is returned,
otherwise True is returned.
Return type [Link]
Raises [Link]
edit_message_live_location(chat_id=None, message_id=None, in-
line_message_id=None, latitude=None, longitude=None,
location=None, reply_markup=None, timeout=None,
**kwargs)
Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A
location can be edited until its live_period expires or editing is explicitly disabled by a call to
stop_message_live_location.

Note: You can either supply a latitude and longitude or a location.

3.2. telegram package 65


Python Telegram Bot Documentation, Release 12.1.1

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) – 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.
• latitude (float, optional) – Latitude of location.
• longitude (float, optional) – Longitude of location.
• location ([Link], optional) – The location to send.
• reply_markup ([Link], 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).
Returns On success the edited message.
Return type [Link]

edit_message_media(chat_id=None, message_id=None, inline_message_id=None, me-


dia=None, reply_markup=None, timeout=None, **kwargs)
Use this method to edit audio, document, photo, or video messages. If a message is a part of a message
album, then it can be edited only to a photo or a video. Otherwise, message type can be changed
arbitrarily. When inline message is edited, new file can’t be uploaded. Use previously uploaded file
via its file_id or specify a URL. On success, if the edited message was sent by the bot, the edited
Message is returned, otherwise True is returned.
Parameters
• chat_id (int | str, optional) – 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 sent message.
• inline_message_id (str, optional) – Required if chat_id and message_id are
not specified. Identifier of the inline message.
• media ([Link]) – An object for a new media content of the
message.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
edit_message_reply_markup(chat_id=None, message_id=None, inline_message_id=None,
reply_markup=None, timeout=None, **kwargs)
Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline
bots).
Parameters

66 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

• chat_id (int | str) – 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 sent message.
• inline_message_id (str, optional) – Required if chat_id and message_id are
not specified. Identifier of the inline message.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, if edited message is sent by the bot, the editedMessage is returned,
otherwise True is returned.
Return type [Link]
Raises [Link]
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, **kwargs)
Use this method to edit text and game messages sent by the bot or via the bot (for inline bots).
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) – 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.
• text (str) – New text of the message.
• parse_mode (str) – 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 [Link] for the available modes.
• disable_web_page_preview (bool, optional) – Disables link previews for
links in this message.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, if edited message is sent by the bot, the edited Message is returned,
otherwise True is returned.
Return type [Link]
Raises [Link]
exportChatInviteLink(chat_id, timeout=None, **kwargs)
Alias for export_chat_invite_link

3.2. telegram package 67


Python Telegram Bot Documentation, Release 12.1.1

export_chat_invite_link(chat_id, timeout=None, **kwargs)


Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator
in the chat for this to work and must have the appropriate admin rights.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments
Returns Exported invite link on success.
Return type str
Raises [Link]
first_name
Bot’s first name.
Type str
forwardMessage(chat_id, from_chat_id, message_id, disable_notification=False, timeout=None,
**kwargs)
Alias for forward_message
forward_message(chat_id, from_chat_id, message_id, disable_notification=False, time-
out=None, **kwargs)
Use this method to forward messages of any kind.
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).
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• message_id (int) – Message identifier in the chat specified in from_chat_id.
• timeout (int | float, optional) – If this value is specified, use it as
• read timeout (the) – from the server (instead of the one specified during creation
of the connection pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type [Link]
Raises [Link]
getChat(chat_id, timeout=None, **kwargs)
Alias for get_chat
getChatAdministrators(chat_id, timeout=None, **kwargs)
Alias for get_chat_administrators
getChatMember(chat_id, user_id, timeout=None, **kwargs)
Alias for get_chat_member
getChatMembersCount(chat_id, timeout=None, **kwargs)
Alias for get_chat_members_count

68 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

getFile(file_id, timeout=None, **kwargs)


Alias for get_file
getGameHighScores(user_id, chat_id=None, message_id=None, inline_message_id=None,
timeout=None, **kwargs)
Alias for get_game_high_scores
getMe(timeout=None, **kwargs)
Alias for get_me
getStickerSet(name, timeout=None, **kwargs)
Alias for get_sticker_set
getUpdates(offset=None, limit=100, timeout=0, read_latency=2.0, allowed_updates=None,
**kwargs)
Alias for get_updates
getUserProfilePhotos(user_id, offset=None, limit=100, timeout=None, **kwargs)
Alias for get_user_profile_photos
getWebhookInfo(timeout=None, **kwargs)
Alias for get_webhook_info
get_chat(chat_id, timeout=None, **kwargs)
Use this method to get up to date information about the chat (current name of the user for one-on-one
conversations, current username of a user, group or channel, etc.).
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
Raises [Link]
get_chat_administrators(chat_id, timeout=None, **kwargs)
Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember
objects that contains information about all chat administrators except other bots. If the chat is a group
or a supergroup and no administrators were appointed, only the creator will be returned.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns List[[Link]]
Raises [Link]
get_chat_member(chat_id, user_id, timeout=None, **kwargs)
Use this method to get information about a member of a chat.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).

3.2. telegram package 69


Python Telegram Bot Documentation, Release 12.1.1

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


• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
Raises [Link]
get_chat_members_count(chat_id, timeout=None, **kwargs)
Use this method to get the number of members in a chat
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns Number of members in the chat.
Return type int
Raises [Link]
get_file(file_id, timeout=None, **kwargs)
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 [Link].
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.
Parameters
• file_id (str | [Link] | [Link] | telegram.
ChatPhoto | [Link] | [Link] | telegram.
Sticker | [Link] | [Link] | [Link])
– Either the file identifier or an object that has a file_id attribute to get file information
about.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
Raises [Link]
get_game_high_scores(user_id, chat_id=None, message_id=None, in-
line_message_id=None, timeout=None, **kwargs)
Use this method to get data for high score tables. Will return the score of the specified user and several
of his neighbors in a game
Parameters
• user_id (int) – User identifier.
• 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.

70 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

• 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).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns List[[Link]]
Raises [Link]
get_me(timeout=None, **kwargs)
A simple method for testing your bot’s auth token. Requires no parameters.
Parameters timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
Returns A [Link] instance representing that bot if the credentials are valid,
None otherwise.
Return type [Link]
Raises [Link]
get_sticker_set(name, timeout=None, **kwargs)
Use this method to get a sticker set.
Parameters
• name (str) – Short name of the sticker set that is used in [Link]/addstickers/ URLs
(e.g., animals)
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
Raises [Link]
get_updates(offset=None, limit=100, timeout=0, read_latency=2.0, allowed_updates=None,
**kwargs)
Use this method to receive incoming updates using long polling.
Parameters
• offset (int, optional) – Identifier of the first update to be returned. Must be greater
by one than the highest among the identifiers of previously received updates. By
default, updates starting with the earliest unconfirmed update are returned. An update
is considered confirmed as soon as getUpdates is called with an offset higher than its
update_id. The negative offset can be specified to retrieve updates starting from -offset
update from the end of the updates queue. All previous updates will forgotten.
• limit (int, optional) – Limits the number of updates to be retrieved. Values be-
tween 1-100 are accepted. Defaults to 100.
• timeout (int, optional) – Timeout in seconds for long polling. Defaults to 0, i.e.
usual short polling. Should be positive, short polling should be used for testing pur-
poses only.
• allowed_updates (List[str]), optional) – List the types of updates you want
your bot to receive. For example, specify [“message”, “edited_channel_post”, “call-
back_query”] to only receive updates of these types. See [Link] for

3.2. telegram package 71


Python Telegram Bot Documentation, Release 12.1.1

a complete list of available update types. Specify an empty list to receive all up-
dates regardless of type (default). If not specified, the previous setting will be used.
Please note that this parameter doesn’t affect updates created before the call to the
get_updates, so unwanted updates may be received for a short period of time.
• **kwargs (dict) – Arbitrary keyword arguments.

Notes

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 [Link]

Returns List[[Link]]
Raises [Link]

get_user_profile_photos(user_id, offset=None, limit=100, timeout=None, **kwargs)


Use this method to get a list of profile pictures for a user.
Parameters
• user_id (int) – Unique identifier of the target user.
• offset (int, optional) – Sequential number of the first photo to be returned. By
default, all photos are returned.
• limit (int, optional) – Limits the number of photos to be retrieved. Values between
1-100 are accepted. Defaults to 100.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
Raises [Link]
get_webhook_info(timeout=None, **kwargs)
Use this method to get current webhook status. Requires no parameters.
If the bot is using getUpdates, will return an object with the url field empty.
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
id
Unique identifier for this bot.
Type int
kickChatMember(chat_id, user_id, timeout=None, until_date=None, **kwargs)
Alias for kick_chat_member
kick_chat_member(chat_id, user_id, timeout=None, until_date=None, **kwargs)
Use this method to kick a user from a group or a supergroup. In the case of supergroups, the user will

72 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

not be able to return to the group on their own using invite links, etc., unless unbanned first. The bot
must be an administrator in the group for this to work.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• user_id (int) – Unique identifier of the target user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• until_date (int | [Link], optional) – Date when the user will
be unbanned, unix time. If user is banned for more than 366 days or less than 30
seconds from the current time they are considered to be banned forever.
• **kwargs (dict) – Arbitrary keyword arguments.

Note: In regular groups (non-supergroups), 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.

Returns bool On success, True is returned.


Raises [Link]

last_name
Optional. Bot’s last name.
Type str
leaveChat(chat_id, timeout=None, **kwargs)
Alias for leave_chat
leave_chat(chat_id, timeout=None, **kwargs)
Use this method for your bot to leave a group, supergroup or channel.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns bool On success, True is returned.
Raises [Link]
name
Bot’s @username.
Type str
pinChatMessage(chat_id, message_id, disable_notification=None, timeout=None, **kwargs)
Alias for pin_chat_message
pin_chat_message(chat_id, message_id, disable_notification=None, timeout=None,
**kwargs)
Use this method to pin a message in a supergroup. The bot must be an administrator in the chat for
this to work and must have the appropriate admin rights.

3.2. telegram package 73


Python Telegram Bot Documentation, Release 12.1.1

Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• message_id (int) – Identifier of a message to pin.
• disable_notification (bool, optional) – Pass True, if it is not necessary to
send a notification to all group members about the new pinned message.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments
Returns Returns True on success.
Return type bool
Raises [Link]
promoteChatMember(chat_id, user_id, can_change_info=None, can_post_messages=None,
can_edit_messages=None, can_delete_messages=None,
can_invite_users=None, can_restrict_members=None,
can_pin_messages=None, can_promote_members=None, timeout=None,
**kwargs)
Alias for promote_chat_member
promote_chat_member(chat_id, user_id, can_change_info=None, can_post_messages=None,
can_edit_messages=None, can_delete_messages=None,
can_invite_users=None, can_restrict_members=None,
can_pin_messages=None, can_promote_members=None, time-
out=None, **kwargs)
Use this method to promote or demote a user in a supergroup or a channel. The bot must be an
administrator in the chat for this to work and must have the appropriate admin rights. Pass False for
all boolean parameters to demote a user
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
supergroup (in the format @supergroupusername).
• user_id (int) – Unique identifier of the target user.
• can_change_info (bool, optional) – Pass True, if the administrator can change
chat title, photo and other settings.
• can_post_messages (bool, optional) – Pass True, if the administrator can create
channel posts, channels only.
• can_edit_messages (bool, optional) – Pass True, if the administrator can edit
messages of other users, channels only.
• can_delete_messages (bool, optional) – Pass True, if the administrator can
delete messages of other users.
• can_invite_users (bool, optional) – Pass True, if the administrator can invite
new users to the chat.
• can_restrict_members (bool, optional) – Pass True, if the administrator can
restrict, ban or unban chat members.
• can_pin_messages (bool, optional) – Pass True, if the administrator can pin
messages, supergroups only.
• can_promote_members (bool, optional) – Pass True, if the administrator can
add new administrators with a subset of his own privileges or demote administrators

74 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

that he has promoted, directly or indirectly (promoted by administrators that were


appointed by him).
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments
Returns Returns True on success.
Return type bool
Raises [Link]
restrictChatMember(chat_id, user_id, permissions, until_date=None, timeout=None,
**kwargs)
Alias for restrict_chat_member
restrict_chat_member(chat_id, user_id, permissions, until_date=None, timeout=None,
**kwargs)
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 [Link]. 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 | [Link], optional) – Date when restrictions
will be lifted for the user, unix time. If user is restricted for more than 366 days or less
than 30 seconds from the current time, they are considered to be restricted forever.
• permissions ([Link]) – New user permissions.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments
Returns Returns True on success.
Return type bool
Raises [Link]

sendAnimation(chat_id, animation, duration=None, width=None, height=None, thumb=None,


caption=None, parse_mode=None, disable_notification=False, re-
ply_to_message_id=None, reply_markup=None, timeout=20, **kwargs)
Alias for send_animation
sendAudio(chat_id, audio, duration=None, performer=None, title=None, caption=None, dis-
able_notification=False, reply_to_message_id=None, reply_markup=None, time-
out=20, parse_mode=None, thumb=None, **kwargs)
Alias for send_audio
sendChatAction(chat_id, action, timeout=None, **kwargs)
Alias for send_chat_action

3.2. telegram package 75


Python Telegram Bot Documentation, Release 12.1.1

sendContact(chat_id, phone_number=None, first_name=None, last_name=None, dis-


able_notification=False, reply_to_message_id=None, reply_markup=None,
timeout=None, contact=None, vcard=None, **kwargs)
Alias for send_contact
sendDocument(chat_id, document, filename=None, caption=None, disable_notification=False,
reply_to_message_id=None, reply_markup=None, timeout=20,
parse_mode=None, thumb=None, **kwargs)
Alias for send_document
sendGame(chat_id, game_short_name, disable_notification=False, reply_to_message_id=None,
reply_markup=None, timeout=None, **kwargs)
Alias for send_game
sendInvoice(chat_id, title, description, payload, provider_token, start_parameter, cur-
rency, prices, photo_url=None, photo_size=None, photo_width=None,
photo_height=None, need_name=None, need_phone_number=None,
need_email=None, need_shipping_address=None, is_flexible=None, dis-
able_notification=False, reply_to_message_id=None, reply_markup=None,
provider_data=None, send_phone_number_to_provider=None,
send_email_to_provider=None, timeout=None, **kwargs)
Alias for send_invoice
sendLocation(chat_id, latitude=None, longitude=None, disable_notification=False, re-
ply_to_message_id=None, reply_markup=None, timeout=None, location=None,
live_period=None, **kwargs)
Alias for send_location
sendMediaGroup(chat_id, media, disable_notification=None, reply_to_message_id=None, time-
out=20, **kwargs)
Alias for send_media_group
sendMessage(chat_id, text, parse_mode=None, disable_web_page_preview=None, dis-
able_notification=False, reply_to_message_id=None, reply_markup=None,
timeout=None, **kwargs)
Alias for send_message
sendPhoto(chat_id, photo, caption=None, disable_notification=False, re-
ply_to_message_id=None, reply_markup=None, timeout=20, parse_mode=None,
**kwargs)
Alias for send_photo
sendPoll(chat_id, question, options, disable_notification=None, reply_to_message_id=None, re-
ply_markup=None, timeout=None, **kwargs)
Alias for send_poll
sendSticker(chat_id, sticker, disable_notification=False, reply_to_message_id=None, re-
ply_markup=None, timeout=20, **kwargs)
Alias for send_sticker
sendVenue(chat_id, latitude=None, longitude=None, title=None, address=None,
foursquare_id=None, disable_notification=False, reply_to_message_id=None, re-
ply_markup=None, timeout=None, venue=None, foursquare_type=None, **kwargs)
Alias for send_venue
sendVideo(chat_id, video, duration=None, caption=None, disable_notification=False, re-
ply_to_message_id=None, reply_markup=None, timeout=20, width=None,
height=None, parse_mode=None, supports_streaming=None, thumb=None,
**kwargs)
Alias for send_video
sendVideoNote(chat_id, video_note, duration=None, length=None, disable_notification=False,
reply_to_message_id=None, reply_markup=None, timeout=20, thumb=None,
**kwargs)
Alias for send_video_note

76 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

sendVoice(chat_id, voice, duration=None, caption=None, disable_notification=False, re-


ply_to_message_id=None, reply_markup=None, timeout=20, parse_mode=None,
**kwargs)
Alias for send_voice
send_animation(chat_id, animation, duration=None, width=None, height=None, thumb=None,
caption=None, parse_mode=None, disable_notification=False, re-
ply_to_message_id=None, reply_markup=None, timeout=20, **kwargs)
Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound).
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 | [Link]) – Animation to send.
Pass a file_id as String to send an animation that exists on the Telegram servers (rec-
ommended), pass an HTTP URL as a String for Telegram to get an animation from the
Internet, or upload a new animation using multipart/form-data. Lastly you can pass an
existing [Link] object to send.
• duration (int, optional) – Duration of sent animation in seconds.
• width (int, optional) – Animation width.
• height (int, optional) – Animation height.
• thumb (filelike object, optional) – Thumbnail of the file sent. The thumbnail should
be in JPEG format and less than 200 kB in size. A thumbnail’s width and height
should not exceed 90. Ignored if the file is not is passed as a string or file_id.
• caption (str, optional) – Animation caption (may also be used when resending
animations by file_id), 0-1024 characters.
• 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 [Link] for the available modes.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – Send file timeout (default: 20 seconds).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type [Link]
Raises [Link]
send_audio(chat_id, audio, duration=None, performer=None, title=None, caption=None, dis-
able_notification=False, reply_to_message_id=None, reply_markup=None, time-
out=20, parse_mode=None, thumb=None, **kwargs)
Use this method to send audio files, if you want Telegram clients to display them in the music player.
Your audio must be in the .mp3 format. On success, the sent Message is returned. Bots can currently
send audio files of up to 50 MB in size, this limit may be changed in the future.
For sending voice messages, use the sendVoice method instead.

3.2. telegram package 77


Python Telegram Bot Documentation, Release 12.1.1

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 | [Link]) – Audio file to send. Pass a file_id
as String to send an audio file that exists on the Telegram servers (recommended), pass
an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload
a new one using multipart/form-data. Lastly you can pass an existing telegram.
Audio object to send.
• caption (str, optional) – Audio caption, 0-1024 characters.
• 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 [Link] for the available modes.
• duration (int, optional) – Duration of sent audio in seconds.
• performer (str, optional) – Performer.
• title (str, optional) – Track name.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• thumb (filelike object, optional) – Thumbnail of the file sent. The thumbnail should
be in JPEG format and less than 200 kB in size. A thumbnail’s width and height
should not exceed 90. Ignored if the file is not is passed as a string or file_id.
• timeout (int | float, optional) – Send file timeout (default: 20 seconds).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type [Link]
Raises [Link]

send_chat_action(chat_id, action, timeout=None, **kwargs)


Use this method when you need to tell the user that something is happening on the bot’s side. The
status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its
typing status).
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• action ([Link] | str) – Type of action to broadcast. Choose
one, depending on what the user is about to receive. For convenience look at the
constants in [Link]

78 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns True on success.
Return type bool
Raises [Link]
send_contact(chat_id, phone_number=None, first_name=None, last_name=None, dis-
able_notification=False, reply_to_message_id=None, reply_markup=None,
timeout=None, contact=None, vcard=None, **kwargs)
Use this method to send phone contacts.

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 ([Link], optional) – The contact to send.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type [Link]
Raises [Link]

send_document(chat_id, document, filename=None, caption=None, disable_notification=False,


reply_to_message_id=None, reply_markup=None, timeout=20,
parse_mode=None, thumb=None, **kwargs)
Use this method to send general files.

Note: The document argument can be either a file_id, an URL or a file from disk open(filename,
'rb')

3.2. telegram package 79


Python Telegram Bot Documentation, Release 12.1.1

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 | [Link]) – File to send. Pass a
file_id as String to send a file that exists on the Telegram servers (recommended),
pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload
a new one using multipart/form-data. Lastly you can pass an existing telegram.
Document object to send.
• filename (str, optional) – File name that shows in telegram message (it is useful
when you send file generated by temp module, for example). Undocumented.
• caption (str, optional) – Document caption (may also be used when resending
documents by file_id), 0-1024 characters.
• 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 [Link] for the available modes.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• thumb (filelike object, optional) – Thumbnail of the file sent. The thumbnail should
be in JPEG format and less than 200 kB in size. A thumbnail’s width and height
should not exceed 90. Ignored if the file is not is passed as a string or file_id.
• timeout (int | float, optional) – Send file timeout (default: 20 seconds).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type [Link]
Raises [Link]

send_game(chat_id, game_short_name, disable_notification=False, reply_to_message_id=None,


reply_markup=None, timeout=None, **kwargs)
Use this method to send a game.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• game_short_name (str) – Short name of the game, serves as the unique identifier
for the game. Set up your games via Botfather.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup ([Link], 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.

80 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type [Link]
Raises [Link]
send_invoice(chat_id, title, description, payload, provider_token, start_parameter, cur-
rency, prices, photo_url=None, photo_size=None, photo_width=None,
photo_height=None, need_name=None, need_phone_number=None,
need_email=None, need_shipping_address=None, is_flexible=None, dis-
able_notification=False, reply_to_message_id=None, reply_markup=None,
provider_data=None, send_phone_number_to_provider=None,
send_email_to_provider=None, timeout=None, **kwargs)
Use this method to send invoices.
Parameters
• chat_id (int | str) – Unique identifier for the target private chat.
• title (str) – Product name.
• description (str) – Product description.
• payload (str) – Bot-defined invoice payload, 1-128 bytes. This will not be dis-
played to the user, use for your internal processes.
• provider_token (str) – Payments provider token, obtained via Botfather.
• start_parameter (str) – Unique deep-linking parameter that can be used to
generate this invoice when used as a start parameter.
• currency (str) – Three-letter ISO 4217 currency code.
• prices (List[[Link]) – Price breakdown, a list of compo-
nents (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.).
• provider_data (str | object, optional) – JSON-encoded data about the in-
voice, which will be shared with the payment provider. A detailed description of re-
quired fields should be provided by the payment provider. When an object is passed,
it will be encoded as JSON.
• photo_url (str, optional) – URL of the product photo for the invoice. Can be a
photo of the goods or a marketing image for a service. People like it better when they
see what they are paying for.
• photo_size (str, optional) – Photo size.
• photo_width (int, optional) – Photo width.
• photo_height (int, optional) – Photo height.
• need_name (bool, optional) – Pass True, if you require the user’s full name to
complete the order.
• 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 to com-
plete the order.
• need_shipping_address (bool, optional) – Pass True, if you require the user’s
shipping address to complete the order.

3.2. telegram package 81


Python Telegram Bot Documentation, Release 12.1.1

• 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.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup ([Link], optional) – Additional interface op-
tions. An inlinekeyboard. 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).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type [Link]
Raises [Link]
send_location(chat_id, latitude=None, longitude=None, disable_notification=False, re-
ply_to_message_id=None, reply_markup=None, timeout=None, loca-
tion=None, live_period=None, **kwargs)
Use this method to send point on the map.

Note: You can either supply a latitude and longitude or a location.

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 ([Link], optional) – The location to send.
• live_period (int, optional) – Period in seconds for which the location will be
updated, should be between 60 and 86400.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.

82 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

Returns On success, the sent Message is returned.


Return type [Link]
Raises [Link]

send_media_group(chat_id, media, disable_notification=None, reply_to_message_id=None,


timeout=20, **kwargs)
Use this method to send a group of photos or videos as an album.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• media (List[[Link]]) – An array describing photos and videos
to be sent, must include 2–10 items.
• 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.
• timeout (int | float, optional) – Send file timeout (default: 20 seconds).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns An array of the sent Messages.
Return type List[[Link]]
Raises [Link]
send_message(chat_id, text, parse_mode=None, disable_web_page_preview=None, dis-
able_notification=False, reply_to_message_id=None, reply_markup=None,
timeout=None, **kwargs)
Use this method to send text messages.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• text (str) – Text of the message to be sent. Max 4096 characters. Also found as
[Link].MAX_MESSAGE_LENGTH.
• parse_mode (str) – 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 [Link] for the available modes.
• disable_web_page_preview (bool, optional) – Disables link previews for
links in this message.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.

3.2. telegram package 83


Python Telegram Bot Documentation, Release 12.1.1

Returns On success, the sent message is returned.


Return type [Link]
Raises [Link]
send_photo(chat_id, photo, caption=None, disable_notification=False, re-
ply_to_message_id=None, reply_markup=None, timeout=20, parse_mode=None,
**kwargs)
Use this method to send photos.

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 | [Link]) – 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.
• caption (str, optional) – Photo caption (may also be used when resending photos
by file_id), 0-1024 characters.
• 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 [Link] for the available modes.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – Send file timeout (default: 20 seconds).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type [Link]
Raises [Link]

send_poll(chat_id, question, options, disable_notification=None, reply_to_message_id=None,


reply_markup=None, timeout=None, **kwargs)
Use this method to send a native poll. A native poll can’t be sent to a private chat.
Parameters
• chat_id (int | str) – Unique identifier for the target private chat.
• question (str) – Poll question, 1-255 characters.
• options (List[str]) – List of answer options, 2-10 strings 1-100 characters each.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.

84 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

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


original message.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type [Link]
Raises [Link]
send_sticker(chat_id, sticker, disable_notification=False, reply_to_message_id=None, re-
ply_markup=None, timeout=20, **kwargs)
Use this method to send .webp stickers.

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 [Link]) – Sticker to send. Pass a
file_id as String to send a file that exists on the Telegram servers (recommended), pass
an HTTP URL as a String for Telegram to get a .webp file from the Internet, or upload
a new one using multipart/form-data. Lastly you can pass an existing telegram.
Sticker object to send.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – Send file timeout (default: 20 seconds).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type [Link]
Raises [Link]

send_venue(chat_id, latitude=None, longitude=None, title=None, address=None,


foursquare_id=None, disable_notification=False, reply_to_message_id=None,
reply_markup=None, timeout=None, venue=None, foursquare_type=None,
**kwargs)
Use this method to send information about a venue.

3.2. telegram package 85


Python Telegram Bot Documentation, Release 12.1.1

Note: you can either supply venue, or latitude, longitude, title and address and
optionally foursquare_id and optionally foursquare_type.

Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• latitude (float, optional) – Latitude of venue.
• longitude (float, optional) – Longitude of venue.
• title (str, optional) – Name of the venue.
• address (str, optional) – Address of the venue.
• foursquare_id (str, optional) – Foursquare identifier of the venue.
• foursquare_type (str, optional) – Foursquare type of the venue, if
known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium”
or “food/icecream”.)
• venue ([Link], optional) – The venue to send.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type [Link]
Raises [Link]

send_video(chat_id, video, duration=None, caption=None, disable_notification=False, re-


ply_to_message_id=None, reply_markup=None, timeout=20, width=None,
height=None, parse_mode=None, supports_streaming=None, thumb=None,
**kwargs)
Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent
as Document).

Note: The video argument can be either a file_id, an URL or a file from disk open(filename,
'rb')

Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• video (str | filelike object | [Link]) – 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

86 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

a new one using multipart/form-data. Lastly you can pass an existing telegram.
Video object to send.
• duration (int, optional) – Duration of sent video in seconds.
• width (int, optional) – Video width.
• height (int, optional) – Video height.
• caption (str, optional) – Video caption (may also be used when resending videos
by file_id), 0-1024 characters.
• 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 [Link] for the available modes.
• supports_streaming (bool, optional) – Pass True, if the uploaded video is
suitable for streaming.
• disable_notification (bool, optional) – Sends the message silently. Users
will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• thumb (filelike object, optional) – Thumbnail of the file sent. The thumbnail should
be in JPEG format and less than 200 kB in size. A thumbnail’s width and height
should not exceed 90. Ignored if the file is not is passed as a string or file_id.
• timeout (int | float, optional) – Send file timeout (default: 20 seconds).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type [Link]
Raises [Link]

send_video_note(chat_id, video_note, duration=None, length=None, dis-


able_notification=False, reply_to_message_id=None, reply_markup=None,
timeout=20, thumb=None, **kwargs)
Use this method to send video messages.

Note: The video_note argument can be either a file_id or a file from disk open(filename,
'rb')

Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• video_note (str | filelike object | [Link]) – Video note to
send. Pass a file_id as String to send a video note that exists on the Telegram servers
(recommended) or upload a new video using multipart/form-data. Or you can pass an
existing [Link] object to send. Sending video notes by a URL is
currently unsupported.
• duration (int, optional) – Duration of sent video in seconds.
• length (int, optional) – Video width and height

3.2. telegram package 87


Python Telegram Bot Documentation, Release 12.1.1

• disable_notification (bool, optional) – Sends the message silently. Users


will receive a notification with no sound.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the
original message.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• thumb (filelike object, optional) – Thumbnail of the file sent. The thumbnail should
be in JPEG format and less than 200 kB in size. A thumbnail’s width and height
should not exceed 90. Ignored if the file is not is passed as a string or file_id.
• timeout (int | float, optional) – Send file timeout (default: 20 seconds).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, the sent Message is returned.
Return type [Link]
Raises [Link]

send_voice(chat_id, voice, duration=None, caption=None, disable_notification=False, re-


ply_to_message_id=None, reply_markup=None, timeout=20, parse_mode=None,
**kwargs)
Use this method to send audio files, if you want Telegram clients to display the file as a playable voice
message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may
be sent as Audio or Document).

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 | [Link]) – Voice file to send. Pass a file_id
as String to send an voice file that exists on the Telegram servers (recommended), pass
an HTTP URL as a String for Telegram to get an voice file from the Internet, or upload
a new one using multipart/form-data. Lastly you can pass an existing telegram.
Voice object to send.
• caption (str, optional) – Voice message caption, 0-1024 characters.
• 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 [Link] for the available modes.
• 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.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – Send file timeout (default: 20 seconds).
• **kwargs (dict) – Arbitrary keyword arguments.

88 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

Returns On success, the sent Message is returned.


Return type [Link]
Raises [Link]

setChatDescription(chat_id, description, timeout=None, **kwargs)


Alias for set_chat_description
setChatPermissions(chat_id, permissions, timeout=None, **kwargs)
Alias for set_chat_permissions
setChatPhoto(chat_id, photo, timeout=20, **kwargs)
Alias for set_chat_photo
setChatStickerSet(chat_id, sticker_set_name, timeout=None, **kwargs)
Alias for set_chat_sticker_set
setChatTitle(chat_id, title, timeout=None, **kwargs)
Alias for set_chat_title
setGameScore(user_id, score, chat_id=None, message_id=None, inline_message_id=None,
force=None, disable_edit_message=None, timeout=None, **kwargs)
Alias for set_game_score
setPassportDataErrors(user_id, errors, timeout=None, **kwargs)
Alias for set_passport_data_errors
setStickerPositionInSet(sticker, position, timeout=None, **kwargs)
Alias for set_sticker_position_in_set
setWebhook(url=None, certificate=None, timeout=None, max_connections=40, al-
lowed_updates=None, **kwargs)
Alias for set_webhook
set_chat_description(chat_id, description, timeout=None, **kwargs)
Use this method to change the description of a group, a supergroup or a channel. The bot must be an
administrator in the chat for this to work and must have the appropriate admin rights.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• description (str) – New chat description, 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).
• **kwargs (dict) – Arbitrary keyword arguments
Returns Returns True on success.
Return type bool
Raises [Link]
set_chat_permissions(chat_id, permissions, timeout=None, **kwargs)
Use this method to set default chat permissions for all members. The bot must be an administrator
in the group or a supergroup for this to work and must have the can_restrict_members admin
rights. Returns True on success.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
supergroup (in the format @supergroupusername).
• permissions ([Link]) – New default chat permis-
sions.

3.2. telegram package 89


Python Telegram Bot Documentation, Release 12.1.1

• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments
Returns Returns True on success.
Return type bool
Raises [Link]
set_chat_photo(chat_id, photo, timeout=20, **kwargs)
Use this method to set a new profile photo for the chat.
Photos can’t be changed for private chats. The bot must be an administrator in the chat for this to work
and must have the appropriate admin rights.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• photo (filelike object) – New chat photo.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments

Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are
Admins’ setting is off in the target group.

Returns Returns True on success.


Return type bool
Raises [Link]

set_chat_sticker_set(chat_id, sticker_set_name, timeout=None, **kwargs)


Use this method to set a new group sticker set for a supergroup. The bot must be an administrator
in the chat for this to work and must have the appropriate admin rights. Use the field telegram.
Chat.can_set_sticker_set optionally returned in get_chat requests to check if the bot can
use this method.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
supergroup (in the format @supergroupusername).
• 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).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns True on success.
Return type bool
set_chat_title(chat_id, title, timeout=None, **kwargs)
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.

90 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

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).
• **kwargs (dict) – Arbitrary keyword arguments

Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are
Admins’ setting is off in the target group.

Returns Returns True on success.


Return type bool
Raises [Link]

set_game_score(user_id, score, chat_id=None, message_id=None, inline_message_id=None,


force=None, disable_edit_message=None, timeout=None, **kwargs)
Use this method to set the score of the specified user in a game. On success, if the message was sent
by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is
not greater than the user’s current score in the chat and force is False.
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 speci-
fied. 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).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns The edited message, or if the message wasn’t sent by the bot , True.
Return type [Link]
Raises
• [Link] – If the new score is not greater than the user’s
• current score in the chat and force is False.
set_passport_data_errors(user_id, errors, timeout=None, **kwargs)
Informs a user that some of the Telegram Passport elements they provided contains errors. The user

3.2. telegram package 91


Python Telegram Bot Documentation, Release 12.1.1

will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for
which you returned the error must change). Returns True on success.
Use this if the data submitted by the user doesn’t satisfy the standards your service requires for any
reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows
evidence of tampering, etc. Supply some details in the error message to make sure the user knows how
to correct the issues.
Parameters
• user_id (int) – User identifier
• errors (List[PassportElementError]) – A JSON-serialized array describing
the errors.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, True is returned.
Return type bool
Raises [Link]
set_sticker_position_in_set(sticker, position, timeout=None, **kwargs)
Use this method to move a sticker in a set created by the bot to a specific position.
Parameters
• sticker (str) – File identifier of the sticker.
• position (int) – New sticker position in the set, zero-based.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns On success, True is returned.
Return type bool
Raises [Link]
set_webhook(url=None, certificate=None, timeout=None, max_connections=40, al-
lowed_updates=None, **kwargs)
Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever
there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a
JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount
of attempts.
If you’d like to make sure that the Webhook request comes from Telegram, we recommend using a
secret path in the URL, e.g. [Link] Since nobody else knows your bot’s
token, you can be pretty sure it’s us.

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.

92 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

• certificate (filelike) – Upload your public key certificate so that the root
certificate in use can be checked. See our self-signed guide for details. ([Link]
rw7w6Y)
• max_connections (int, optional) – Maximum allowed number of simultaneous
HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use
lower values to limit the load on your bot’s server, and higher values to increase your
bot’s throughput.
• allowed_updates (List[str], optional) – List the types of updates you want
your bot to receive. For example, specify [“message”, “edited_channel_post”, “call-
back_query”] to only receive updates of these types. See [Link] for
a complete list of available update types. Specify an empty list to receive all up-
dates regardless of type (default). If not specified, the previous setting will be used.
Please note that this parameter doesn’t affect updates created before the call to the
set_webhook, so unwanted updates may be received for a short period of time.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.

Note:
1. You will not be able to receive updates using get_updates for as long as an outgoing webhook is
set up.
2. To use a self-signed certificate, you need to upload your public key certificate using certificate
parameter. Please upload as InputFile, sending a String will not work.
3. Ports currently supported for Webhooks: 443, 80, 88, 8443.

Returns bool On success, True is returned.


Raises [Link]

stopMessageLiveLocation(chat_id=None, message_id=None, inline_message_id=None, re-


ply_markup=None, timeout=None, **kwargs)
Alias for stop_message_live_location
stopPoll(chat_id, message_id, reply_markup=None, timeout=None, **kwargs)
Alias for stop_poll
stop_message_live_location(chat_id=None, message_id=None, in-
line_message_id=None, reply_markup=None, time-
out=None, **kwargs)
Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots)
before live_period expires.
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) – 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.
• reply_markup ([Link], 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.

3.2. telegram package 93


Python Telegram Bot Documentation, Release 12.1.1

• 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 the edited message.
Return type [Link]
stop_poll(chat_id, message_id, reply_markup=None, timeout=None, **kwargs)
Use this method to stop a poll which was sent by the bot.
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 original message with the poll.
• reply_markup ([Link], optional) – Additional interface op-
tions. A JSON-serialized object for an inline keyboard, custom reply keyboard, in-
structions to remove reply keyboard or to force a reply from the user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns
On success, the stopped Poll with the final results is returned.
Return type [Link]
Raises [Link]
unbanChatMember(chat_id, user_id, timeout=None, **kwargs)
Alias for unban_chat_member
unban_chat_member(chat_id, user_id, timeout=None, **kwargs)
Use this method to unban a previously kicked user in a supergroup.
The user will not return to the group automatically, but will be able to join via link, etc. The bot must
be an administrator in the group for this to work.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• user_id (int) – Unique identifier of the target user.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns bool On success, True is returned.
Raises [Link]
unpinChatMessage(chat_id, timeout=None, **kwargs)
Alias for unpin_chat_message
unpin_chat_message(chat_id, timeout=None, **kwargs)
Use this method to unpin a message in a supergroup. The bot must be an administrator in the chat for
this to work and must have the appropriate admin rights.
Parameters

94 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments
Returns Returns True on success.
Return type bool
Raises [Link]
uploadStickerFile(user_id, png_sticker, timeout=20, **kwargs)
Alias for upload_sticker_file
upload_sticker_file(user_id, png_sticker, timeout=20, **kwargs)
Use this method to upload a .png file with a sticker for later use in create_new_sticker_set
and add_sticker_to_set methods (can be used multiple times).

Note: The png_sticker argument can be either a file_id, an URL or a file from disk
open(filename, 'rb')

Parameters
• user_id (int) – User identifier of sticker file owner.
• png_sticker (str | filelike object) – Png image with the sticker, must be up to 512
kilobytes in size, dimensions must not exceed 512px, and either width or height must
be exactly 512px.
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns The uploaded File
Return type [Link]
Raises [Link]

username
Bot’s username.
Type str

3.2.4 [Link]

class [Link](id, from_user, chat_instance, message=None, data=None, in-


line_message_id=None, game_short_name=None, bot=None,
**kwargs)
Bases: [Link]
This object represents an incoming callback query from a callback button in an inline keyboard.
If the button that originated the query was attached to a message sent by the bot, the field message
will be present. If the button was attached to a message sent via the bot (in inline mode), the field
inline_message_id will be present.

Note:

3.2. telegram package 95


Python Telegram Bot Documentation, Release 12.1.1

• In Python from is a reserved word, use from_user instead.


• Exactly one of the fields data or game_short_name will be present.

id
Unique identifier for this query.
Type str
from_user
Sender.
Type [Link]
message
Optional. Message with the callback button that originated the query.
Type [Link]
inline_message_id
Optional. Identifier of the message sent via the bot in inline mode, that originated the query.
Type str
chat_instance
Optional. Global identifier, uniquely corresponding to the chat to which the message with the callback
button was sent.
Type str
data
Optional. Data associated with the callback button.
Type str
game_short_name
Optional. Short name of a Game to be returned.
Type str

Parameters
• id (str) – Unique identifier for this query.
• from_user ([Link]) – Sender.
• message ([Link], 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.
• inline_message_id (str, optional) – Identifier of the message sent via the bot in
inline mode, that originated the query.
• chat_instance (str, optional) – Global identifier, uniquely corresponding to the
chat to which the message with the callback button was sent. Useful for high scores in
games.
• data (str, optional) – Data associated with the callback button. Be aware that a bad
client can send arbitrary data in this field.
• game_short_name (str, optional) – Short name of a Game to be returned, serves
as the unique identifier for the game

Note: After the user presses an inline button, Telegram clients will display a progress bar until you call
answer. It is, therefore, necessary to react by calling [Link].answer_callback_query
even if no notification to the user is needed (e.g., without specifying any of the optional parameters).

96 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

answer(*args, **kwargs)
Shortcut for:

bot.answer_callback_query(update.callback_query.id, *args, **kwargs)

Returns On success, True is returned.


Return type bool

edit_message_caption(caption, *args, **kwargs)


Shortcut for either:

bot.edit_message_caption(caption=caption,
chat_id=update.callback_query.message.chat_id,
message_id=update.callback_query.message.message_id,
*args, **kwargs)

or:

bot.edit_message_caption(caption=caption
inline_message_id=update.callback_query.inline_
˓→message_id,

*args, **kwargs)

Returns On success, if edited message is sent by the bot, the edited Message is returned,
otherwise True is returned.
Return type [Link]

edit_message_reply_markup(reply_markup, *args, **kwargs)


Shortcut for either:

bot.edit_message_replyMarkup(chat_id=update.callback_query.message.chat_id,
message_id=update.callback_query.message.
˓→message_id,

reply_markup=reply_markup,
*args, **kwargs)

or:

bot.edit_message_reply_markup(inline_message_id=update.callback_query.
˓→inline_message_id,

reply_markup=reply_markup,
*args, **kwargs)

Returns On success, if edited message is sent by the bot, the edited Message is returned,
otherwise True is returned.
Return type [Link]

edit_message_text(text, *args, **kwargs)


Shortcut for either:

bot.edit_message_text(text, chat_id=update.callback_query.message.chat_id,
message_id=update.callback_query.message.message_id,
*args, **kwargs)

or:

3.2. telegram package 97


Python Telegram Bot Documentation, Release 12.1.1

bot.edit_message_text(text, inline_message_id=update.callback_query.inline_
˓→message_id,

*args, **kwargs)

Returns On success, if edited message is sent by the bot, the edited Message is returned,
otherwise True is returned.
Return type [Link]

3.2.5 [Link]

class [Link](id, type, title=None, username=None, first_name=None, last_name=None,


bot=None, photo=None, description=None, invite_link=None,
pinned_message=None, permissions=None, sticker_set_name=None,
can_set_sticker_set=None, **kwargs)
Bases: [Link]
This object represents a chat.
id
Unique identifier for this chat.
Type int
type
Type of chat.
Type str
title
Optional. Title, for supergroups, channels and group chats.
Type str
username
Optional. Username.
Type str
first_name
Optional. First name of the other party in a private chat.
Type str
last_name
Optional. Last name of the other party in a private chat.
Type str
photo
Optional. Chat photo.
Type [Link]
description
Optional. Description, for groups, supergroups and channel chats.
Type str
invite_link
Optional. Chat invite link, for supergroups and channel chats.
Type str
pinned_message
Optional. Pinned message, for supergroups. Returned only in get_chat.
Type [Link]

98 Chapter 3. Reference
Python Telegram Bot Documentation, Release 12.1.1

permissions
Optional. Default chat member permissions, for groups and supergroups. Returned only in getChat.
Type [Link]
sticker_set_name
Optional. For supergroups, name of Group sticker set.
Type str
can_set_sticker_set
Optional. True, if the bot can change group the sticker set.
Type bool

Parameters
• id (int) – Unique identifier for this chat. This number may be greater than 32 bits and
some programming languages may have difficulty/silent defects in interpreting it. But it
is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe
for storing this identifier.
• type (str) – Type of chat, can be either ‘private’, ‘group’, ‘supergroup’ or ‘channel’.
• title (str, optional) – Title, for supergroups, channels and group chats.
• username (str, optional) – Username, for private chats, supergroups and channels if
available.
• first_name (str, optional) – First name of the other party in a private chat.
• last_name (str, optional) – Last name of the other party in a private chat.
• photo ([Link], optional) – Chat photo. Returned only in getChat.
• description (str, optional) – Description, for groups, supergroups and channel
chats. Returned only in get_chat.
• invite_link (str, optional) – Chat invite link, for supergroups and channel chats.
Returned only in get_chat.
• pinned_message ([Link], optional) – Pinned message, for super-
groups. Returned only in get_chat.
• permissions ([Link]) – Optional. Default chat member
permissions, for groups and supergroups. Returned only in getChat.
• bot ([Link], optional) – The Bot to use for instance methods.
• sticker_set_name (str, optional) – For supergroups, name of Group sticker set.
Returned only in get_chat.
• can_set_sticker_set (bool, optional) – True, if the bot can change group the
sticker set. Returned only in get_chat.
• **kwargs (dict) – Arbitrary keyword arguments.

CHANNEL = 'channel'
‘channel’
Type str
GROUP = 'group'
‘group’
Type str
PRIVATE = 'private'
‘private’
Type str

3.2. telegram package 99


Python Telegram Bot Documentation, Release 12.1.1

SUPERGROUP = 'supergroup'
‘supergroup’
Type str
get_administrators(*args, **kwargs)
Shortcut for:

bot.get_chat_administrators([Link], *args, **kwargs)

Returns A list of administrators in a chat. An Array of [Link] 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[[Link]]

get_member(*args, **kwargs)
Shortcut for:

bot.get_chat_member([Link], *args, **kwargs)

Returns [Link]

get_members_count(*args, **kwargs)
Shortcut for:

bot.get_chat_members_count([Link], *args, **kwargs)

Returns int

kick_member(*args, **kwargs)
Shortcut for:

bot.kick_chat_member([Link], *args, **kwargs)

Returns If the action was sent succesfully.


Return type bool

Note: This method will only work if the All Members Are Admins setting is off in the target group.
Otherwise members may only be removed by the group’s creator or by the member that added them.

leave(*args, **kwargs)
Shortcut for:

bot.leave_chat([Link], *args, **kwargs)

Returns bool If the action was sent successfully.

link
Convenience property. If the chat has a username, returns a [Link] link of the chat.
Type str
send_action(*args, **kwargs)
Shortcut for:

100 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

bot.send_chat_action([Link], *args, **kwargs)

Returns If the action was sent successfully.


Return type bool

send_animation(*args, **kwargs)
Shortcut for:

bot.send_animation([Link], *args, **kwargs)

Where Chat is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
send_audio(*args, **kwargs)
Shortcut for:

bot.send_audio([Link], *args, **kwargs)

Where Chat is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
send_document(*args, **kwargs)
Shortcut for:

bot.send_document([Link], *args, **kwargs)

Where Chat is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
send_message(*args, **kwargs)
Shortcut for:

bot.send_message([Link], *args, **kwargs)

Where Chat is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
send_photo(*args, **kwargs)
Shortcut for:

bot.send_photo([Link], *args, **kwargs)

Where Chat is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
send_poll(*args, **kwargs)
Shortcut for:

bot.send_poll([Link], *args, **kwargs)

Where Chat is the current instance.

3.2. telegram package 101


Python Telegram Bot Documentation, Release 12.1.1

Returns On success, instance representing the message posted.


Return type [Link]
send_sticker(*args, **kwargs)
Shortcut for:

bot.send_sticker([Link], *args, **kwargs)

Where Chat is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
send_video(*args, **kwargs)
Shortcut for:

bot.send_video([Link], *args, **kwargs)

Where Chat is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
send_video_note(*args, **kwargs)
Shortcut for:

bot.send_video_note([Link], *args, **kwargs)

Where Chat is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
send_voice(*args, **kwargs)
Shortcut for:

bot.send_voice([Link], *args, **kwargs)

Where Chat is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
set_permissions(*args, **kwargs)
Shortcut for:

bot.set_chat_permissions([Link], *args, **kwargs)

Returns: bool: If the action was sent successfully.


unban_member(*args, **kwargs)
Shortcut for:

bot.unban_chat_member([Link], *args, **kwargs)

Returns If the action was sent successfully.


Return type bool

102 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

3.2.6 [Link]

class [Link]
Bases: object
Helper class to provide constants for different chatactions.
FIND_LOCATION = 'find_location'
‘find_location’
Type str
RECORD_AUDIO = 'record_audio'
‘record_audio’
Type str
RECORD_VIDEO = 'record_video'
‘record_video’
Type str
RECORD_VIDEO_NOTE = 'record_video_note'
‘record_video_note’
Type str
TYPING = 'typing'
‘typing’
Type str
UPLOAD_AUDIO = 'upload_audio'
‘upload_audio’
Type str
UPLOAD_DOCUMENT = 'upload_document'
‘upload_document’
Type str
UPLOAD_PHOTO = 'upload_photo'
‘upload_photo’
Type str
UPLOAD_VIDEO = 'upload_video'
‘upload_video’
Type str
UPLOAD_VIDEO_NOTE = 'upload_video_note'
‘upload_video_note’
Type str

3.2. telegram package 103


Python Telegram Bot Documentation, Release 12.1.1

3.2.7 [Link]

class [Link](user, status, until_date=None, can_be_edited=None,


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,
can_send_messages=None, can_send_media_messages=None,
can_send_polls=None, can_send_other_messages=None,
can_add_web_page_previews=None, is_member=None,
**kwargs)
Bases: [Link]
This object contains information about one member of the chat.
user
Information about the user.
Type [Link]
status
The member’s status in the chat.
Type str
until_date
Optional. Date when restrictions will be lifted for this user.
Type [Link]
can_be_edited
Optional. If the bot is allowed to edit administrator privileges of that user.
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

104 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

can_promote_members
Optional. If the administrator can add new administrators.
Type bool
is_member
Optional. Restricted only. True, if the user is a member of the chat at the moment of the request.
Type bool
can_send_messages
Optional. If the user can send text messages, contacts, locations and venues.
Type bool
can_send_media_messages
Optional. If the user can send media messages, implies can_send_messages.
Type bool
can_send_polls
Optional. True, if the user is allowed to send polls.
Type bool
can_send_other_messages
Optional. If the user can send animations, games, stickers and use inline bots, implies
can_send_media_messages.
Type bool
can_add_web_page_previews
Optional. If user may add web page previews to his messages, implies can_send_media_messages
Type bool

Parameters
• user ([Link]) – Information about the user.
• status (str) – The member’s status in the chat. Can be ‘creator’, ‘administrator’,
‘member’, ‘restricted’, ‘left’ or ‘kicked’.
• until_date ([Link], optional) – Restricted and kicked only. Date
when restrictions will be lifted for this user.
• can_be_edited (bool, optional) – Administrators only. True, if the bot is allowed
to edit administrator privileges of that user.
• can_change_info (bool, optional) – Administrators and restricted only. True, if
the user can change the chat title, photo and other settings.
• can_post_messages (bool, optional) – Administrators only. True, if the admin-
istrator can post in the channel, channels only.
• can_edit_messages (bool, optional) – Administrators only. True, if the admin-
istrator can edit messages of other users, channels only.
• can_delete_messages (bool, optional) – Administrators only. True, if the ad-
ministrator can delete messages of other user.
• can_invite_users (bool, optional) – Administrators and restricted only. True, if
the user can invite new users to the chat.
• can_restrict_members (bool, optional) – Administrators only. True, if the ad-
ministrator can restrict, ban or unban chat members.
• can_pin_messages (bool, optional) – Administrators and restricted only. True, if
the user can pin messages, supergroups only.

3.2. telegram package 105


Python Telegram Bot Documentation, Release 12.1.1

• can_promote_members (bool, optional) – Administrators only. True, if the ad-


ministrator 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 the user).
• is_member (bool, optional) – Restricted only. True, if the user is a member of the
chat at the moment of the request.
• can_send_messages (bool, optional) – Restricted only. True, if the user can send
text messages, contacts, locations and venues.
• can_send_media_messages (bool, optional) – Restricted only. True, if the
user can send audios, documents, photos, videos, video notes and voice notes, implies
can_send_messages.
• can_send_polls (bool, optional) – Restricted only. True, if the user is allowed to
send polls.
• can_send_other_messages (bool, optional) – Restricted only. True, if
the user can send animations, games, stickers and use inline bots, implies
can_send_media_messages.
• can_add_web_page_previews (bool, optional) – Restricted only. True, if user
may add web page previews to his messages, implies can_send_media_messages.

ADMINISTRATOR = 'administrator'
‘administrator’
Type str
CREATOR = 'creator'
‘creator’
Type str
KICKED = 'kicked'
‘kicked’
Type str
LEFT = 'left'
‘left’
Type str
MEMBER = 'member'
‘member’
Type str
RESTRICTED = 'restricted'
‘restricted’
Type str

3.2.8 [Link]

class [Link](can_send_messages=None, can_send_media_messages=None,


can_send_polls=None, can_send_other_messages=None,
can_add_web_page_previews=None,
can_change_info=None, can_invite_users=None,
can_pin_messages=None, **kwargs)
Bases: [Link]
Describes actions that a non-administrator user is allowed to take in a chat.

106 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

can_send_messages
Optional. True, if the user is allowed to send text messages, contacts, locations and venues.
Type bool
can_send_media_messages
Optional. True, if the user is allowed to send audios, documents, photos, videos, video notes and voice
notes, implies can_send_messages.
Type bool
can_send_polls
Optional. True, if the user is allowed to send polls, implies can_send_messages.
Type bool
can_send_other_messages
Optional. True, if the user is allowed to send animations, games, stickers and use inline bots, implies
can_send_media_messages.
Type bool
can_add_web_page_previews
Optional. True, if the user is allowed to add web page previews to their messages, implies
can_send_media_messages.
Type bool
can_change_info
Optional. True, if the user is allowed to change the chat title, photo and other settings. Ignored in
public supergroups.
Type bool
can_invite_users
Optional. True, if the user is allowed to invite new users to the chat.
Type bool
can_pin_messages
Optional. True, if the user is allowed to pin messages. Ignored in public supergroups.
Type bool

Parameters
• 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, im-
plies 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.

3.2. telegram package 107


Python Telegram Bot Documentation, Release 12.1.1

• can_pin_messages (bool, optional) – True, if the user is allowed to pin messages.


Ignored in public supergroups.

3.2.9 [Link]

class [Link](small_file_id, big_file_id, bot=None, **kwargs)


Bases: [Link]
This object represents a chat photo.
small_file_id
File identifier of small (160x160) chat photo.
Type str
big_file_id
File identifier of big (640x640) chat photo.
Type str

Parameters
• small_file_id (str) – File identifier of small (160x160) chat photo. This file_id
can be used only for photo download and only for as long as the photo is not changed.
• big_file_id (str) – File identifier of big (640x640) chat photo. This file_id can
be used only for photo download and only for as long as the photo is not changed.
• bot ([Link], optional) – The Bot to use for instance methods
• **kwargs (dict) – Arbitrary keyword arguments.

get_big_file(timeout=None, **kwargs)
Convenience wrapper over [Link].get_file for getting the big (640x640) chat photo
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
Raises [Link]
get_small_file(timeout=None, **kwargs)
Convenience wrapper over [Link].get_file for getting the small (160x160) chat photo
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
Raises [Link]

3.2.10 [Link] Module

Constants in the Telegram network.


The following constants were extracted from the Telegram Bots FAQ.

108 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

[Link].MAX_MESSAGE_LENGTH
4096
Type int
[Link].MAX_CAPTION_LENGTH
1024
Type int
[Link].SUPPORTED_WEBHOOK_PORTS
[443, 80, 88, 8443]
Type List[int]
[Link].MAX_FILESIZE_DOWNLOAD
In bytes (20MB)
Type int
[Link].MAX_FILESIZE_UPLOAD
In bytes (50MB)
Type int
[Link].MAX_MESSAGES_PER_SECOND_PER_CHAT
1. Telegram may allow short bursts that go over this limit, but eventually you’ll begin receiving 429 errors.
Type int
[Link].MAX_MESSAGES_PER_SECOND
30
Type int
[Link].MAX_MESSAGES_PER_MINUTE_PER_GROUP
20
Type int
[Link].MAX_INLINE_QUERY_RESULTS
50
Type int
The following constant have been found by experimentation:
[Link].MAX_MESSAGE_ENTITIES
100 (Beyond this cap telegram will simply ignore further formatting styles)
Type int

3.2.11 [Link]

class [Link](phone_number, first_name, last_name=None, user_id=None,


vcard=None, **kwargs)
Bases: [Link]
This object represents a phone contact.
phone_number
Contact’s phone number.
Type str
first_name
Contact’s first name.
Type str

3.2. telegram package 109


Python Telegram Bot Documentation, Release 12.1.1

last_name
Optional. Contact’s last name.
Type str
user_id
Optional. Contact’s user identifier in Telegram.
Type int
vcard
Optional. Additional data about the contact in the form of a vCard.
Type str

Parameters
• phone_number (str) – Contact’s phone number.
• first_name (str) – Contact’s first name.
• last_name (str, optional) – Contact’s last name.
• user_id (int, optional) – Contact’s user identifier in Telegram.
• vcard (str, optional) – Additional data about the contact in the form of a vCard.
• **kwargs (dict) – Arbitrary keyword arguments.

3.2.12 [Link]

class [Link](file_id, thumb=None, file_name=None, mime_type=None,


file_size=None, bot=None, **kwargs)
Bases: [Link]
This object represents a general file (as opposed to photos, voice messages and audio files).
file_id
Unique file identifier.
Type str
thumb
Optional. Document thumbnail.
Type [Link]
file_name
Original filename.
Type str
mime_type
Optional. MIME type of the file.
Type str
file_size
Optional. File size.
Type int
bot
Optional. The Bot to use for instance methods.
Type [Link]

Parameters
• file_id (str) – Unique file identifier

110 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

• thumb ([Link], optional) – Document thumbnail as defined by


sender.
• file_name (str, optional) – Original filename as defined by sender.
• mime_type (str, optional) – MIME type of the file as defined by sender.
• file_size (int, optional) – File size.
• bot ([Link], optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.

get_file(timeout=None, **kwargs)
Convenience wrapper over [Link].get_file
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
Raises [Link]

3.2.13 [Link] module

This module contains an object that represents Telegram errors.


exception [Link](message)
Bases: [Link]
exception [Link](new_chat_id)
Bases: [Link]
Parameters new_chat_id (int) –
exception [Link](msg)
Bases: [Link]
Raised when a long poll or webhook conflicts with another one.
Parameters msg (str) – The message from telegrams server.
exception [Link]
Bases: [Link]
exception [Link](message)
Bases: [Link]
exception [Link](retry_after)
Bases: [Link]
Parameters retry_after (int) –
exception [Link](message)
Bases: Exception
exception [Link]
Bases: [Link]
exception [Link](message)
Bases: [Link]

3.2. telegram package 111


Python Telegram Bot Documentation, Release 12.1.1

3.2.14 [Link]

class [Link](file_id, bot=None, file_size=None, file_path=None, **kwargs)


Bases: [Link]
This object represents a file ready to be downloaded. The file can be downloaded with 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 getFile.

Note: Maximum file size to download is 20 MB

file_id
Unique identifier for this file.
Type str
file_size
Optional. File size.
Type str
file_path
Optional. File path. Use download to get the file.
Type str

Parameters
• file_id (str) – Unique identifier for this file.
• file_size (int, optional) – Optional. File size, if known.
• file_path (str, optional) – File path. Use download to get the file.
• bot ([Link], optional) – Bot to use with shortcut method.
• **kwargs (dict) – Arbitrary keyword arguments.

Note: If you obtain an instance of this class from [Link].get_file, then it will
automatically be decrypted as it downloads when you call download().

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 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 [Link] method.

Note: custom_path and out are mutually exclusive.

Parameters
• custom_path (str, optional) – Custom path.
• out ([Link], 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.

112 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

Return type str | [Link]


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.15 [Link]

class [Link](force_reply=True, selective=False, **kwargs)


Bases: [Link]
Upon receiving a message with this object, Telegram clients will display a reply interface to the user (act as
if the user has selected the bot’s message and tapped ‘Reply’). This can be extremely useful if you want to
create user-friendly step-by-step interfaces without having to sacrifice privacy mode.
force_reply
Shows reply interface to the user.
Type True
selective
Optional. Force reply from specific users only.
Type bool

Parameters
• selective (bool, optional) – Use this parameter if you want to force reply from
specific users only. Targets:
1) users that are @mentioned in the text of the Message object
2) if the bot’s message is a reply (has reply_to_message_id), sender of the original mes-
sage.
• **kwargs (dict) – Arbitrary keyword arguments.

3.2.16 [Link]

class [Link](text, url=None, callback_data=None,


switch_inline_query=None,
switch_inline_query_current_chat=None, call-
back_game=None, pay=None, login_url=None,
**kwargs)
Bases: [Link]
This object represents one button of an inline keyboard.

Note: You must use exactly one of the optional fields. Mind that callback_game is not working as
expected. Putting a game short name in it might, but is not guaranteed to work.

text
Label text on the button.

3.2. telegram package 113


Python Telegram Bot Documentation, Release 12.1.1

Type str
url
Optional. HTTP url to be opened when button is pressed.
Type str
login_url
authorize the user.
Type [Link]
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.
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.
Type str
callback_game
Optional. Description of the game that will be launched when the user presses the button.
Type [Link]
pay
Optional. Specify True, to send a Pay button.
Type bool

Parameters
• text (str) – Label text on the button.
• url (str) – HTTP url to be opened when button is pressed.
• login_url ([Link], optional) – authorize the user.
• callback_data (str, optional) – Data to be sent in a callback query to the bot
when button is pressed, 1-64 UTF-8 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 ([Link], 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.

114 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

• **kwargs (dict) – Arbitrary keyword arguments.

3.2.17 [Link]

class [Link](inline_keyboard, **kwargs)


Bases: [Link]
This object represents an inline keyboard that appears right next to the message it belongs to.
inline_keyboard
Array of button rows, each represented by an Array of InlineKeyboardButton objects.
Type List[List[[Link]]]

Parameters
• inline_keyboard (List[List[[Link]]]) – Ar-
ray of button rows, each represented by an Array of InlineKeyboardButton objects.
• **kwargs (dict) – Arbitrary keyword arguments.

classmethod from_button(button, **kwargs)


Shortcut for:

InlineKeyboardMarkup([[button]], **kwargs)

Return an InlineKeyboardMarkup from a single InlineKeyboardButton


Parameters
• button ([Link]) – The button to use in the
markup
• **kwargs (dict) – Arbitrary keyword arguments.
classmethod from_column(button_column, **kwargs)
Shortcut for:

InlineKeyboardMarkup([[button] for button in button_column], **kwargs)

Return an InlineKeyboardMarkup from a single column of InlineKeyboardButtons


Parameters
• button_column (List[[Link]]) – The button
to use in the markup
• **kwargs (dict) – Arbitrary keyword arguments.
classmethod from_row(button_row, **kwargs)
Shortcut for:

InlineKeyboardMarkup([button_row], **kwargs)

Return an InlineKeyboardMarkup from a single row of InlineKeyboardButtons


Parameters
• button_row (List[[Link]]) – The button to use
in the markup
• **kwargs (dict) – Arbitrary keyword arguments.

3.2. telegram package 115


Python Telegram Bot Documentation, Release 12.1.1

3.2.18 [Link]

class [Link](obj, filename=None, attach=None)


Bases: object
This object represents a Telegram InputFile.
input_file_content
The binaray content of the file to send.
Type bytes
filename
Optional, Filename for the file to be sent.
Type str
attach
Optional, attach id for sending multiple files.
Type str

Parameters
• obj (File handler) – An open file descriptor.
• filename (str, optional) – Filename for this InputFile.
• attach (bool, optional) – Whether this should be send as one file or is part of a
collection of files.
Raises TelegramError

static is_image(stream)
Check if the content file is an image by analyzing its headers.
Parameters stream (str) – A str representing the content of a file.
Returns The str mime-type of an image.
Return type str

3.2.19 [Link]

class [Link]
Bases: [Link]
Base class for Telegram InputMedia Objects.
See [Link], [Link], telegram.
InputMediaDocument, [Link] and [Link]
for detailed use.

3.2.20 [Link]

class [Link](media, thumb=None, caption=None,


parse_mode=None, width=None, height=None,
duration=None)
Bases: [Link]
Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent.
type
animation.
Type str

116 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

media
Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers
(recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet,
or upload a new animation using multipart/form-data. Lastly you can pass an existing telegram.
Animation object to send.
Type str | filelike object | [Link]
thumb
Optional. Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB
in size. A thumbnail’s width and height should not exceed 90. Ignored if the file is not is passed as a
string or file_id.
Type filelike object
caption
Optional. Caption of the animation to be sent, 0-1024 characters.
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 [Link] for the available
modes.
Type str
width
Optional. Animation width.
Type int
height
Optional. Animation height.
Type int
duration
Optional. Animation duration.
Type int

Parameters
• media (str) – 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 [Link] object to send.
• thumb (filelike object, optional) – Thumbnail of the file sent. The thumbnail should be
in JPEG format and less than 200 kB in size. A thumbnail’s width and height should
not exceed 90. Ignored if the file is not is passed as a string or file_id.
• caption (str, optional) – Caption of the animation to be sent, 0-1024 characters.
• 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 [Link] for the available modes.
• width (int, optional) – Animation width.
• height (int, optional) – Animation height.
• duration (int, optional) – Animation duration.

Note: When using a [Link] for the media attribute. It will take the width, height and
duration from that video, unless otherwise specified with the optional arguments.

3.2. telegram package 117


Python Telegram Bot Documentation, Release 12.1.1

3.2.21 [Link]

class [Link](media, thumb=None, caption=None, parse_mode=None,


duration=None, performer=None, title=None)
Bases: [Link]
Represents an audio file to be treated as music to be sent.
type
audio.
Type str
media
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 [Link]
object to send.
Type str | filelike object | [Link]
caption
Optional. Caption of the audio to be sent, 0-1024 characters.
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 [Link] for the available
modes.
Type str
duration
Duration of the audio in seconds.
Type int
performer
Optional. Performer of the audio as defined by sender or by audio tags.
Type str
title
Optional. Title of the audio as defined by sender or by audio tags.
Type str
thumb
Optional. Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB
in size. A thumbnail’s width and height should not exceed 90. Ignored if the file is not is passed as a
string or file_id.
Type filelike object

Parameters
• media (str) – 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 [Link] object to send.
• caption (str, optional) – Caption of the audio to be sent, 0-1024 characters.
• 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 [Link] for the available modes.
• duration (int) – Duration of the audio in seconds as defined by sender.

118 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

• performer (str, optional) – Performer of the audio as defined by sender or by audio


tags.
• title (str, optional) – Title of the audio as defined by sender or by audio tags.
• thumb (filelike object, optional) – Thumbnail of the file sent. The thumbnail should be
in JPEG format and less than 200 kB in size. A thumbnail’s width and height should
not exceed 90. Ignored if the file is not is passed as a string or file_id.

Note: When using a [Link] for the media attribute. It will take the duration, performer and
title from that video, unless otherwise specified with the optional arguments.

3.2.22 [Link]

class [Link](media, thumb=None, caption=None,


parse_mode=None)
Bases: [Link]
Represents a general file to be sent.
type
document.
Type str
media
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 [Link] object to send.
Type str | filelike object | [Link]
caption
Optional. Caption of the document to be sent, 0-1024 characters.
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 [Link] for the available
modes.
Type str
thumb
Optional. Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB
in size. A thumbnail’s width and height should not exceed 90. Ignored if the file is not is passed as a
string or file_id.
Type filelike object

Parameters
• media (str) – 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 [Link] object to send.
• caption (str, optional) – Caption of the document to be sent, 0-1024 characters.
• 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 [Link] for the available modes.

3.2. telegram package 119


Python Telegram Bot Documentation, Release 12.1.1

• thumb (filelike object, optional) – Thumbnail of the file sent. The thumbnail should be
in JPEG format and less than 200 kB in size. A thumbnail’s width and height should
not exceed 90. Ignored if the file is not is passed as a string or file_id.

3.2.23 [Link]

class [Link](media, caption=None, parse_mode=None)


Bases: [Link]
Represents a photo to be sent.
type
photo.
Type str
media
Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recom-
mended), 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 [Link]
object to send.
Type str | filelike object | [Link]
caption
Optional. Caption of the photo to be sent, 0-1024 characters.
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 [Link] for the available
modes.
Type str

Parameters
• media (str) – 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 [Link] object to send.
• caption (str, optional) – Caption of the photo to be sent, 0-1024 characters.
• 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 [Link] for the available modes.

3.2.24 [Link]

class [Link](media, caption=None, width=None, height=None, dura-


tion=None, supports_streaming=None, parse_mode=None,
thumb=None)
Bases: [Link]
Represents a video to be sent.
type
video.
Type str

120 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

media
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 [Link]
object to send.
Type str | filelike object | [Link]
caption
Optional. Caption of the video to be sent, 0-1024 characters.
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 [Link] for the available
modes.
Type str
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 sent. The thumbnail should be in JPEG format and less than 200 kB
in size. A thumbnail’s width and height should not exceed 90. Ignored if the file is not is passed as a
string or file_id.
Type filelike object

Parameters
• media (str) – 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 [Link] object to send.
• caption (str, optional) – Caption of the video to be sent, 0-1024 characters.
• 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 [Link] for the available modes.
• width (int, optional) – Video width.
• height (int, optional) – Video height.
• duration (int, optional) – Video duration.
• supports_streaming (bool, optional) – Pass True, if the uploaded video is suit-
able for streaming.

3.2. telegram package 121


Python Telegram Bot Documentation, Release 12.1.1

• thumb (filelike object, optional) – Thumbnail of the file sent. The thumbnail should be
in JPEG format and less than 200 kB in size. A thumbnail’s width and height should
not exceed 90. Ignored if the file is not is passed as a string or file_id.

Note: When using a [Link] for the media attribute. It will take the width, height and
duration from that video, unless otherwise specified with the optional arguments.

3.2.25 [Link]

class [Link](text, request_contact=None, request_location=None,


**kwargs)
Bases: [Link]
This object represents one button of the reply keyboard. For simple text buttons String can be used instead
of this object to specify text of the button.

Note: Optional fields are mutually exclusive.

text
Text of the button.
Type str
request_contact
Optional. If the user’s phone number will be sent.
Type bool
request_location
Optional. If the user’s current location will be sent.
Type bool

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.

Note: request_contact and request_location options will only work in Telegram versions
released after 9 April, 2016. Older clients will ignore them.

3.2.26 [Link]

class [Link](longitude, latitude, **kwargs)


Bases: [Link]
This object represents a point on the map.
longitude
Longitude as defined by sender.
Type float

122 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

latitude
Latitude as defined by sender.
Type float

Parameters
• longitude (float) – Longitude as defined by sender.
• latitude (float) – Latitude as defined by sender.
• **kwargs (dict) – Arbitrary keyword arguments.

3.2.27 [Link]

class [Link](url, forward_text=None, bot_username=None, re-


quest_write_access=None)
Bases: [Link]
This object represents a parameter of the inline keyboard button used to automatically authorize a user.
Serves as a great replacement for the Telegram Login Widget when the user is coming from Telegram. All
the user needs to do is tap/click a button and confirm that they want to log in. Telegram apps support these
buttons as of version 5.7.
Sample bot: @discussbot
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

Parameters
• url (str) – An HTTP URL to be opened with user authorization data added to the
query string when the button is pressed. If the user refuses to provide authorization data,
the original URL without information about the user will be opened. The data added is
the same as described in Receiving authorization data. NOTE: You must always check
the hash of the received data to verify the authentication and the integrity of the data as
described in Checking authorization.
• 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.

3.2. telegram package 123


Python Telegram Bot Documentation, Release 12.1.1

3.2.28 [Link]

class [Link](message_id, from_user, date, chat, forward_from=None, for-


ward_from_chat=None, forward_from_message_id=None, for-
ward_date=None, reply_to_message=None, edit_date=None,
text=None, entities=None, caption_entities=None, audio=None, doc-
ument=None, game=None, photo=None, sticker=None, video=None,
voice=None, video_note=None, new_chat_members=None,
caption=None, contact=None, location=None,
venue=None, left_chat_member=None, new_chat_title=None,
new_chat_photo=None, delete_chat_photo=False,
group_chat_created=False, supergroup_chat_created=False,
channel_chat_created=False, migrate_to_chat_id=None,
migrate_from_chat_id=None, pinned_message=None, in-
voice=None, successful_payment=None, forward_signature=None,
author_signature=None, media_group_id=None, con-
nected_website=None, animation=None, passport_data=None,
poll=None, forward_sender_name=None, reply_markup=None,
bot=None, **kwargs)
Bases: [Link]
This object represents a message.

Note:
• In Python from is a reserved word, use from_user instead.

message_id
Unique message identifier inside this chat.
Type int
from_user
Optional. Sender.
Type [Link]
date
Date the message was sent.
Type [Link]
chat
Conversation the message belongs to.
Type [Link]
forward_from
Optional. Sender of the original message.
Type [Link]
forward_from_chat
Optional. Information about the original channel.
Type [Link]
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 [Link]

124 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

reply_to_message
Optional. The original message.
Type [Link]
edit_date
Optional. Date the message was last edited.
Type [Link]
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[[Link]]
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[[Link]]
audio
Optional. Information about the file.
Type [Link]
document
Optional. Information about the file.
Type [Link]
animation
For backward compatibility, when this field is set, the document field will also be set.
Type [Link]
game
Optional. Information about the game.
Type [Link]
photo
Optional. Available sizes of the photo.
Type List[[Link]]
sticker
Optional. Information about the sticker.
Type [Link]
video
Optional. Information about the video.
Type [Link]
voice
Optional. Information about the file.
Type [Link]

3.2. telegram package 125


Python Telegram Bot Documentation, Release 12.1.1

video_note
Optional. Information about the video message.
Type [Link]
new_chat_members
Optional. Information about new members to the chat. (the bot itself may be one of these members).
Type List[[Link]]
caption
Optional. Caption for the document, photo or video, 0-1024 characters.
Type str
contact
Optional. Information about the contact.
Type [Link]
location
Optional. Information about the location.
Type [Link]
venue
Optional. Information about the venue.
Type [Link]
left_chat_member
Optional. Information about the user that left the group. (this member may be the bot itself).
Type [Link]
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[[Link]]
delete_chat_photo
Optional. The chat photo was deleted.
Type bool
group_chat_created
Optional. The group has been created.
Type bool
supergroup_chat_created
Optional. The supergroup has been created.
Type bool
channel_chat_created
Optional. The channel has been created.
Type bool
migrate_to_chat_id
Optional. The group has been migrated to a supergroup with the specified identifier.
Type int
migrate_from_chat_id
Optional. The supergroup has been migrated from a group with the specified identifier.

126 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

Type int
pinned_message
Optional. Specified message was pinned.
Type [Link]
invoice
Optional. Information about the invoice.
Type [Link]
successful_payment
Optional. Information about the payment.
Type [Link]
connected_website
Optional. The domain name of the website on which the user has logged in.
Type str
forward_signature
Optional. Signature of the post author for messages forwarded from channels.
Type str
forward_sender_name
Optional. Sender’s name for messages forwarded from users who disallow adding a link to their
account in forwarded messages.
Type str
author_signature
Optional. Signature of the post author for messages in channels.
Type str
passport_data
Optional. Telegram Passport data.
Type [Link]
poll
Optional. Message is a native poll, information about the poll.
Type [Link]
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
bot
Optional. The Bot to use for instance methods.
Type [Link]

Parameters
• message_id (int) – Unique message identifier inside this chat.
• from_user ([Link], optional) – Sender, can be empty for messages sent
to channels.
• date ([Link]) – Date the message was sent in Unix time. Converted
to [Link].
• chat ([Link]) – Conversation the message belongs to.
• forward_from ([Link], optional) – For forwarded messages, sender of
the original message.

3.2. telegram package 127


Python Telegram Bot Documentation, Release 12.1.1

• forward_from_chat ([Link], optional) – For messages forwarded


from a channel, information about the original channel.
• forward_from_message_id (int, optional) – For forwarded channel posts, iden-
tifier of the original message in the channel.
• forward_sender_name (str, optional) – Sender’s name for messages forwarded
from users who disallow adding a link to their account in forwarded messages.
• forward_date ([Link], optional) – For forwarded messages, date
the original message was sent in Unix time. Converted to [Link].
• reply_to_message ([Link], optional) – For replies, the origi-
nal message. Note that the Message object in this field will not contain further
reply_to_message fields even if it itself is a reply.
• edit_date ([Link], optional) – Date the message was last edited
in Unix time. Converted to [Link].
• media_group_id (str, optional) – The unique identifier of a media message group
this message belongs to.
• text (str, optional) – For text messages, the actual UTF-8 text of
the message, 0-4096 characters. Also found as [Link].
MAX_MESSAGE_LENGTH.
• entities (List[[Link]], optional) – For text messages,
special entities like usernames, URLs, bot commands, etc. that appear in the text. See
attr:parse_entity and attr:parse_entities methods for how to use properly.
• caption_entities (List[[Link]]) – Optional. For Mes-
sages with a Caption. Special entities like usernames, URLs, bot commands,
etc. that appear in the caption. See Message.parse_caption_entity and
parse_caption_entities methods for how to use properly.
• audio ([Link], optional) – Message is an audio file, information about
the file.
• document ([Link], optional) – Message is a general file, informa-
tion about the file.
• animation ([Link], optional) – Message is an animation, infor-
mation about the animation. For backward compatibility, when this field is set, the
document field will also be set.
• game ([Link], optional) – Message is a game, information about the game.
• photo (List[[Link]], optional) – Message is a photo, available
sizes of the photo.
• sticker ([Link], optional) – Message is a sticker, information about
the sticker.
• video ([Link], optional) – Message is a video, information about the
video.
• voice ([Link], optional) – Message is a voice message, information
about the file.
• video_note ([Link], optional) – Message is a video note, infor-
mation about the video message.
• new_chat_members (List[[Link]], optional) – New members that were
added to the group or supergroup and information about them (the bot itself may be one
of these members).
• caption (str, optional) – Caption for the document, photo or video, 0-1024 charac-
ters.

128 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

• contact ([Link], optional) – Message is a shared contact, informa-


tion about the contact.
• location ([Link], optional) – Message is a shared location, infor-
mation about the location.
• venue ([Link], optional) – Message is a venue, information about the
venue.
• left_chat_member ([Link], optional) – A member was removed from
the group, information about them (this member may be the bot itself).
• new_chat_title (str, optional) – A chat title was changed to this value.
• new_chat_photo (List[[Link]], optional) – A chat photo was
change to this value.
• delete_chat_photo (bool, optional) – Service message: The chat photo was
deleted.
• group_chat_created (bool, optional) – Service message: The group has been
created.
• supergroup_chat_created (bool, optional) – Service message: The super-
group has been created. This field can’t be received in a message coming through
updates, because bot can’t be a member of a supergroup when it is created. It can
only be found in reply_to_message if someone replies to a very first message in a
directly created supergroup.
• channel_chat_created (bool, optional) – Service message: The channel has
been created. This field can’t be received in a message coming through updates, be-
cause bot can’t be a member of a channel when it is created. It can only be found in
attr:reply_to_message if someone replies to a very first message in a channel.
• migrate_to_chat_id (int, optional) – The group has been migrated to a super-
group with the specified identifier. This number may be greater than 32 bits and some
programming languages may have difficulty/silent defects in interpreting it. But it is
smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for
storing this identifier.
• migrate_from_chat_id (int, optional) – The supergroup has been migrated
from a group with the specified identifier. This number may be greater than 32 bits
and some programming languages may have difficulty/silent defects in interpreting it.
But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type
are safe for storing this identifier.
• pinned_message ([Link], optional) – Specified message was
pinned. Note that the Message object in this field will not contain further
attr:reply_to_message fields even if it is itself a reply.
• invoice ([Link], optional) – Message is an invoice for a payment,
information about the invoice.
• successful_payment ([Link], optional) – Mes-
sage is a service message about a successful payment, information about the payment.
• connected_website (str, optional) – The domain name of the website on which
the user has logged in.
• forward_signature (str, optional) – Signature of the post author for messages
forwarded from channels.
• author_signature (str, optional) – Signature of the post author for messages in
channels.
• passport_data ([Link], optional) – Telegram Passport
data.

3.2. telegram package 129


Python Telegram Bot Documentation, Release 12.1.1

• poll ([Link], optional) – Message is a native poll, information about the


poll.
• reply_markup ([Link], optional) – Inline key-
board attached to the message. login_url buttons are represented as ordinary url buttons.

caption_html
Creates an HTML-formatted string from the markup entities found in the message’s caption.
Use this if you want to retrieve the message caption with the caption entities formatted as HTML in
the same way the original message was formatted.
Returns Message caption with captionentities formatted as HTML.
Return type str
caption_html_urled
Creates an HTML-formatted string from the markup entities found in the message’s caption.
Use this if you want to retrieve the message caption with the caption entities formatted as HTML. This
also formats [Link] as a hyperlink.
Returns Message caption with caption entities formatted as HTML.
Return type str
caption_markdown
Creates an Markdown-formatted string from the markup entities found in the message’s caption.
Use this if you want to retrieve the message caption with the caption entities formatted as Markdown
in the same way the original message was formatted.
Returns Message caption with caption entities formatted as Markdown.
Return type str
caption_markdown_urled
Creates an Markdown-formatted string from the markup entities found in the message’s caption.
Use this if you want to retrieve the message caption with the caption entities formatted as Markdown.
This also formats [Link] as a hyperlink.
Returns Message caption with caption entities formatted as Markdown.
Return type str
chat_id
Shortcut for [Link] for chat.
Type int
delete(*args, **kwargs)
Shortcut for:

bot.delete_message(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)

Returns On success, True is returned.


Return type bool

edit_caption(*args, **kwargs)
Shortcut for:

130 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

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, therefore this method can only be used on
the return value of the bot.send_* family of methods.

Returns On success, instance representing the edited message.


Return type [Link]

edit_media(media, *args, **kwargs)


Shortcut for:

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, therefore this method can only be used on
the return value of the bot.send_* family of methods.

Returns On success, instance representing the edited message.


Return type [Link]

edit_reply_markup(*args, **kwargs)
Shortcut for:

bot.edit_message_reply_markup(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)

Note: You can only edit messages that the bot sent itself, therefore this method can only be used on
the return value of the bot.send_* family of methods.

Returns On success, instance representing the edited message.


Return type [Link]

edit_text(*args, **kwargs)
Shortcut for:

bot.edit_message_text(chat_id=message.chat_id,
message_id=message.message_id,
*args,
**kwargs)

Note: You can only edit messages that the bot sent itself, therefore this method can only be used on
the return value of the bot.send_* family of methods.

3.2. telegram package 131


Python Telegram Bot Documentation, Release 12.1.1

Returns On success, instance representing the edited message.


Return type [Link]

effective_attachment
[Link] or [Link] or [Link] or telegram.
Animation or [Link] or [Link] or telegram.
Location or List[[Link]] or [Link] or telegram.
SuccessfulPayment or [Link] or [Link] or telegram.
VideoNote or [Link]: The attachment that this message was sent with. May
be None if no attachment was sent.
forward(chat_id, disable_notification=False)
Shortcut for:

bot.forward_message(chat_id=chat_id,
from_chat_id=[Link].chat_id,
disable_notification=disable_notification,
message_id=[Link].message_id)

Returns On success, instance representing the message forwarded.


Return type [Link]

link
Convenience property. If the chat of the message is a supergroup or a channel and has a Chat.
username, returns a [Link] link of the message.
Type str
parse_caption_entities(types=None)
Returns a dict that maps [Link] to str. It contains entities from this
message’s caption filtered by their [Link] 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.

Parameters types (List[str], optional) – List of [Link] types


as strings. If the type attribute of an entity is contained in this list, it will be returned.
Defaults to a list of all types. All types can be found as constants in telegram.
MessageEntity.
Returns A dictionary of entities mapped to the text that belongs to them, calculated based
on UTF-16 codepoints.
Return type Dict[[Link], str]

parse_caption_entity(entity)
Returns the text from a given [Link].

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
[Link] with the offset and length.)

Parameters entity ([Link]) – The entity to extract the text


from. It must be an entity that belongs to this message.

132 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

Returns The text of the given entity


Return type str

parse_entities(types=None)
Returns a dict that maps [Link] to str. It contains entities from this
message filtered by their [Link] 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.

Parameters types (List[str], optional) – List of [Link] types


as strings. If the type attribute of an entity is contained in this list, it will be returned.
Defaults to a list of all types. All types can be found as constants in telegram.
MessageEntity.
Returns A dictionary of entities mapped to the text that belongs to them, calculated based
on UTF-16 codepoints.
Return type Dict[[Link], str]

parse_entity(entity)
Returns the text from a given [Link].

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
[Link] with the offset and length.)

Parameters entity ([Link]) – The entity to extract the text


from. It must be an entity that belongs to this message.
Returns The text of the given entity
Return type str

reply_animation(*args, **kwargs)
Shortcut for:

bot.send_animation([Link].chat_id, *args, **kwargs)

Keyword Arguments quote (bool, optional) – If set to True, the photo is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type [Link]

reply_audio(*args, **kwargs)
Shortcut for:

bot.send_audio([Link].chat_id, *args, **kwargs)

Keyword Arguments quote (bool, optional) – If set to True, the photo is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.

3.2. telegram package 133


Python Telegram Bot Documentation, Release 12.1.1

Returns On success, instance representing the message posted.


Return type [Link]

reply_contact(*args, **kwargs)
Shortcut for:

bot.send_contact([Link].chat_id, *args, **kwargs)

Keyword Arguments quote (bool, optional) – If set to True, the photo is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type [Link]

reply_document(*args, **kwargs)
Shortcut for:

bot.send_document([Link].chat_id, *args, **kwargs)

Keyword Arguments quote (bool, optional) – If set to True, the photo is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type [Link]

reply_html(*args, **kwargs)
Shortcut for:

bot.send_message([Link].chat_id, parse_mode=[Link], *args,


˓→**kwargs)

Sends a message with HTML formatting.


Keyword Arguments quote (bool, optional) – If set to True, the message is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
reply_location(*args, **kwargs)
Shortcut for:

bot.send_location([Link].chat_id, *args, **kwargs)

Keyword Arguments quote (bool, optional) – If set to True, the photo is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type [Link]

reply_markdown(*args, **kwargs)
Shortcut for:

bot.send_message([Link].chat_id, parse_mode=[Link],
˓→*args,

**kwargs)

Sends a message with markdown formatting.

134 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

Keyword Arguments quote (bool, optional) – If set to True, the message is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
reply_media_group(*args, **kwargs)
Shortcut for:

bot.reply_media_group([Link].chat_id, *args, **kwargs)

Keyword Arguments quote (bool, optional) – If set to True, the media group is sent
as an actual reply to this message. If reply_to_message_id is passed in kwargs,
this parameter will be ignored. Default: True in group chats and False in private
chats.
Returns An array of the sent Messages.
Return type List[[Link]]
Raises [Link]

reply_photo(*args, **kwargs)
Shortcut for:

bot.send_photo([Link].chat_id, *args, **kwargs)

Keyword Arguments quote (bool, optional) – If set to True, the photo is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type [Link]

reply_poll(*args, **kwargs)
Shortcut for:

bot.send_poll([Link].chat_id, *args, **kwargs)

Keyword Arguments quote (bool, optional) – If set to True, the photo is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type [Link]

reply_sticker(*args, **kwargs)
Shortcut for:

bot.send_sticker([Link].chat_id, *args, **kwargs)

Keyword Arguments quote (bool, optional) – If set to True, the photo is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type [Link]

reply_text(*args, **kwargs)
Shortcut for:

3.2. telegram package 135


Python Telegram Bot Documentation, Release 12.1.1

bot.send_message([Link].chat_id, *args, **kwargs)

Keyword Arguments quote (bool, optional) – If set to True, the message is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.

reply_venue(*args, **kwargs)
Shortcut for:

bot.send_venue([Link].chat_id, *args, **kwargs)

Keyword Arguments quote (bool, optional) – If set to True, the photo is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type [Link]

reply_video(*args, **kwargs)
Shortcut for:

bot.send_video([Link].chat_id, *args, **kwargs)

Keyword Arguments quote (bool, optional) – If set to True, the photo is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type [Link]

reply_video_note(*args, **kwargs)
Shortcut for:

bot.send_video_note([Link].chat_id, *args, **kwargs)

Keyword Arguments quote (bool, optional) – If set to True, the photo is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type [Link]

reply_voice(*args, **kwargs)
Shortcut for:

bot.send_voice([Link].chat_id, *args, **kwargs)

Keyword Arguments quote (bool, optional) – If set to True, the photo is sent as an
actual reply to this message. If reply_to_message_id is passed in kwargs, this
parameter will be ignored. Default: True in group chats and False in private chats.
Returns On success, instance representing the message posted.
Return type [Link]

136 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

text_html
Creates an HTML-formatted string from the markup entities found in the message.
Use this if you want to retrieve the message text with the entities formatted as HTML in the same way
the original message was formatted.
Returns Message text with entities formatted as HTML.
Return type str
text_html_urled
Creates an HTML-formatted string from the markup entities found in the message.
Use this if you want to retrieve the message text with the entities formatted as HTML. This also formats
[Link] as a hyperlink.
Returns Message text with entities formatted as HTML.
Return type str
text_markdown
Creates an Markdown-formatted string from the markup entities found in the message.
Use this if you want to retrieve the message text with the entities formatted as Markdown in the same
way the original message was formatted.
Returns Message text with entities formatted as Markdown.
Return type str
text_markdown_urled
Creates an Markdown-formatted string from the markup entities found in the message.
Use this if you want to retrieve the message text with the entities formatted as Markdown. This also
formats [Link] as a hyperlink.
Returns Message text with entities formatted as Markdown.
Return type str

3.2.29 [Link]

class [Link](type, offset, length, url=None, user=None, **kwargs)


Bases: [Link]
This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc.
type
Type of the entity.
Type str
offset
Offset in UTF-16 code units to the start of the entity.
Type int
length
Length of the entity in UTF-16 code units.
Type int
url
Optional. Url that will be opened after user taps on the text.
Type str
user
Optional. The mentioned user.

3.2. telegram package 137


Python Telegram Bot Documentation, Release 12.1.1

Type [Link]

Parameters
• type (str) – Type of the entity. Can be mention (@username), hashtag,
bot_command, url, email, bold (bold text), italic (italic text), code (monowidth string),
pre (monowidth block), text_link (for clickable text URLs), text_mention (for users
without usernames).
• offset (int) – Offset in UTF-16 code units to the start of the entity.
• length (int) – Length of the entity in UTF-16 code units.
• url (str, optional) – For “text_link” only, url that will be opened after usertaps on the
text.
• user ([Link], optional) – For “text_mention” only, the mentioned user.

ALL_TYPES = ['mention', 'hashtag', 'cashtag', 'phone_number', 'bot_command', 'url',


List of all the types.
Type List[str]
BOLD = 'bold'
‘bold’
Type str
BOT_COMMAND = 'bot_command'
‘bot_command’
Type str
CASHTAG = 'cashtag'
‘cashtag’
Type str
CODE = 'code'
‘code’
Type str
EMAIL = 'email'
‘email’
Type str
HASHTAG = 'hashtag'
‘hashtag’
Type str
ITALIC = 'italic'
‘italic’
Type str
MENTION = 'mention'
‘mention’
Type str
PHONE_NUMBER = 'phone_number'
‘phone_number’
Type str
PRE = 'pre'
‘pre’

138 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

Type str
TEXT_LINK = 'text_link'
‘text_link’
Type str
TEXT_MENTION = 'text_mention'
‘text_mention’
Type str
URL = 'url'
‘url’
Type str

3.2.30 [Link]

class [Link]
Bases: object
This object represents a Telegram Message Parse Modes.
HTML = 'HTML'
‘HTML’
Type str
MARKDOWN = 'Markdown'
‘Markdown’
Type str

3.2.31 [Link]

class [Link](file_id, width, height, file_size=None, bot=None, **kwargs)


Bases: [Link]
This object represents one size of a photo or a file/sticker thumbnail.
file_id
Unique identifier for this file.
Type str
width
Photo width.
Type int
height
Photo height.
Type int
file_size
Optional. File size.
Type int
bot
Optional. The Bot to use for instance methods.
Type [Link]

Parameters

3.2. telegram package 139


Python Telegram Bot Documentation, Release 12.1.1

• file_id (str) – Unique identifier for this file.


• width (int) – Photo width.
• height (int) – Photo height.
• file_size (int, optional) – File size.
• bot ([Link], optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.

get_file(timeout=None, **kwargs)
Convenience wrapper over [Link].get_file
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
Raises [Link]

3.2.32 [Link]

class [Link](id, question, options, is_closed, **kwargs)


Bases: [Link]
This object contains information about a poll.
id
Unique poll identifier.
Type str
question
Poll question, 1-255 characters.
Type str
options
List of poll options.
Type List[PollOption]
is_closed
True, if the poll is closed.
Type bool

Parameters
• id (str) – Unique poll identifier.
• question (str) – Poll question, 1-255 characters.
• options (List[PollOption]) – List of poll options.
• is_closed (bool) – True, if the poll is closed.

140 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

3.2.33 [Link]

class [Link](text, voter_count, **kwargs)


Bases: [Link]
This object contains information about one answer option in a poll.
text
Option text, 1-100 characters.
Type str
voter_count
Number of users that voted for this option.
Type int

Parameters
• text (str) – Option text, 1-100 characters.
• voter_count (int) – Number of users that voted for this option.

3.2.34 [Link]

class [Link](selective=False, **kwargs)


Bases: [Link]
Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and
display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent
by a bot. An exception is made for one-time keyboards that are hidden immediately after the user presses a
button (see [Link]).
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

Example
A user votes in a poll, bot returns confirmation message in reply to the vote and removes the keyboard for
that user, while still showing the keyboard with poll options to users who haven’t voted yet.

Parameters
• selective (bool, optional) – Use this parameter if you want to remove the keyboard
for specific users only. Targets:
1) users that are @mentioned in the text of the Message object
2) if the bot’s message is a reply (has reply_to_message_id), sender of the original mes-
sage.
• **kwargs (dict) – Arbitrary keyword arguments.

3.2. telegram package 141


Python Telegram Bot Documentation, Release 12.1.1

3.2.35 [Link]

class [Link](keyboard, resize_keyboard=False,


one_time_keyboard=False, selective=False,
**kwargs)
Bases: [Link]
This object represents a custom keyboard with reply options.
keyboard
Array of button rows.
Type List[List[[Link] | 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

Example
A user requests to change the bot’s language, bot replies to the request with a keyboard to select the new
language. Other users in the group don’t see the keyboard.

Parameters
• keyboard (List[List[str | [Link]]]) – Array of button
rows, each represented by an Array of [Link] objects.
• resize_keyboard (bool, optional) – Requests clients to resize the keyboard ver-
tically for optimal fit (e.g., make the keyboard smaller if there are just two rows of
buttons). Defaults to false, in which case the custom keyboard is always of the same
height as the app’s standard keyboard. Defaults to False
• one_time_keyboard (bool, optional) – Requests clients to hide the keyboard as
soon as it’s been used. The keyboard will still be available, but clients will automatically
display the usual letter-keyboard in the chat - the user can press a special button in the
input field to see the custom keyboard again. Defaults to False.
• selective (bool, optional) – Use this parameter if you want to show the keyboard
to specific users only. Targets:
1) users that are @mentioned in the text of the Message object
2) if the bot’s message is a reply (has reply_to_message_id), sender of the original mes-
sage.
Defaults to False.
• **kwargs (dict) – Arbitrary keyword arguments.

classmethod from_button(button, resize_keyboard=False, one_time_keyboard=False, selec-


tive=False, **kwargs)
Shortcut for:

142 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

ReplyKeyboardMarkup([[button]], **kwargs)

Return an ReplyKeyboardMarkup from a single KeyboardButton


Parameters
• button ([Link] | str) – The button to use in the markup
• resize_keyboard (bool, optional) – Requests clients to resize the keyboard ver-
tically for optimal fit (e.g., make the keyboard smaller if there are just two rows of
buttons). Defaults to false, in which case the custom keyboard is always of the same
height as the app’s standard keyboard. Defaults to False
• one_time_keyboard (bool, optional) – Requests clients to hide the keyboard as
soon as it’s been used. The keyboard will still be available, but clients will automati-
cally display the usual letter-keyboard in the chat - the user can press a special button
in the input field to see the custom keyboard again. Defaults to False.
• selective (bool, optional) – Use this parameter if you want to show the keyboard
to specific users only. Targets:
1) users that are @mentioned in the text of the Message object
2) if the bot’s message is a reply (has reply_to_message_id), sender of the
original 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)

Return an ReplyKeyboardMarkup from a single column of KeyboardButtons


Parameters
• button_column (List[[Link] | str]) – The button to
use in the markup
• resize_keyboard (bool, optional) – Requests clients to resize the keyboard ver-
tically for optimal fit (e.g., make the keyboard smaller if there are just two rows of
buttons). Defaults to false, in which case the custom keyboard is always of the same
height as the app’s standard keyboard. Defaults to False
• one_time_keyboard (bool, optional) – Requests clients to hide the keyboard as
soon as it’s been used. The keyboard will still be available, but clients will automati-
cally display the usual letter-keyboard in the chat - the user can press a special button
in the input field to see the custom keyboard again. Defaults to False.
• selective (bool, optional) – Use this parameter if you want to show the keyboard
to specific users only. Targets:
1) users that are @mentioned in the text of the Message object
2) if the bot’s message is a reply (has reply_to_message_id), sender of the
original message.
Defaults to False.
• **kwargs (dict) – Arbitrary keyword arguments.
classmethod from_row(button_row, resize_keyboard=False, one_time_keyboard=False, se-
lective=False, **kwargs)
Shortcut for:

3.2. telegram package 143


Python Telegram Bot Documentation, Release 12.1.1

ReplyKeyboardMarkup([button_row], **kwargs)

Return an ReplyKeyboardMarkup from a single row of KeyboardButtons


Parameters
• button_row (List[[Link] | str]) – The button to use in
the markup
• resize_keyboard (bool, optional) – Requests clients to resize the keyboard ver-
tically for optimal fit (e.g., make the keyboard smaller if there are just two rows of
buttons). Defaults to false, in which case the custom keyboard is always of the same
height as the app’s standard keyboard. Defaults to False
• one_time_keyboard (bool, optional) – Requests clients to hide the keyboard as
soon as it’s been used. The keyboard will still be available, but clients will automati-
cally display the usual letter-keyboard in the chat - the user can press a special button
in the input field to see the custom keyboard again. Defaults to False.
• selective (bool, optional) – Use this parameter if you want to show the keyboard
to specific users only. Targets:
1) users that are @mentioned in the text of the Message object
2) if the bot’s message is a reply (has reply_to_message_id), sender of the
original message.
Defaults to False.
• **kwargs (dict) – Arbitrary keyword arguments.

3.2.36 [Link]

class [Link]
Bases: [Link]
Base class for Telegram ReplyMarkup Objects.
See [Link] and [Link] for detailed
use.

3.2.37 [Link]

class [Link]
Bases: object
Base class for most telegram objects.
to_json()
Returns str

3.2.38 [Link]

class [Link](update_id, message=None, edited_message=None, chan-


nel_post=None, edited_channel_post=None, inline_query=None, cho-
sen_inline_result=None, callback_query=None, shipping_query=None,
pre_checkout_query=None, poll=None, **kwargs)
Bases: [Link]
This object represents an incoming update.

144 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

Note: At most one of the optional parameters can be present in any given update.

update_id
The update’s unique identifier.
Type int
message
Optional. New incoming message.
Type [Link]
edited_message
Optional. New version of a message.
Type [Link]
channel_post
Optional. New incoming channel post.
Type [Link]
edited_channel_post
Optional. New version of a channel post.
Type [Link]
inline_query
Optional. New incoming inline query.
Type [Link]
chosen_inline_result
Optional. The result of an inline query that was chosen by a user.
Type [Link]
callback_query
Optional. New incoming callback query.
Type [Link]
shipping_query
Optional. New incoming shipping query.
Type [Link]
pre_checkout_query
Optional. New incoming pre-checkout query.
Type [Link]
poll
Optional. New poll state. Bots receive only updates about polls, which are sent or stopped by the bot
Type [Link]

Parameters
• update_id (int) – The update’s unique identifier. Update identifiers start from a
certain positive number and increase sequentially. This ID becomes especially handy if
you’re using Webhooks, since it allows you to ignore repeated updates or to restore the
correct update sequence, should they get out of order.
• message ([Link], optional) – New incoming message of any kind -
text, photo, sticker, etc.
• edited_message ([Link], optional) – New version of a message
that is known to the bot and was edited.

3.2. telegram package 145


Python Telegram Bot Documentation, Release 12.1.1

• channel_post ([Link], optional) – New incoming channel post of


any kind - text, photo, sticker, etc.
• edited_channel_post ([Link], optional) – New version of a
channel post that is known to the bot and was edited.
• inline_query ([Link], optional) – New incoming inline
query.
• chosen_inline_result ([Link], optional) –
The result of an inline query that was chosen by a user and sent to their chat partner.
• callback_query ([Link], optional) – New incoming
callback query.
• shipping_query ([Link], optional) – New incoming
shipping query. Only for invoices with flexible price.
• pre_checkout_query ([Link], optional) – New in-
coming pre-checkout query. Contains full information about checkout
• poll ([Link], optional) – New poll state. Bots receive only updates about
polls, which are sent or stopped by the bot
• **kwargs (dict) – Arbitrary keyword arguments.

classmethod de_json(data, bot)


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 and poll.
Type [Link]
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 and poll.
Type [Link]
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 [Link]

3.2.39 [Link]

class [Link](id, first_name, is_bot, last_name=None, username=None, lan-


guage_code=None, bot=None, **kwargs)
Bases: [Link]
This object represents a Telegram user or bot.
id
Unique identifier for this user or bot.
Type int
is_bot
True, if this user is a bot
Type bool

146 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

first_name
User’s or bot’s first name.
Type str
last_name
Optional. User’s or bot’s last name.
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
bot
Optional. The Bot to use for instance methods.
Type [Link]

Parameters
• id (int) – Unique identifier for this user or bot.
• is_bot (bool) – True, if this user is a bot
• first_name (str) – User’s or bot’s first name.
• last_name (str, optional) – User’s or bot’s last name.
• username (str, optional) – User’s or bot’s username.
• language_code (str, optional) – IETF language tag of the user’s language.
• bot ([Link], optional) – The Bot to use for instance methods.

classmethod de_json(data, bot)


classmethod de_list(data, bot)
full_name
Convenience property. The user’s first_name, followed by (if available) last_name.
Type str
get_profile_photos(*args, **kwargs)
Shortcut for:

bot.get_user_profile_photos([Link].from_user.id, *args, **kwargs)

link
Convenience property. If username is available, returns a [Link] link of the user.
Type str
mention_html(name=None)
Parameters name (str) – The name used as a link for the user. Defaults to full_name.
Returns The inline mention for the user as HTML.
Return type str
mention_markdown(name=None)
Parameters name (str) – The name used as a link for the user. Defaults to full_name.

3.2. telegram package 147


Python Telegram Bot Documentation, Release 12.1.1

Returns The inline mention for the user as markdown.


Return type str
name
Convenience property. If available, returns the user’s username prefixed with “@”. If username
is not available, returns full_name.
Type str
send_animation(*args, **kwargs)
Shortcut for:

bot.send_animation([Link], *args, **kwargs)

Where User is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
send_audio(*args, **kwargs)
Shortcut for:

bot.send_audio([Link], *args, **kwargs)

Where User is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
send_document(*args, **kwargs)
Shortcut for:

bot.send_document([Link], *args, **kwargs)

Where User is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
send_message(*args, **kwargs)
Shortcut for:

bot.send_message([Link], *args, **kwargs)

Where User is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
send_photo(*args, **kwargs)
Shortcut for:

bot.send_photo([Link], *args, **kwargs)

Where User is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
send_sticker(*args, **kwargs)
Shortcut for:

148 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

bot.send_sticker([Link], *args, **kwargs)

Where User is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
send_video(*args, **kwargs)
Shortcut for:

bot.send_video([Link], *args, **kwargs)

Where User is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
send_video_note(*args, **kwargs)
Shortcut for:

bot.send_video_note([Link], *args, **kwargs)

Where User is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]
send_voice(*args, **kwargs)
Shortcut for:

bot.send_voice([Link], *args, **kwargs)

Where User is the current instance.


Returns On success, instance representing the message posted.
Return type [Link]

3.2.40 [Link]

class [Link](total_count, photos, **kwargs)


Bases: [Link]
This object represent a user’s profile pictures.
total_count
Total number of profile pictures.
Type int
photos
Requested profile pictures.
Type List[List[[Link]]]

Parameters
• total_count (int) – Total number of profile pictures the target user has.
• photos (List[List[[Link]]]) – Requested profile pictures (in up to
4 sizes each).

3.2. telegram package 149


Python Telegram Bot Documentation, Release 12.1.1

3.2.41 [Link]

class [Link](location, title, address, foursquare_id=None, foursquare_type=None,


**kwargs)
Bases: [Link]
This object represents a venue.
location
Venue location.
Type [Link]
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. (For example, “arts_entertainment/default”,
“arts_entertainment/aquarium” or “food/icecream”.)
Type str

Parameters
• location ([Link]) – Venue location.
• title (str) – Name of the venue.
• address (str) – Address of the venue.
• foursquare_id (str, optional) – Foursquare identifier of the venue.
• foursquare_type (str, optional) – Foursquare type of the venue. (For example,
“arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.)
• **kwargs (dict) – Arbitrary keyword arguments.

3.2.42 [Link]

class [Link](file_id, width, height, duration, thumb=None, mime_type=None,


file_size=None, bot=None, **kwargs)
Bases: [Link]
This object represents a video file.
file_id
Unique identifier for this file.
Type str
width
Video width as defined by sender.
Type int
height
Video height as defined by sender.

150 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

Type int
duration
Duration of the video in seconds as defined by sender.
Type int
thumb
Optional. Video thumbnail.
Type [Link]
mime_type
Optional. Mime type of a file as defined by sender.
Type str
file_size
Optional. File size.
Type int
bot
Optional. The Bot to use for instance methods.
Type [Link]

Parameters
• file_id (str) – Unique identifier for this file.
• width (int) – Video width as defined by sender.
• height (int) – Video height as defined by sender.
• duration (int) – Duration of the video in seconds as defined by sender.
• thumb ([Link], optional) – Video thumbnail.
• mime_type (str, optional) – Mime type of a file as defined by sender.
• file_size (int, optional) – File size.
• bot ([Link], optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.

get_file(timeout=None, **kwargs)
Convenience wrapper over [Link].get_file
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
Raises [Link]

3.2.43 [Link]

class [Link](file_id, length, duration, thumb=None, file_size=None, bot=None,


**kwargs)
Bases: [Link]
This object represents a video message (available in Telegram apps as of v.4.0).

3.2. telegram package 151


Python Telegram Bot Documentation, Release 12.1.1

file_id
Unique identifier for this file.
Type str
length
Video width and height as defined by sender.
Type int
duration
Duration of the video in seconds as defined by sender.
Type int
thumb
Optional. Video thumbnail.
Type [Link]
file_size
Optional. File size.
Type int
bot
Optional. The Bot to use for instance methods.
Type [Link]

Parameters
• file_id (str) – Unique identifier for this file.
• length (int) – Video width and height as defined by sender.
• duration (int) – Duration of the video in seconds as defined by sender.
• thumb ([Link], optional) – Video thumbnail.
• file_size (int, optional) – File size.
• bot ([Link], optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.

get_file(timeout=None, **kwargs)
Convenience wrapper over [Link].get_file
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
Raises [Link]

3.2.44 [Link]

class [Link](file_id, duration, mime_type=None, file_size=None, bot=None, **kwargs)


Bases: [Link]
This object represents a voice note.
file_id
Unique identifier for this file.

152 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

Type str
duration
Duration of the audio in seconds as defined by sender.
Type int
mime_type
Optional. MIME type of the file as defined by sender.
Type str
file_size
Optional. File size.
Type int
bot
Optional. The Bot to use for instance methods.
Type [Link]

Parameters
• file_id (str) – Unique identifier for this file.
• duration (int, optional) – Duration of the audio in seconds as defined by sender.
• mime_type (str, optional) – MIME type of the file as defined by sender.
• file_size (int, optional) – File size.
• bot ([Link], optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.

get_file(timeout=None, **kwargs)
Convenience wrapper over [Link].get_file
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
Raises [Link]

3.2.45 [Link]

class [Link](url, has_custom_certificate, pending_update_count,


last_error_date=None, last_error_message=None,
max_connections=None, allowed_updates=None, **kwargs)
Bases: [Link]
This object represents a Telegram WebhookInfo.
Contains information about the current status of a webhook.
url
Webhook URL.
Type str
has_custom_certificate
If a custom certificate was provided for webhook.

3.2. telegram package 153


Python Telegram Bot Documentation, Release 12.1.1

Type bool
pending_update_count
Number of updates awaiting delivery.
Type int
last_error_date
Optional. Unix time for the most recent error that happened.
Type int
last_error_message
Optional. Error message in human-readable format.
Type str
max_connections
Optional. Maximum allowed number of simultaneous HTTPS connections.
Type int
allowed_updates
Optional. A list of update types the bot is subscribed to.
Type List[str]

Parameters
• url (str) – Webhook URL, may be empty if webhook is not set up.
• has_custom_certificate (bool) – True, if a custom certificate was provided
for webhook certificate checks.
• pending_update_count (int) – Number of updates awaiting delivery.
• last_error_date (int, optional) – Unix time for the most recent error that hap-
pened when trying todeliver an update via webhook.
• last_error_message (str, optional) – Error message in human-readable format
for the most recent error that happened when trying to deliver an update via webhook.
• max_connections (int, optional) – Maximum allowed number of simultaneous
HTTPS connections to the webhook for update delivery.
• allowed_updates (List[str], optional) – A list of update types the bot is sub-
scribed to. Defaults to all update types.

3.2.46 Stickers

[Link]

class [Link](file_id, width, height, is_animated, thumb=None, emoji=None,


file_size=None, set_name=None, mask_position=None, bot=None,
**kwargs)
Bases: [Link]
This object represents a sticker.
file_id
Unique identifier for this file.
Type str
width
Sticker width.
Type int

154 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

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 [Link]
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 [Link]
file_size
Optional. File size.
Type int
bot
Optional. The Bot to use for instance methods.
Type [Link]

Parameters
• file_id (str) – Unique identifier for this file.
• width (int) – Sticker width.
• height (int) – Sticker height.
• is_animated (bool) – True, if the sticker is animated.
• thumb ([Link], optional) – Sticker thumbnail in the .webp or .jpg
format.
• emoji (str, optional) – Emoji associated with the sticker
• set_name (str, optional) – Name of the sticker set to which the sticker belongs.
• mask_position ([Link], optional) – For mask stickers, the
position where the mask should be placed.
• file_size (int, optional) – File size.
• (obj (**kwargs) – dict): Arbitrary keyword arguments.7
• bot ([Link], optional) – The Bot to use for instance methods.

get_file(timeout=None, **kwargs)
Convenience wrapper over [Link].get_file
Parameters

3.2. telegram package 155


Python Telegram Bot Documentation, Release 12.1.1

• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
Raises [Link]

[Link]

class [Link](name, title, is_animated, contains_masks, stickers, bot=None,


**kwargs)
Bases: [Link]
This object represents a sticker set.
name
Sticker set name.
Type str
title
Sticker set title.
Type str
is_animated
True, if the sticker set contains animated stickers.
Type bool
contains_masks
True, if the sticker set contains masks.
Type bool
stickers
List of all set stickers.
Type List[[Link]]

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[[Link]]) – List of all set stickers.

[Link]

class [Link](point, x_shift, y_shift, scale, **kwargs)


Bases: [Link]
This object describes the position on faces where a mask should be placed by default.
point
The part of the face relative to which the mask should be placed.
Type str

156 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

x_shift
Shift by X-axis measured in widths of the mask scaled to the face size, from left to right.
Type float
y_shift
Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom.
Type float
scale
Mask scaling coefficient. For example, 2.0 means double size.
Type float

Notes

type should be one of the following: forehead, eyes, mouth or chin. You can use the classconstants for
those.
Parameters
• point (str) – The part of the face relative to which the mask should be placed.
• x_shift (float) – Shift by X-axis measured in widths of the mask scaled to the face
size, from left to right. For example, choosing -1.0 will place mask just to the left of the
default mask position.
• y_shift (float) – Shift by Y-axis measured in heights of the mask scaled to the face
size, from top to bottom. For example, 1.0 will place the mask just below the default
mask position.
• scale (float) – Mask scaling coefficient. For example, 2.0 means double size.
CHIN = 'chin'
‘chin’
Type str
EYES = 'eyes'
‘eyes’
Type str
FOREHEAD = 'forehead'
‘forehead’
Type str
MOUTH = 'mouth'
‘mouth’
Type str

3.2.47 Inline Mode

[Link]

class [Link](id, from_user, query, offset, location=None, bot=None, **kwargs)


Bases: [Link]
This object represents an incoming inline query. When the user sends an empty query, your bot could return
some default or trending results.

Note:

3.2. telegram package 157


Python Telegram Bot Documentation, Release 12.1.1

• In Python from is a reserved word, use from_user instead.

id
Unique identifier for this query.
Type str
from_user
Sender.
Type [Link]
location
Optional. Sender location, only for bots that request user location.
Type [Link]
query
Text of the query (up to 512 characters).
Type str
offset
Offset of the results to be returned, can be controlled by the bot.
Type str

Parameters
• id (str) – Unique identifier for this query.
• from_user ([Link]) – Sender.
• location ([Link], optional) – Sender location, only for bots that
request user location.
• query (str) – Text of the query (up to 512 characters).
• offset (str) – Offset of the results to be returned, can be controlled by the bot.
• bot ([Link], optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.

answer(*args, **kwargs)
Shortcut for:

bot.answer_inline_query(update.inline_query.id, *args, **kwargs)

Parameters
• results (List[[Link]]) – A list of results for the
inline query.
• cache_time (int, optional) – The maximum amount of time in seconds that the
result of the inline query may be cached on the server. Defaults to 300.
• is_personal (bool, optional) – Pass True, if results may be cached on the server
side only for the user that sent the query. By default, results may be returned to any
user who sends the same query.
• next_offset (str, optional) – Pass the offset that a client should send in the next
query with the same text to receive more results. Pass an empty string if there are no
more results or if you don’t support pagination. Offset length can’t exceed 64 bytes.
• switch_pm_text (str, optional) – If passed, clients will display a button with
specified text that switches the user to a private chat with the bot and sends the bot a
start message with the parameter switch_pm_parameter.

158 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

• 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.

[Link]

class [Link](type, id, **kwargs)


Bases: [Link]
Baseclass for the InlineQueryResult* classes.
type
Type of the result.
Type str
id
Unique identifier for this result, 1-64 Bytes.
Type str

Parameters
• type (str) – Type of the result.
• id (str) – Unique identifier for this result, 1-64 Bytes.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](id, title, input_message_content,


reply_markup=None, url=None,
hide_url=None, description=None,
thumb_url=None, thumb_width=None,
thumb_height=None, **kwargs)
Bases: [Link]
This object represents a Telegram InlineQueryResultArticle.
type
‘article’.
Type str
id
Unique identifier for this result, 1-64 Bytes.
Type str
title
Title of the result.
Type str
input_message_content
Content of the message to be sent.
Type [Link]
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
url
Optional. URL of the result.

3.2. telegram package 159


Python Telegram Bot Documentation, Release 12.1.1

Type str
hide_url
Optional. Pass True, if you don’t want the URL to be shown in the message.
Type bool
description
Optional. Short description of the result.
Type str
thumb_url
Optional. Url of the thumbnail for the result.
Type str
thumb_width
Optional. Thumbnail width.
Type int
thumb_height
Optional. Thumbnail height.
Type int

Parameters
• id (str) – Unique identifier for this result, 1-64 Bytes.
• title (str) – Title of the result.
• input_message_content ([Link]) – Content
of the message to be sent.
• reply_markup ([Link], optional) – Inline keyboard attached
to the message
• url (str, optional) – URL of the result.
• hide_url (bool, optional) – Pass True, if you don’t want the URL to be shown in
the message.
• description (str, optional) – Short description of the result.
• thumb_url (str, optional) – Url of the thumbnail for the result.
• thumb_width (int, optional) – Thumbnail width.
• thumb_height (int, optional) – Thumbnail height.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](id, audio_url, title, performer=None,


audio_duration=None, cap-
tion=None, reply_markup=None, in-
put_message_content=None, parse_mode=None,
**kwargs)
Bases: [Link]
Represents a link to an mp3 audio file. By default, this audio file will be sent by the user. Alternatively, you
can use input_message_content to send a message with the specified content instead of the audio.
type
‘audio’.
Type str

160 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

id
Unique identifier for this result, 1-64 bytes.
Type str
audio_url
A valid URL for the audio file.
Type str
title
Title.
Type str
performer
Optional. Caption, 0-200 characters.
Type str
audio_duration
Optional. Performer.
Type str
caption
Optional. Audio duration in seconds.
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 [Link] for the available
modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the audio.
Type [Link]

Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• audio_url (str) – A valid URL for the audio file.
• title (str) – Title.
• performer (str, optional) – Caption, 0-200 characters.
• audio_duration (str, optional) – Performer.
• caption (str, optional) – Audio duration in seconds.
• 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 [Link] for the available modes.
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• input_message_content ([Link], optional) –
Content of the message to be sent instead of the audio.
• **kwargs (dict) – Arbitrary keyword arguments.

3.2. telegram package 161


Python Telegram Bot Documentation, Release 12.1.1

[Link]

class [Link](id, audio_file_id, caption=None,


reply_markup=None, in-
put_message_content=None,
parse_mode=None, **kwargs)
Bases: [Link]
Represents a link to an mp3 audio file stored on the Telegram servers. By default, this audio file will be sent
by the user. Alternatively, you can use input_message_content to send amessage with the specified
content instead of the audio.
type
‘audio’.
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
audio_file_id
A valid file identifier for the audio file.
Type str
caption
Optional. Caption, 0-1024 characters
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 [Link] for the available
modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the audio.
Type [Link]

Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• audio_file_id (str) – A valid file identifier for the audio file.
• caption (str, optional) – Caption, 0-1024 characters
• 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 [Link] for the available modes.
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• input_message_content ([Link], optional) –
Content of the message to be sent instead of the audio.
• **kwargs (dict) – Arbitrary keyword arguments.

162 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

[Link]

class [Link](id, title, document_file_id, de-


scription=None, caption=None,
reply_markup=None, in-
put_message_content=None,
parse_mode=None, **kwargs)
Bases: [Link]
Represents a link to a file stored on the Telegram servers. By default, this file will be sent by the user with
an optional caption. Alternatively, you can use input_message_content to send a message with the
specified content instead of the file.
type
‘document’.
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
title
Title for the result.
Type str
document_file_id
A valid file identifier for the file.
Type str
description
Optional. Short description of the result.
Type str
caption
Optional. Caption, 0-1024 characters
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 [Link] for the available
modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the file.
Type [Link]

Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• title (str) – Title for the result.
• document_file_id (str) – A valid file identifier for the file.
• description (str, optional) – Short description of the result.

3.2. telegram package 163


Python Telegram Bot Documentation, Release 12.1.1

• caption (str, optional) – Caption, 0-1024 characters


• 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 [Link] for the available modes.
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• input_message_content ([Link], optional) –
Content of the message to be sent instead of the file.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](id, gif_file_id, title=None, cap-


tion=None, reply_markup=None,
input_message_content=None,
parse_mode=None, **kwargs)
Bases: [Link]
Represents a link to an animated GIF file stored on the Telegram servers. By default, this animated GIF file
will be sent by the user with an optional caption. Alternatively, you can use input_message_content
to send a message with specified content instead of the animation.
type
‘gif’.
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, 0-1024 characters
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 [Link] for the available
modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the gif.
Type [Link]

164 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• gif_file_id (str) – A valid file identifier for the GIF file.
• title (str, optional) – Title for the [Link] (str, optional):
• caption (str, optional) – Caption, 0-1024 characters
• 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 [Link] for the available modes.
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• input_message_content ([Link], optional) –
Content of the message to be sent instead of the gif.
• **kwargs (dict) – Arbitrary keyword arguments.

telegram.InlineQueryResultCachedMpeg4Gif

class telegram.InlineQueryResultCachedMpeg4Gif(id, mpeg4_file_id, title=None, cap-


tion=None, reply_markup=None,
input_message_content=None,
parse_mode=None, **kwargs)
Bases: [Link]
Represents a link to a video animation (H.264/MPEG-4 AVC video without sound) stored on the Telegram
servers. By default, this animated MPEG-4 file will be sent by the user with an optional caption. Alterna-
tively, you can use input_message_content to send a message with the specified content instead of
the animation.
type
‘mpeg4_gif’.
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
mpeg4_file_id
A valid file identifier for the MP4 file.
Type str
title
Optional. Title for the result.
Type str
caption
Optional. Caption, 0-1024 characters
Type str
parse_mode
Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline
URLs in the media caption. See the constants in [Link] for the available modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.

3.2. telegram package 165


Python Telegram Bot Documentation, Release 12.1.1

Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the MPEG-4 file.
Type [Link]

Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• mpeg4_file_id (str) – A valid file identifier for the MP4 file.
• title (str, optional) – Title for the result.
• caption (str, optional) – Caption, 0-1024 characters
• 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 [Link] for the available modes.
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• input_message_content ([Link], optional) –
Content of the message to be sent instead of the MPEG-4 file.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](id, photo_file_id, title=None, de-


scription=None, caption=None,
reply_markup=None, in-
put_message_content=None,
parse_mode=None, **kwargs)
Bases: [Link]
Represents a link to a photo stored on the Telegram servers. By default, this photo will be sent by the user
with an optional caption. Alternatively, you can use input_message_content to send a message with
the specified content instead of the photo.
type
‘photo’.
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
photo_file_id
A valid file identifier of the photo.
Type str
title
Optional. Title for the result.
Type str
description
Optional. Short description of the result.
Type str
caption
Optional. Caption, 0-1024 characters

166 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

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 [Link] for the available
modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the photo.
Type [Link]

Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• photo_file_id (str) – A valid file identifier of the photo.
• title (str, optional) – Title for the result.
• description (str, optional) – Short description of the result.
• caption (str, optional) – Caption, 0-1024 characters
• 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 [Link] for the available modes.
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• input_message_content ([Link], optional) –
Content of the message to be sent instead of the photo.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](id, sticker_file_id, re-


ply_markup=None, in-
put_message_content=None,
**kwargs)
Bases: [Link]
Represents a link to a sticker stored on the Telegram servers. By default, this sticker will be sent by the user.
Alternatively, you can use input_message_content to send a message with the specified content
instead of the sticker.
type
‘sticker‘.
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
sticker_file_id
A valid file identifier of the sticker.
Type str

3.2. telegram package 167


Python Telegram Bot Documentation, Release 12.1.1

reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the sticker.
Type [Link]

Parameters
• id (str) –
• sticker_file_id (str) –
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• input_message_content ([Link], optional) –
Content of the message to be sent instead of the sticker.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](id, video_file_id, title, description=None,


caption=None, reply_markup=None,
input_message_content=None,
parse_mode=None, **kwargs)
Bases: [Link]
Represents a link to a video file stored on the Telegram servers. By default, this video file will be sent by the
user with an optional caption. Alternatively, you can use input_message_content to send a message
with the specified content instead of the video.
type
‘video’.
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
video_file_id
A valid file identifier for the video file.
Type str
title
Title for the result.
Type str
description
Optional. Short description of the result.
Type str
caption
Optional. Caption, 0-1024 characters.
Type str

168 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

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 [Link] for the available
modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the video.
Type [Link]

Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• video_file_id (str) – A valid file identifier for the video file.
• title (str) – Title for the result.
• description (str, optional) – Short description of the result.
• caption (str, optional) – Caption, 0-1024 characters.
• 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 [Link] for the available modes.
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• input_message_content ([Link], optional) –
Content of the message to be sent instead of the video.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](id, voice_file_id, title, cap-


tion=None, reply_markup=None,
input_message_content=None,
parse_mode=None, **kwargs)
Bases: [Link]
Represents a link to a voice message stored on the Telegram servers. By default, this voice message will
be sent by the user. Alternatively, you can use input_message_content to send a message with the
specified content instead of the voice message.
type
‘voice’.
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
voice_file_id
A valid file identifier for the voice message.
Type str

3.2. telegram package 169


Python Telegram Bot Documentation, Release 12.1.1

title
Voice message title.
Type str
caption
Optional. Caption, 0-1024 characters.
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 [Link] for the available
modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the voice.
Type [Link]

Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• voice_file_id (str) – A valid file identifier for the voice message.
• title (str) – Voice message title.
• caption (str, optional) – Caption, 0-1024 characters.
• 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 [Link] for the available modes.
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• input_message_content ([Link], optional) –
Content of the message to be sent instead of the voice.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](id, phone_number, first_name,


last_name=None, reply_markup=None,
input_message_content=None,
thumb_url=None, thumb_width=None,
thumb_height=None, vcard=None, **kwargs)
Bases: [Link]
Represents a contact with a phone number. By default, this contact will be sent by the user. Alternatively,
you can use input_message_content to send a message with the specified content instead of the
contact.
type
‘contact’.
Type str

170 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

id
Unique identifier for this result, 1-64 bytes.
Type str
phone_number
Contact’s phone number.
Type str
first_name
Contact’s first name.
Type str
last_name
Optional. Contact’s last name.
Type str
vcard
Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the contact.
Type [Link]
thumb_url
Optional. Url of the thumbnail for the result.
Type str
thumb_width
Optional. Thumbnail width.
Type int
thumb_height
Optional. Thumbnail height.
Type int

Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• phone_number (str) – Contact’s phone number.
• first_name (str) – Contact’s first name.
• last_name (str, optional) – Contact’s last name.
• vcard (str, optional) – Additional data about the contact in the form of a vCard,
0-2048 bytes.
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• input_message_content ([Link], optional) –
Content of the message to be sent instead of the contact.
• thumb_url (str, optional) – Url of the thumbnail for the result.
• thumb_width (int, optional) – Thumbnail width.

3.2. telegram package 171


Python Telegram Bot Documentation, Release 12.1.1

• thumb_height (int, optional) – Thumbnail height.


• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](id, document_url, title, mime_type,


caption=None, description=None,
reply_markup=None, in-
put_message_content=None,
thumb_url=None, thumb_width=None,
thumb_height=None, parse_mode=None,
**kwargs)
Bases: [Link]
Represents a link to a file. By default, this file will be sent by the user with an optional caption. Alternatively,
you can use input_message_content to send a message with the specified content instead of the file.
Currently, only .PDF and .ZIP files can be sent using this method.
type
‘document’.
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
title
Title for the result.
Type str
caption
Optional. Caption, 0-1024 characters
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 [Link] for the available
modes.
Type str
document_url
A valid URL for the file.
Type str
mime_type
Mime type of the content of the file, either “application/pdf” or “application/zip”.
Type str
description
Optional. Short description of the result.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the file.

172 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

Type [Link]
thumb_url
Optional. URL of the thumbnail (jpeg only) for the file.
Type str
thumb_width
Optional. Thumbnail width.
Type int
thumb_height
Optional. Thumbnail height.
Type int

Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• title (str) – Title for the result.
• caption (str, optional) – Caption, 0-1024 characters
• 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 [Link] for the available modes.
• document_url (str) – A valid URL for the file.
• mime_type (str) – Mime type of the content of the file, either “application/pdf” or
“application/zip”.
• description (str, optional) – Short description of the result.
• reply_markup ([Link]) – Optional. Inline key-
board attached to the message.
• input_message_content ([Link]) – Op-
tional. Content of the message to be sent instead of the file.
• thumb_url (str, optional) – URL of the thumbnail (jpeg only) for the file.
• thumb_width (int, optional) – Thumbnail width.
• thumb_height (int, optional) – Thumbnail height.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](id, game_short_name, reply_markup=None,


**kwargs)
Bases: [Link]
Represents a Game.
type
‘game’.
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
game_short_name
Short name of the game.

3.2. telegram package 173


Python Telegram Bot Documentation, Release 12.1.1

Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]

Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• game_short_name (str) – Short name of the game.
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](id, gif_url, thumb_url, gif_width=None,


gif_height=None, title=None, caption=None, re-
ply_markup=None, input_message_content=None,
gif_duration=None, parse_mode=None, **kwargs)
Bases: [Link]
Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with
optional caption. Alternatively, you can use input_message_content to send a message with the
specified content instead of the animation.
type
‘gif’.
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
gif_url
A valid URL for the GIF file. File size must not exceed 1MB.
Type str
gif_width
Optional. Width of the GIF.
Type int
gif_height
Optional. Height of the GIF.
Type int
gif_duration
Optional. Duration of the GIF.
Type int
thumb_url
URL of the static thumbnail for the result (jpeg or gif).
Type str
title
Optional. Title for the result.
Type str

174 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

caption
Optional. Caption, 0-1024 characters
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 [Link] for the available
modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the gif.
Type [Link]

Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• gif_url (str) – A valid URL for the GIF file. File size must not exceed 1MB.
• gif_width (int, optional) – Width of the GIF.
• gif_height (int, optional) – Height of the GIF.
• gif_duration (int, optional) – Duration of the GIF
• thumb_url (str) – URL of the static thumbnail for the result (jpeg or gif).
• title (str, optional) – Title for the [Link] (str, optional):
• caption (str, optional) – Caption, 0-1024 characters
• 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 [Link] for the available modes.
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• input_message_content ([Link], optional) –
Content of the message to be sent instead of the gif.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](id, latitude, longitude, title,


live_period=None, reply_markup=None,
input_message_content=None,
thumb_url=None, thumb_width=None,
thumb_height=None, **kwargs)
Bases: [Link]
Represents a location on a map. By default, the location will be sent by the user. Alternatively, you can use
input_message_content to send a message with the specified content instead of the location.
type
‘location’.
Type str

3.2. telegram package 175


Python Telegram Bot Documentation, Release 12.1.1

id
Unique identifier for this result, 1-64 bytes.
Type str
latitude
Location latitude in degrees.
Type float
longitude
Location longitude in degrees.
Type float
title
Location title.
Type str
live_period
Optional. Period in seconds for which the location can be updated, should be between 60 and 86400.
Type int
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the location.
Type [Link]
thumb_url
Optional. Url of the thumbnail for the result.
Type str
thumb_width
Optional. Thumbnail width.
Type int
thumb_height
Optional. Thumbnail height.
Type int

Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• latitude (float) – Location latitude in degrees.
• longitude (float) – Location longitude in degrees.
• title (str) – Location title.
• live_period (int, optional) – Period in seconds for which the location can be
updated, should be between 60 and 86400.
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• input_message_content ([Link], 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.

176 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

• thumb_height (int, optional) – Thumbnail height.


• **kwargs (dict) – Arbitrary keyword arguments.

telegram.InlineQueryResultMpeg4Gif

class telegram.InlineQueryResultMpeg4Gif(id, mpeg4_url, thumb_url,


mpeg4_width=None, mpeg4_height=None,
title=None, caption=None,
reply_markup=None, in-
put_message_content=None,
mpeg4_duration=None, parse_mode=None,
**kwargs)
Bases: [Link]
Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). By default, this
animated MPEG-4 file will be sent by the user with optional caption. Alternatively, you can use
input_message_content to send a message with the specified content instead of the animation.
type
‘mpeg4_gif’.
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
mpeg4_url
A valid URL for the MP4 file. File size must not exceed 1MB.
Type str
mpeg4_width
Optional. Video width.
Type int
mpeg4_height
Optional. Video height.
Type int
mpeg4_duration
Optional. Video duration.
Type int
thumb_url
URL of the static thumbnail (jpeg or gif) for the result.
Type str
title
Optional. Title for the result.
Type str
caption
Optional. Caption, 0-1024 characters
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 [Link] for the available
modes.

3.2. telegram package 177


Python Telegram Bot Documentation, Release 12.1.1

Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the MPEG-4 file.
Type [Link]

Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• mpeg4_url (str) – A valid URL for the MP4 file. File size must not exceed 1MB.
• mpeg4_width (int, optional) – Video width.
• mpeg4_height (int, optional) – Video height.
• mpeg4_duration (int, optional) – Video duration.
• thumb_url (str) – URL of the static thumbnail (jpeg or gif) for the result.
• title (str, optional) – Title for the result.
• caption (str, optional) – Caption, 0-1024 characters
• 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 [Link] for the available modes.
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• input_message_content ([Link], optional) –
Content of the message to be sent instead of the MPEG-4 file.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](id, photo_url, thumb_url, photo_width=None,


photo_height=None, title=None, descrip-
tion=None, caption=None, reply_markup=None,
input_message_content=None,
parse_mode=None, **kwargs)
Bases: [Link]
Represents a link to a photo. By default, this photo will be sent by the user with optional caption. Alterna-
tively, you can use input_message_content to send a message with the specified content instead of
the photo.
type
‘photo’.
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
photo_url
A valid URL of the photo. Photo must be in jpeg format. Photo size must not exceed 5MB.
Type str

178 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

thumb_url
URL of the thumbnail for the photo.
Type str
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, 0-1024 characters
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 [Link] for the available
modes.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the photo.
Type [Link]

Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• photo_url (str) – A valid URL of the photo. Photo must be in jpeg format. Photo
size must not exceed 5MB.
• thumb_url (str) – URL of the thumbnail for the photo.
• photo_width (int, optional) – Width of the photo.
• photo_height (int, optional) – Height of the photo.
• title (str, optional) – Title for the result.
• description (str, optional) – Short description of the result.
• caption (str, optional) – Caption, 0-1024 characters
• 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 [Link] for the available modes.
• reply_markup ([Link], optional) – Inline key-
board attached to the message.

3.2. telegram package 179


Python Telegram Bot Documentation, Release 12.1.1

• input_message_content ([Link], optional) –


Content of the message to be sent instead of the photo.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](id, latitude, longitude, title,


address, foursquare_id=None,
foursquare_type=None, reply_markup=None,
input_message_content=None, thumb_url=None,
thumb_width=None, thumb_height=None,
**kwargs)
Bases: [Link]
Represents a venue. By default, the venue will be sent by the user. Alternatively, you can use
input_message_content to send a message with the specified content instead of the venue.
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. (For example, “arts_entertainment/default”,
“arts_entertainment/aquarium” or “food/icecream”.)
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the venue.
Type [Link]

180 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

thumb_url
Optional. Url of the thumbnail for the result.
Type str
thumb_width
Optional. Thumbnail width.
Type int
thumb_height
Optional. Thumbnail height.
Type int

Parameters
• id (str) – Unique identifier for this result, 1-64 Bytes.
• latitude (float) – Latitude of the venue location in degrees.
• longitude (float) – Longitude of the venue location in degrees.
• title (str) – Title of the venue.
• address (str) – Address of the venue.
• foursquare_id (str, optional) – Foursquare identifier of the venue if known.
• foursquare_type (str, optional) – Foursquare type of the venue, if
known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or
“food/icecream”.)
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• input_message_content ([Link], 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.

[Link]

class [Link](id, video_url, mime_type, thumb_url, ti-


tle, caption=None, video_width=None,
video_height=None, video_duration=None,
description=None, reply_markup=None, in-
put_message_content=None, parse_mode=None,
**kwargs)
Bases: [Link]
Represents a link to a page containing an embedded video player or a video file. By default, this video file
will be sent by the user with an optional caption. Alternatively, you can use input_message_content
to send a message with the specified content instead of the video.
type
‘video’.
Type str
id
Unique identifier for this result, 1-64 bytes.

3.2. telegram package 181


Python Telegram Bot Documentation, Release 12.1.1

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, 0-1024 characters
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 [Link] for the available
modes.
Type str
video_width
Optional. Video width.
Type int
video_height
Optional. Video height.
Type int
video_duration
Optional. Video duration in seconds.
Type int
description
Optional. Short description of the result.
Type str
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the video.
Type [Link]

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”.

182 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

• 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.
• 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 [Link] for the available modes.
• video_width (int, optional) – Video width.
• video_height (int, optional) – Video height.
• video_duration (int, optional) – Video duration in seconds.
• description (str, optional) – Short description of the result.
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• input_message_content ([Link], optional) –
Content of the message to be sent instead of the video.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](id, voice_url, title, voice_duration=None,


caption=None, reply_markup=None, in-
put_message_content=None, parse_mode=None,
**kwargs)
Bases: [Link]
Represents a link to a voice recording in an .ogg container encoded with OPUS. By default, this voice
recording will be sent by the user. Alternatively, you can use input_message_content to send a
message with the specified content instead of the the voice message.
type
‘voice’.
Type str
id
Unique identifier for this result, 1-64 bytes.
Type str
voice_url
A valid URL for the voice recording.
Type str
title
Voice message title.
Type str
caption
Optional. Caption, 0-1024 characters.
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 [Link] for the available
modes.
Type str

3.2. telegram package 183


Python Telegram Bot Documentation, Release 12.1.1

voice_duration
Optional. Recording duration in seconds.
Type int
reply_markup
Optional. Inline keyboard attached to the message.
Type [Link]
input_message_content
Optional. Content of the message to be sent instead of the voice.
Type [Link]

Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• voice_url (str) – A valid URL for the voice recording.
• title (str) – Voice message title.
• caption (str, optional) – Caption, 0-1024 characters.
• 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 [Link] for the available modes.
• voice_duration (int, optional) – Recording duration in seconds.
• reply_markup ([Link], optional) – Inline key-
board attached to the message.
• input_message_content ([Link], optional) –
Content of the message to be sent instead of the voice.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link]
Bases: [Link]
Base class for Telegram InputMessageContent Objects.
See: [Link], telegram.
InputLocationMessageContent, [Link] and
[Link] for more details.

[Link]

class [Link](message_text, parse_mode=None, dis-


able_web_page_preview=None, **kwargs)
Bases: [Link]
Represents the content of a text message to be sent as the result of an inline query.
message_text
Text of the message to be sent, 1-4096 characters.
Type str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in your bot’s message.

184 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

Type str
disable_web_page_preview
Optional. Disables link previews for links in the sent message.
Type bool

Parameters
• message_text (str) – Text of the message to be sent, 1-4096 characters. Also
found as [Link].MAX_MESSAGE_LENGTH.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram apps
to show bold, italic, fixed-width text or inline URLs in your bot’s message.
• disable_web_page_preview (bool, optional) – Disables link previews for links
in the sent message.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](latitude, longitude, live_period=None,


**kwargs)
Bases: [Link]
Represents the content of a location message to be sent as the result of an inline query.
latitude
Latitude of the location in degrees.
Type float
longitude
Longitude of the location in degrees.
Type float

Parameters
• latitude (float) – Latitude of the location in degrees.
• longitude (float) – Longitude of the location in degrees.
• live_period (int, optional) – Period in seconds for which the location can be
updated, should be between 60 and 86400.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](latitude, longitude, title, address,


foursquare_id=None, foursquare_type=None,
**kwargs)
Bases: [Link]
Represents the content of a venue message to be sent as the result of an inline query.
latitude
Latitude of the location in degrees.
Type float
longitude
Longitude of the location in degrees.
Type float

3.2. telegram package 185


Python Telegram Bot Documentation, Release 12.1.1

title
Name of the venue.
Type str
address
Address of the venue.
Type str
foursquare_id
Optional. Foursquare identifier of the venue, if known.
Type str
foursquare_type
Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”,
“arts_entertainment/aquarium” or “food/icecream”.)
Type str

Parameters
• latitude (float) – Latitude of the location in degrees.
• longitude (float) – Longitude of the location in degrees.
• title (str) – Name of the venue.
• address (str) – Address of the venue.
• foursquare_id (str, optional) – Foursquare identifier of the venue, if known.
• foursquare_type (str, optional) – Foursquare type of the venue, if
known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or
“food/icecream”.)
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](phone_number, first_name,


last_name=None, vcard=None, **kwargs)
Bases: [Link]
Represents the content of a contact message to be sent as the result of an inline query.
phone_number
Contact’s phone number.
Type str
first_name
Contact’s first name.
Type str
last_name
Optional. Contact’s last name.
Type str
vcard
Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes.
Type str

Parameters
• phone_number (str) – Contact’s phone number.

186 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

• first_name (str) – Contact’s first name.


• last_name (str, optional) – Contact’s last name.
• vcard (str, optional) – Additional data about the contact in the form of a vCard,
0-2048 bytes.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](result_id, from_user, query, location=None, in-


line_message_id=None, **kwargs)
Bases: [Link]
Represents a result of an inline query that was chosen by the user and sent to their chat partner.

Note: In Python from is a reserved word, use from_user instead.

result_id
The unique identifier for the result that was chosen.
Type str
from_user
The user that chose the result.
Type [Link]
location
Optional. Sender location.
Type [Link]
inline_message_id
Optional. Identifier of the sent inline message.
Type str
query
The query that was used to obtain the result.
Type str

Parameters
• result_id (str) – The unique identifier for the result that was chosen.
• from_user ([Link]) – The user that chose the result.
• location ([Link], optional) – Sender location, only for bots that
require user location.
• inline_message_id (str, optional) – Identifier of the sent inline message. Avail-
able only if there is an inline keyboard attached to the message. Will be also received in
callback queries and can be used to edit the message.
• query (str) – The query that was used to obtain the result.
• **kwargs (dict) – Arbitrary keyword arguments.

3.2. telegram package 187


Python Telegram Bot Documentation, Release 12.1.1

3.2.48 Payments

[Link]

class [Link](label, amount, **kwargs)


Bases: [Link]
This object represents a portion of the price for goods or services.
label
Portion label.
Type str
amount
Price of the product in the smallest units of the currency.
Type int

Parameters
• label (str) – Portion label
• amount (int) – Price of the product in the smallest units of the currency (integer, not
float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp
parameter in [Link], it shows the number of digits past the decimal point for
each currency (2 for the majority of currencies).
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](title, description, start_parameter, currency, total_amount, **kwargs)


Bases: [Link]
This object contains basic information about an invoice.
title
Product name.
Type str
description
Product description.
Type str
start_parameter
Unique bot deep-linking parameter.
Type str
currency
Three-letter ISO 4217 currency code.
Type str
total_amount
Total price in the smallest units of the currency.
Type int

Parameters
• title (str) – Product name.
• description (str) – Product description.

188 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

• start_parameter (str) – Unique bot deep-linking parameter that can be used to


generate this invoice.
• currency (str) – Three-letter ISO 4217 currency code.
• total_amount (int) – Total price in the smallest units of the currency (integer, not
float/double). For example, for a price of US$ 1.45 pass amount = 145.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](country_code, state, city, street_line1, street_line2,


post_code, **kwargs)
Bases: [Link]
This object represents a Telegram ShippingAddress.
country_code
ISO 3166-1 alpha-2 country code.
Type str
state
State, if applicable.
Type str
city
City.
Type str
street_line1
First line for the address.
Type str
street_line2
Second line for the address.
Type str
post_code
Address post code.
Type str

Parameters
• country_code (str) – ISO 3166-1 alpha-2 country code.
• state (str) – State, if applicable.
• city (str) – City.
• street_line1 (str) – First line for the address.
• street_line2 (str) – Second line for the address.
• post_code (str) – Address post code.
• **kwargs (dict) – Arbitrary keyword arguments.

3.2. telegram package 189


Python Telegram Bot Documentation, Release 12.1.1

[Link]

class [Link](name=None, phone_number=None, email=None, ship-


ping_address=None, **kwargs)
Bases: [Link]
This object represents information about an order.
name
Optional. User name.
Type str
phone_number
Optional. User’s phone number.
Type str
email
Optional. User email.
Type str
shipping_address
Optional. User shipping address.
Type [Link]

Parameters
• name (str, optional) – User name.
• phone_number (str, optional) – User’s phone number.
• email (str, optional) – User email.
• shipping_address ([Link], optional) – User ship-
ping address.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](id, title, prices, **kwargs)


Bases: [Link]
This object represents one shipping option.
id
Shipping option identifier.
Type str
title
Option title.
Type str
prices
List of price portions.
Type List[[Link]]

Parameters
• id (str) – Shipping option identifier.
• title (str) – Option title.
• prices (List[[Link]]) – List of price portions.

190 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](currency, total_amount, invoice_payload, tele-


gram_payment_charge_id, provider_payment_charge_id,
shipping_option_id=None, order_info=None, **kwargs)
Bases: [Link]
This object contains basic information about a successful payment.
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 [Link]
telegram_payment_charge_id
Telegram payment identifier.
Type str
provider_payment_charge_id
Provider payment identifier.
Type str

Parameters
• currency (str) – Three-letter ISO 4217 currency code.
• total_amount (int) – Total price in the smallest units of the currency (integer, not
float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp
parameter in [Link], 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 ([Link], optional) – Order info provided by the user
• telegram_payment_charge_id (str) – Telegram payment identifier.
• provider_payment_charge_id (str) – Provider payment identifier.
• **kwargs (dict) – Arbitrary keyword arguments.

3.2. telegram package 191


Python Telegram Bot Documentation, Release 12.1.1

[Link]

class [Link](id, from_user, invoice_payload, shipping_address, bot=None,


**kwargs)
Bases: [Link]
This object contains information about an incoming shipping query.

Note:
• In Python from is a reserved word, use from_user instead.

id
Unique query identifier.
Type str
from_user
User who sent the query.
Type [Link]
invoice_payload
Bot specified invoice payload.
Type str
shipping_address
User specified shipping address.
Type [Link]
bot
Optional. The Bot to use for instance methods.
Type [Link]

Parameters
• id (str) – Unique query identifier.
• from_user ([Link]) – User who sent the query.
• invoice_payload (str) – Bot specified invoice payload.
• shipping_address ([Link]) – User specified ship-
ping address.
• bot ([Link], optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.

answer(*args, **kwargs)
Shortcut for:

bot.answer_shipping_query(update.shipping_query.id, *args, **kwargs)

Parameters
• ok (bool) – Specify True if delivery to the specified address is possible and False if
there are any problems (for example, if delivery to the specified address is not possi-
ble).
• shipping_options (List[[Link]], optional) – Re-
quired if ok is True. A JSON-serialized array of available shipping options.

192 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

• error_message (str, optional) – Required if ok is False. Error message in human


readable form that explains why it is impossible to complete the order (e.g. “Sorry,
delivery to your desired address is unavailable’). Telegram will display this message
to the user.

[Link]

class [Link](id, from_user, currency, total_amount, invoice_payload,


shipping_option_id=None, order_info=None, bot=None,
**kwargs)
Bases: [Link]
This object contains information about an incoming pre-checkout query.

Note:
• In Python from is a reserved word, use from_user instead.

id
Unique query identifier.
Type str
from_user
User who sent the query.
Type [Link]
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 [Link]
bot
Optional. The Bot to use for instance methods.
Type [Link]

Parameters
• id (str) – Unique query identifier.
• from_user ([Link]) – User who sent the query.
• currency (str) – Three-letter ISO 4217 currency code

3.2. telegram package 193


Python Telegram Bot Documentation, Release 12.1.1

• 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 [Link], 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 ([Link], optional) – Order info provided by the user.
• bot ([Link], optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.

answer(*args, **kwargs)
Shortcut for:

bot.answer_pre_checkout_query(update.pre_checkout_query.id, *args,
˓→**kwargs)

Parameters
• ok (bool) – Specify True if everything is alright (goods are available, etc.) and the
bot is ready to proceed with the order. Use False if there are any problems.
• error_message (str, optional) – Required if ok is False. Error message in human
readable form that explains the reason for failure to proceed with the checkout (e.g.
“Sorry, somebody just bought the last of our amazing black T-shirts while you were
busy filling out your payment details. Please choose a different color or garment!”).
Telegram will display this message to the user.
• **kwargs (dict) – Arbitrary keyword arguments.

3.2.49 Games

[Link]

class [Link](title, description, photo, text=None, text_entities=None, animation=None,


**kwargs)
Bases: [Link]
This object represents a game. Use BotFather to create and edit games, their short names will act as unique
identifiers.
title
Title of the game.
Type str
description
Description of the game.
Type str
photo
Photo that will be displayed in the game message in chats.
Type List[[Link]]
text
Optional. Brief description of the game or high scores included in the game message. Can be auto-
matically edited to include current high scores for the game when the bot calls set_game_score, or
manually edited using edit_message_text.

194 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

Type str
text_entities
Optional. Special entities that appear in text, such as usernames, URLs, bot commands, etc.
Type List[[Link]]
animation
Optional. Animation that will be displayed in the game message in chats. Upload via BotFather.
Type [Link]

Parameters
• title (str) – Title of the game.
• description (str) – Description of the game.
• photo (List[[Link]]) – Photo that will be displayed in the game
message in chats.
• text (str, optional) – Brief description of the game or high scores included in the
game message. Can be automatically edited to include current high scores for the game
when the bot calls set_game_score, or manually edited using edit_message_text. 0-4096
characters. Also found as [Link].MAX_MESSAGE_LENGTH.
• text_entities (List[[Link]], optional) – Special entities
that appear in text, such as usernames, URLs, bot commands, etc.
• animation ([Link], optional) – Animation that will be displayed
in the game message in chats. Upload via BotFather.

parse_text_entities(types=None)
Returns a dict that maps [Link] 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.

Parameters types (List[str], optional) – List of MessageEntity types as strings. If


the type attribute of an entity is contained in this list, it will be returned. Defaults to
[Link].ALL_TYPES.
Returns A dictionary of entities mapped to the text that belongs to them, calculated based
on UTF-16 codepoints.
Return type Dict[[Link], str]

parse_text_entity(entity)
Returns the text from a given [Link].

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
[Link] with the offset and length.)

Parameters entity ([Link]) – The entity to extract the text


from. It must be an entity that belongs to this message.
Returns The text of the given entity.

3.2. telegram package 195


Python Telegram Bot Documentation, Release 12.1.1

Return type str

[Link]

class [Link]
Bases: [Link]
A placeholder, currently holds no information. Use BotFather to set up your game.

[Link]

class [Link](position, user, score)


Bases: [Link]
This object represents one row of the high scores table for a game.
position
Position in high score table for the game.
Type int
user
User.
Type [Link]
score
Score.
Type int

Parameters
• position (int) – Position in high score table for the game.
• user ([Link]) – User.
• score (int) – Score.

3.2.50 Passport

[Link]

class [Link](source, type, message, **kwargs)


Bases: [Link]
Baseclass for the PassportElementError* classes.
source
Error source.
Type str
type
The section of the user’s Telegram Passport which has the error.
Type str
message
Error message
Type str

Parameters

196 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

• source (str) – Error source.


• type (str) – The section of the user’s Telegram Passport which has the error.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](type, file_hash, message, **kwargs)


Bases: [Link]
Represents an issue with a document scan. The error is considered resolved when the file with the document
scan changes.
type
The section of the user’s Telegram Passport which has the issue, one of “utility_bill”,
“bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”.
Type str
file_hash
Base64-encoded file hash.
Type str
message
Error message.
Type str

Parameters
• type (str) – The section of the user’s Telegram Passport which has the issue, one of
“utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “tempo-
rary_registration”.
• file_hash (str) – Base64-encoded file hash.
• message (str) – Error message.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](type, file_hash, message, **kwargs)


Bases: [Link]
Represents an issue with the front side of a document. The error is considered resolved when the file with
the reverse side of the document changes.
type
The section of the user’s Telegram Passport which has the issue, one of “passport”, “driver_license”,
“identity_card”, “internal_passport”.
Type str
file_hash
Base64-encoded hash of the file with the reverse side of the document.
Type str
message
Error message.
Type str

Parameters

3.2. telegram package 197


Python Telegram Bot Documentation, Release 12.1.1

• type (str) – The section of the user’s Telegram Passport which has the issue, one of
“driver_license”, “identity_card”.
• file_hash (str) – Base64-encoded hash of the file with the reverse side of the
document.
• message (str) – Error message.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](type, file_hash, message, **kwargs)


Bases: [Link]
Represents an issue with the front side of a document. The error is considered resolved when the file with
the front side of the document changes.
type
The section of the user’s Telegram Passport which has the issue, one of “passport”, “driver_license”,
“identity_card”, “internal_passport”.
Type str
file_hash
Base64-encoded hash of the file with the front side of the document.
Type str
message
Error message.
Type str

Parameters
• type (str) – The section of the user’s Telegram Passport which has the issue, one of
“passport”, “driver_license”, “identity_card”, “internal_passport”.
• file_hash (str) – Base64-encoded hash of the file with the front side of the docu-
ment.
• message (str) – Error message.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](type, file_hashes, message, **kwargs)


Bases: [Link]
Represents an issue with a list of scans. The error is considered resolved when the file with the document
scan changes.
type
The section of the user’s Telegram Passport which has the issue, one of “utility_bill”,
“bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration”.
Type str
file_hash
Base64-encoded file hash.
Type str
message
Error message.

198 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

Type str

Parameters
• type (str) – The section of the user’s Telegram Passport which has the issue, one of
“utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “tempo-
rary_registration”.
• file_hashes (List[str]) – List of base64-encoded file hashes.
• message (str) – Error message.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](type, field_name, data_hash, message,


**kwargs)
Bases: [Link]
Represents an issue in one of the data fields that was provided by the user. The error is considered resolved
when the field’s value changes.
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

Parameters
• type (str) – The section of the user’s Telegram Passport which has the error, one of
“personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”,
“address”.
• field_name (str) – Name of the data field which has the error.
• data_hash (str) – Base64-encoded data hash.
• message (str) – Error message.
• **kwargs (dict) – Arbitrary keyword arguments.

[Link]

class [Link](secure_data, nonce, bot=None, **kwargs)


Bases: [Link]
secure_data
Credentials for encrypted data
Type [Link]

3.2. telegram package 199


Python Telegram Bot Documentation, Release 12.1.1

nonce
Bot-specified nonce
Type str

[Link]

class [Link](data_hash, secret, **kwargs)


Bases: [Link]._CredentialsBase
These credentials can be used to decrypt encrypted data from the data field in EncryptedPassportData.
Parameters
• data_hash (str) – Checksum of encrypted data
• secret (str) – Secret of encrypted data
hash
Checksum of encrypted data
Type str
secret
Secret of encrypted data
Type str

[Link]

class [Link](personal_details=None, passport=None, internal_passport=None,


driver_license=None, identity_card=None, address=None, util-
ity_bill=None, bank_statement=None, rental_agreement=None,
passport_registration=None, temporary_registration=None,
bot=None, **kwargs)
Bases: [Link]
This object represents the credentials that were used to decrypt the encrypted data. All fields are optional
and depend on fields that were requested.
personal_details
Credentials for encrypted personal details.
Type [Link], optional
passport
Credentials for encrypted passport.
Type [Link], optional
internal_passport
Credentials for encrypted internal passport.
Type [Link], optional
driver_license
Credentials for encrypted driver license.
Type [Link], optional
identity_card
Credentials for encrypted ID card
Type [Link], optional
address
Credentials for encrypted residential address.

200 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

Type [Link], optional


utility_bill
Credentials for encrypted utility bill.
Type [Link], optional
bank_statement
Credentials for encrypted bank statement.
Type [Link], optional
rental_agreement
Credentials for encrypted rental agreement.
Type [Link], optional
passport_registration
Credentials for encrypted registration from internal passport.
Type [Link], optional
temporary_registration
Credentials for encrypted temporary registration.
Type [Link], optional

[Link]

class [Link](file_hash, secret, **kwargs)


Bases: [Link]._CredentialsBase
These credentials can be used to decrypt encrypted files from the front_side, reverse_side, selfie and files
fields in EncryptedPassportData.
Parameters
• file_hash (str) – Checksum of encrypted file
• secret (str) – Secret of encrypted file
hash
Checksum of encrypted file
Type str
secret
Secret of encrypted file
Type str

[Link]

class [Link](document_no, expiry_date, bot=None, **kwargs)


Bases: [Link]
This object represents the data of an identity document.
document_no
Document number.
Type str
expiry_date
Optional. Date of expiry, in [Link] format.
Type str

3.2. telegram package 201


Python Telegram Bot Documentation, Release 12.1.1

[Link]

class [Link](first_name, last_name, birth_date, gender, country_code,


residence_country_code, first_name_native=None,
last_name_native=None, middle_name=None, mid-
dle_name_native=None, bot=None, **kwargs)
Bases: [Link]
This object represents personal details.
first_name
First Name.
Type str
middle_name
Optional. First Name.
Type str
last_name
Last Name.
Type str
birth_date
Date of birth in [Link] format.
Type str
gender
Gender, male or female.
Type str
country_code
Citizenship (ISO 3166-1 alpha-2 country code).
Type str
residence_country_code
Country of residence (ISO 3166-1 alpha-2 country code).
Type str
first_name
First Name in the language of the user’s country of residence.
Type str
middle_name
Optional. Middle Name in the language of the user’s country of residence.
Type str
last_name
Last Name in the language of the user’s country of residence.
Type str

[Link]

class [Link](street_line1, street_line2, city, state, country_code,


post_code, bot=None, **kwargs)
Bases: [Link]
This object represents a residential address.

202 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

street_line1
First line for the address.
Type str
street_line2
Optional. Second line for the address.
Type str
city
City.
Type str
state
Optional. State.
Type str
country_code
ISO 3166-1 alpha-2 country code.
Type str
post_code
Address post code.
Type str

[Link]

class [Link](data, credentials, bot=None, **kwargs)


Bases: [Link]
Contains information about Telegram Passport data shared with the bot by the user.
data
Array with encrypted information about documents and other Telegram Passport elements that was
shared with the bot.
Type List[[Link]]
credentials
Encrypted credentials.
Type [Link]
bot
The Bot to use for instance methods.
Type [Link], optional

Parameters
• data (List[[Link]]) – Array with encrypted
information about documents and other Telegram Passport elements that was shared
with the bot.
• credentials (str) – Encrypted credentials.
• bot ([Link], optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.

3.2. telegram package 203


Python Telegram Bot Documentation, Release 12.1.1

Note: To be able to decrypt this object, you must pass your private_key to either [Link]
or [Link]. Decrypted data is then found in decrypted_data and the payload can be found
in decrypted_credentials’s attribute [Link].

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.

Raises [Link] – Decryption failed. Usually due to


bad private/public key but can also suggest malformed/tampered data.
Type [Link]

decrypted_data
Lazily decrypt and return information about documents and other Telegram Passport elements
which were shared with the bot.

Raises [Link] – Decryption failed. Usually due to


bad private/public key but can also suggest malformed/tampered data.
Type List[[Link]]

[Link]

class [Link](file_id, file_date, file_size=None, bot=None, credentials=None,


**kwargs)
Bases: [Link]
This object represents a file uploaded to Telegram Passport. Currently all Telegram Passport files are in
JPEG format when decrypted and don’t exceed 10MB.
file_id
Unique identifier for this file.
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 [Link]

Parameters
• file_id (str) – Unique identifier for this file.
• file_size (int) – File size.
• file_date (int) – Unix time when the file was uploaded.
• bot ([Link], optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.

204 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

get_file(timeout=None, **kwargs)
Wrapper over [Link].get_file. Will automatically assign the correct creden-
tials to the returned [Link] if originating from [Link].
decrypted_data.
Parameters
• timeout (int | float, optional) – If this value is specified, use it as the read
timeout from the server (instead of the one specified during creation of the connection
pool).
• **kwargs (dict) – Arbitrary keyword arguments.
Returns [Link]
Raises [Link]

[Link]

class [Link](type, data=None, phone_number=None,


email=None, files=None, front_side=None,
reverse_side=None, selfie=None, transla-
tion=None, hash=None, bot=None, creden-
tials=None, **kwargs)
Bases: [Link]
Contains information about documents or other Telegram Passport elements shared with the bot by the user.
The data has been automatically decrypted by python-telegram-bot.
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 [Link] or [Link] or telegram.
ResidentialAddress or 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[[Link]]
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 [Link]

3.2. telegram package 205


Python Telegram Bot Documentation, Release 12.1.1

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 [Link]
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 [Link]
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[[Link]]
hash
Base64-encoded element hash for using in [Link].
Type str
bot
Optional. The Bot to use for instance methods.
Type [Link]

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 ([Link] or [Link] or
[Link] or str, optional) – Decrypted or encrypted
data, available for “personal_details”, “passport”, “driver_license”, “identity_card”,
“identity_passport” and “address” types.
• phone_number (str, optional) – User’s verified phone number, available only for
“phone_number” type.
• email (str, optional) – User’s verified email address, available only for “email” type.
• files (List[[Link]], optional) – Array of en-
crypted/decrypted files with documents provided by the user, available for “util-
ity_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “tempo-
rary_registration” types.
• front_side ([Link], 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”.
• reverse_side ([Link], optional) – Encrypted/decrypted
file with the reverse side of the document, provided by the user. Available for
“driver_license” and “identity_card”.
• selfie ([Link], optional) – Encrypted/decrypted file with
the selfie of the user holding a document, provided by the user; available for “pass-
port”, “driver_license”, “identity_card” and “internal_passport”.
• translation (List[[Link]], optional) – Array of en-
crypted/decrypted files with translated versions of documents provided by the
user. Available if requested for “passport”, “driver_license”, “identity_card”,

206 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

“internal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “pass-


port_registration” and “temporary_registration” types.
• hash (str) – Base64-encoded element hash for using in telegram.
PassportElementErrorUnspecified.
• bot ([Link], optional) – The Bot to use for instance methods.
• **kwargs (dict) – Arbitrary keyword arguments.

Note: This object is decrypted only when originating from [Link].


decrypted_data.

[Link]

class [Link](data, hash, secret, bot=None, **kwargs)


Bases: [Link]
Contains data required for decrypting and authenticating EncryptedPassportElement. See the Telegram
Passport Documentation for a complete description of the data decryption and authentication processes.
data
Decrypted data with unique user’s nonce, data hashes and secrets used for EncryptedPassportElement
decryption and authentication or base64 encrypted data.
Type [Link] or str
hash
Base64-encoded data hash for data authentication.
Type str
secret
Decrypted or encrypted secret used for decryption.
Type str

Parameters
• data ([Link] 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.

Note: This object is decrypted only when originating from [Link].


decrypted_credentials.

decrypted_data
Lazily decrypt and return credentials data. This object also contains the user specified nonce as
decrypted_data.nonce.

Raises [Link] – Decryption failed. Usually due to


bad private/public key but can also suggest malformed/tampered data.
Type [Link]

3.2. telegram package 207


Python Telegram Bot Documentation, Release 12.1.1

decrypted_secret
Lazily decrypt and return secret.
Raises [Link] – Decryption failed. Usually due to
bad private/public key but can also suggest malformed/tampered data.
Type str

3.3 [Link] package

3.3.1 [Link] Module

This module contains helper functions.


[Link].create_deep_linked_url(bot_username, payload=None,
group=False)
Creates a deep-linked URL for this bot_username with the specified payload. See [Link]
[Link]/bots#deep-linking to learn more.
The payload may consist of the following characters: A-Z, a-z, 0-9, _, -

Note: Works well in conjunction with CommandHandler("start", callback, filters =


[Link]('payload'))

Examples
create_deep_linked_url(bot.get_me().username, "some-params")

Parameters
• bot_username (str) – The username to link to
• payload (str, optional) – Parameters to encode in the created URL
• group (bool, optional) – If True the user is prompted to select a group to add the bot
to. If False, opens a one-on-one conversation with the bot. Defaults to False.
Returns An URL to start the bot with specific parameters
Return type str

[Link].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
[Link].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
[Link].effective_message_type(entity)
Extracts the type of message as a string identifier from a [Link] or a [Link].

208 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

Parameters entity (Update | Message) –


Returns One of Message.MESSAGE_TYPES
Return type str
[Link].enocde_conversations_to_json(conversations)
Helper method to encode a conversations dict (that uses tuples as keys) to a JSON-serializable way. Use
_decode_conversations_from_json to decode.
Parameters conversations (dict) – The conversations dict to transofrm to JSON.
Returns The JSON-serialized conversations dict
Return type str
[Link].escape_markdown(text)
Helper function to escape telegram markup symbols.
[Link].from_timestamp(unixtime)
Parameters unixtime (int) –
Returns
Return type [Link]
[Link].get_signal_name(signum)
Returns the signal name of the given signal number.
[Link].mention_html(user_id, name)
Parameters
• user_id (int) –
• name (str) –
Returns The inline mention for the user as html.
Return type str
[Link].mention_markdown(user_id, name)
Parameters
• user_id (int) –
• name (str) –
Returns The inline mention for the user as markdown.
Return type str
[Link].to_timestamp(dt_obj)
Parameters dt_obj ([Link]) –
Returns
Return type int

3.3.2 [Link]

class [Link](pooled_function, args, kwargs)


Bases: object
A simple Promise implementation for use with the run_async decorator, DelayQueue etc.
Parameters
• pooled_function (callable) – The callable that will be called concurrently.

3.3. [Link] package 209


Python Telegram Bot Documentation, Release 12.1.1

• args (list | tuple) – Positional arguments for pooled_function.


• kwargs (dict) – Keyword arguments for pooled_function.
pooled_function
The callable that will be called concurrently.
Type callable
args
Positional arguments for pooled_function.
Type list | tuple
kwargs
Keyword arguments for pooled_function.
Type dict
done
Is set when the result is available.
Type [Link]
exception
The exception raised by pooled_function or None if no exception has been raised (yet).
result(timeout=None)
Return the result of the Promise.
Parameters timeout (float, optional) – Maximum time in seconds to wait for the result
to be calculated. None means indefinite. Default is None.
Returns Returns the return value of pooled_function or None if the timeout ex-
pires.
Raises Any exception raised by pooled_function.
run()
Calls the pooled_function callable.

3.3.3 [Link]

class [Link](con_pool_size=1, proxy_url=None, url-


lib3_proxy_kwargs=None, connect_timeout=5.0,
read_timeout=5.0)
Bases: object
Helper class for python-telegram-bot which provides methods to perform POST & GET towards telegram
servers.
Parameters
• con_pool_size (int) – Number of connections to keep in the connection pool.
• proxy_url (str) – The URL to the proxy server. For example:
[Link]
• urllib3_proxy_kwargs (dict) – Arbitrary arguments passed as-is to url-
[Link]. This value will be ignored if proxy_url is not set.
• connect_timeout (int|float) – The maximum amount of time (in seconds) to
wait for a connection attempt to a server to succeed. None will set an infinite timeout
for connection attempts. (default: 5.)
• read_timeout (int|float) – The maximum amount of time (in seconds) to wait
between consecutive read operations for a response from the server. None will set an

210 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

infinite timeout. This value is usually overridden by the various [Link] meth-
ods. (default: 5.)
con_pool_size
The size of the connection pool used.
download(url, filename, timeout=None)
Download a file by its URL.
Parameters
• url (str) – The web location we want to retrieve.
• timeout – 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).
get(url, timeout=None)
Request an 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).
Returns A JSON object.
post(url, data, timeout=None)
Request an URL.
Parameters
• url (str) – The web location we want to retrieve.
• data (dict[str, str|int]) – A dict of key/value pairs. Note: On py2.7 value
is unicode.
• 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).
Returns A JSON object.
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).

3.4 Changelog

3.4.1 Changelog

Version 12.1.1

Released 2019-09-18
Hot fix release
Fixed regression in the vendored urllib3 (#1517).

3.4. Changelog 211


Python Telegram Bot Documentation, Release 12.1.1

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 [Link] for a detailed guide on how to migrate from version 11 to version
12.

Context based callbacks (#1100)

• Use of pass_ in handlers is deprecated.


• Instead use use_context=True on Updater or Dispatcher and change callback from (bot, update,
others. . . ) to (update, context).
• This also applies to error handlers Dispatcher.add_error_handler and JobQueue jobs (change
(bot, job) to (context) here).
• For users with custom handlers subclassing Handler, this is mostly backwards compatible, but to use the
new context based callbacks you need to implement the new collect_additional_context method.
• Passing bot to JobQueue.__init__ is deprecated. Use JobQueue.set_dispatcher with a dispatcher in-
stead.

212 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

• Dispatcher makes sure to use a single CallbackContext for a entire update. This means that if an update is
handled by multiple handlers (by using the group argument), you can add custom arguments to the Callback-
Context in a lower group handler and use it in higher group handler. NOTE: Never use with @run_async,
see docs for more info. (#1283)
• If you have custom handlers they will need to be updated to support the changes in this release.
• Update all examples to use context based callbacks.

Persistence (#1017)

• Added PicklePersistence and DictPersistence for adding persistence to your bots.


• BasePersistence can be subclassed for all your persistence needs.
• Add a new example that shows a persistent ConversationHandler bot

Handler overhaul (#1114)

• 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 “!”).

Filter overhaul (#1221)

• 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

• Remove run_async_timeout and timed_out_behavior arguments (#1344)


• Replace with WAITING constant and behavior from states (#1344)
• Only emit one warning for multiple CallbackQueryHandlers in a ConversationHandler (#1319)
• Use [Link] for ConversationHandler warnings (#1343)
• Fix unresolvable promises (#1270)

Bug fixes & improvements

• Handlers should be faster due to deduped logic.


• Avoid compiling compiled regex in regex filter. (#1314)
• Add missing left_chat_member to Message.MESSAGE_TYPES (#1336)
• Make custom timeouts actually work properly (#1330)
• Add convenience classmethods (from_button, from_row and from_column) to InlineKeyboardMarkup

3.4. Changelog 213


Python Telegram Bot Documentation, Release 12.1.1

• Small typo fix in [Link] (#1306)


• Add Conflict error (HTTP error code 409) (#1154)
• Change MAX_CAPTION_LENGTH to 1024 (#1262)
• Remove some unnecessary clauses (#1247, #1239)
• Allow filenames without dots in them when sending files (#1228)
• Fix uploading files with unicode filenames (#1214)
• Replace [Link] with Tornado (#1191)
• Allow SOCKSConnection to parse username and password from URL (#1211)
• Fix for arguments in passport/[Link] (#1213)
• Improve message entity parsing by adding text_mention (#1206)
• Documentation fixes (#1348, #1397, #1436)
• Merged filters short-circuit (#1350)
• Fix webhook listen with tornado (#1383)
• Call task_done() on update queue after update processing finished (#1428)
• Fix send_location() - latitude may be 0 (#1437)
• Make MessageEntity objects comparable (#1465)
• Add prefix to thread names (#1358)

Buf fixes since v12.0.0b1

• Fix setting bot on ShippingQuery (#1355)


• Fix _trigger_timeout() missing 1 required positional argument: ‘job’ (#1367)
• Add missing [Link] check in PrefixHandler check_update (#1375)
• Make updates persist even on DispatcherHandlerStop (#1463)
• Dispatcher force updating persistence object’s chat data attribute(#1462)

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

214 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

• 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 [Link] 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 [Link]. (#1172)
Non Bot API 4.0 changes:
• Minor integer comparison fix (#1147)

3.4. Changelog 215


Python Telegram Bot Documentation, Release 12.1.1

• Fix [Link] failing on non-text message (#1158)


• Fix ProcessLookupError if process finishes before we kill it (#1126)
• Add [Link] 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 [Link] (#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 [Link] (#1028)
• Filters for Category and file types (#1046)
• Added video note filter (#1067)
Fixes:
• Fix in [Link] (#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)

216 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

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 [Link].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)
• Add .send_*() methods to User and Chat (PR #963)
• Get jobs by name (PR #1011)
• Add Message caption html/markdown methods (PR #1013)
• File.download_as_bytearray - new method to get a d/led file as bytearray (PR #1019)
• [Link](): Now returns a meaningful return value (PR #1019)
• Added conversation timeout in ConversationHandler (PR #895)
Changes
• Store bot in PreCheckoutQuery (PR #953)
• Updater: Issue INFO log upon received signal (PR #951)
• JobQueue: Thread safety fixes (PR #977)
• WebhookHandler: Fix exception thrown during error handling (PR #985)
• Explicitly check update.effective_chat in ConversationHandler.check_update (PR #959)
• Updater: Better handling of timeouts during get_updates (PR #1007)
• Remove unnecessary to_dict() (PR #834)
• CommandHandler - ignore strings in entities and “/” followed by whitespace (PR #1020)
• Documentation & style fixes (PR #942, PR #956, PR #962, PR #980, PR #983)

Version 9.0.0

Released 2017-12-08
Breaking changes (possibly)
• Drop support for python 3.3 (PR #930)
New Features

3.4. Changelog 217


Python Telegram Bot Documentation, Release 12.1.1

• 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.

218 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

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 [Link].
• 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

3.4. Changelog 219


Python Telegram Bot Documentation, Release 12.1.1

• Fix Message.text_html and Message.text_markdown for messages with emoji


2017-05-19
Released 6.0.0
• Add support for Bot API 2.3.1
• Add support for deleteMessage API method
• New, simpler API for JobQueue - [Link]
• Download files into file-like objects - [Link]
459
• Use vendor urllib3 to address issues with timeouts - The default timeout for messages is now 5 seconds.
For sending media, the default timeout is now 20 seconds.
• String attributes that are not set are now None by default, instead of empty strings
• Add text_markdown and text_html properties to Message - [Link]
python-telegram-bot/python-telegram-bot/pull/507
• Add support for Socks5 proxy - [Link]
• Add support for filters in CommandHandler - [Link]
python-telegram-bot/pull/536
• Add the ability to invert (not) filters - [Link]
• Add [Link] and [Link]
• Compatibility with GAE via [Link] package - [Link]
python-telegram-bot/pull/583
• Add equality rich comparision operators to telegram objects - [Link]
python-telegram-bot/pull/604
• Several bugfixes and other improvements
• Remove some deprecated code
2017-04-17
Released 5.3.1
• Hotfix release due to bug introduced by urllib3 version 1.21
2016-12-11
Released 5.3
• Implement API changes of November 21st (Bot API 2.3)
• JobQueue now supports [Link] in addition to seconds
• JobQueue now supports running jobs only on certain days
• New [Link] filter
• Bugfix for Message.edit_reply_markup
• Other bugfixes
2016-10-25
Released 5.2
• Implement API changes of October 3rd (games update)
• Add Message.edit_* methods
• Filters for the MessageHandler can now be combined using bitwise operators (& and |)
• Add a way to save user- and chat-related data temporarily

220 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

• Other bugfixes and improvements


2016-09-24
Released 5.1
• Drop Python 2.6 support
• Deprecate [Link]
• Use ujson if available
• Add instance methods to Message, Chat, User, InlineQuery and CallbackQuery
• RegEx filtering for CallbackQueryHandler and InlineQueryHandler
• New MessageHandler filters: forwarded and entity
• Add Message.get_entity to correctly handle UTF-16 codepoints and MessageEntity offsets
• Fix bug in ConversationHandler when first handler ends the conversation
• Allow multiple Dispatcher instances
• Add ChatMigrated Exception
• Properly split and handle arguments in CommandHandler
2016-07-15
Released 5.0
• Rework JobQueue
• Introduce ConversationHandler
• Introduce [Link] - [Link]
342
2016-07-12
Released 4.3.4
• Fix proxy support with urllib3 when proxy requires auth
2016-07-08
Released 4.3.3
• Fix proxy support with urllib3
2016-07-04
Released 4.3.2
• Fix: Use timeout parameter in all API methods
2016-06-29
Released 4.3.1
• Update wrong requirement: urllib3>=1.10
2016-06-28
Released 4.3
• Use [Link] for connection re-use
• Rewrite run_async decorator to re-use threads
• New requirements: urllib3 and certifi
2016-06-10
Released 4.2.1

3.4. Changelog 221


Python Telegram Bot Documentation, Release 12.1.1

• Fix CallbackQuery.to_dict() bug (thanks to @jlmadurga)


• Fix editMessageText exception when receiving a CallbackQuery
2016-05-28
Released 4.2
• Implement Bot API 2.1
• Move botan module to [Link]
• New exception type: BadRequest
2016-05-22
Released 4.1.2
• Fix MessageEntity decoding with Bot API 2.1 changes
2016-05-16
Released 4.1.1
• Fix deprecation warning in Dispatcher
2016-05-15
Released 4.1
• Implement API changes from May 6, 2016
• Fix bug when start_polling with clean=True
• Methods now have snake_case equivalent, for example [Link].send_message is the same as
[Link]
2016-05-01
Released 4.0.3
• Add missing attribute location to InlineQuery
2016-04-29
Released 4.0.2
• Bugfixes
• KeyboardReplyMarkup now accepts str again
2016-04-27
Released 4.0.1
• Implement Bot API 2.0
• Almost complete recode of Dispatcher
• Please read the Transition Guide to 4.0
• Changes from 4.0rc1
– The syntax of filters for MessageHandler (upper/lower cases)
– Handler groups are now identified by int only, and ordered
• Note: v4.0 has been skipped due to a PyPI accident
2016-04-22
Released 4.0rc1
• Implement Bot API 2.0
• Almost complete recode of Dispatcher

222 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

• Please read the Transistion Guide to 4.0


2016-03-22
Released 3.4
• Move Updater, Dispatcher and JobQueue to new [Link] submodule (thanks to @rahiel)
• Add disable_notification parameter (thanks to @aidarbiktimirov)
• 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 [Link] (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)

3.4. Changelog 223


Python Telegram Bot Documentation, Release 12.1.1

2015-12-08
Released 3.0.0
• Introducing the Updater and Dispatcher classes
2015-11-11
Released 2.9.2
• Error handling on request timeouts has been improved
2015-11-10
Released 2.9.1
• Add parameter network_delay to [Link] for slow connections
2015-11-10
Released 2.9
• Emoji class now uses bytes_to_native_str from future 3rd party lib
• Make user_from optional to work with channels
• Raise exception if Telegram times out on long-polling
Special thanks to @jh0ker for all hard work
2015-10-08
Released 2.8.7
• Type as optional for GroupChat class
2015-10-08
Released 2.8.6
• Adds type to User and GroupChat classes (pre-release Telegram feature)
2015-09-24
Released 2.8.5
• Handles HTTP Bad Gateway (503) errors on request
• Fixes regression on Audio and Document for unicode fields
2015-09-20
Released 2.8.4
• getFile and [Link] is now fully supported
2015-09-10
Released 2.8.3
• Moved Bot._requestURL to its own class ([Link])
• Much better, such wow, Telegram Objects tests
• Add consistency for str properties on Telegram Objects
• Better design to test if chat_id is invalid
• Add ability to set custom filename on [Link](..,filename='')
• Fix Sticker as InputFile
• Send JSON requests over urlencoded post data
• Markdown support for [Link](..., parse_mode=[Link])
• Refactor of TelegramError class (no more handling IOError or URLError)

224 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

2015-09-05
Released 2.8.2
• Fix regression on Telegram ReplyMarkup
• Add certificate to is_inputfile method
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
• [Link] and Message.forward_date are now datetime objects
2015-08-12
Released 2.5.3
• [Link] now supports to be unpickled
2015-08-11
Released 2.5.2
• New changes from Telegram Bot API have been applied
• [Link] now supports to be pickled
• Return empty str instead None when [Link] is empty

3.4. Changelog 225


Python Telegram Bot Documentation, Release 12.1.1

2015-08-10
Released 2.5.1
• Moved from GPLv2 to LGPLv3
2015-08-09
Released 2.5
• Fixes logging calls in API
2015-08-08
Released 2.4
• Fixes Emoji class for Python 3
• PEP8 improvements
2015-08-08
Released 2.3
• Fixes ForceReply class
• Remove [Link] from library
2015-07-25
Released 2.2
• Allows debug=True when initializing [Link]
2015-07-20
Released 2.1
• Fix to_dict for Document and Video
2015-07-19
Released 2.0
• Fixes bugs
• Improves __str__ over to_json()
• Creates abstract class TelegramObject
2015-07-15
Released 1.9
• Python 3 officially supported
• PEP8 improvements
2015-07-12
Released 1.8
• Fixes crash when replying an unicode text message (special thanks to JRoot3D)
2015-07-11
Released 1.7
• Fixes crash when username is not defined on chat (special thanks to JRoot3D)
2015-07-10
Released 1.6
• Improvements for GAE support

226 Chapter 3. Reference


Python Telegram Bot Documentation, Release 12.1.1

2015-07-10
Released 1.5
• Fixes randomly unicode issues when using InputFile
2015-07-10
Released 1.4
• requests lib is no longer required
• Google App Engine (GAE) is supported
2015-07-10
Released 1.3
• Added support to setWebhook (special thanks to macrojames)
2015-07-09
Released 1.2
• CustomKeyboard classes now available
• Emojis available
• PEP8 improvements
2015-07-08
Released 1.1
• PyPi package now available
2015-07-08
Released 1.0
• Initial checkin of python-telegram-bot

3.4. Changelog 227


Python Telegram Bot Documentation, Release 12.1.1

228 Chapter 3. Reference


Python Module Index

t
[Link], 108
[Link], 111
[Link], 11
[Link], 208

229
Python Telegram Bot Documentation, Release 12.1.1

230 Python Module Index


Index

Symbols answer() ([Link] method), 192


__call__() ([Link] method), 24 answer_callback_query() ([Link]
__call__() ([Link] method), method), 59
23 answer_inline_query() ([Link] method),
__init__() ([Link] method), 24 60
__init__() ([Link] method), answer_pre_checkout_query() ([Link]
23 method), 61
__weakref__ ([Link] at- answer_shipping_query() ([Link]
tribute), 23 method), 61
_queue ([Link] attribute), 20 answerCallbackQuery() ([Link] method),
59
A answerInlineQuery() ([Link] method), 59
add_error_handler() ([Link] answerPreCheckoutQuery() ([Link]
method), 8 method), 59
add_handler() ([Link] method), answerShippingQuery() ([Link] method),
9 59
add_sticker_to_set() ([Link] method), apk ([Link] attribute), 12, 13
59 application ([Link] attribute),
address ([Link] at- 12, 13
tribute), 180 args ([Link] attribute), 25
address ([Link] at- args ([Link] attribute), 210
tribute), 186 attach ([Link] attribute), 116
address ([Link] attribute), 200 Audio (class in telegram), 57
address ([Link] attribute), 150 audio ([Link] attribute), 11–13
addStickerToSet() ([Link] method), 59 audio ([Link] attribute), 125
ADMINISTRATOR ([Link] attribute), audio_duration (tele-
106 [Link] attribute),
all ([Link] attribute), 11 161
ALL_TYPES ([Link] attribute), 138 audio_file_id (tele-
allow_edited ([Link] at- [Link] at-
tribute), 34 tribute), 162
allow_reentry ([Link] audio_url ([Link]
attribute), 32 attribute), 161
allowed_updates ([Link] at- author_signature ([Link] attribute),
tribute), 154 127
amount ([Link] attribute), 188
Animation (class in telegram), 56
B
animation ([Link] attribute), 11 BadRequest, 111
animation ([Link] attribute), 195 bank_statement ([Link] attribute),
animation ([Link] attribute), 125 201
answer() ([Link] method), 96 BaseFilter (class in [Link]), 17
answer() ([Link] method), 158 BasePersistence (class in [Link]), 51
answer() ([Link] method), big_file_id ([Link] attribute), 108
194

231
Python Telegram Bot Documentation, Release 12.1.1

birth_date ([Link] attribute), callback_query ([Link] attribute), 145


202 CallbackContext (class in [Link]), 25
BOLD ([Link] attribute), 138 CallbackGame (class in telegram), 196
Bot (class in telegram), 58 CallbackQuery (class in telegram), 95
bot ([Link] attribute), 56 CallbackQueryHandler (class in [Link]),
bot ([Link] attribute), 58 28
bot ([Link] attribute), 110 can_add_web_page_previews (tele-
bot ([Link] attribute), [Link] attribute), 105
206 can_add_web_page_previews (tele-
bot ([Link] attribute), 26 [Link] attribute), 107
bot ([Link] attribute), 8 can_be_edited ([Link] attribute),
bot ([Link] attribute), 20 104
bot ([Link] attribute), 5 can_change_info ([Link] at-
bot ([Link] attribute), 127 tribute), 104
bot ([Link] attribute), 203 can_change_info ([Link] at-
bot ([Link] attribute), 204 tribute), 107
bot ([Link] attribute), 139 can_delete_messages ([Link]
bot ([Link] attribute), 193 attribute), 104
bot ([Link] attribute), 192 can_edit_messages ([Link] at-
bot ([Link] attribute), 155 tribute), 104
bot ([Link] attribute), 147 can_invite_users ([Link] at-
bot ([Link] attribute), 151 tribute), 104
bot ([Link] attribute), 152 can_invite_users ([Link] at-
bot ([Link] attribute), 153 tribute), 107
BOT_COMMAND ([Link] attribute), can_pin_messages ([Link] at-
138 tribute), 104
bot_username ([Link] attribute), 123 can_pin_messages ([Link] at-
burst_limit ([Link] attribute), tribute), 107
23 can_post_messages ([Link] at-
tribute), 104
C can_promote_members ([Link]
callback ([Link] at- attribute), 104
tribute), 28 can_restrict_members ([Link]
callback ([Link] attribute), 104
attribute), 30 can_send_media_messages (tele-
callback ([Link] attribute), [Link] attribute), 105
34 can_send_media_messages (tele-
callback ([Link] attribute), 26 [Link] attribute), 107
callback ([Link] at- can_send_messages ([Link] at-
tribute), 36 tribute), 105
callback ([Link] attribute), 19 can_send_messages ([Link]
callback ([Link] attribute), attribute), 106
38 can_send_other_messages (tele-
callback ([Link] [Link] attribute), 105
attribute), 40 can_send_other_messages (tele-
callback ([Link] attribute), 42 [Link] attribute), 107
callback ([Link] attribute), 44 can_send_polls ([Link] attribute),
callback ([Link] at- 105
tribute), 46 can_send_polls ([Link] at-
callback ([Link] at- tribute), 107
tribute), 47 can_set_sticker_set ([Link] attribute),
callback ([Link] at- 99
tribute), 49 caption ([Link] at-
callback ([Link] attribute), 50 tribute), 161
callback_data ([Link] caption ([Link]
attribute), 114 attribute), 162
callback_game ([Link] caption ([Link]
attribute), 114 attribute), 163

232 Index
Python Telegram Bot Documentation, Release 12.1.1

caption ([Link] at- 55


tribute), 164 chat_data ([Link] attribute), 8
caption (telegram.InlineQueryResultCachedMpeg4Gif chat_data_json ([Link] at-
attribute), 165 tribute), 55
caption ([Link] chat_id ([Link] attribute), 130
attribute), 166 chat_instance ([Link] at-
caption ([Link] tribute), 96
attribute), 168 ChatAction (class in telegram), 103
caption ([Link] ChatMember (class in telegram), 104
attribute), 170 ChatMigrated, 111
caption ([Link] at- ChatPermissions (class in telegram), 106
tribute), 172 ChatPhoto (class in telegram), 108
caption ([Link] attribute), check_update() (tele-
174 [Link] method),
caption (telegram.InlineQueryResultMpeg4Gif at- 29
tribute), 177 check_update() (tele-
caption ([Link] at- [Link]
tribute), 179 method), 31
caption ([Link] at- check_update() ([Link]
tribute), 182 method), 36
caption ([Link] at- check_update() (tele-
tribute), 183 [Link] method),
caption ([Link] attribute), 33
117 check_update() ([Link] method),
caption ([Link] attribute), 118 27
caption ([Link] attribute), check_update() (tele-
119 [Link] method),
caption ([Link] attribute), 120 38
caption ([Link] attribute), 121 check_update() ([Link]
caption ([Link] attribute), 126 method), 40
caption_entities ([Link] attribute), check_update() (tele-
125 [Link]
caption_html ([Link] attribute), 130 method), 41
caption_html_urled ([Link] at- check_update() ([Link]
tribute), 130 method), 44
caption_markdown ([Link] attribute), check_update() (tele-
130 [Link] method),
caption_markdown_urled ([Link] 47
attribute), 130 check_update() (tele-
CASHTAG ([Link] attribute), 138 [Link] method),
category ([Link] attribute), 12 48
CHANNEL ([Link] attribute), 99 check_update() (tele-
channel_chat_created ([Link] at- [Link] method),
tribute), 126 50
channel_post ([Link] at- check_update() ([Link]
tribute), 16 method), 51
channel_post ([Link] attribute), 145 CHIN ([Link] attribute), 157
channel_post_updates (tele- chosen_inline_result ([Link]
[Link] attribute), 39 attribute), 145
channel_posts ([Link] at- ChosenInlineResult (class in telegram), 187
tribute), 16 ChosenInlineResultHandler (class in tele-
Chat (class in telegram), 98 [Link]), 30
chat ([Link] attribute), 124 city ([Link] attribute), 203
chat_created ([Link] at- city ([Link] attribute), 189
tribute), 15 CODE ([Link] attribute), 138
chat_data ([Link] attribute), collect_additional_context() (tele-
25 [Link] method),
chat_data ([Link] attribute), 30

Index 233
Python Telegram Bot Documentation, Release 12.1.1

collect_additional_context() (tele- tribute), 55


[Link] method), 36 conversations_json (tele-
collect_additional_context() (tele- [Link] attribute), 55
[Link] method), 27 country_code ([Link] attribute),
collect_additional_context() (tele- 202
[Link] method), country_code ([Link] at-
38 tribute), 203
collect_additional_context() (tele- country_code ([Link] at-
[Link] method), 40 tribute), 189
collect_additional_context() (tele- create_deep_linked_url() (in module tele-
[Link] method), 44 [Link]), 208
collect_additional_context() (tele- create_new_sticker_set() ([Link]
[Link] method), method), 62
48 createNewStickerSet() ([Link] method),
collect_additional_context() (tele- 62
[Link] method), CREATOR ([Link] attribute), 106
50 Credentials (class in telegram), 199
collect_optional_args() (tele- credentials ([Link] attribute),
[Link] method), 203
30 currency ([Link] attribute), 188
collect_optional_args() (tele- currency ([Link] attribute),
[Link] method), 36 193
collect_optional_args() (tele- currency ([Link] attribute),
[Link] method), 27 191
collect_optional_args() (tele-
[Link] method), D
38 data ([Link] attribute), 96
collect_optional_args() (tele- data ([Link] attribute), 207
[Link] method), 45 data ([Link] attribute),
collect_optional_args() (tele- 205
[Link] method), data ([Link] attribute), 203
48 data_filter ([Link] at-
collect_optional_args() (tele- tribute), 18
[Link] method), data_hash ([Link]
50 attribute), 199
command ([Link] attribute), DataCredentials (class in telegram), 200
34 date ([Link] attribute), 124
command ([Link] attribute), 11 days ([Link] attribute), 19
command ([Link] attribute), 42 de_json() ([Link] class method), 146
command ([Link] at- de_json() ([Link] class method), 147
tribute), 47 de_list() ([Link] class method), 147
CommandHandler (class in [Link]), 34 decode_conversations_from_json() (in
con_pool_size ([Link] at- module [Link]), 208
tribute), 211 decode_user_chat_data_from_json() (in
Conflict, 111 module [Link]), 208
connected_website ([Link] at- decrypted_credentials (tele-
tribute), 127 [Link] attribute), 204
Contact (class in telegram), 109 decrypted_data ([Link]
contact ([Link] attribute), 11 attribute), 207
contact ([Link] attribute), 126 decrypted_data ([Link] at-
contains_masks ([Link] attribute), tribute), 204
156 decrypted_secret (tele-
context ([Link] attribute), 19 [Link] attribute),
conversation_timeout (tele- 207
[Link] attribute), DelayQueue (class in [Link]), 23
32 delete() ([Link] method), 130
ConversationHandler (class in [Link]), 31 delete_chat_photo ([Link]
conversations ([Link] at- attribute), 16

234 Index
Python Telegram Bot Documentation, Release 12.1.1

delete_chat_photo ([Link] at- done ([Link] attribute), 210


tribute), 126 download() ([Link] method), 112
delete_chat_photo() ([Link] method), 63 download() ([Link]
delete_chat_sticker_set() ([Link] method), 211
method), 63 download_as_bytearray() ([Link]
delete_message() ([Link] method), 63 method), 113
delete_sticker_from_set() ([Link] driver_license ([Link] attribute),
method), 64 200
delete_webhook() ([Link] method), 64 duration ([Link] attribute), 56
deleteChatPhoto() ([Link] method), 63 duration ([Link] attribute), 57
deleteChatStickerSet() ([Link] duration ([Link] attribute),
method), 63 117
deleteMessage() ([Link] method), 63 duration ([Link] attribute), 118
deleteStickerFromSet() ([Link] duration ([Link] attribute), 121
method), 63 duration ([Link] attribute), 151
deleteWebhook() ([Link] method), 63 duration ([Link] attribute), 152
description ([Link] attribute), 98 duration ([Link] attribute), 153
description ([Link] attribute), 194
description ([Link] E
attribute), 160 edit_caption() ([Link] method), 130
description (tele- edit_date ([Link] attribute), 125
[Link] edit_media() ([Link] method), 131
attribute), 163 edit_message_caption() ([Link]
description (tele- method), 65
[Link] at- edit_message_caption() (tele-
tribute), 166 [Link] method), 97
description (tele- edit_message_live_location() (tele-
[Link] at- [Link] method), 65
tribute), 168 edit_message_media() ([Link] method),
description (tele- 66
[Link] attribute), edit_message_reply_markup() ([Link]
172 method), 66
description ([Link] at- edit_message_reply_markup() (tele-
tribute), 179 [Link] method), 97
description ([Link] at- edit_message_text() ([Link] method), 67
tribute), 182 edit_message_text() ([Link]
description ([Link] attribute), 188 method), 97
DictPersistence (class in [Link]), 54 edit_reply_markup() ([Link]
disable_web_page_preview (tele- method), 131
[Link] attribute), edit_text() ([Link] method), 131
185 edited_channel_post (tele-
dispatch_error() ([Link] [Link] attribute), 16
method), 9 edited_channel_post ([Link] at-
Dispatcher (class in [Link]), 8 tribute), 145
dispatcher ([Link] attribute), 6 edited_message ([Link]
doc ([Link] attribute), 12, 13 attribute), 16
Document (class in telegram), 110 edited_message ([Link] attribute), 145
document ([Link] attribute), 11 edited_updates ([Link]
document ([Link] attribute), 125 attribute), 39
document_file_id (tele- editMessageCaption() ([Link] method),
[Link] 64
attribute), 163 editMessageLiveLocation() ([Link]
document_no ([Link] attribute), method), 64
201 editMessageMedia() ([Link] method), 65
document_url (tele- editMessageReplyMarkup() ([Link]
[Link] attribute), method), 65
172 editMessageText() ([Link] method), 65
docx ([Link] attribute), 12, 13

Index 235
Python Telegram Bot Documentation, Release 12.1.1

effective_attachment ([Link] at- file_id ([Link] attribute), 112


tribute), 132 file_id ([Link] attribute), 204
effective_chat ([Link] attribute), 146 file_id ([Link] attribute), 139
effective_message ([Link] attribute), file_id ([Link] attribute), 154
146 file_id ([Link] attribute), 150
effective_message_type() (in module tele- file_id ([Link] attribute), 151
[Link]), 208 file_id ([Link] attribute), 152
effective_user ([Link] attribute), 146 file_name ([Link] attribute), 56
email ([Link] file_name ([Link] attribute), 110
at-
tribute), 205 file_path ([Link] attribute), 112
EMAIL ([Link] attribute), 138 file_size ([Link] attribute), 56
email ([Link] attribute), 190 file_size ([Link] attribute), 57
emoji ([Link] attribute), 155 file_size ([Link] attribute), 110
enabled ([Link] attribute), 19 file_size ([Link] attribute), 112
EncryptedCredentials (class in telegram), 207 file_size ([Link] attribute), 204
EncryptedPassportElement (class in tele- file_size ([Link] attribute), 139
gram), 205 file_size ([Link] attribute), 155
END ([Link] attribute), 33
file_size ([Link] attribute), 151
enocde_conversations_to_json() (in mod- file_size ([Link] attribute), 152
ule [Link]), 209 file_size ([Link] attribute), 153
entities ([Link] attribute), 125 FileCredentials (class in telegram), 201
entry_points ([Link] filename ([Link] attribute),
attribute), 32 53
error ([Link] attribute), 25filename ([Link] attribute), 116
error_handlers ([Link] at- files ([Link] at-
tribute), 9 tribute), 205
escape_markdown() (in module filter() ([Link] method), 18
tele-
[Link]), 209 filter() ([Link]
exc_route ([Link] attribute), 24 method), 18
exception ([Link] at- filter() ([Link] method),
tribute), 210 18
exe ([Link] attribute), 12, 13
Filters (class in [Link]), 11
expiry_date ([Link] attribute), filters ([Link] attribute),
201 34
export_chat_invite_link() ([Link]
filters ([Link] attribute), 38
method), 67 filters ([Link] attribute), 42
exportChatInviteLink() ([Link]
Filters.caption_entity (class in tele-
method), 67 [Link]), 11
EYES ([Link] attribute), 157 [Link] (class in [Link]), 11
[Link] (class in [Link]), 14
F [Link] (class in [Link]),
fallbacks ([Link] at- 14
tribute), 32 [Link] (class in [Link]), 15
field_name ([Link] (class in [Link]), 16
attribute), 199 FIND_LOCATION ([Link] attribute),
File (class in telegram), 112 103
file_date ([Link] attribute), 204 first_name ([Link] attribute), 68
file_hash ([Link] at- first_name ([Link] attribute), 98
tribute), 197 first_name ([Link] attribute), 109
file_hash ([Link] at- first_name ([Link] at-
tribute), 198 tribute), 171
file_hash ([Link] first_name ([Link]
attribute), 198 attribute), 186
first_name
file_hash ([Link] ([Link] attribute),
attribute), 197 202
file_id ([Link] attribute), 56 first_name ([Link] attribute), 146
file_id ([Link] attribute), 57 flush() ([Link] method), 52
file_id ([Link] attribute), 110 flush() ([Link] method), 53

236 Index
Python Telegram Bot Documentation, Release 12.1.1

force_reply ([Link] attribute), 113 G


ForceReply (class in telegram), 113 Game (class in telegram), 194
FOREHEAD ([Link] attribute), 157 game ([Link] attribute), 14
forward() ([Link] method), 132 game ([Link] attribute), 125
forward_date ([Link] attribute), 124 game_short_name ([Link]
forward_from ([Link] attribute), 124 attribute), 96
forward_from_chat ([Link] at- game_short_name (tele-
tribute), 124 [Link] attribute),
forward_from_message_id ([Link] 173
attribute), 124 GameHighScore (class in telegram), 196
forward_message() ([Link] method), 68 gender ([Link] attribute), 202
forward_sender_name ([Link] at- get() ([Link] method), 211
tribute), 127 get_administrators() ([Link] method),
forward_signature ([Link] at- 100
tribute), 127 get_big_file() ([Link] method),
forward_text ([Link] attribute), 123 108
forwarded ([Link] attribute), 14 get_chat() ([Link] method), 69
forwardMessage() ([Link] method), 68 get_chat_administrators() ([Link]
foursquare_id ([Link] method), 69
attribute), 180 get_chat_data() ([Link]
foursquare_id (tele- method), 52
[Link] attribute), get_chat_data() ([Link]
186 method), 55
foursquare_id ([Link] attribute), 150 get_chat_data() ([Link]
foursquare_type (tele- method), 53
[Link] attribute), get_chat_member() ([Link] method), 69
180 get_chat_members_count() ([Link]
foursquare_type (tele- method), 70
[Link] attribute), get_conversations() (tele-
186 [Link] method), 52
foursquare_type ([Link] attribute), 150 get_conversations() (tele-
from_button() ([Link] [Link] method), 55
class method), 115 get_conversations() (tele-
from_button() ([Link] [Link] method), 53
class method), 142 get_file() ([Link] method), 57
from_column() ([Link] get_file() ([Link] method), 58
class method), 115 get_file() ([Link] method), 70
from_column() ([Link] get_file() ([Link] method), 111
class method), 143 get_file() ([Link] method), 204
from_row() ([Link] class get_file() ([Link] method), 140
method), 115 get_file() ([Link] method), 155
from_row() ([Link] class get_file() ([Link] method), 151
method), 143 get_file() ([Link] method), 152
from_timestamp() (in module tele- get_file() ([Link] method), 153
[Link]), 209 get_game_high_scores() ([Link]
from_user ([Link] attribute), 96 method), 70
from_user ([Link] attribute), get_instance() ([Link] class
187 method), 9
from_user ([Link] attribute), 158 get_jobs_by_name() ([Link]
from_user ([Link] attribute), 124 method), 20
from_user ([Link] attribute), get_me() ([Link] method), 71
193 get_member() ([Link] method), 100
from_user ([Link] attribute), 192 get_members_count() ([Link] method),
front_side ([Link] 100
attribute), 205 get_profile_photos() ([Link] method),
full_name ([Link] attribute), 147 147
get_signal_name() (in module tele-
[Link]), 209

Index 237
Python Telegram Bot Documentation, Release 12.1.1

get_small_file() ([Link] method), hash ([Link] attribute),


108 206
get_sticker_set() ([Link] method), 71 hash ([Link] attribute), 201
get_updates() ([Link] method), 71 HASHTAG ([Link] attribute), 138
get_user_data() ([Link] height ([Link] attribute), 56
method), 52 height ([Link] attribute),
get_user_data() ([Link] 117
method), 55 height ([Link] attribute), 121
get_user_data() ([Link] height ([Link] attribute), 139
method), 54 height ([Link] attribute), 154
get_user_profile_photos() ([Link] height ([Link] attribute), 150
method), 72 hide_url ([Link] at-
get_webhook_info() ([Link] method), 72 tribute), 160
getChat() ([Link] method), 68 HTML ([Link] attribute), 139
getChatAdministrators() ([Link]
method), 68 I
getChatMember() ([Link] method), 68 id ([Link] attribute), 72
getChatMembersCount() ([Link] method), id ([Link] attribute), 96
68 id ([Link] attribute), 98
getFile() ([Link] method), 68 id ([Link] attribute), 158
getGameHighScores() ([Link] method), 69 id ([Link] attribute), 159
getMe() ([Link] method), 69 id ([Link] attribute), 159
getStickerSet() ([Link] method), 69 id ([Link] attribute), 161
getUpdates() ([Link] method), 69 id ([Link] at-
getUserProfilePhotos() ([Link] tribute), 162
method), 69 id ([Link] at-
getWebhookInfo() ([Link] method), 69 tribute), 163
gif ([Link] attribute), 12, 13 id ([Link] attribute),
gif_duration ([Link] at- 164
tribute), 174 id (telegram.InlineQueryResultCachedMpeg4Gif at-
gif_file_id (tele- tribute), 165
[Link] at-
id ([Link] at-
tribute), 164 tribute), 166
gif_height ([Link] at- id ([Link] at-
tribute), 174 tribute), 167
gif_url ([Link] attribute), id ([Link] at-
174 tribute), 168
gif_width ([Link] at- id ([Link] at-
tribute), 174 tribute), 169
GROUP ([Link] attribute), 99 id ([Link] attribute), 170
group ([Link] attribute), 14 id ([Link] attribute),
group_chat_created ([Link] at- 172
tribute), 126 id ([Link] attribute), 173
groups ([Link] attribute), 9 id ([Link] attribute), 174
id ([Link] attribute),
H 175
handle_update() (tele- id (telegram.InlineQueryResultMpeg4Gif attribute),
[Link] method), 177
34 id ([Link] attribute), 178
handle_update() ([Link] method), id ([Link] attribute), 180
28 id ([Link] attribute), 181
Handler (class in [Link]), 26 id ([Link] attribute), 183
handlers ([Link] attribute), 9 id ([Link] attribute), 140
has_custom_certificate (tele- id ([Link] attribute), 193
[Link] attribute), 153 id ([Link] attribute), 190
hash ([Link] attribute), 200 id ([Link] attribute), 192
hash ([Link] attribute), 207 id ([Link] attribute), 146
IdDocumentData (class in telegram), 201

238 Index
Python Telegram Bot Documentation, Release 12.1.1

identity_card ([Link] attribute), [Link] attribute),


200 159
idle() ([Link] method), 6 input_message_content (tele-
image ([Link] attribute), 12, 13 [Link] attribute),
inline_keyboard (tele- 161
[Link] attribute), input_message_content (tele-
115 [Link] at-
inline_message_id ([Link] at- tribute), 162
tribute), 96 input_message_content (tele-
inline_message_id (tele- [Link]
[Link] attribute), 187 attribute), 163
inline_query ([Link] attribute), 145 input_message_content (tele-
InlineKeyboardButton (class in telegram), 113 [Link] at-
InlineKeyboardMarkup (class in telegram), 115 tribute), 164
InlineQuery (class in telegram), 157 input_message_content (tele-
InlineQueryHandler (class in [Link]), 36 gram.InlineQueryResultCachedMpeg4Gif
InlineQueryResult (class in telegram), 159 attribute), 166
InlineQueryResultArticle (class in tele- input_message_content (tele-
gram), 159 [Link] at-
InlineQueryResultAudio (class in telegram), tribute), 167
160 input_message_content (tele-
InlineQueryResultCachedAudio (class in [Link]
telegram), 162 attribute), 168
InlineQueryResultCachedDocument (class in input_message_content (tele-
telegram), 163 [Link] at-
InlineQueryResultCachedGif (class in tele- tribute), 169
gram), 164 input_message_content (tele-
InlineQueryResultCachedMpeg4Gif (class in [Link] at-
telegram), 165 tribute), 170
InlineQueryResultCachedPhoto (class in input_message_content (tele-
telegram), 166 [Link] attribute),
InlineQueryResultCachedSticker (class in 171
telegram), 167 input_message_content (tele-
InlineQueryResultCachedVideo (class in [Link] attribute),
telegram), 168 172
InlineQueryResultCachedVoice (class in input_message_content (tele-
telegram), 169 [Link] attribute),
InlineQueryResultContact (class in tele- 175
gram), 170 input_message_content (tele-
InlineQueryResultDocument (class in tele- [Link] attribute),
gram), 172 176
InlineQueryResultGame (class in telegram), 173 input_message_content (tele-
InlineQueryResultGif (class in telegram), 174 gram.InlineQueryResultMpeg4Gif attribute),
InlineQueryResultLocation (class in tele- 178
gram), 175 input_message_content (tele-
InlineQueryResultMpeg4Gif (class in tele- [Link] attribute),
gram), 177 179
InlineQueryResultPhoto (class in telegram), input_message_content (tele-
178 [Link] attribute),
InlineQueryResultVenue (class in telegram), 180
180 input_message_content (tele-
InlineQueryResultVideo (class in telegram), [Link] attribute),
181 182
InlineQueryResultVoice (class in telegram), input_message_content (tele-
183 [Link] attribute),
input_file_content ([Link] at- 184
tribute), 116 InputContactMessageContent (class in tele-
input_message_content (tele- gram), 186

Index 239
Python Telegram Bot Documentation, Release 12.1.1

InputFile (class in telegram), 116 kwargs ([Link] attribute),


InputLocationMessageContent (class in tele- 210
gram), 185
InputMedia (class in telegram), 116 L
InputMediaAnimation (class in telegram), 116 label ([Link] attribute), 188
InputMediaAudio (class in telegram), 118 LabeledPrice (class in telegram), 188
InputMediaDocument (class in telegram), 119 language_code ([Link] attribute), 147
InputMediaPhoto (class in telegram), 120 last_error_date ([Link] at-
InputMediaVideo (class in telegram), 120 tribute), 154
InputMessageContent (class in telegram), 184 last_error_message ([Link] at-
InputTextMessageContent (class in telegram), tribute), 154
184 last_name ([Link] attribute), 73
InputVenueMessageContent (class in tele- last_name ([Link] attribute), 98
gram), 185 last_name ([Link] attribute), 109
internal_passport ([Link] at- last_name ([Link] at-
tribute), 200 tribute), 171
interval ([Link] attribute), 19 last_name ([Link]
interval_seconds ([Link] attribute), 20 attribute), 186
InvalidToken, 111 last_name ([Link] attribute), 202
InvertedFilter (class in [Link]), 18 last_name ([Link] attribute), 147
invite_link ([Link] attribute), 98 latitude ([Link] at-
Invoice (class in telegram), 188 tribute), 176
invoice ([Link] attribute), 14 latitude ([Link] at-
invoice ([Link] attribute), 127 tribute), 180
invoice_payload ([Link] latitude ([Link]
attribute), 193 attribute), 185
invoice_payload ([Link] latitude ([Link] at-
attribute), 192 tribute), 185
invoice_payload ([Link] latitude ([Link] attribute), 123
attribute), 191 leave() ([Link] method), 100
is_animated ([Link] attribute), 155 leave_chat() ([Link] method), 73
is_animated ([Link] attribute), 156 leaveChat() ([Link] method), 73
is_bot ([Link] attribute), 146 LEFT ([Link] attribute), 106
is_closed ([Link] attribute), 140 left_chat_member ([Link] at-
is_image() ([Link] static method), 116 tribute), 16
is_member ([Link] attribute), 105 left_chat_member ([Link] attribute),
ITALIC ([Link] attribute), 138 126
length ([Link] attribute), 137
J length ([Link] attribute), 152
Job (class in [Link]), 19 link ([Link] attribute), 100
job ([Link] attribute), 26 link ([Link] attribute), 132
job_queue ([Link] attribute), link ([Link] attribute), 147
26 live_period ([Link]
job_queue ([Link] attribute), 8 attribute), 176
job_queue ([Link] attribute), 20 Location (class in telegram), 122
job_queue ([Link] attribute), 5 location ([Link] attribute),
JobQueue (class in [Link]), 20 187
jobs() ([Link] method), 20 location ([Link] attribute), 15
jpg ([Link] attribute), 12, 13 location ([Link] attribute), 158
location ([Link] attribute), 126
K location ([Link] attribute), 150
keyboard ([Link] at- login_url ([Link] at-
tribute), 142 tribute), 114
KeyboardButton (class in telegram), 122 LoginUrl (class in telegram), 123
kick_chat_member() ([Link] method), 72 longitude ([Link] at-
kick_member() ([Link] method), 100 tribute), 176
kickChatMember() ([Link] method), 72 longitude ([Link]
KICKED ([Link] attribute), 106 attribute), 180

240 Index
Python Telegram Bot Documentation, Release 12.1.1

longitude ([Link] message ([Link]


attribute), 185 attribute), 198
longitude ([Link] at- message ([Link]
tribute), 185 attribute), 198
longitude ([Link] attribute), 122 message ([Link]
attribute), 197
M message ([Link] attribute), 145
MARKDOWN ([Link] attribute), 139 message_id ([Link] attribute), 124
mask_position ([Link] attribute), 155 message_text ([Link]
MaskPosition (class in telegram), 156 attribute), 184
match ([Link] attribute), 26 message_updates ([Link]
matches ([Link] attribute), 25 attribute), 39
MAX_CAPTION_LENGTH (in module tele- MessageEntity (class in telegram), 137
[Link]), 109 MessageHandler (class in [Link]), 38
max_connections ([Link] at- MessageQueue (class in [Link]), 22
tribute), 154 messages ([Link] attribute), 16
MAX_FILESIZE_DOWNLOAD (in module tele- middle_name ([Link] attribute),
[Link]), 109 202
MAX_FILESIZE_UPLOAD (in module tele- migrate ([Link] attribute), 16
[Link]), 109 migrate_from_chat_id ([Link] at-
MAX_INLINE_QUERY_RESULTS (in module tele- tribute), 126
[Link]), 109 migrate_to_chat_id ([Link] at-
MAX_MESSAGE_ENTITIES (in module tele- tribute), 126
[Link]), 109 mime_type ([Link] attribute), 56
MAX_MESSAGE_LENGTH (in module tele- mime_type ([Link] attribute), 57
[Link]), 108 mime_type ([Link] attribute), 110
MAX_MESSAGES_PER_MINUTE_PER_GROUP (in mime_type ([Link] attribute), 12,
module [Link]), 109 13
MAX_MESSAGES_PER_SECOND (in module tele- mime_type ([Link]
[Link]), 109 attribute), 172
MAX_MESSAGES_PER_SECOND_PER_CHAT (in mime_type ([Link]
module [Link]), 109 attribute), 182
media ([Link] attribute), 116 mime_type ([Link] attribute), 151
media ([Link] attribute), 118 mime_type ([Link] attribute), 153
media ([Link] attribute), 119 MOUTH ([Link] attribute), 157
media ([Link] attribute), 120 mp3 ([Link] attribute), 12, 14
media ([Link] attribute), 120 mpeg4_duration (tele-
media_group_id ([Link] attribute), 125 gram.InlineQueryResultMpeg4Gif attribute),
MEMBER ([Link] attribute), 106 177
MENTION ([Link] attribute), 138 mpeg4_file_id (tele-
mention_html() (in module tele- gram.InlineQueryResultCachedMpeg4Gif
[Link]), 209 attribute), 165
mention_html() ([Link] method), 147 mpeg4_height (tele-
mention_markdown() (in module tele- gram.InlineQueryResultMpeg4Gif attribute),
[Link]), 209 177
mention_markdown() ([Link] method), mpeg4_url (telegram.InlineQueryResultMpeg4Gif
147 attribute), 177
MergedFilter (class in [Link]), 18 mpeg4_width (tele-
Message (class in telegram), 124 gram.InlineQueryResultMpeg4Gif attribute),
message ([Link] attribute), 96 177
message ([Link] attribute), 16
message ([Link] attribute), N
196 name ([Link] attribute), 73
message ([Link] name ([Link] attribute), 32
attribute), 199 name ([Link] attribute), 24
message ([Link] at- name ([Link] attribute), 17
tribute), 197 name ([Link] attribute), 19
name ([Link] attribute), 190

Index 241
Python Telegram Bot Documentation, Release 12.1.1

name ([Link] attribute), 156 parse_mode (telegram.InlineQueryResultMpeg4Gif


name ([Link] attribute), 148 attribute), 177
NetworkError, 111 parse_mode ([Link] at-
new_chat_members ([Link] at- tribute), 179
tribute), 16 parse_mode ([Link] at-
new_chat_members ([Link] attribute), tribute), 182
126 parse_mode ([Link] at-
new_chat_photo ([Link] tribute), 183
attribute), 16 parse_mode ([Link] at-
new_chat_photo ([Link] attribute), 126 tribute), 117
new_chat_title ([Link]
parse_mode ([Link] attribute),
attribute), 16 118
new_chat_title ([Link] attribute), 126 parse_mode ([Link] at-
nonce ([Link] attribute), 199 tribute), 119
parse_mode ([Link] attribute),
O 120
offset ([Link] attribute), 158 parse_mode ([Link] attribute),
offset ([Link] attribute), 137 121
on_flush ([Link] attribute), parse_mode ([Link] at-
53 tribute), 184
one_time_keyboard (tele- parse_text_entities() ([Link]
[Link] attribute), method), 195
142 parse_text_entity() ([Link] method),
options ([Link] attribute), 140 195
order_info ([Link] attribute), ParseMode (class in telegram), 139
193 pass_args ([Link] at-
order_info ([Link] attribute), tribute), 34
191 pass_args ([Link] attribute),
OrderInfo (class in telegram), 190 42
pass_args ([Link]
P attribute), 47
parse_caption_entities() (tele- pass_chat_data (tele-
[Link] method), 132 [Link] attribute),
parse_caption_entity() ([Link] 29
method), 132 pass_chat_data (tele-
parse_entities() ([Link] method), [Link] at-
133 tribute), 30
parse_entity() ([Link] method), 133 pass_chat_data ([Link]
parse_mode ([Link] at- attribute), 35
tribute), 161 pass_chat_data ([Link] attribute),
parse_mode ([Link] 26
attribute), 162 pass_chat_data (tele-
parse_mode ([Link] [Link] attribute),
attribute), 163 37
parse_mode ([Link] pass_chat_data ([Link]
attribute), 164 attribute), 39
parse_mode (telegram.InlineQueryResultCachedMpeg4Gif pass_chat_data (tele-
attribute), 165 [Link] at-
parse_mode ([Link] tribute), 41
attribute), 167 pass_chat_data ([Link] at-
parse_mode ([Link] tribute), 43
attribute), 168 pass_chat_data ([Link] at-
parse_mode ([Link] tribute), 45
attribute), 170 pass_chat_data (tele-
parse_mode ([Link] [Link] attribute),
attribute), 172 46
parse_mode ([Link] at- pass_groupdict (tele-
tribute), 175 [Link] attribute),

242 Index
Python Telegram Bot Documentation, Release 12.1.1

28 34
pass_groupdict (tele- pass_update_queue ([Link]
[Link] attribute), attribute), 26
37 pass_update_queue (tele-
pass_groupdict ([Link] at- [Link] attribute),
tribute), 44 36
pass_groupdict (tele- pass_update_queue (tele-
[Link] attribute), [Link] attribute), 39
49 pass_update_queue (tele-
pass_groups ([Link] [Link] at-
attribute), 28 tribute), 40
pass_groups ([Link] at- pass_update_queue ([Link]
tribute), 37 attribute), 42
pass_groups ([Link] at- pass_update_queue ([Link]
tribute), 44 attribute), 44
pass_groups ([Link] at- pass_update_queue (tele-
tribute), 49 [Link] attribute),
pass_job_queue (tele- 46
[Link] attribute), pass_update_queue (tele-
28 [Link] attribute),
pass_job_queue (tele- 47
[Link] at- pass_update_queue (tele-
tribute), 30 [Link] attribute),
pass_job_queue ([Link] 49
attribute), 35 pass_update_queue ([Link]
pass_job_queue ([Link] attribute), attribute), 50
26 pass_user_data (tele-
pass_job_queue (tele- [Link] attribute),
[Link] attribute), 29
36 pass_user_data (tele-
pass_job_queue ([Link] [Link] at-
attribute), 39 tribute), 30
pass_job_queue (tele- pass_user_data ([Link]
[Link] at- attribute), 35
tribute), 41 pass_user_data ([Link] attribute),
pass_job_queue ([Link] at- 26
tribute), 42 pass_user_data (tele-
pass_job_queue ([Link] at- [Link] attribute),
tribute), 44 37
pass_job_queue (tele- pass_user_data ([Link]
[Link] attribute), attribute), 39
46 pass_user_data (tele-
pass_job_queue (tele- [Link] at-
[Link] attribute), tribute), 41
47 pass_user_data ([Link] at-
pass_job_queue (tele- tribute), 43
[Link] attribute), pass_user_data ([Link] at-
49 tribute), 44
pass_job_queue ([Link] pass_user_data (tele-
attribute), 50 [Link] attribute),
pass_update_queue (tele- 46
[Link] attribute), passport ([Link] attribute), 200
28 passport_data ([Link] at-
pass_update_queue (tele- tribute), 15
[Link] at- passport_data ([Link] attribute), 127
tribute), 30 passport_registration ([Link]
pass_update_queue (tele- attribute), 201
[Link] attribute), PassportData (class in telegram), 203

Index 243
Python Telegram Bot Documentation, Release 12.1.1

PassportElementError (class in telegram), 196 photo ([Link] attribute), 194


PassportElementErrorDataField (class in photo ([Link] attribute), 125
telegram), 199 photo_file_id (tele-
PassportElementErrorFile (class in tele- [Link] at-
gram), 197 tribute), 166
PassportElementErrorFiles (class in tele- photo_height ([Link]
gram), 198 attribute), 179
PassportElementErrorFrontSide (class in photo_url ([Link]
telegram), 198 attribute), 178
PassportElementErrorReverseSide (class in photo_width ([Link] at-
telegram), 197 tribute), 179
PassportFile (class in telegram), 204 photos ([Link] attribute), 149
pattern ([Link] PhotoSize (class in telegram), 139
attribute), 28 PicklePersistence (class in [Link]), 53
pattern ([Link] at- pin_chat_message() ([Link] method), 73
tribute), 37 pinChatMessage() ([Link] method), 73
pattern ([Link] attribute), 44 pinned_message ([Link] attribute), 98
pattern ([Link] at- pinned_message ([Link]
tribute), 49 attribute), 16
pay ([Link] attribute), 114 pinned_message ([Link] attribute), 127
pdf ([Link] attribute), 12, 14 point ([Link] attribute), 156
pending_update_count ([Link] Poll (class in telegram), 140
attribute), 154 poll ([Link] attribute), 127
per_chat ([Link] at- poll ([Link] attribute), 145
tribute), 32 PollOption (class in telegram), 141
per_message ([Link] pooled_function ([Link]
attribute), 32 attribute), 210
per_user ([Link] at- position ([Link] attribute), 196
tribute), 32 post() ([Link] method), 211
performer ([Link] attribute), 57 post_code ([Link] attribute),
performer ([Link] 203
attribute), 161 post_code ([Link] attribute),
performer ([Link] attribute), 189
118 PRE ([Link] attribute), 138
permissions ([Link] attribute), 99 pre_checkout_query ([Link] at-
persistence ([Link] tribute), 145
attribute), 34 PreCheckoutQuery (class in telegram), 193
persistence ([Link] attribute), 8 PreCheckoutQueryHandler (class in tele-
persistence ([Link] attribute), 6 [Link]), 40
persistent ([Link] at- prefix ([Link] attribute), 42
tribute), 32 PrefixHandler (class in [Link]), 42
personal_details ([Link] at- prices ([Link] attribute), 190
tribute), 200 PRIVATE ([Link] attribute), 99
PersonalDetails (class in telegram), 202 private ([Link] attribute), 15
phone_number ([Link] attribute), 109 process_update() ([Link]
phone_number (tele- method), 10
[Link] attribute), Promise (class in [Link]), 209
205 promote_chat_member() ([Link] method),
phone_number ([Link] 74
attribute), 171 promoteChatMember() ([Link] method), 74
phone_number (tele- provider_payment_charge_id (tele-
[Link] at- [Link] attribute), 191
tribute), 186 py ([Link] attribute), 12, 14
PHONE_NUMBER ([Link] attribute),
138 Q
phone_number ([Link] attribute), 190 query ([Link] attribute), 187
photo ([Link] attribute), 98 query ([Link] attribute), 158
photo ([Link] attribute), 15 question ([Link] attribute), 140

244 Index
Python Telegram Bot Documentation, Release 12.1.1

R reply_markup ([Link]
RECORD_AUDIO ([Link] attribute), 103 attribute), 171
RECORD_VIDEO ([Link] attribute), 103 reply_markup (tele-
RECORD_VIDEO_NOTE ([Link] at- [Link] attribute),
tribute), 103 172
RegexHandler (class in [Link]), 44 reply_markup ([Link]
remove_error_handler() (tele- attribute), 174
[Link] method), 10 reply_markup ([Link] at-
remove_handler() ([Link] tribute), 175
method), 10 reply_markup (tele-
remove_keyboard (tele- [Link] attribute),
[Link] attribute), 176
141 reply_markup (tele-
removed ([Link] attribute), 20 gram.InlineQueryResultMpeg4Gif attribute),
rental_agreement ([Link] at- 178
tribute), 201 reply_markup ([Link]
repeat ([Link] attribute), 20 attribute), 179
reply ([Link] attribute), 15 reply_markup ([Link]
reply_animation() ([Link] method), attribute), 180
133 reply_markup ([Link]
reply_audio() ([Link] method), 133 attribute), 182
reply_contact() ([Link] method), reply_markup ([Link]
134 attribute), 184
reply_document() ([Link] method), reply_markup ([Link] attribute), 127
134 reply_media_group() ([Link]
reply_html() ([Link] method), 134 method), 135
reply_location() ([Link] method), reply_photo() ([Link] method), 135
134 reply_poll() ([Link] method), 135
reply_markdown() ([Link] method), reply_sticker() ([Link] method),
134 135
reply_markup ([Link] reply_text() ([Link] method), 135
attribute), 159 reply_to_message ([Link] attribute),
reply_markup ([Link] 124
attribute), 161 reply_venue() ([Link] method), 136
reply_markup (tele- reply_video() ([Link] method), 136
[Link] at- reply_video_note() ([Link]
tribute), 162 method), 136
reply_markup (tele- reply_voice() ([Link] method), 136
[Link] ReplyKeyboardMarkup (class in telegram), 142
attribute), 163 ReplyKeyboardRemove (class in telegram), 141
reply_markup (tele- ReplyMarkup (class in telegram), 144
[Link] at- Request (class in [Link]), 210
tribute), 164 request_contact ([Link] at-
reply_markup (tele- tribute), 122
gram.InlineQueryResultCachedMpeg4Gif request_location ([Link] at-
attribute), 165 tribute), 122
reply_markup (tele- request_write_access ([Link] at-
[Link] at- tribute), 123
tribute), 167 residence_country_code (tele-
reply_markup (tele- [Link] attribute), 202
[Link] ResidentialAddress (class in telegram), 202
attribute), 168 resize_keyboard (tele-
reply_markup (tele- [Link] attribute),
[Link] at- 142
tribute), 169 restrict_chat_member() ([Link]
reply_markup (tele- method), 75
[Link] at- restrictChatMember() ([Link] method),
tribute), 170 75

Index 245
Python Telegram Bot Documentation, Release 12.1.1

RESTRICTED ([Link] attribute), 106 send_message() ([Link] method), 148


result() ([Link] method), send_photo() ([Link] method), 84
210 send_photo() ([Link] method), 101
result_id ([Link] attribute),send_photo() ([Link] method), 148
187 send_poll() ([Link] method), 84
retrieve() ([Link]
send_poll() ([Link] method), 101
method), 211 send_sticker() ([Link] method), 85
RetryAfter, 111 send_sticker() ([Link] method), 102
reverse_side (tele-
send_sticker() ([Link] method), 148
[Link] attribute), send_venue() ([Link] method), 85
205 send_video() ([Link] method), 86
run() ([Link] method), 25 send_video() ([Link] method), 102
run() ([Link] method), 20 send_video() ([Link] method), 149
run() ([Link] method), 210send_video_note() ([Link] method), 87
run_async() ([Link] method), 10 send_video_note() ([Link] method), 102
run_daily() ([Link] method), 20 send_video_note() ([Link] method), 149
run_once() ([Link] method), 21 send_voice() ([Link] method), 88
run_repeating() ([Link]
send_voice() ([Link] method), 102
method), 21 send_voice() ([Link] method), 149
running ([Link] attribute), 10 sendAnimation() ([Link] method), 75
running ([Link] attribute), 6 sendAudio() ([Link] method), 75
sendChatAction() ([Link] method), 75
S sendContact() ([Link] method), 75
scale ([Link] attribute), 157 sendDocument() ([Link] method), 76
schedule_removal() ([Link] method), sendGame() ([Link] method), 76
20 sendInvoice() ([Link] method), 76
score ([Link] attribute), 196 sendLocation() ([Link] method), 76
secret ([Link] attribute), 200 sendMediaGroup() ([Link] method), 76
secret ([Link] attribute), sendMessage() ([Link] method), 76
207 sendPhoto() ([Link] method), 76
secret ([Link] attribute), 201 sendPoll() ([Link] method), 76
secure_data ([Link] attribute), 199 sendSticker() ([Link] method), 76
SecureData (class in telegram), 200 sendVenue() ([Link] method), 76
selective ([Link] attribute), 113 sendVideo() ([Link] method), 76
selective ([Link] at- sendVideoNote() ([Link] method), 76
tribute), 142 sendVoice() ([Link] method), 76
selective ([Link] at- set_chat_description() ([Link]
tribute), 141 method), 89
selfie ([Link] at- set_chat_permissions() ([Link]
tribute), 206 method), 89
send_action() ([Link] method), 100 set_chat_photo() ([Link] method), 90
send_animation() ([Link] method), 77 set_chat_sticker_set() ([Link]
send_animation() ([Link] method), 101 method), 90
send_animation() ([Link] method), 148 set_chat_title() ([Link] method), 90
send_audio() ([Link] method), 77 set_game_score() ([Link] method), 91
send_audio() ([Link] method), 101 set_name ([Link] attribute), 155
send_audio() ([Link] method), 148 set_passport_data_errors() ([Link]
send_chat_action() ([Link] method), 78 method), 91
send_contact() ([Link] method), 79 set_permissions() ([Link] method), 102
send_document() ([Link] method), 79 set_sticker_position_in_set() (tele-
send_document() ([Link] method), 101 [Link] method), 92
send_document() ([Link] method), 148 set_webhook() ([Link] method), 92
send_game() ([Link] method), 80 setChatDescription() ([Link] method),
send_invoice() ([Link] method), 81 89
send_location() ([Link] method), 82 setChatPermissions() ([Link] method),
send_media_group() ([Link] method), 83 89
send_message() ([Link] method), 83 setChatPhoto() ([Link] method), 89
send_message() ([Link] method), 101 setChatStickerSet() ([Link] method), 89

246 Index
Python Telegram Bot Documentation, Release 12.1.1

setChatTitle() ([Link] method), 89 stop_poll() ([Link] method), 94


setGameScore() ([Link] method), 89 stopMessageLiveLocation() ([Link]
setPassportDataErrors() ([Link] method), 93
method), 89 stopPoll() ([Link] method), 93
setStickerPositionInSet() ([Link] store_chat_data ([Link]
method), 89 attribute), 51
setWebhook() ([Link] method), 89 store_chat_data ([Link]
shipping_address ([Link] attribute), attribute), 54
190 store_chat_data ([Link]
shipping_address ([Link] at- attribute), 53
tribute), 192 store_user_data ([Link]
shipping_option_id (tele- attribute), 51
[Link] attribute), 193 store_user_data ([Link]
shipping_option_id (tele- attribute), 54
[Link] attribute), 191 store_user_data ([Link]
shipping_query ([Link] attribute), 145 attribute), 53
ShippingAddress (class in telegram), 189 street_line1 ([Link] at-
ShippingOption (class in telegram), 190 tribute), 202
ShippingQuery (class in telegram), 192 street_line1 ([Link] at-
ShippingQueryHandler (class in [Link]), tribute), 189
46 street_line2 ([Link] at-
single_file ([Link] tribute), 203
attribute), 53 street_line2 ([Link] at-
small_file_id ([Link] attribute), tribute), 189
108 strict ([Link] attribute), 50
source ([Link] attribute), StringCommandHandler (class in [Link]),
196 47
start() ([Link] method), 10 StringRegexHandler (class in [Link]), 48
start() ([Link] method), 22 successful_payment ([Link]
start() ([Link] method), 23 attribute), 16
start_parameter ([Link] attribute), 188 successful_payment ([Link] at-
start_polling() ([Link] method), tribute), 127
7 SuccessfulPayment (class in telegram), 191
start_webhook() ([Link] method), SUPERGROUP ([Link] attribute), 100
7 supergroup_chat_created ([Link]
state ([Link] attribute), 203 attribute), 126
state ([Link] attribute), 189 SUPPORTED_WEBHOOK_PORTS (in module tele-
states ([Link] attribute), [Link]), 109
32 supports_streaming ([Link]
status ([Link] attribute), 104 attribute), 121
status_update ([Link] at- svg ([Link] attribute), 12, 14
tribute), 15 switch_inline_query (tele-
Sticker (class in telegram), 154 [Link] attribute),
sticker ([Link] attribute), 16 114
sticker ([Link] attribute), 125 switch_inline_query_current_chat (tele-
sticker_file_id (tele- [Link] attribute), 114
[Link]
attribute), 167 T
sticker_set_name ([Link] attribute), 99 targz ([Link] attribute), 12, 14
stickers ([Link] attribute), 156 [Link] (module), 108
StickerSet (class in telegram), 156 [Link] (module), 111
stop() ([Link] method), 25 [Link] (module), 11
stop() ([Link] method), 10 [Link] (module), 208
stop() ([Link] method), 22 telegram_payment_charge_id (tele-
stop() ([Link] method), 23 [Link] attribute), 191
stop() ([Link] method), 8 TelegramError, 111
stop_message_live_location() (tele- TelegramObject (class in telegram), 144
[Link] method), 93

Index 247
Python Telegram Bot Documentation, Release 12.1.1

temporary_registration (tele- thumb_width ([Link]


[Link] attribute), 201 attribute), 160
text ([Link] attribute), 12, 13, 16 thumb_width ([Link]
text ([Link] attribute), 194 attribute), 171
text ([Link] attribute), 113 thumb_width (tele-
text ([Link] attribute), 122 [Link] attribute),
text ([Link] attribute), 125 173
text ([Link] attribute), 141 thumb_width ([Link]
text_entities ([Link] attribute), 195 attribute), 176
text_html ([Link] attribute), 136 thumb_width ([Link] at-
text_html_urled ([Link] attribute), tribute), 181
137 tick() ([Link] method), 22
TEXT_LINK ([Link] attribute), 139 time_limit ([Link] attribute), 24
text_markdown ([Link] attribute), 137 TimedOut, 111
text_markdown_urled ([Link] at- TIMEOUT ([Link] at-
tribute), 137 tribute), 33
TEXT_MENTION ([Link] attribute), title ([Link] attribute), 57
139 title ([Link] attribute), 98
thumb ([Link] attribute), 56 title ([Link] attribute), 194
thumb ([Link] attribute), 58 title ([Link] attribute),
thumb ([Link] attribute), 110 159
thumb ([Link] attribute), 117 title ([Link] attribute),
thumb ([Link] attribute), 118 161
thumb ([Link] attribute), 119 title ([Link]
thumb ([Link] attribute), 121 attribute), 163
thumb ([Link] attribute), 155 title ([Link] at-
thumb ([Link] attribute), 151 tribute), 164
thumb ([Link] attribute), 152 title (telegram.InlineQueryResultCachedMpeg4Gif
thumb_height ([Link] attribute), 165
attribute), 160 title ([Link] at-
thumb_height ([Link] tribute), 166
attribute), 171 title ([Link] at-
thumb_height (tele- tribute), 168
[Link] attribute), title ([Link] at-
173 tribute), 169
thumb_height (tele- title ([Link] at-
[Link] attribute), tribute), 172
176 title ([Link] attribute), 174
thumb_height ([Link] title ([Link] at-
attribute), 181 tribute), 176
thumb_url ([Link] at- title (telegram.InlineQueryResultMpeg4Gif at-
tribute), 160 tribute), 177
thumb_url ([Link] at- title ([Link] attribute),
tribute), 171 179
thumb_url ([Link] title ([Link] attribute),
attribute), 173 180
thumb_url ([Link] at- title ([Link] attribute),
tribute), 174 182
thumb_url ([Link] at- title ([Link] attribute),
tribute), 176 183
thumb_url (telegram.InlineQueryResultMpeg4Gif title ([Link] attribute), 118
attribute), 177 title ([Link] at-
thumb_url ([Link] tribute), 185
attribute), 178 title ([Link] attribute), 188
thumb_url ([Link] title ([Link] attribute), 190
attribute), 180 title ([Link] attribute), 156
thumb_url ([Link] title ([Link] attribute), 150
attribute), 182 to_json() ([Link] method), 144

248 Index
Python Telegram Bot Documentation, Release 12.1.1

to_timestamp() (in module tele- type ([Link] attribute), 120


[Link]), 209 type ([Link] attribute), 120
total_amount ([Link] attribute), 188 type ([Link] attribute), 137
total_amount ([Link] at- type ([Link] attribute), 196
tribute), 193 type ([Link] at-
total_amount ([Link] at- tribute), 199
tribute), 191 type ([Link] attribute),
total_count ([Link] at- 197
tribute), 149 type ([Link] attribute),
translation ([Link] 198
attribute), 206 type ([Link] at-
txt ([Link] attribute), 12, 14 tribute), 198
type ([Link] attribute), 98 type ([Link] at-
type ([Link] attribute), tribute), 197
205 TypeHandler (class in [Link]), 50
type ([Link] attribute), 50 TYPING ([Link] attribute), 103
type ([Link] attribute), 159
type ([Link] attribute), U
159 Unauthorized, 111
type ([Link] attribute), unban_chat_member() ([Link] method), 94
160 unban_member() ([Link] method), 102
type ([Link] unbanChatMember() ([Link] method), 94
attribute), 162 unpin_chat_message() ([Link] method),
type ([Link] 94
attribute), 163 unpinChatMessage() ([Link] method), 94
type ([Link] at- until_date ([Link] attribute), 104
tribute), 164 Update (class in telegram), 144
type (telegram.InlineQueryResultCachedMpeg4Gif update ([Link] attribute), 16
attribute), 165 update_chat_data() (tele-
type ([Link] at- [Link] method), 52
tribute), 166 update_chat_data() (tele-
type ([Link] at- [Link] method), 55
tribute), 167 update_chat_data() (tele-
type ([Link] [Link] method), 54
attribute), 168 update_conversation() (tele-
type ([Link] [Link] method), 52
attribute), 169 update_conversation() (tele-
type ([Link] attribute), [Link] method), 55
170 update_conversation() (tele-
type ([Link] at- [Link] method), 54
tribute), 172 update_filter ([Link] at-
type ([Link] attribute), tribute), 18
173 update_id ([Link] attribute), 145
type ([Link] attribute), 174 update_persistence() ([Link]
type ([Link] attribute), method), 10
175 update_queue ([Link] at-
type (telegram.InlineQueryResultMpeg4Gif at- tribute), 26
tribute), 177 update_queue ([Link] attribute),
type ([Link] attribute), 8
178 update_queue ([Link] attribute), 5
type ([Link] attribute), update_user_data() (tele-
180 [Link] method), 52
type ([Link] attribute), update_user_data() (tele-
181 [Link] method), 55
type ([Link] attribute), 183 update_user_data() (tele-
type ([Link] attribute), 116 [Link] method), 54
type ([Link] attribute), 118 Updater (class in [Link]), 5
type ([Link] attribute), 119 UPLOAD_AUDIO ([Link] attribute), 103

Index 249
Python Telegram Bot Documentation, Release 12.1.1

UPLOAD_DOCUMENT ([Link] attribute), video_note ([Link] attribute), 126


103 video_url ([Link]
UPLOAD_PHOTO ([Link] attribute), 103 attribute), 182
upload_sticker_file() ([Link] method), video_width ([Link] at-
95 tribute), 182
UPLOAD_VIDEO ([Link] attribute), 103 VideoNote (class in telegram), 151
UPLOAD_VIDEO_NOTE ([Link] at- Voice (class in telegram), 152
tribute), 103 voice ([Link] attribute), 17
uploadStickerFile() ([Link] method), 95 voice ([Link] attribute), 125
url ([Link] attribute), 114 voice_duration (tele-
url ([Link] attribute), 159 [Link] attribute),
url ([Link] attribute), 123 183
URL ([Link] attribute), 139 voice_file_id (tele-
url ([Link] attribute), 137 [Link] at-
url ([Link] attribute), 153 tribute), 169
use_context ([Link] attribute), 6 voice_url ([Link] at-
User (class in telegram), 146 tribute), 183
user ([Link] attribute), 104 voter_count ([Link] attribute), 141
user ([Link] attribute), 196
user ([Link] attribute), 137 W
user_data ([Link] attribute), WAITING ([Link] at-
25 tribute), 33
user_data ([Link] attribute), wav ([Link] attribute), 12, 14
56 WebhookInfo (class in telegram), 153
user_data ([Link] attribute), 8, 10 width ([Link] attribute), 56
user_data_json ([Link] at- width ([Link] attribute), 117
tribute), 56 width ([Link] attribute), 121
user_id ([Link] attribute), 110 width ([Link] attribute), 139
user_sig_handler ([Link] at- width ([Link] attribute), 154
tribute), 5 width ([Link] attribute), 150
username ([Link] attribute), 95 workers ([Link] attribute), 8
username ([Link] attribute), 98
username ([Link] attribute), 147 X
UserProfilePhotos (class in telegram), 149 x_shift ([Link] attribute), 156
utility_bill ([Link] attribute), 201 xml ([Link] attribute), 12, 14
V Y
vcard ([Link] attribute), 110 y_shift ([Link] attribute), 157
vcard ([Link] attribute),
171 Z
vcard ([Link]
zip ([Link] attribute), 12, 14
attribute), 186
Venue (class in telegram), 150
venue ([Link] attribute), 17
venue ([Link] attribute), 126
Video (class in telegram), 150
video ([Link] attribute), 12, 13, 17
video ([Link] attribute), 125
video_duration (tele-
[Link] attribute),
182
video_file_id (tele-
[Link] at-
tribute), 168
video_height ([Link]
attribute), 182
video_note ([Link] attribute),
17

250 Index

You might also like