Docs Python Telegram Bot Org en Latest
Docs Python Telegram Bot Org en Latest
Release 20.0a4
Leandro Toledo
1 Note 3
3 Installing 7
3.1 Dependencies & Their Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 Optional Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
4 Quick Start 9
5 Resources 11
6 Getting help 13
7 Concurrency 15
8 Contributing 17
9 Donating 19
10 License 21
10.1 telegram package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
10.1.1 Version Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
10.1.2 Available Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
10.2 telegram.ext package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
10.2.1 telegram.ext.Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
10.2.2 telegram.ext.ApplicationBuilder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
10.2.3 telegram.ext.ApplicationHandlerStop . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
10.2.4 telegram.ext.CallbackContext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
10.2.5 telegram.ext.ContextTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
10.2.6 telegram.ext.Defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
10.2.7 telegram.ext.ExtBot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
10.2.8 telegram.ext.Job . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
10.2.9 telegram.ext.JobQueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
10.2.10 telegram.ext.Updater . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
10.2.11 Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
10.2.12 Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
10.2.13 Arbitrary Callback Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
10.2.14 Rate Limiting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
10.3 Auxiliary modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
10.3.1 telegram.constants Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
10.3.2 telegram.error Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
10.3.3 telegram.helpers Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
10.3.4 telegram.request Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
10.3.5 telegram.warnings Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
i
10.4 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
10.4.1 echobot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
10.4.2 timerbot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
10.4.3 conversationbot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
10.4.4 conversationbot2.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
10.4.5 nestedconversationbot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
10.4.6 persistentconversationbot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
10.4.7 inlinekeyboard.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
10.4.8 inlinekeyboard2.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
10.4.9 deeplinking.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
10.4.10 inlinebot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
10.4.11 pollbot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
10.4.12 passportbot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
10.4.13 paymentbot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
10.4.14 errorhandlerbot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
10.4.15 chatmemberbot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
10.4.16 webappbot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
10.4.17 contexttypesbot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
10.4.18 customwebhookbot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
10.4.19 arbitrarycallbackdatabot.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
10.4.20 Pure API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
10.5 Changelog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
10.5.1 Version 20.0a4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
10.5.2 Version 20.0a3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
10.5.3 Version 20.0a2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534
10.5.4 Version 20.0a1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
10.5.5 Version 20.0a0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
10.5.6 Version 13.11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
10.5.7 Version 13.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
10.5.8 Version 13.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
10.5.9 Version 13.8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
10.5.10 Version 13.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
10.5.11 Version 13.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
10.5.12 Version 13.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
10.5.13 Version 13.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
10.5.14 Version 13.4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
10.5.15 Version 13.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
10.5.16 Version 13.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
10.5.17 Version 13.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
10.5.18 Version 13.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
10.5.19 Version 13.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
10.5.20 Version 12.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
10.5.21 Version 12.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
10.5.22 Version 12.6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
10.5.23 Version 12.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
10.5.24 Version 12.5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
10.5.25 Version 12.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
10.5.26 Version 12.4.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
10.5.27 Version 12.4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
10.5.28 Version 12.4.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
10.5.29 Version 12.3.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
10.5.30 Version 12.2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
10.5.31 Version 12.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
10.5.32 Version 12.1.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
10.5.33 Version 12.0.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
10.5.34 Version 11.1.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
10.5.35 Version 11.0.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
10.5.36 Version 10.1.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
ii
10.5.37 Version 10.0.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
10.5.38 Version 10.0.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
10.5.39 Version 10.0.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
10.5.40 Version 9.0.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
10.5.41 Version 8.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
10.5.42 Version 8.1.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
10.5.43 Version 8.0.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
10.5.44 Version 7.0.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
10.5.45 Version 7.0.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
10.5.46 Pre-version 7.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
10.6 How To Contribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
10.6.1 Setting things up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
10.6.2 Finding something to do . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
10.6.3 Instructions for making a code change . . . . . . . . . . . . . . . . . . . . . . . . . . . 566
10.6.4 Documenting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
10.6.5 Style commandments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
10.7 Contributor Covenant Code of Conduct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
10.7.1 Our Pledge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
10.7.2 Our Standards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
10.7.3 Our Responsibilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
10.7.4 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
10.7.5 Enforcement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
10.7.6 Attribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
Index 573
iii
iv
python-telegram-bot Documentation, Release 20.0a4
REFERENCE 1
python-telegram-bot Documentation, Release 20.0a4
2 REFERENCE
CHAPTER
ONE
NOTE
3
python-telegram-bot Documentation, Release 20.0a4
4 Chapter 1. Note
CHAPTER
TWO
All types and methods of the Telegram Bot API 6.2 are supported.
5
python-telegram-bot Documentation, Release 20.0a4
THREE
INSTALLING
python-telegram-bot tries to use as few 3rd party dependencies as possible. However, for some features using
a 3rd party library is more sane than implementing the functionality again. The dependencies are:
• httpx ~= 0.23.0 for telegram.request.HTTPXRequest, the default networking backend
• tornado~=6.2 for telegram.ext.Updater.start_webhook
• cachetools~=5.2.0 for telegram.ext.CallbackDataCache
• APScheduler~=3.9.1 for telegram.ext.JobQueue
python-telegram-bot is most useful when used along with additional libraries. To minimize dependency con-
flicts, we try to be liberal in terms of version requirements on the dependencies. On the other hand, we have to
ensure stability of python-telegram-bot, which is why we do apply version bounds. If you encounter depen-
dency conflicts due to these bounds, feel free to reach out.
7
python-telegram-bot Documentation, Release 20.0a4
8 Chapter 3. Installing
CHAPTER
FOUR
QUICK START
Our Wiki contains an Introduction to the API explaining how the pure Bot API can be accessed via
python-telegram-bot. Moreover, the Tutorial: Your first Bot gives an introduction on how chatbots can be
easily programmed with the help of the telegram.ext module.
9
python-telegram-bot Documentation, Release 20.0a4
FIVE
RESOURCES
• The package documentation is the technical reference for python-telegram-bot. It contains descriptions
of all available classes, modules, methods and arguments as well as the changelog.
• The wiki is home to number of more elaborate introductions of the different features of
python-telegram-bot and other useful resources that go beyond the technical documentation.
• Our examples section contains several examples that showcase the different features of both the Bot API and
python-telegram-bot. Even if it is not your approach for learning, please take a look at echobot.py.
It is the de facto base for most of the bots out there. The code for these examples is released to the public
domain, so you can start by grabbing the code and building on top of it.
• The official Telegram Bot API documentation is of course always worth a read.
11
python-telegram-bot Documentation, Release 20.0a4
12 Chapter 5. Resources
CHAPTER
SIX
GETTING HELP
If the resources mentioned above don’t answer your questions or simply overwhelm you, there are several ways of
getting help.
1. We have a vibrant community of developers helping each other in our Telegram group. Join us! Asking a
question here is often the quickest way to get a pointer in the right direction.
2. Ask questions by opening a discussion.
3. You can even ask for help on Stack Overflow using the python-telegram-bot tag.
13
python-telegram-bot Documentation, Release 20.0a4
SEVEN
CONCURRENCY
Since v20.0, python-telegram-bot is built on top of Pythons asyncio module. Because asyncio is in gen-
eral single-threaded, python-telegram-bot does currently not aim to be thread-safe. Noteworthy parts of
python-telegram-bots API that are likely to cause issues (e.g. race conditions) when used in a multi-threaded
setting include:
• telegram.ext.Application/Updater.update_queue
• telegram.ext.ConversationHandler.check/handle_update
• telegram.ext.CallbackDataCache
• telegram.ext.BasePersistence
• all classes in the telegram.ext.filters module that allow to add/remove allowed users/chats at runtime
15
python-telegram-bot Documentation, Release 20.0a4
16 Chapter 7. Concurrency
CHAPTER
EIGHT
CONTRIBUTING
Contributions of all sizes are welcome. Please review our contribution guidelines to get started. You can also help
by reporting bugs or feature requests.
17
python-telegram-bot Documentation, Release 20.0a4
18 Chapter 8. Contributing
CHAPTER
NINE
DONATING
Occasionally we are asked if we accept donations to support the development. While we appreciate the thought,
maintaining PTB is our hobby, and we have almost no running costs for it. We therefore have nothing set up to
accept donations. If you still want to donate, we kindly ask you to donate to another open source project/initiative
of your choice instead.
19
python-telegram-bot Documentation, Release 20.0a4
20 Chapter 9. Donating
CHAPTER
TEN
LICENSE
You may copy, distribute and modify the software provided that modifications are described and licensed for free
under LGPL-3. Derivatives works (including modifications or anything statically linked to the library) can only be
redistributed under LGPL-3, but applications that use the library don’t have to be.
21
python-telegram-bot Documentation, Release 20.0a4
telegram.Animation
thumb
Optional. Animation thumbnail as defined by sender.
Type
telegram.PhotoSize
file_name
Optional. Original animation filename as defined by sender.
Type
str
mime_type
Optional. MIME type of the file as defined by sender.
Type
str
file_size
Optional. File size in bytes.
Type
int
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
async get_file(*, read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Convenience wrapper over telegram.Bot.get_file
For the documentation of the arguments, please see telegram.Bot.get_file().
Returns
telegram.File
Raises
telegram.error.TelegramError –
telegram.Audio
telegram.Bot
is roughly equivalent to
try:
await bot.initialize()
# code
finally:
await request_object.shutdown()
Note:
• Most bot methods have the argument api_kwargs which allows passing arbitrary keywords to the
Telegram API. This can be used to access new features of the API before they are incorporated into
PTB. However, this is not guaranteed to work, i.e. it will fail for passing files.
• Bots should not be serialized since if you for e.g. change the bots token, then your serialized instance
will not reflect that change. Trying to pickle a bot instance will raise pickle.PicklingError.
See also:
telegram.ext.Application.bot, telegram.ext.CallbackContext.bot, telegram.ext.
Updater.bot
New in version 13.2: Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their bot is equal.
Changed in version 20.0:
• Removed the deprecated methods kick_chat_member, kickChatMember,
get_chat_members_count and getChatMembersCount.
• Removed the deprecated property commands.
• Removed the deprecated defaults parameter. If you want to use telegram.ext.Defaults, please
use the subclass telegram.ext.ExtBot instead.
• Attempting to pickle a bot instance will now raise pickle.PicklingError.
• The following are now keyword-only arguments in Bot methods: location, filename, venue,
contact, {read, write, connect, pool}_timeout, api_kwargs. Use a named argument for
those, and notice that some positional arguments changed position as a result.
• For uploading files, file paths are now always accepted. If local_mode is False, the file contents will
be read in binary mode and uploaded. Otherwise, the file path will be passed in the file URI scheme.
Parameters
• token (str) – Bot’s unique authentication token.
• base_url (str, optional) – Telegram Bot API service URL.
• base_file_url (str, optional) – Telegram Bot API file URL.
• request (telegram.request.BaseRequest, optional) – Pre initialized telegram.
request.BaseRequest instances. Will be used for all bot methods except for
get_updates(). If not passed, an instance of telegram.request.HTTPXRequest
will be used.
• get_updates_request (telegram.request.BaseRequest, optional) – Pre ini-
tialized telegram.request.BaseRequest instances. Will be used exclusively for
get_updates(). If not passed, an instance of telegram.request.HTTPXRequest
will be used.
• private_key (bytes, optional) – Private key for decryption of telegram passport data.
• private_key_password (bytes, optional) – Password for above private key.
• local_mode (bool, optional) – Set to True, if the base_url is the URI of a Local Bot
API Server that runs with the --local flag. Currently, the only effect of this is that files
are uploaded using their local path in the file URI scheme. Defaults to False.
New in version 20.0..
Warning: As of API 4.7 png_sticker is an optional argument and therefore the order of the
arguments had to be changed. Use keyword arguments to make sure that the arguments are passed
correctly.
Parameters
• user_id (int) – User identifier of created sticker set owner.
• name (str) – Sticker set name.
• png_sticker (str | file object | bytes | pathlib.Path, optional) – PNG image with
the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and
either width or height must be exactly 512px. Pass a file_id as 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. To upload a file,
you can either pass a file object (e.g. open("filename", "rb")), the file contents
as bytes or the path of the file (as string or pathlib.Path object). In the latter case,
the file contents will either be read as bytes or the file path will be passed to Telegram,
depending on the local_mode setting.
Changed in version 13.2: Accept bytes as input.
Changed in version 20.0: File paths as input is also accepted for bots not running in
local_mode.
• tgs_sticker (str | file object | bytes | pathlib.Path, optional) – TGS ani-
mation with the sticker. To upload a file, you can either pass a file object (e.g.
open("filename", "rb")), the file contents as bytes or the path of the file (as string
or pathlib.Path object). In the latter case, the file contents will either be read as
bytes or the file path will be passed to Telegram, depending on the local_mode set-
ting. See https://core.telegram.org/stickers#animated-sticker-requirements for techni-
cal requirements.
Changed in version 13.2: Accept bytes as input.
Changed in version 20.0: File paths as input is also accepted for bots not running in
local_mode.
• webm_sticker (str | file object | bytes | pathlib.Path, optional) – WEBM
video with the sticker. To upload a file, you can either pass a file object (e.g.
open("filename", "rb")), the file contents as bytes or the path of the file (as string
or pathlib.Path object). In the latter case, the file contents will either be read as
bytes or the file path will be passed to Telegram, depending on the local_mode set-
ting. See https://core.telegram.org/stickers#video-sticker-requirements for technical
requirements.
New in version 13.11.
Changed in version 20.0: File paths as input is also accepted for bots not running in
local_mode.
• emojis (str) – One or more emoji corresponding to the sticker.
• mask_position (telegram.MaskPosition, optional) – Position where the mask
should be placed on faces.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
Parameters
• callback_query_id (str) – Unique identifier for the query to be answered.
• text (str, optional) – Text of the notification. If not specified, nothing will be shown
to the user, 0-200 characters.
• show_alert (bool, optional) – If True, an alert will be shown by the client instead
of a notification at the top of the chat screen. Defaults to False.
• url (str, optional) – URL that will be opened by the user’s client. If you have created
a Game and accepted the conditions via @BotFather, specify the URL that opens your
game - note that this will only work if the query comes from a callback game button.
Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with
a parameter.
• cache_time (int, optional) – The maximum amount of time in seconds that the result
of the callback query may be cached client-side. Defaults to 0.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
bool On success, True is returned.
Raises
telegram.error.TelegramError –
Warning: In most use cases current_offset should not be passed manually. Instead of call-
ing this method directly, use the shortcut telegram.InlineQuery.answer() with telegram.
InlineQuery.answer.auto_pagination set to True, which will take care of passing the cor-
rect value.
See also:
telegram.InlineQuery.answer
Parameters
• inline_query_id (str) – Unique identifier for the answered query.
• results (List[telegram.InlineQueryResult] | Callable) – A list of results for the
inline query. In case current_offset is passed, results may also be a callable that
accepts the current page index starting from 0. It must return either a list of telegram.
InlineQueryResult instances or None if there are no more results.
• 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 spec-
ified 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 mes-
sage sent to the bot when user presses the switch button. 1-64 characters, only A-Z,
a-z, 0-9, _ and - are allowed.
Keyword Arguments
• current_offset (str, optional) – The telegram.InlineQuery.offset of the in-
line query to answer. If passed, PTB will automatically take care of the pagination for
you, i.e. pass the correct next_offset and truncate the results list/get the results from
the callable you passed.
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Example
An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account
to adapt search results accordingly. To do this, it displays a ‘Connect your YouTube account’ button
above the results, or even before showing any. The user presses the button, switches to a private chat
with the bot and, in doing so, passes a start parameter that instructs the bot to return an oauth link.
Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where
they wanted to use the bot’s inline capabilities.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
Once the user has confirmed their payment and shipping details, the Bot API sends the final confirma-
tion in the form of an telegram.Update with the field telegram.Update.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.
See also:
telegram.PreCheckoutQuery.answer
Parameters
• pre_checkout_query_id (str) – Unique identifier for the query to be answered.
• 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.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
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 possible).
• shipping_options (List[telegram.ShippingOption]) – Required if ok is True.
An 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.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
Returns
On success, a sent telegram.SentWebAppMessage is returned.
Return type
telegram.SentWebAppMessage
Raises
telegram.error.TelegramError –
async approveChatJoinRequest(chat_id, user_id, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Alias for approve_chat_join_request()
async approve_chat_join_request(chat_id, user_id, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None,
api_kwargs=None)
Use this method to approve a chat join request.
The bot must be an administrator in the chat for this to work and must have the telegram.
ChatPermissions.can_invite_users administrator right.
See also:
telegram.Chat.approve_join_request, telegram.ChatJoinRequest.approve, telegram.
User.approve_join_request
New in version 13.8.
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.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
async banChatMember(chat_id, user_id, until_date=None, revoke_messages=None, *,
read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Alias for ban_chat_member()
Parameters
• chat_id (int | str) – Unique identifier for the target group or username of the target
supergroup or channel (in the format @channelusername).
• user_id (int) – Unique identifier of the target user.
• until_date (int | datetime.datetime, optional) – Date when the user will be
unbanned, unix time. If user is banned for more than 366 days or less than 30 sec-
onds from the current time they are considered to be banned forever. Applied for
supergroups and channels only. For timezone naive datetime.datetime objects,
the default timezone of the bot will be used, which is UTC unless telegram.ext.
Defaults.tzinfo is used.
• revoke_messages (bool, optional) – Pass True to delete all messages from the chat
for the user that is being removed. If False, the user will be able to see messages in
the group that were sent before the user was removed. Always True for supergroups
and channels.
New in version 13.4.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
Warning: This value is the cached return value of get_me(). If the bots profile is changed during
runtime, this value won’t reflect the changes until get_me() is called again.
See also:
initialize()
Type
telegram.User
property can_join_groups
Bot’s telegram.User.can_join_groups attribute. Shortcut for the corresponding attribute of bot.
Type
bool
property can_read_all_group_messages
Bot’s telegram.User.can_read_all_group_messages attribute. Shortcut for the corresponding
attribute of bot.
Type
bool
async close(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None,
api_kwargs=None)
Use this method to close the bot instance before moving it from one local server to another. You need
to delete the webhook before calling this method to ensure that the bot isn’t launched again after server
restart. The method will return error 429 in the first 10 minutes after the bot is launched.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success
Return type
True
Raises
telegram.error.TelegramError –
async copyMessage(chat_id, from_chat_id, message_id, caption=None, parse_mode=None,
caption_entities=None, disable_notification=None, reply_to_message_id=None,
allow_sending_without_reply=None, reply_markup=None, protect_content=None,
*, read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Alias for copy_message()
async copy_message(chat_id, from_chat_id, message_id, caption=None, parse_mode=None,
caption_entities=None, disable_notification=None, reply_to_message_id=None,
allow_sending_without_reply=None, reply_markup=None,
protect_content=None, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Use this method to copy messages of any kind. Service messages and invoice messages can’t be copied.
The method is analogous to the method forward_message(), but the copied message doesn’t have a
link to the original message.
See also:
telegram.Message.copy, telegram.Chat.send_copy, telegram.Chat.copy_message,
telegram.User.send_copy, telegram.User.copy_message
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• from_chat_id (int | str) – Unique identifier for the chat where the original message
was sent (or channel username in the format @channelusername).
• message_id (int) – Message identifier in the chat specified in from_chat_id.
• caption (str, optional) – New caption for media, 0-1024 characters after entities
parsing. If not specified, the original caption is kept.
• parse_mode (str, optional) – Mode for parsing entities in the new caption. See the
constants in telegram.constants.ParseMode for the available modes.
• caption_entities (List[telegram.MessageEntity], optional) – List of special
entities that appear in the new caption, which can be specified instead of parse_mode.
• disable_notification (bool, optional) – Sends the message silently. Users will
receive a notification with no sound.
• protect_content (bool, optional) – Protects the contents of the sent message from
forwarding and saving.
New in version 13.10.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the original
message.
• allow_sending_without_reply (bool, optional) – Pass True, if the message
should be sent even if the specified replied-to message is not found.
• reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup |
ReplyKeyboardRemove | ForceReply, optional) – Additional interface op-
tions. An object for an inline keyboard, custom reply keyboard, instructions to remove
reply keyboard or to force a reply from the user.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success
Return type
telegram.MessageId
Raises
telegram.error.TelegramError –
Warning: As of API 4.7 png_sticker is an optional argument and therefore the order of the
arguments had to be changed. Use keyword arguments to make sure that the arguments are passed
correctly.
Changed in version 20.0: The parameter contains_masks has been removed. Use sticker_type
instead.
Parameters
• user_id (int) – User identifier of created sticker set owner.
• name (str) – Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g.,
animals). Can contain only english letters, digits and underscores. Must begin with a
letter, can’t contain consecutive underscores and must end in “_by_<bot username>”.
<bot_username> is case insensitive. 1-64 characters.
• title (str) – Sticker set title, 1-64 characters.
• png_sticker (str | file object | bytes | pathlib.Path, optional) – PNG image with
the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and
either width or height must be exactly 512px. Pass a file_id as 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. To upload a file,
you can either pass a file object (e.g. open("filename", "rb")), the file contents
as bytes or the path of the file (as string or pathlib.Path object). In the latter case,
the file contents will either be read as bytes or the file path will be passed to Telegram,
depending on the local_mode setting.
Changed in version 13.2: Accept bytes as input.
Changed in version 20.0: File paths as input is also accepted for bots not running in
local_mode.
• tgs_sticker (str | file object | bytes | pathlib.Path, optional) – TGS ani-
mation with the sticker. To upload a file, you can either pass a file object (e.g.
open("filename", "rb")), the file contents as bytes or the path of the file (as string
or pathlib.Path object). In the latter case, the file contents will either be read as
bytes or the file path will be passed to Telegram, depending on the local_mode set-
ting. See https://core.telegram.org/stickers#animated-sticker-requirements for techni-
cal requirements.
Changed in version 13.2: Accept bytes as input.
Changed in version 20.0: File paths as input is also accepted for bots not running in
local_mode.
• webm_sticker (str | file object | bytes | pathlib.Path, optional) – WEBM
video with the sticker. To upload a file, you can either pass a file object (e.g.
open("filename", "rb")), the file contents as bytes or the path of the file (as string
or pathlib.Path object). In the latter case, the file contents will either be read as
bytes or the file path will be passed to Telegram, depending on the local_mode set-
ting. See https://core.telegram.org/stickers#video-sticker-requirements for technical
requirements.
New in version 13.11.
Changed in version 20.0: File paths as input is also accepted for bots not running in
local_mode.
• emojis (str) – One or more emoji corresponding to the sticker.
• mask_position (telegram.MaskPosition, optional) – Position where the mask
should be placed on faces.
• sticker_type (str, optional) – Type of stickers in the set, pass telegram.
Sticker.REGULAR or telegram.Sticker.MASK. Custom emoji sticker sets can’t
be created via the Bot API at the moment. By default, a regular sticker set is created.
New in version 20.0.
Keyword Arguments
Return type
bool
Raises
telegram.error.TelegramError –
async deleteChatPhoto(chat_id, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Alias for delete_chat_photo()
async deleteChatStickerSet(chat_id, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Alias for delete_chat_sticker_set()
async deleteMessage(chat_id, message_id, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Alias for delete_message()
async deleteMyCommands(scope=None, language_code=None, *, read_timeout=None,
write_timeout=None, connect_timeout=None, pool_timeout=None,
api_kwargs=None)
Alias for delete_my_commands()
async deleteStickerFromSet(sticker, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Alias for delete_sticker_from_set()
async deleteWebhook(drop_pending_updates=None, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Alias for delete_webhook()
async delete_chat_photo(chat_id, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
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.
See also:
telegram.Chat.delete_photo
Parameters
chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
Raises
telegram.error.TelegramError –
async delete_sticker_from_set(sticker, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Use this method to delete a sticker from a set created by the bot.
Parameters
sticker (str) – File identifier of the sticker.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
async delete_webhook(drop_pending_updates=None, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Use this method to remove webhook integration if you decide to switch back to get_updates().
Parameters
drop_pending_updates (bool, optional) – Pass True to drop all pending updates.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
Note: Though not stated explicitly in the official docs, Telegram changes not only the optional pa-
rameters that are explicitly passed, but also replaces all other optional parameters to the default values.
However, since not documented, this behaviour may change unbeknown to PTB.
See also:
telegram.Chat.edit_invite_link
New in version 13.4.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• invite_link (str | telegram.ChatInviteLink) – The invite link to edit.
Changed in version 20.0: Now also accepts telegram.ChatInviteLink instances.
• expire_date (int | datetime.datetime, optional) – Date when the link will ex-
pire. For timezone naive datetime.datetime objects, the default timezone of the
bot will be used, which is UTC unless telegram.ext.Defaults.tzinfo is used.
• member_limit (int, optional) – Maximum number of users that can be members of
the chat simultaneously after joining the chat via this invite link; 1-99999.
• name (str, optional) – Invite link name; 0-32 characters.
New in version 13.8.
• creates_join_request (bool, optional) – True, if users joining the chat via the
link need to be approved by chat administrators. If True, member_limit can’t be
specified.
New in version 13.8.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
telegram.ChatInviteLink
Raises
telegram.error.TelegramError –
async edit_message_caption(chat_id=None, message_id=None, inline_message_id=None,
caption=None, reply_markup=None, parse_mode=None,
caption_entities=None, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Use this method to edit captions of messages.
See also:
telegram.Message.edit_caption, telegram.CallbackQuery.edit_message_caption
Parameters
• chat_id (int | str, optional) – Required if inline_message_id is not specified.
Unique identifier for the target chat or username of the target channel (in the format
@channelusername)
• message_id (int, optional) – Required if inline_message_id is not specified. Identi-
fier of the message to edit.
• inline_message_id (str, optional) – Required if chat_id and message_id are not
specified. Identifier of the inline message.
• caption (str, optional) – New caption of the message, 0-1024 characters after enti-
ties parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram apps
to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.constants.ParseMode for the available modes.
• caption_entities (List[telegram.MessageEntity], optional) – List of special
entities that appear in message text, which can be specified instead of parse_mode.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – An object for an
inline keyboard.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, if edited message is not an inline message, the edited message is returned,
otherwise True is returned.
Return type
telegram.Message
Raises
telegram.error.TelegramError –
See also:
telegram.Message.edit_live_location, telegram.CallbackQuery.
edit_message_live_location
Parameters
• chat_id (int | str, optional) – Required if inline_message_id is not specified.
Unique identifier for the target chat or username of the target channel (in the format
@channelusername).
See also:
telegram.Message.edit_media, telegram.CallbackQuery.edit_message_media
Parameters
See also:
telegram.Message.edit_reply_markup, telegram.CallbackQuery.
edit_message_reply_markup
Parameters
• chat_id (int | str, optional) – Required if inline_message_id is not specified.
Unique identifier for the target chat or username of the target channel (in the format
@channelusername).
• message_id (int, optional) – Required if inline_message_id is not specified. Identi-
fier of the message to edit.
See also:
telegram.Message.edit_text, telegram.CallbackQuery.edit_message_text
Parameters
• chat_id (int | str, optional) – Required if inline_message_id is not specified.
Unique identifier for the target chat or username of the target channel (in the format
@channelusername)
• message_id (int, optional) – Required if inline_message_id is not specified. Identi-
fier of the message to edit.
• inline_message_id (str, optional) – Required if chat_id and message_id are not
specified. Identifier of the inline message.
• text (str) – New text of the message, 1-4096 characters after entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram apps
to show bold, italic, fixed-width text or inline URLs in your bot’s message. See the
constants in telegram.constants.ParseMode for the available modes.
Note: Each administrator in a chat generates their own invite links. Bots can’t use invite links generated
by other administrators. If you want your bot to work with invite links, it will need to generate its own
link using export_chat_invite_link() or by calling the get_chat() method. If your bot needs to
generate a new primary invite link replacing its previous one, use export_chat_invite_link again.
See also:
telegram.Chat.export_invite_link
Parameters
chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
property first_name
Bot’s first name. Shortcut for the corresponding attribute of bot.
Type
str
async forwardMessage(chat_id, from_chat_id, message_id, disable_notification=None,
protect_content=None, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Alias for forward_message()
async forward_message(chat_id, from_chat_id, message_id, disable_notification=None,
protect_content=None, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Use this method to forward messages of any kind. Service messages can’t be forwarded.
Note: Since the release of Bot API 5.5 it can be impossible to forward messages from some
chats. Use the attributes telegram.Message.has_protected_content and telegram.Chat.
has_protected_content to check this.
As a workaround, it is still possible to use copy_message(). However, this behaviour is undocumented
and might be changed by Telegram.
See also:
telegram.Message.forward, telegram.Chat.forward_to, telegram.Chat.forward_from
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• from_chat_id (int | str) – Unique identifier for the chat where the original message
was sent (or channel username in the format @channelusername).
• message_id (int) – Message identifier in the chat specified in from_chat_id.
• disable_notification (bool, optional) – Sends the message silently. Users will
receive a notification with no sound.
• protect_content (bool, optional) – Protects the contents of the sent message from
forwarding and saving.
New in version 13.10.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, the sent Message is returned.
Return type
telegram.Message
Raises
telegram.error.TelegramError –
See also:
telegram.Chat.get_administrators
Parameters
chat_id (int | str) – Unique identifier for the target chat or username of the target
supergroup or channel (in the format @channelusername).
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, returns a list of ChatMember objects that contains information about all chat
administrators except other bots. If the chat is a group or a supergroup and no adminis-
trators were appointed, only the creator will be returned.
Return type
List[telegram.ChatMember]
Raises
telegram.error.TelegramError –
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
supergroup or channel (in the format @channelusername).
• user_id (int) – Unique identifier of the target user.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
telegram.ChatMember
Raises
telegram.error.TelegramError –
Note: This function may not preserve the original file name and MIME type. You should save the
file’s MIME type and name (if available) when the File object is received.
Parameters
file_id – Either the file identifier or an object that has a file_id attribute to get file
information about.
Returns
telegram.File
Raises
telegram.error.TelegramError –
Note: This method will currently return scores for the target user, plus two of their closest neighbors
on each side. Will also return the top three users if the user and his neighbors are not among them.
Please note that this behavior is subject to change.
See also:
telegram.CallbackQuery.get_game_high_scores
Parameters
• user_id (int) – Target user id.
• 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. Identi-
fier of the sent message.
• inline_message_id (str, optional) – Required if chat_id and message_id are not
specified. Identifier of the inline message.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
List[telegram.GameHighScore]
Raises
telegram.error.TelegramError –
Use this method to get the current default administrator rights of the bot.
See also:
set_my_default_administrator_rights()
New in version 20.0.
Parameters
for_channels (bool, optional) – Pass True to get default administrator rights of the bot
in channels. Otherwise, default administrator rights of the bot for groups and supergroups
will be returned.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success.
Return type
telegram.ChatAdministratorRights
Raises
telegram.error.TelegramError –
async get_sticker_set(name, *, read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Use this method to get a sticker set.
Parameters
name (str) – Name of the sticker set.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
telegram.StickerSet
Raises
telegram.error.TelegramError –
Note:
1. This method will not work if an outgoing webhook is set up.
2. In order to avoid getting duplicate updates, recalculate offset after each server response.
3. To take full advantage of this library take a look at telegram.ext.Updater
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 de-
fault, updates starting with the earliest unconfirmed update are returned. An update
is considered confirmed as soon as this method is called with an offset higher than
its telegram.Update.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 between
1-100 are accepted. Defaults to 100.
• timeout (int, optional) – Timeout in seconds for long polling. Defaults to 0, i.e.
usual short polling. Should be positive, short polling should be used for testing pur-
poses only.
• allowed_updates (List[str]), optional) – A 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 telegram.Update for a
complete list of available update types. Specify an empty list to receive all updates
except telegram.Update.chat_member (default). If not specified, the previous set-
ting 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.
Keyword Arguments
• read_timeout (float, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to 2. timeout will be added to this
value.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
List[telegram.Update]
Raises
telegram.error.TelegramError –
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.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
telegram.UserProfilePhotos
Raises
telegram.error.TelegramError –
property id
Unique identifier for this bot. Shortcut for the corresponding attribute of bot.
Type
int
async initialize()
Initialize resources used by this class. Currently calls get_me() to cache bot and calls telegram.
request.BaseRequest.initialize() for the request objects used by this bot.
See also:
shutdown()
New in version 20.0.
property last_name
Optional. Bot’s last name. Shortcut for the corresponding attribute of bot.
Type
str
async leaveChat(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Alias for leave_chat()
async leave_chat(chat_id, *, read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Use this method for your bot to leave a group, supergroup or channel.
See also:
telegram.Chat.leave
Parameters
chat_id (int | str) – Unique identifier for the target chat or username of the target
supergroup or channel (in the format @channelusername).
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
property link
Convenience property. Returns the t.me link of the bot.
Type
str
property local_mode
Whether this bot is running in local mode.
New in version 20.0.
Type
bool
async logOut(*, read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Alias for log_out()
async log_out(*, read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Use this method to log out from the cloud Bot API server before launching the bot locally. You must log
out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates.
After a successful call, you can immediately log in on a local server, but will not be able to log in back
to the cloud Bot API server for 10 minutes.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
New in version 20.0.
Returns
On success
Return type
True
Raises
telegram.error.TelegramError –
property name
Bot’s @username. Shortcut for the corresponding attribute of bot.
Type
str
async pinChatMessage(chat_id, message_id, disable_notification=None, *, read_timeout=None,
write_timeout=None, connect_timeout=None, pool_timeout=None,
api_kwargs=None)
Alias for pin_chat_message()
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• message_id (int) – Identifier of a message to pin.
• disable_notification (bool, optional) – Pass True, if it is not necessary to send
a notification to all chat members about the new pinned message. Notifications are
always disabled in channels and private chats.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
property private_key
Deserialized private key for decryption of telegram passport data.
New in version 20.0.
async 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,
is_anonymous=None, can_manage_chat=None,
can_manage_video_chats=None, *, read_timeout=None,
write_timeout=None, connect_timeout=None, pool_timeout=None,
api_kwargs=None)
Alias for promote_chat_member()
Warning: Requests to the Bot API are made by the various methods of this class. This attribute
should not be used manually.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
supergroup (in the format @supergroupusername).
• user_id (int) – Unique identifier of the target user.
• until_date (int | datetime.datetime, optional) – Date when restrictions will be
lifted for the user, unix time. If user is restricted for more than 366 days or less than
30 seconds from the current time, they are considered to be restricted forever. For
timezone naive datetime.datetime objects, the default timezone of the bot will be
used, which is UTC unless telegram.ext.Defaults.tzinfo is used.
• permissions (telegram.ChatPermissions) – An object for new user permissions.
Keyword Arguments
Raises
telegram.error.TelegramError –
async sendAnimation(chat_id, animation, duration=None, width=None, height=None, thumb=None,
caption=None, parse_mode=None, disable_notification=None,
reply_to_message_id=None, reply_markup=None,
allow_sending_without_reply=None, caption_entities=None,
protect_content=None, *, filename=None, read_timeout=None,
write_timeout=20, connect_timeout=None, pool_timeout=None,
api_kwargs=None)
Alias for send_animation()
async sendAudio(chat_id, audio, duration=None, performer=None, title=None, caption=None,
disable_notification=None, reply_to_message_id=None, reply_markup=None,
parse_mode=None, thumb=None, allow_sending_without_reply=None,
caption_entities=None, protect_content=None, *, filename=None,
read_timeout=None, write_timeout=20, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Alias for send_audio()
async sendChatAction(chat_id, action, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Alias for send_chat_action()
async sendContact(chat_id, phone_number=None, first_name=None, last_name=None,
disable_notification=None, reply_to_message_id=None, reply_markup=None,
vcard=None, allow_sending_without_reply=None, protect_content=None, *,
contact=None, read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Alias for send_contact()
async sendDice(chat_id, disable_notification=None, reply_to_message_id=None, reply_markup=None,
emoji=None, allow_sending_without_reply=None, protect_content=None, *,
read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Alias for send_dice()
async sendDocument(chat_id, document, caption=None, disable_notification=None,
reply_to_message_id=None, reply_markup=None, parse_mode=None,
thumb=None, disable_content_type_detection=None,
allow_sending_without_reply=None, caption_entities=None,
protect_content=None, *, filename=None, read_timeout=None,
write_timeout=20, connect_timeout=None, pool_timeout=None,
api_kwargs=None)
Alias for send_document()
async sendGame(chat_id, game_short_name, disable_notification=None, reply_to_message_id=None,
reply_markup=None, allow_sending_without_reply=None, protect_content=None, *,
read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Alias for send_game()
Note: thumb will be ignored for small files, for which Telegram can easily generate thumbnails.
However, this behaviour is undocumented and might be changed by Telegram.
See also:
telegram.Message.reply_animation, telegram.Chat.send_animation, telegram.User.
send_animation
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• animation (str | file object | bytes | pathlib.Path | telegram.Animation) –
Animation 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. To upload a file, you can either pass a file object
(e.g. open("filename", "rb")), the file contents as bytes or the path of the file (as
string or pathlib.Path object). In the latter case, the file contents will either be read
as bytes or the file path will be passed to Telegram, depending on the local_mode
setting. Lastly you can pass an existing telegram.Animation object to send.
Changed in version 13.2: Accept bytes as input.
• duration (int, optional) – Duration of sent animation in seconds.
• width (int, optional) – Animation width.
• height (int, optional) – Animation height.
• thumb (file object | bytes | pathlib.Path | str, optional) – Thumbnail of the file
sent; can be ignored if thumbnail generation for the file is supported server-side. The
thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail’s
width and height should not exceed 320. Ignored if the file is not uploaded using
multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new
file. To upload a file, you can either pass a file object (e.g. open("filename",
"rb")), the file contents as bytes or the path of the file (as string or pathlib.Path
object). In the latter case, the file contents will either be read as bytes or the file path
will be passed to Telegram, depending on the local_mode setting.
Changed in version 13.2: Accept bytes as input.
Changed in version 20.0: File paths as input is also accepted for bots not running in
local_mode.
• caption (str, optional) – Animation caption (may also be used when resending ani-
mations by file_id), 0-1024 characters after entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram apps
to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.constants.ParseMode for the available modes.
• caption_entities (List[telegram.MessageEntity], optional) – List of special
entities that appear in message text, which can be specified instead of parse_mode.
• disable_notification (bool, optional) – Sends the message silently. Users will
receive a notification with no sound.
• protect_content (bool, optional) – Protects the contents of the sent message from
forwarding and saving.
New in version 13.10.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the original
message.
• allow_sending_without_reply (bool, optional) – Pass True, if the message
should be sent even if the specified replied-to message is not found.
• reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup |
ReplyKeyboardRemove | ForceReply, optional) – Additional interface op-
tions. An object for an inline keyboard, custom reply keyboard, instructions to remove
reply keyboard or to force a reply from the user.
Keyword Arguments
• filename (str, optional) – Custom file name for the animation, when uploading a
new file. Convenience parameter, useful e.g. when sending files generated by the
tempfile module.
New in version 13.1.
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to 20.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• audio (str | file object | bytes | pathlib.Path | telegram.Audio) – Audio 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. To upload a file, you can either pass a file object (e.g.
open("filename", "rb")), the file contents as bytes or the path of the file (as string
or pathlib.Path object). In the latter case, the file contents will either be read as
bytes or the file path will be passed to Telegram, depending on the local_mode setting.
Lastly you can pass an existing telegram.Audio object to send.
Changed in version 13.2: Accept bytes as input.
Changed in version 20.0: File paths as input is also accepted for bots not running in
local_mode.
• caption (str, optional) – Audio caption, 0-1024 characters after entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram apps
to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.constants.ParseMode for the available modes.
• caption_entities (List[telegram.MessageEntity], optional) – List of special
entities that appear in message text, which can be specified instead of parse_mode.
• duration (int, optional) – Duration of sent audio in seconds.
• performer (str, optional) – Performer.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• action (str) – Type of action to broadcast. Choose one, depending on what the user
is about to receive. For convenience look at the constants in telegram.constants.
ChatAction.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
Note: You can either supply contact or phone_number and first_name with optionally
last_name and optionally vcard.
See also:
telegram.Message.reply_contact, telegram.Chat.send_contact, telegram.User.
send_contact
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.
• disable_notification (bool, optional) – Sends the message silently. Users will
receive a notification with no sound.
• protect_content (bool, optional) – Protects the contents of the sent message from
forwarding and saving.
New in version 13.10.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the original
message.
• allow_sending_without_reply (bool, optional) – Pass True, if the message
should be sent even if the specified replied-to message is not found.
• reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup |
ReplyKeyboardRemove | ForceReply, optional) – Additional interface op-
tions. An object for an inline keyboard, custom reply keyboard, instructions to remove
reply keyboard or to force a reply from the user.
Keyword Arguments
• contact (telegram.Contact, optional) – The contact to send.
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, the sent Message is returned.
Return type
telegram.Message
Raises
telegram.error.TelegramError –
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• 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 (InlineKeyboardMarkup | ReplyKeyboardMarkup |
ReplyKeyboardRemove | ForceReply, optional) – Additional interface op-
tions. An object for an inline keyboard, custom reply keyboard, instructions to remove
reply keyboard or to force a reply from the user
• emoji (str, optional) – Emoji on which the dice throw animation is based. Currently,
must be one of telegram.constants.DiceEmoji. Dice can have values 1-6 for '', ''
and '', values 1-5 for '' and '', and values 1-64 for ''. Defaults to ''.
Changed in version 13.4: Added the '' emoji..
• allow_sending_without_reply (bool, optional) – Pass True, if the message
should be sent even if the specified replied-to message is not found.
• protect_content (bool, optional) – Protects the contents of the sent message from
forwarding and saving.
New in version 13.10.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, the sent Message is returned.
Return type
telegram.Message
Raises
telegram.error.TelegramError –
See also:
telegram.Message.reply_document, telegram.Chat.send_document, telegram.User.
send_document
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• document (str | file object | bytes | pathlib.Path | telegram.Document) – File
to send. Pass a file_id as String to send a file that exists on the Telegram servers
(recommended), pass an HTTP URL as a String for Telegram to get a file from the
Internet, or upload a new one. To upload a file, you can either pass a file object (e.g.
open("filename", "rb")), the file contents as bytes or the path of the file (as string
or pathlib.Path object). In the latter case, the file contents will either be read as
bytes or the file path will be passed to Telegram, depending on the local_mode setting.
Lastly you can pass an existing telegram.Document object to send.
Note: Sending by URL will currently only work GIF, PDF & ZIP files.
object). In the latter case, the file contents will either be read as bytes or the file path
will be passed to Telegram, depending on the local_mode setting.
Changed in version 13.2: Accept bytes as input.
Changed in version 20.0: File paths as input is also accepted for bots not running in
local_mode.
Keyword Arguments
• filename (str, optional) – Custom file name for the document, when uploading a
new file. Convenience parameter, useful e.g. when sending files generated by the
tempfile module.
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to 20.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, the sent Message is returned.
Return type
telegram.Message
Raises
telegram.error.TelegramError –
Parameters
• chat_id (int | str) – Unique identifier for the target chat.
• 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.
• protect_content (bool, optional) – Protects the contents of the sent message from
forwarding and saving.
New in version 13.10.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the original
message.
• allow_sending_without_reply (bool, optional) – Pass True, if the message
should be sent even if the specified replied-to message is not found.
Warning: As of API 5.2 start_parameter is an optional argument and therefore the order of
the arguments had to be changed. Use keyword arguments to make sure that the arguments are
passed correctly.
See also:
telegram.Message.reply_invoice, telegram.Chat.send_invoice, telegram.User.
send_invoice
Changed in version 13.5: As of Bot API 5.2, the parameter start_parameter is optional.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• title (str) – Product name. 1- 32 characters.
• description (str) – Product description. 1- 255 characters.
• payload (str) – Bot-defined invoice payload. 1- 128 bytes. This will not be displayed
to the user, use for your internal processes.
• protect_content (bool, optional) – Protects the contents of the sent message from
forwarding and saving.
New in version 13.10.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the original
message.
• allow_sending_without_reply (bool, optional) – Pass True, if the message
should be sent even if the specified replied-to message is not found.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – An object for an
inline keyboard. If empty, one ‘Pay total price’ button will be shown. If not empty, the
first button must be a Pay button.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, the sent Message is returned.
Return type
telegram.Message
Raises
telegram.error.TelegramError –
async send_location(chat_id, latitude=None, longitude=None, disable_notification=None,
reply_to_message_id=None, reply_markup=None, live_period=None,
horizontal_accuracy=None, heading=None, proximity_alert_radius=None,
allow_sending_without_reply=None, protect_content=None, *, location=None,
read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Use this method to send point on the map.
See also:
telegram.Message.reply_location, telegram.Chat.send_location, telegram.User.
send_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.
See also:
telegram.Message.reply_media_group, telegram.Chat.send_media_group, telegram.
User.send_media_group
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• media (List[telegram.InputMediaAudio, telegram.InputMediaDocument,
telegram.InputMediaPhoto, telegram.InputMediaVideo]) – An array
describing messages to be sent, must include 2–10 items.
• disable_notification (bool, optional) – Sends the message silently. Users will
receive a notification with no sound.
• protect_content (bool, optional) – Protects the contents of the sent message from
forwarding and saving.
New in version 13.10.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the original
message.
• allow_sending_without_reply (bool, optional) – Pass True, if the message
should be sent even if the specified replied-to message is not found.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to 20.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
An array of the sent Messages.
Return type
List[telegram.Message]
Raises
telegram.error.TelegramError –
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• text (str) – Text of the message to be sent. Max 4096 characters after entities pars-
ing.
• 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 telegram.constants.ParseMode for the available modes.
• entities (List[telegram.MessageEntity], optional) – List of special entities that
appear in message text, which can be specified instead of parse_mode.
• disable_web_page_preview (bool, optional) – Disables link previews for links in
this message.
• disable_notification (bool, optional) – Sends the message silently. Users will
receive a notification with no sound.
• protect_content (bool, optional) – Protects the contents of sent messages from
forwarding and saving.
New in version 13.10.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the original
message.
• allow_sending_without_reply (bool, optional) – Pass True, if the message
should be sent even if the specified replied-to message is not found.
• reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup |
ReplyKeyboardRemove | ForceReply, optional) – Additional interface op-
tions. An object for an inline keyboard, custom reply keyboard, instructions to remove
reply keyboard or to force a reply from the user.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, the sent message is returned.
Return type
telegram.Message
Raises
telegram.error.TelegramError –
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• photo (str | file object | bytes | pathlib.Path | telegram.PhotoSize) – Photo
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. To upload a file, you can either pass a file object (e.g.
open("filename", "rb")), the file contents as bytes or the path of the file (as string
or pathlib.Path object). In the latter case, the file contents will either be read as
bytes or the file path will be passed to Telegram, depending on the local_mode setting.
Lastly you can pass an existing telegram.PhotoSize object to send.
Changed in version 13.2: Accept bytes as input.
Changed in version 20.0: File paths as input is also accepted for bots not running in
local_mode.
• caption (str, optional) – Photo caption (may also be used when resending photos
by file_id), 0-1024 characters after entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram apps
to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.constants.ParseMode for the available modes.
• caption_entities (List[telegram.MessageEntity], optional) – List of special
entities that appear in message text, which can be specified instead of parse_mode.
• disable_notification (bool, optional) – Sends the message silently. Users will
receive a notification with no sound.
• protect_content (bool, optional) – Protects the contents of the sent message from
forwarding and saving.
New in version 13.10.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the original
message.
• allow_sending_without_reply (bool, optional) – Pass True, if the message
should be sent even if the specified replied-to message is not found.
• reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup |
ReplyKeyboardRemove | ForceReply, optional) – Additional interface op-
tions. An object for an inline keyboard, custom reply keyboard, instructions to remove
reply keyboard or to force a reply from the user.
Keyword Arguments
• filename (str, optional) – Custom file name for the photo, when uploading a new
file. Convenience parameter, useful e.g. when sending files generated by the tempfile
module.
New in version 13.1.
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• question (str) – Poll question, 1-300 characters.
• options (List[str]) – List of answer options, 2-10 strings 1-100 characters each.
• is_anonymous (bool, optional) – True, if the poll needs to be anonymous, defaults
to True.
• type (str, optional) – Poll type, 'quiz' or 'regular', defaults to 'regular'.
• allows_multiple_answers (bool, optional) – True, if the poll allows multiple an-
swers, ignored for polls in quiz mode, defaults to False.
• correct_option_id (int, optional) – 0-based identifier of the correct answer op-
tion, required for polls in quiz mode.
• explanation (str, optional) – Text that is shown when a user chooses an incorrect
answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2
line feeds after entities parsing.
• explanation_parse_mode (str, optional) – Mode for parsing entities in the ex-
planation. See the constants in telegram.constants.ParseMode for the available
modes.
• explanation_entities (List[telegram.MessageEntity], optional) – List of
special entities that appear in message text, which can be specified instead of
explanation_parse_mode.
• open_period (int, optional) – Amount of time in seconds the poll will be active after
creation, 5-600. Can’t be used together with close_date.
• close_date (int | datetime.datetime, optional) – Point in time (Unix timestamp)
when the poll will be automatically closed. Must be at least 5 and no more than 600
seconds in the future. Can’t be used together with open_period. For timezone naive
datetime.datetime objects, the default timezone of the bot will be used, which is
UTC unless telegram.ext.Defaults.tzinfo is used.
• is_closed (bool, optional) – Pass True, if the poll needs to be immediately closed.
This can be useful for poll preview.
• disable_notification (bool, optional) – Sends the message silently. Users will
receive a notification with no sound.
• protect_content (bool, optional) – Protects the contents of the sent message from
forwarding and saving.
New in version 13.10.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the original
message.
• allow_sending_without_reply (bool, optional) – Pass True, if the message
should be sent even if the specified replied-to message is not found.
• reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup |
ReplyKeyboardRemove | ForceReply, optional) – Additional interface op-
tions. An object for an inline keyboard, custom reply keyboard, instructions to remove
reply keyboard or to force a reply from the user.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, the sent Message is returned.
Return type
telegram.Message
Raises
telegram.error.TelegramError –
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• sticker (str | file object | bytes | pathlib.Path | telegram.Sticker) – Sticker
to send. Pass a file_id as String to send a file that exists on the Telegram servers
(recommended), pass an HTTP URL as a String for Telegram to get a file from the
Internet, or upload a new one. To upload a file, you can either pass a file object (e.g.
open("filename", "rb")), the file contents as bytes or the path of the file (as string
or pathlib.Path object). In the latter case, the file contents will either be read as
bytes or the file path will be passed to Telegram, depending on the local_mode setting.
Lastly you can pass an existing telegram.Sticker object to send.
Changed in version 13.2: Accept bytes as input.
Changed in version 20.0: File paths as input is also accepted for bots not running in
local_mode.
• disable_notification (bool, optional) – Sends the message silently. Users will
receive a notification with no sound.
• protect_content (bool, optional) – Protects the contents of the sent message from
forwarding and saving.
New in version 13.10.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the original
message.
• allow_sending_without_reply (bool, optional) – Pass True, if the message
should be sent even if the specified replied-to message is not found.
• reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup |
ReplyKeyboardRemove | ForceReply, optional) – Additional interface op-
tions. An object for an inline keyboard, custom reply keyboard, instructions to remove
reply keyboard or to force a reply from the user.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to 20.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, the sent Message is returned.
Return type
telegram.Message
Raises
telegram.error.TelegramError –
Note:
• You can either supply venue, or latitude, longitude, title and address and
optionally foursquare_id and foursquare_type or optionally google_place_id and
google_place_type.
• Foursquare details and Google Place details are mutually exclusive. However, this behaviour is
undocumented and might be changed by Telegram.
See also:
telegram.Message.reply_venue, telegram.Chat.send_venue, telegram.User.
send_venue
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• latitude (float, optional) – Latitude of venue.
• longitude (float, optional) – Longitude of venue.
• title (str, optional) – Name of the venue.
• address (str, optional) – Address of the venue.
• foursquare_id (str, optional) – Foursquare identifier of the venue.
• foursquare_type (str, optional) – Foursquare type of the venue, if known.
(For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or
“food/icecream”.)
• google_place_id (str, optional) – Google Places identifier of the venue.
• google_place_type (str, optional) – Google Places type of the venue. (See sup-
ported types.)
• disable_notification (bool, optional) – Sends the message silently. Users will
receive a notification with no sound.
• protect_content (bool, optional) – Protects the contents of the sent message from
forwarding and saving.
New in version 13.10.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the original
message.
• allow_sending_without_reply (bool, optional) – Pass True, if the message
should be sent even if the specified replied-to message is not found.
• reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup |
ReplyKeyboardRemove | ForceReply, optional) – Additional interface op-
tions. An object for an inline keyboard, custom reply keyboard, instructions to remove
reply keyboard or to force a reply from the user.
Keyword Arguments
Note: thumb will be ignored for small video files, for which Telegram can easily generate thumbnails.
However, this behaviour is undocumented and might be changed by Telegram.
See also:
telegram.Message.reply_video, telegram.Chat.send_video, telegram.User.
send_video
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• video (str | file object | bytes | pathlib.Path | telegram.Video) – Video 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. To upload a file, you can either pass a file object (e.g.
open("filename", "rb")), the file contents as bytes or the path of the file (as string
or pathlib.Path object). In the latter case, the file contents will either be read as
bytes or the file path will be passed to Telegram, depending on the local_mode setting.
Lastly you can pass an existing telegram.Video object to send.
Changed in version 13.2: Accept bytes as input.
Changed in version 20.0: File paths as input is also accepted for bots not running in
local_mode.
Note: thumb will be ignored for small video files, for which Telegram can easily generate thumbnails.
However, this behaviour is undocumented and might be changed by Telegram.
See also:
telegram.Message.reply_video_note, telegram.Chat.send_video_note, telegram.
User.send_video_note
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• video_note (str | file object | bytes | pathlib.Path | telegram.VideoNote) –
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.
To upload a file, you can either pass a file object (e.g. open("filename", "rb")),
the file contents as bytes or the path of the file (as string or pathlib.Path object). In
the latter case, the file contents will either be read as bytes or the file path will be passed
to Telegram, depending on the local_mode setting. Lastly you can pass an existing
telegram.VideoNote object to send. Sending video notes by a URL is currently
unsupported.
Changed in version 13.2: Accept bytes as input.
Changed in version 20.0: File paths as input is also accepted for bots not running in
local_mode.
• duration (int, optional) – Duration of sent video in seconds.
• length (int, optional) – Video width and height, i.e. diameter of the video message.
• disable_notification (bool, optional) – Sends the message silently. Users will
receive a notification with no sound.
• protect_content (bool, optional) – Protects the contents of the sent message from
forwarding and saving.
New in version 13.10.
be sent as Audio or Document). Bots can currently send voice messages of up to 50 MB in size, this
limit may be changed in the future.
Note: To use this method, the file must have the type audio/ogg and be no more than 1MB in size.
1-20MB voice notes will be sent as files.
See also:
telegram.Message.reply_voice, telegram.Chat.send_voice, telegram.User.
send_voice
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• voice (str | file object | bytes | pathlib.Path | telegram.Voice) – Voice 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. To upload a file, you can either pass a file object (e.g.
open("filename", "rb")), the file contents as bytes or the path of the file (as string
or pathlib.Path object). In the latter case, the file contents will either be read as
bytes or the file path will be passed to Telegram, depending on the local_mode setting.
Lastly you can pass an existing telegram.Voice object to send.
Changed in version 13.2: Accept bytes as input.
Changed in version 20.0: File paths as input is also accepted for bots not running in
local_mode.
• caption (str, optional) – Voice message caption, 0-1024 characters after entities
parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram apps
to show bold, italic, fixed-width text or inline URLs in the media caption. See the
constants in telegram.constants.ParseMode for the available modes.
• caption_entities (List[telegram.MessageEntity], optional) – List of special
entities that appear in message text, which can be specified instead of parse_mode.
• duration (int, optional) – Duration of the voice message in seconds.
• disable_notification (bool, optional) – Sends the message silently. Users will
receive a notification with no sound.
• protect_content (bool, optional) – Protects the contents of the sent message from
forwarding and saving.
New in version 13.10.
• reply_to_message_id (int, optional) – If the message is a reply, ID of the original
message.
• allow_sending_without_reply (bool, optional) – Pass True, if the message
should be sent even if the specified replied-to message is not found.
• reply_markup (InlineKeyboardMarkup | ReplyKeyboardMarkup |
ReplyKeyboardRemove | ForceReply, optional) – Additional interface op-
tions. An object for an inline keyboard, custom reply keyboard, instructions to remove
reply keyboard or to force a reply from the user.
Keyword Arguments
• filename (str, optional) – Custom file name for the voice, when uploading a new file.
Convenience parameter, useful e.g. when sending files generated by the tempfile
module.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
supergroup (in the format @supergroupusername).
• user_id (int) – Unique identifier of the target administrator.
• custom_title (str) – New custom title for the administrator; 0-16 characters, emoji
are not allowed.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• description (str, optional) – New chat description, 0-255 characters.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
Parameters
• chat_id (int, optional) – Unique identifier for the target private chat. If not specified,
default bot’s menu button will be changed
• menu_button (telegram.MenuButton, optional) – An object for the new bot’s menu
button. Defaults to telegram.MenuButtonDefault.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
async set_chat_permissions(chat_id, permissions, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
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 telegram.ChatMemberAdministrator.
can_restrict_members admin rights.
See also:
telegram.Chat.set_permissions
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
supergroup (in the format @supergroupusername).
• permissions (telegram.ChatPermissions) – New default chat permissions.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• photo (file object | bytes | pathlib.Path) – New chat photo. To upload a file, you
can either pass a file object (e.g. open("filename", "rb")), the file contents as
bytes or the path of the file (as string or pathlib.Path object). In the latter case, the
file contents will either be read as bytes or the file path will be passed to Telegram,
depending on the local_mode setting.
Changed in version 13.2: Accept bytes as input.
Changed in version 20.0: File paths as input is also accepted for bots not running in
local_mode.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
supergroup (in the format @supergroupusername).
• sticker_set_name (str) – Name of the sticker set to be set as the group sticker set.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
async set_chat_title(chat_id, title, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Use this method to change the title of a chat. Titles can’t be changed for private chats. The bot must be
an administrator in the chat for this to work and must have the appropriate admin rights.
See also:
telegram.Chat.set_title
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.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
Note:
1. You will not be able to receive updates using get_updates() for long as an outgoing webhook
is set up.
2. To use a self-signed certificate, you need to upload your public key certificate using certificate
parameter. Please upload as InputFile, sending a String will not work.
3. Ports currently supported for Webhooks: telegram.constants.SUPPORTED_WEBHOOK_PORTS.
If you’re having any trouble setting up webhooks, please check out this guide to Webhooks.
Parameters
• url (str) – HTTPS url to send updates to. Use an empty string to remove webhook
integration.
• certificate (file object | bytes | pathlib.Path | str) – Upload your public key
certificate so that the root certificate in use can be checked. See our self-signed guide
for details. To upload a file, you can either pass a file object (e.g. open("filename",
"rb")) or the file contents as bytes. If the bot is running in local_mode, passing the
path of the file (as string or pathlib.Path object) is supported as well.
• ip_address (str, optional) – The fixed IP address which will be used to send web-
hook requests instead of the IP address resolved through DNS.
• max_connections (int, optional) – Maximum allowed number of simultaneous
HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use
lower values to limit the load on your bot’s server, and higher values to increase your
bot’s throughput.
• allowed_updates (List[str], optional) – A 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 telegram.Update for a
complete list of available update types. Specify an empty list to receive all updates
async shutdown()
Stop & clear resources used by this class. Currently just calls telegram.request.BaseRequest.
shutdown() for the request objects used by this bot.
See also:
initialize()
New in version 20.0.
async stopMessageLiveLocation(chat_id=None, message_id=None, inline_message_id=None,
reply_markup=None, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Alias for stop_message_live_location()
async stopPoll(chat_id, message_id, reply_markup=None, *, read_timeout=None,
write_timeout=None, connect_timeout=None, pool_timeout=None,
api_kwargs=None)
Alias for stop_poll()
async stop_message_live_location(chat_id=None, message_id=None, inline_message_id=None,
reply_markup=None, *, read_timeout=None,
write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
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.
See also:
telegram.Message.stop_live_location telegram.CallbackQuery.
stop_message_live_location
Parameters
• chat_id (int | str) – Required if inline_message_id is not specified. Unique
identifier for the target chat or username of the target channel (in the format
@channelusername).
• message_id (int, optional) – Required if inline_message_id is not specified. Identi-
fier of the sent message with live location to stop.
• inline_message_id (str, optional) – Required if chat_id and message_id are not
specified. Identifier of the inline message.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – An object for a
new inline keyboard.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, if edited message is not an inline message, the edited message is returned,
otherwise True is returned.
Return type
telegram.Message
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 (telegram.InlineKeyboardMarkup, optional) – An object for a
new message inline keyboard.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
property supports_inline_queries
Bot’s telegram.User.supports_inline_queries attribute. Shortcut for the corresponding at-
tribute of bot.
Type
bool
to_dict()
See telegram.TelegramObject.to_dict().
property token
Bot’s unique authentication token.
New in version 20.0.
Type
str
async unbanChatMember(chat_id, user_id, only_if_banned=None, *, read_timeout=None,
write_timeout=None, connect_timeout=None, pool_timeout=None,
api_kwargs=None)
Alias for unban_chat_member()
async unbanChatSenderChat(chat_id, sender_chat_id, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Alias for unban_chat_sender_chat()
async unban_chat_member(chat_id, user_id, only_if_banned=None, *, read_timeout=None,
write_timeout=None, connect_timeout=None, pool_timeout=None,
api_kwargs=None)
Use this method to unban a previously kicked user in a supergroup or channel.
The user will not return to the group or channel automatically, but will be able to join via link, etc. The
bot must be an administrator for this to work. By default, this method guarantees that after the call the
user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they
will also be removed from the chat. If you don’t want this, use the parameter only_if_banned.
See also:
telegram.Chat.unban_member
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
supergroup or channel (in the format @channelusername).
Return type
bool
Raises
telegram.error.TelegramError –
async unpinAllChatMessages(chat_id, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Alias for unpin_all_chat_messages()
async unpinChatMessage(chat_id, message_id=None, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Alias for unpin_chat_message()
async unpin_all_chat_messages(chat_id, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Use this method to clear the list of pinned messages in a chat. If the chat is not a private chat, the bot
must be an administrator in the chat for this to work and must have the can_pin_messages admin
right in a supergroup or can_edit_messages admin right in a channel.
See also:
telegram.Chat.unpin_all_messages, telegram.User.unpin_all_messages
Parameters
chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
Parameters
• chat_id (int | str) – Unique identifier for the target chat or username of the target
channel (in the format @channelusername).
• message_id (int, optional) – Identifier of a message to unpin. If not specified, the
most recent pinned message (by sending date) will be unpinned.
Keyword Arguments
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
• api_kwargs (dict, optional) – Arbitrary keyword arguments to be passed to the Tele-
gram API.
Returns
On success, True is returned.
Return type
bool
Raises
telegram.error.TelegramError –
telegram.BotCommand
telegram.BotCommandScope
• telegram.BotCommandScopeAllChatAdministrators
• telegram.BotCommandScopeChat
• telegram.BotCommandScopeChatAdministrators
• telegram.BotCommandScopeChatMember
Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if
their type is equal. For subclasses with additional attributes, the notion of equality is overridden.
Note: Please see the official docs on how Telegram determines which commands to display.
telegram.BotCommandScopeAllChatAdministrators
telegram.BotCommandScopeAllGroupChats
telegram.BotCommandScopeAllPrivateChats
telegram.BotCommandScopeChat
type
Scope type 'chat'.
Type
str
chat_id
Unique identifier for the target chat or username of the target supergroup (in the format
@supergroupusername)
Type
str | int
telegram.BotCommandScopeChatAdministrators
telegram.BotCommandScopeChatMember
type
Scope type 'chat_member'.
Type
str
chat_id
Unique identifier for the target chat or username of the target supergroup (in the format
@supergroupusername)
Type
str | int
user_id
Unique identifier of the target user.
Type
int
telegram.BotCommandScopeDefault
telegram.CallbackQuery
Note:
• In Python from is a reserved word use from_user instead.
• Exactly one of the fields data or game_short_name will be present.
• After the user presses an inline button, Telegram clients will display a progress bar until you call
answer. It is, therefore, necessary to react by calling telegram.Bot.answer_callback_query
even if no notification to the user is needed (e.g., without specifying any of the optional parameters).
Parameters
• id (str) – Unique identifier for this query.
• from_user (telegram.User) – Sender.
• chat_instance (str) – Global identifier, uniquely corresponding to the chat to which
the message with the callback button was sent. Useful for high scores in games.
• message (telegram.Message, optional) – Message with the callback button that orig-
inated the query. Note that message content and message date will not be available if the
message is too old.
• data (str, optional) – Data associated with the callback button. Be aware that the
message, which originated the query, can contain no callback buttons with this data.
• inline_message_id (str, optional) – Identifier of the message sent via the bot in
inline mode, that originated the query.
• game_short_name (str, optional) – Short name of a Game to be returned, serves as
the unique identifier for the game
id
Unique identifier for this query.
Type
str
from_user
Sender.
Type
telegram.User
chat_instance
Global identifier, uniquely corresponding to the chat to which the message with the callback button
was sent.
Type
str
message
Optional. Message with the callback button that originated the query.
Type
telegram.Message
data
Optional. Data associated with the callback button.
Tip: The value here is the same as the value passed in telegram.InlineKeyboardButton.
callback_data.
Type
str | object
inline_message_id
Optional. Identifier of the message sent via the bot in inline mode, that originated the query.
Type
str
game_short_name
Optional. Short name of a Game to be returned.
Type
str
MAX_ANSWER_TEXT_LENGTH = 200
telegram.constants.CallbackQueryLimit.ANSWER_CALLBACK_QUERY_TEXT_LENGTH
New in version 13.2.
async answer(text=None, show_alert=None, url=None, cache_time=None, *, read_timeout=None,
write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)
Shortcut for:
await update.callback_query.message.copy(
from_chat_id=update.message.chat_id,
message_id=update.message.message_id,
*args,
**kwargs
)
Returns
On success, True is returned.
Return type
bool
async edit_message_caption(caption=None, reply_markup=None, parse_mode=None,
caption_entities=None, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Shortcut for either:
or:
await bot.edit_message_caption(
inline_message_id=update.callback_query.inline_message_id, *args,␣
˓→**kwargs,
or:
await bot.edit_message_live_location(
inline_message_id=update.callback_query.inline_message_id, *args,␣
˓→**kwargs
or:
await bot.edit_message_media(
inline_message_id=update.callback_query.inline_message_id, *args,␣
˓→**kwargs
or:
await bot.edit_message_reply_markup(
inline_message_id=update.callback_query.inline_message_id, *args,␣
˓→**kwargs
or:
await bot.edit_message_text(
inline_message_id=update.callback_query.inline_message_id, *args,␣
˓→**kwargs,
Returns
On success, if edited message is sent by the bot, the edited Message is returned, otherwise
True is returned.
Return type
telegram.Message
async get_game_high_scores(user_id, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Shortcut for either:
or:
await bot.get_game_high_scores(
inline_message_id=update.callback_query.inline_message_id, *args,␣
˓→**kwargs
or:
await bot.set_game_score(
inline_message_id=update.callback_query.inline_message_id, *args,␣
˓→**kwargs
or:
await bot.stop_message_live_location(
inline_message_id=update.callback_query.inline_message_id, *args,␣
˓→**kwargs
telegram.Chat
has_private_forwards
Optional. True, if privacy settings of the other party in the private chat allows to use tg://user?
id=<user_id> links only in chats with the user.
New in version 13.9.
Type
bool
description
Optional. Description, for groups, supergroups and channel chats.
Type
str
invite_link
Optional. Primary invite link, for groups, supergroups and channel. Returned only in telegram.Bot.
get_chat().
Type
str
pinned_message
Optional. The most recent pinned message (by sending date). Returned only in telegram.Bot.
get_chat().
Type
telegram.Message
permissions
Optional. Default chat member permissions, for groups and supergroups. Returned only in telegram.
Bot.get_chat().
Type
telegram.ChatPermissions
slow_mode_delay
Optional. For supergroups, the minimum allowed delay between consecutive messages sent by each
unprivileged user. Returned only in telegram.Bot.get_chat().
Type
int
message_auto_delete_time
Optional. The time after which all messages sent to the chat will be automatically deleted; in seconds.
Returned only in telegram.Bot.get_chat().
New in version 13.4.
Type
int
has_protected_content
Optional. True, if messages from the chat can’t be forwarded to other chats.
New in version 13.9.
Type
bool
sticker_set_name
Optional. For supergroups, name of Group sticker set.
Type
str
can_set_sticker_set
Optional. True, if the bot can change group the sticker set.
Type
bool
linked_chat_id
Optional. Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and
vice versa; for supergroups and channel chats. Returned only in telegram.Bot.get_chat().
Type
int
location
Optional. For supergroups, the location to which the supergroup is connected. Returned only in
telegram.Bot.get_chat().
Type
telegram.ChatLocation
join_to_send_messages
Optional. True, if users need to join the supergroup before they can send messages. Returned only in
telegram.Bot.get_chat().
New in version 20.0.
Type
bool
join_by_request
Optional. True, if all users directly joining the supergroup need to be approved by supergroup admin-
istrators. Returned only in telegram.Bot.get_chat().
New in version 20.0.
Type
bool
has_restricted_voice_and_video_messages
Optional. True, if the privacy settings of the other party restrict sending voice and video note messages
in the private chat. Returned only in telegram.Bot.get_chat().
New in version 20.0.
Type
bool
CHANNEL = 'channel'
telegram.constants.ChatType.CHANNEL
GROUP = 'group'
telegram.constants.ChatType.GROUP
PRIVATE = 'private'
telegram.constants.ChatType.PRIVATE
SENDER = 'sender'
telegram.constants.ChatType.SENDER
New in version 13.5.
SUPERGROUP = 'supergroup'
telegram.constants.ChatType.SUPERGROUP
await bot.ban_chat_sender_chat(
sender_chat_id=update.effective_chat.id, *args, **kwargs
)
Return type
bool
async copy_message(chat_id, message_id, caption=None, parse_mode=None, caption_entities=None,
disable_notification=None, reply_to_message_id=None,
allow_sending_without_reply=None, reply_markup=None,
protect_content=None, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Shortcut for:
await bot.delete_chat_photo(
chat_id=update.effective_chat.id, *args, **kwargs
)
Returns
On success, instance representing the message posted.
Return type
telegram.Message
async forward_to(chat_id, message_id, disable_notification=None, protect_content=None, *,
read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Shortcut for:
Returns
telegram.ChatMember
async get_member_count(*, read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Shortcut for:
See also:
set_menu_button()
New in version 20.0.
Returns
On success, the current menu button is returned.
Return type
telegram.MenuButton
async leave(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None,
api_kwargs=None)
Shortcut for:
Warning: As of API 5.2 start_parameter is an optional argument and therefore the order of
the arguments had to be changed. Use keyword arguments to make sure that the arguments are
passed correctly.
Changed in version 13.5: As of Bot API 5.2, the parameter start_parameter is optional.
Returns
On success, instance representing the message posted.
Return type
telegram.Message
async send_location(latitude=None, longitude=None, disable_notification=None,
reply_to_message_id=None, reply_markup=None, live_period=None,
horizontal_accuracy=None, heading=None, proximity_alert_radius=None,
allow_sending_without_reply=None, protect_content=None, *, location=None,
read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Shortcut for:
Returns
On success, instance representing the message posted.
Return type
telegram.Message
async send_sticker(sticker, disable_notification=None, reply_to_message_id=None,
reply_markup=None, allow_sending_without_reply=None,
protect_content=None, *, read_timeout=None, write_timeout=20,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Shortcut for:
Shortcut for:
await bot.set_chat_administrator_custom_title(
update.effective_chat.id, *args, **kwargs
)
await bot.set_chat_description(
chat_id=update.effective_chat.id, *args, **kwargs
)
Return type
bool
async set_menu_button(menu_button=None, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Shortcut for:
See also:
get_menu_button()
New in version 20.0.
Returns
On success, True is returned.
Return type
bool
async set_permissions(permissions, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Shortcut for:
await bot.set_chat_photo(
chat_id=update.effective_chat.id, *args, **kwargs
)
await bot.set_chat_title(
chat_id=update.effective_chat.id, *args, **kwargs
)
await bot.unban_chat_sender_chat(
sender_chat_id=update.effective_chat.id, *args, **kwargs
)
telegram.ChatAdministratorRights
can_invite_users
True, if the user is allowed to invite new users to the chat.
Type
bool
can_post_messages
Optional. True, if the administrator can post messages in the channel; channels only.
Type
bool
can_edit_messages
Optional. True, if the administrator can edit messages of other users.
Type
bool
can_pin_messages
Optional. True, if the user is allowed to pin messages; groups and supergroups only.
Type
bool
classmethod all_rights()
This method returns the ChatAdministratorRights object with all attributes set to True.
This is e.g. useful when changing the bot’s default administrator rights with telegram.Bot.
set_my_default_administrator_rights().
New in version 20.0.
classmethod no_rights()
This method returns the ChatAdministratorRights object with all attributes set to False.
New in version 20.0.
telegram.ChatInviteLink
Parameters
• invite_link (str) – The invite link.
• creator (telegram.User) – Creator of the link.
• creates_join_request (bool) – True, if users joining the chat via the link need to
be approved by chat administrators.
New in version 13.8.
invite_link
The invite link. If the link was created by another chat administrator, then the second part of the link
will be replaced with '...'.
Type
str
creator
Creator of the link.
Type
telegram.User
creates_join_request
True, if users joining the chat via the link need to be approved by chat administrators.
New in version 13.8.
Type
bool
is_primary
True, if the link is primary.
Type
bool
is_revoked
True, if the link is revoked.
Type
bool
expire_date
Optional. Date when the link will expire or has been expired.
Type
datetime.datetime
member_limit
Optional. Maximum number of users that can be members of the chat simultaneously after joining the
chat via this invite link; 1-99999.
Type
int
name
Optional. Invite link name.
New in version 13.8.
Type
str
pending_join_request_count
Optional. Number of pending join requests created using this link.
New in version 13.8.
Type
int
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
to_dict()
See telegram.TelegramObject.to_dict().
telegram.ChatJoinRequest
Note: Since Bot API 5.5, bots are allowed to contact users who sent a join request to a chat where the bot
is an administrator with the can_invite_users administrator right – even if the user never interacted with
the bot before.
date
Date the request was sent.
Type
datetime.datetime
bio
Optional. Bio of the user.
Type
str
invite_link
Optional. Chat invite link that was used by the user to send the join request.
Type
telegram.ChatInviteLink
async approve(*, read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Shortcut for:
await bot.approve_chat_join_request(
chat_id=update.effective_chat.id, user_id=update.effective_user.id,␣
˓→*args, **kwargs
await bot.decline_chat_join_request(
chat_id=update.effective_chat.id, user_id=update.effective_user.id,␣
˓→*args, **kwargs
telegram.ChatLocation
telegram.ChatMember
Parameters
• user (telegram.User) – Information about the user.
• status (str) – The member’s status in the chat. Can be ADMINISTRATOR, OWNER,
BANNED, LEFT, MEMBER or RESTRICTED.
user
Information about the user.
Type
telegram.User
status
The member’s status in the chat.
Type
str
ADMINISTRATOR = 'administrator'
telegram.constants.ChatMemberStatus.ADMINISTRATOR
BANNED = 'kicked'
telegram.constants.ChatMemberStatus.BANNED
LEFT = 'left'
telegram.constants.ChatMemberStatus.LEFT
MEMBER = 'member'
telegram.constants.ChatMemberStatus.MEMBER
OWNER = 'creator'
telegram.constants.ChatMemberStatus.OWNER
RESTRICTED = 'restricted'
telegram.constants.ChatMemberStatus.RESTRICTED
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
to_dict()
See telegram.TelegramObject.to_dict().
telegram.ChatMemberAdministrator
Parameters
• user (telegram.User) – Information about the user.
• can_be_edited (bool) – True, if the bot is allowed to edit administrator privileges of
that user.
• is_anonymous (bool) – True, if the user’s presence in the chat is hidden.
• can_manage_chat (bool) – True, if the administrator can access the chat event log,
chat statistics, message statistics in channels, see channel members, see anonymous ad-
ministrators in supergroups and ignore slow mode. Implied by any other administrator
privilege.
• can_delete_messages (bool) – True, if the administrator can delete messages of
other users.
• can_manage_video_chats (bool) – True, if the administrator can manage video
chats.
New in version 20.0.
• can_restrict_members (bool) – True, if the administrator can restrict, ban or unban
chat members.
• can_promote_members (bool) – True, if the administrator can add new administra-
tors 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).
• can_change_info (bool) – True, if the user can change the chat title, photo and other
settings.
• can_invite_users (bool) – True, if the user can invite new users to the chat.
• can_post_messages (bool, optional) – True, if the administrator can post in the chan-
nel, channels only.
• can_edit_messages (bool, optional) – True, if the administrator can edit messages
of other users and can pin messages; channels only.
• can_pin_messages (bool, optional) – True, if the user is allowed to pin messages;
groups and supergroups only.
• custom_title (str, optional) – Custom title for this user.
status
The member’s status in the chat, always 'administrator'.
Type
str
user
Information about the user.
Type
telegram.User
can_be_edited
True, if the bot is allowed to edit administrator privileges of that user.
Type
bool
is_anonymous
True, if the user’s presence in the chat is hidden.
Type
bool
can_manage_chat
True, if the administrator can access the chat event log, chat statistics, message statistics in channels,
see channel members, see anonymous administrators in supergroups and ignore slow mode. Implied
by any other administrator privilege.
Type
bool
can_delete_messages
True, if the administrator can delete messages of other users.
Type
bool
can_manage_video_chats
True, if the administrator can manage video chats.
New in version 20.0.
Type
bool
can_restrict_members
True, if the administrator can restrict, ban or unban chat members.
Type
bool
can_promote_members
True, if the administrator can add new administrators with a subset of his own privileges or demote
administrators that he has promoted, directly or indirectly (promoted by administrators that were ap-
pointed by the user).
Type
bool
can_change_info
True, if the user can change the chat title, photo and other settings.
Type
bool
can_invite_users
True, if the user can invite new users to the chat.
Type
bool
can_post_messages
Optional. True, if the administrator can post in the channel, channels only.
Type
bool
can_edit_messages
Optional. True, if the administrator can edit messages of other users and can pin messages; channels
only.
Type
bool
can_pin_messages
Optional. True, if the user is allowed to pin messages; groups and supergroups only.
Type
bool
custom_title
Optional. Custom title for this user.
Type
str
telegram.ChatMemberBanned
telegram.ChatMemberLeft
telegram.ChatMemberMember
telegram.ChatMemberOwner
telegram.ChatMemberRestricted
can_invite_users
True, if the user can invite new users to the chat.
Type
bool
can_pin_messages
True, if the user is allowed to pin messages; groups and supergroups only.
Type
bool
can_send_messages
True, if the user is allowed to send text messages, contacts, locations and venues.
Type
bool
can_send_media_messages
True, if the user is allowed to send audios, documents, photos, videos, video notes and voice notes.
Type
bool
can_send_polls
True, if the user is allowed to send polls.
Type
bool
can_send_other_messages
True, if the user is allowed to send animations, games, stickers and use inline bots.
Type
bool
can_add_web_page_previews
True, if the user is allowed to add web page previews to their messages.
Type
bool
until_date
Date when restrictions will be lifted for this user.
Type
datetime.datetime
telegram.ChatMemberUpdated
Parameters
• chat (telegram.Chat) – Chat the user belongs to.
• from_user (telegram.User) – Performer of the action, which resulted in the change.
• date (datetime.datetime) – Date the change was done in Unix time. Converted to
datetime.datetime.
• old_chat_member (telegram.ChatMember) – Previous information about the chat
member.
• new_chat_member (telegram.ChatMember) – New information about the chat mem-
ber.
• invite_link (telegram.ChatInviteLink, optional) – Chat invite link, which was
used by the user to join the chat. For joining by invite link events only.
chat
Chat the user belongs to.
Type
telegram.Chat
from_user
Performer of the action, which resulted in the change.
Type
telegram.User
date
Date the change was done in Unix time. Converted to datetime.datetime.
Type
datetime.datetime
old_chat_member
Previous information about the chat member.
Type
telegram.ChatMember
new_chat_member
New information about the chat member.
Type
telegram.ChatMember
invite_link
Optional. Chat invite link, which was used by the user to join the chat.
Type
telegram.ChatInviteLink
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
difference()
Computes the difference between old_chat_member and new_chat_member.
Example
>>> chat_member_updated.difference()
{'custom_title': ('old title', 'new title')}
telegram.ChatPermissions
Note: Though not stated explicitly in the official docs, Telegram changes not only the permissions that
are set, but also sets all the others to False. However, since not documented, this behaviour may change
unbeknown to PTB.
Parameters
• can_send_messages (bool, optional) – True, if the user is allowed to send text mes-
sages, contacts, locations and venues.
• can_send_media_messages (bool, optional) – True, if the user is allowed to
send audios, documents, photos, videos, video notes and voice notes, implies
can_send_messages.
• can_send_polls (bool, optional) – True, if the user is allowed to send polls, implies
can_send_messages.
• can_send_other_messages (bool, optional) – True, if the user is allowed to send
animations, games, stickers and use inline bots, implies can_send_media_messages.
• can_add_web_page_previews (bool, optional) – True, if the user is allowed to add
web page previews to their messages, implies can_send_media_messages.
• can_change_info (bool, optional) – True, if the user is allowed to change the chat
title, photo and other settings. Ignored in public supergroups.
• can_invite_users (bool, optional) – True, if the user is allowed to invite new users
to the chat.
can_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
classmethod all_permissions()
This method returns an ChatPermissions instance with all attributes set to True. This is e.g. useful
when unrestricting a chat member with telegram.Bot.restrict_chat_member().
New in version 20.0.
classmethod no_permissions()
This method returns an ChatPermissions instance with all attributes set to False.
New in version 20.0.
telegram.ChatPhoto
Raises
telegram.error.TelegramError –
async get_small_file(*, read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Convenience wrapper over telegram.Bot.get_file for getting the small (160x160) chat photo
For the documentation of the arguments, please see telegram.Bot.get_file().
Returns
telegram.File
Raises
telegram.error.TelegramError –
telegram.Contact
telegram.Dice
Note: If emoji is “”, a value of 6 currently represents a bullseye, while a value of 1 indicates that the
dartboard was missed. However, this behaviour is undocumented and might be changed by Telegram.
If emoji is “”, a value of 4 or 5 currently score a basket, while a value of 1 to 3 indicates that the basket was
missed. However, this behaviour is undocumented and might be changed by Telegram.
If emoji is “”, a value of 4 to 5 currently scores a goal, while a value of 1 to 3 indicates that the goal was
missed. However, this behaviour is undocumented and might be changed by Telegram.
If emoji is “”, a value of 6 knocks all the pins, while a value of 1 means all the pins were missed. However,
this behaviour is undocumented and might be changed by Telegram.
If emoji is “”, each value corresponds to a unique combination of symbols, which can be found at our wiki.
However, this behaviour is undocumented and might be changed by Telegram.
Parameters
• value (int) – Value of the dice. 1-6 for dice, darts and bowling balls, 1-5 for basketball
and football/soccer ball, 1-64 for slot machine.
• emoji (str) – Emoji on which the dice throw animation is based.
value
Value of the dice.
Type
int
emoji
Emoji on which the dice throw animation is based.
Type
str
ALL_EMOJI = [<DiceEmoji.DICE>, <DiceEmoji.DARTS>, <DiceEmoji.BASKETBALL>,
<DiceEmoji.FOOTBALL>, <DiceEmoji.SLOT_MACHINE>, <DiceEmoji.BOWLING>]
A list of all available dice emoji.
Type
List[str]
BASKETBALL = ''
telegram.constants.DiceEmoji.BASKETBALL
BOWLING = ''
telegram.constants.DiceEmoji.BOWLING
New in version 13.4.
DARTS = ''
telegram.constants.DiceEmoji.DARTS
DICE = ''
telegram.constants.DiceEmoji.DICE
FOOTBALL = ''
telegram.constants.DiceEmoji.FOOTBALL
SLOT_MACHINE = ''
telegram.constants.DiceEmoji.SLOT_MACHINE
telegram.Document
file_size
Optional. File size in bytes.
Type
int
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
async get_file(*, read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Convenience wrapper over telegram.Bot.get_file
For the documentation of the arguments, please see telegram.Bot.get_file().
Returns
telegram.File
Raises
telegram.error.TelegramError –
telegram.File
Note:
• Maximum file size to download is 20 MB.
• If you obtain an instance of this class from telegram.PassportFile.get_file, then it will auto-
matically be decrypted as it downloads when you call download().
Parameters
• file_id (str) – Identifier for this file, which can be used to download or reuse the file.
• file_unique_id (str) – Unique identifier for this file, which is supposed to be the
same over time and for different bots. Can’t be used to download or reuse the file.
• file_size (int, optional) – Optional. File size in bytes, if known.
• file_path (str, optional) – File path. Use download to get the file.
file_id
Identifier for this file.
Type
str
file_unique_id
Unique identifier for this file, which is supposed to be the same over time and for different bots. Can’t
be used to download or reuse the file.
Type
str
file_size
Optional. File size in bytes.
Type
str
file_path
Optional. File path. Use download() to get the file.
Type
str
async download(custom_path=None, out=None, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None)
Download this file. By default, the file is saved in the current working directory with its original
filename as reported by Telegram. If the file has no filename, it the file ID will be used as filename.
If a custom_path is supplied, it will be saved to that path instead. If out is defined, the file contents
will be saved to that object using the out.write method.
Note:
• custom_path and out are mutually exclusive.
• If neither custom_path nor out is provided and file_path is the path of a local file (which is
the case when a Bot API Server is running in local mode), this method will just return the path.
Parameters
• custom_path (pathlib.Path | str, optional) – Custom path.
• out (io.BufferedWriter, optional) – A file-like object. Must be opened for writing
in binary mode, if applicable.
• read_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.read_timeout. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.write_timeout. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.connect_timeout. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – Value to pass to telegram.request.
BaseRequest.post.pool_timeout. Defaults to DEFAULT_NONE.
Returns
The same object as out if specified. Otherwise, returns the filename downloaded to or
the file path of the local file.
Return type
pathlib.Path | io.BufferedWriter
Raises
ValueError – If both custom_path and out are passed.
async download_as_bytearray(buf=None)
Download this file and return it as a bytearray.
Parameters
buf (bytearray, optional) – Extend the given bytearray with the downloaded data.
Returns
The same object as buf if it was specified. Otherwise a newly allocated bytearray.
Return type
bytearray
set_credentials(credentials)
Sets the passport credentials for the file.
Parameters
credentials (telegram.FileCredentials) – The credentials.
telegram.ForceReply
telegram.InlineKeyboardButton
Note:
• You must use exactly one of the optional fields. Mind that callback_game is not working as expected.
Putting a game short name in it might, but is not guaranteed to work.
• If your bot allows for arbitrary callback data, in keyboards returned in a response from telegram,
callback_data maybe be an instance of telegram.ext.InvalidCallbackData. This will be the
case, if the data associated with the button was already deleted.
New in version 13.6.
• Since Bot API 5.5, it’s now allowed to mention users by their ID in inline keyboards. This will only
work in Telegram versions released after December 7, 2021. Older clients will display unsupported
message.
Warning:
• If your bot allows your arbitrary callback data, buttons whose callback data is a non-hashable object
will become unhashable. Trying to evaluate hash(button) will result in a TypeError.
Changed in version 13.6.
• After Bot API 6.1, only HTTPS links will be allowed in login_url.
See also:
Inline Keyboard Example 1, Inline Keyboard Example 2, telegram.InlineKeyboardMarkup
Changed in version 20.0: web_app is considered as well when comparing objects of this type in terms of
equality.
Parameters
• text (str) – Label text on the button.
• url (str, optional) – HTTP or tg:// url to be opened when the button is pressed. Links
tg://user?id=<user_id> can be used to mention a user by their ID without using a
username, if this is allowed by their privacy settings.
Changed in version 13.9: You can now mention a user using tg://user?
id=<user_id>.
• login_url (telegram.LoginUrl, optional) – An HTTPS URL used to automatically
authorize the user. Can be used as a replacement for the Telegram Login Widget.
Caution: Only HTTPS links are allowed after Bot API 6.1.
• callback_data (str | object, optional) – Data to be sent in a callback query to the bot
when button is pressed, UTF-8 1-64 bytes. If the bot instance allows arbitrary callback
data, anything can be passed.
Caution: Only HTTPS links are allowed after Bot API 6.1.
Type
telegram.LoginUrl
callback_data
Optional. Data to be sent in a callback query to the bot when button is pressed, UTF-8 1-64 bytes.
Type
str | object
web_app
Optional. Description of the Web App that will be launched when the user presses the button.
The Web App will be able to send an arbitrary message on behalf of the user using the method
answer_web_app_query(). Available only in private chats between a user and the bot.
New in version 20.0.
Type
telegram.WebAppInfo
switch_inline_query
Optional. Will prompt the user to select one of their chats, open that chat and insert the bot’s username
and the specified inline query in the input field. Can be empty, in which case just the bot’s username
will be inserted.
Type
str
switch_inline_query_current_chat
Optional. Will insert the bot’s username and the specified inline query in the current chat’s input field.
Can be empty, in which case just the bot’s username will be inserted.
Type
str
callback_game
Optional. Description of the game that will be launched when the user presses the button.
Type
telegram.CallbackGame
pay
Optional. Specify True, to send a Pay button.
Type
bool
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
update_callback_data(callback_data)
Sets callback_data to the passed object. Intended to be used by telegram.ext.
CallbackDataCache.
New in version 13.6.
Parameters
callback_data (object) – The new callback data.
telegram.InlineKeyboardMarkup
Parameters
inline_keyboard (List[List[telegram.InlineKeyboardButton]]) – List of button
rows, each represented by a list of InlineKeyboardButton objects.
inline_keyboard
List of button rows, each represented by a list of InlineKeyboardButton objects.
Type
List[List[telegram.InlineKeyboardButton]]
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
classmethod from_button(button, **kwargs)
Shortcut for:
InlineKeyboardMarkup([[button]], **kwargs)
InlineKeyboardMarkup([button_row], **kwargs)
telegram.InputFile
Parameters
• obj (file object | bytes | str) – An open file descriptor or the files content as bytes or
string.
input_file_content
The binary content of the file to send.
Type
bytes
attach_name
Optional. If present, the parameter this file belongs to in the request to Telegram should point to the
multipart data via a an URI of the form attach://<attach_name> URI.
Type
str
filename
Filename for the file to be sent.
Type
str
mimetype
The mimetype inferred from the file to be sent.
Type
str
property attach_uri
URI to insert into the JSON data for uploading the file. Returns None, if attach_name is None.
property field_tuple
Field tuple representing the contents of the file for upload to the Telegram servers.
Return type
Tuple[str, bytes, str]
telegram.InputMedia
to_dict()
See telegram.TelegramObject.to_dict().
telegram.InputMediaAnimation
Note: When using a telegram.Animation for the media attribute, it will take the width, height and
duration from that video, unless otherwise specified with the optional arguments.
Parameters
• media (str | file object | bytes | pathlib.Path | telegram.Animation) – File to
send. Pass a file_id as String to send a file that exists on the Telegram servers (rec-
ommended), pass an HTTP URL as a String for Telegram to get a file from the In-
ternet, or upload a new one. To upload a file, you can either pass a file object (e.g.
open("filename", "rb")) or the file contents as bytes. If the bot is running in
local_mode, passing the path of the file (as string or pathlib.Path object) is sup-
ported as well. Lastly you can pass an existing telegram.Animation object to send.
Changed in version 13.2: Accept bytes as input.
• filename (str, optional) – Custom file name for the animation, when uploading a new
file. Convenience parameter, useful e.g. when sending files generated by the tempfile
module.
New in version 13.1.
• thumb (file object | bytes | pathlib.Path | str, optional) – Thumbnail of the file sent;
can be ignored if thumbnail generation for the file is supported server-side. The thumb-
nail should be in JPEG format and less than 200 kB in size. A thumbnail’s width and
height should not exceed 320. Ignored if the file is not uploaded using multipart/form-
data. Thumbnails can’t be reused and can be only uploaded as a new file. To upload a
file, you can either pass a file object (e.g. open("filename", "rb")) or the file con-
tents as bytes. If the bot is running in local_mode, passing the path of the file (as string
or pathlib.Path object) is supported as well.
Changed in version 13.2: Accept bytes as input.
• caption (str, optional) – Caption of the animation to be sent, 0-1024 characters after
entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram apps to
show bold, italic, fixed-width text or inline URLs in the media caption. See the constants
in telegram.constants.ParseMode for the available modes.
• caption_entities (List[telegram.MessageEntity], optional) – List of special en-
tities that appear in the caption, which can be specified instead of parse_mode.
• width (int, optional) – Animation width.
• height (int, optional) – Animation height.
• duration (int, optional) – Animation duration in seconds.
type
'animation'.
Type
str
media
Animation to send.
Type
str | telegram.InputFile
caption
Optional. Caption of the document to be sent.
Type
str
parse_mode
Optional. The parse mode to use for text formatting.
Type
str
caption_entities
Optional. List of special entities that appear in the caption.
Type
List[telegram.MessageEntity]
thumb
Optional. Thumbnail of the file to send.
Type
telegram.InputFile
width
Optional. Animation width.
Type
int
height
Optional. Animation height.
Type
int
duration
Optional. Animation duration in seconds.
Type
int
telegram.InputMediaAudio
Note: When using a telegram.Audio for the media attribute, it will take the duration, performer and title
from that video, unless otherwise specified with the optional arguments.
Parameters
• media (str | file object | bytes | pathlib.Path | telegram.Audio) – File to send.
Pass a file_id as String to send a file that exists on the Telegram servers (recom-
mended), pass an HTTP URL as a String for Telegram to get a file from the Inter-
net, or upload a new one. To upload a file, you can either pass a file object (e.g.
open("filename", "rb")) or the file contents as bytes. If the bot is running in
local_mode, passing the path of the file (as string or pathlib.Path object) is sup-
ported as well. Lastly you can pass an existing telegram.Audio object to send.
Changed in version 13.2: Accept bytes as input.
• filename (str, optional) – Custom file name for the audio, when uploading a new
file. Convenience parameter, useful e.g. when sending files generated by the tempfile
module.
New in version 13.1.
• caption (str, optional) – Caption of the audio to be sent, 0-1024 characters after
entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram apps to
show bold, italic, fixed-width text or inline URLs in the media caption. See the constants
in telegram.constants.ParseMode for the available modes.
• caption_entities (List[telegram.MessageEntity], optional) – List of special en-
tities that appear in the caption, which can be specified instead of parse_mode.
• duration (int) – Duration of the audio in seconds as defined by sender.
• performer (str, optional) – Performer of the audio as defined by sender or by audio
tags.
• title (str, optional) – Title of the audio as defined by sender or by audio tags.
• thumb (file object | bytes | pathlib.Path | str, optional) – Thumbnail of the file sent;
can be ignored if thumbnail generation for the file is supported server-side. The thumb-
nail should be in JPEG format and less than 200 kB in size. A thumbnail’s width and
height should not exceed 320. Ignored if the file is not uploaded using multipart/form-
data. Thumbnails can’t be reused and can be only uploaded as a new file. To upload a
file, you can either pass a file object (e.g. open("filename", "rb")) or the file con-
tents as bytes. If the bot is running in local_mode, passing the path of the file (as string
or pathlib.Path object) is supported as well.
Changed in version 13.2: Accept bytes as input.
type
'audio'.
Type
str
media
Audio file to send.
Type
str | telegram.InputFile
caption
Optional. Caption of the document to be sent.
Type
str
parse_mode
Optional. The parse mode to use for text formatting.
Type
str
caption_entities
Optional. List of special entities that appear in the caption.
Type
List[telegram.MessageEntity]
duration
Duration of the audio in seconds.
Type
int
performer
Optional. Performer of the audio as defined by sender or by audio tags.
Type
str
title
Optional. Title of the audio as defined by sender or by audio tags.
Type
str
thumb
Optional. Thumbnail of the file to send.
Type
telegram.InputFile
telegram.InputMediaDocument
local_mode, passing the path of the file (as string or pathlib.Path object) is sup-
ported as well. Lastly you can pass an existing telegram.Document object to send.
Changed in version 13.2: Accept bytes as input.
• filename (str, optional) – Custom file name for the document, when uploading a new
file. Convenience parameter, useful e.g. when sending files generated by the tempfile
module.
New in version 13.1.
• caption (str, optional) – Caption of the document to be sent, 0-1024 characters after
entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram apps to
show bold, italic, fixed-width text or inline URLs in the media caption. See the constants
in telegram.constants.ParseMode for the available modes.
• caption_entities (List[telegram.MessageEntity], optional) – List of special en-
tities that appear in the caption, which can be specified instead of parse_mode.
• thumb (file object | bytes | pathlib.Path | str, optional) – Thumbnail of the file sent;
can be ignored if thumbnail generation for the file is supported server-side. The thumb-
nail should be in JPEG format and less than 200 kB in size. A thumbnail’s width and
height should not exceed 320. Ignored if the file is not uploaded using multipart/form-
data. Thumbnails can’t be reused and can be only uploaded as a new file. To upload a
file, you can either pass a file object (e.g. open("filename", "rb")) or the file con-
tents as bytes. If the bot is running in local_mode, passing the path of the file (as string
or pathlib.Path object) is supported as well.
Changed in version 13.2: Accept bytes as input.
• disable_content_type_detection (bool, optional) – Disables automatic server-
side content type detection for files uploaded using multipart/form-data. Always True,
if the document is sent as part of an album.
type
'document'.
Type
str
media
File to send.
Type
str | telegram.InputFile
caption
Optional. Caption of the document to be sent.
Type
str
parse_mode
Optional. The parse mode to use for text formatting.
Type
str
caption_entities
Optional. List of special entities that appear in the caption.
Type
List[telegram.MessageEntity]
thumb
Optional. Thumbnail of the file to send.
Type
telegram.InputFile
disable_content_type_detection
Optional. Disables automatic server-side content type detection for files uploaded using
multipart/form-data. Always true, if the document is sent as part of an album.
Type
bool
telegram.InputMediaPhoto
Type
str
parse_mode
Optional. The parse mode to use for text formatting.
Type
str
caption_entities
Optional. List of special entities that appear in the caption.
Type
List[telegram.MessageEntity]
telegram.InputMediaVideo
Note:
• When using a telegram.Video for the media attribute, it will take the width, height and duration
from that video, unless otherwise specified with the optional arguments.
• thumb will be ignored for small video files, for which Telegram can easily generate thumbnails. How-
ever, this behaviour is undocumented and might be changed by Telegram.
Parameters
• media (str | file object | bytes | pathlib.Path | telegram.Video) – File to send.
Pass a file_id as String to send a file that exists on the Telegram servers (recom-
mended), pass an HTTP URL as a String for Telegram to get a file from the Inter-
net, or upload a new one. To upload a file, you can either pass a file object (e.g.
open("filename", "rb")) or the file contents as bytes. If the bot is running in
local_mode, passing the path of the file (as string or pathlib.Path object) is sup-
ported as well. Lastly you can pass an existing telegram.Video object to send.
Changed in version 13.2: Accept bytes as input.
• filename (str, optional) – Custom file name for the video, when uploading a new
file. Convenience parameter, useful e.g. when sending files generated by the tempfile
module.
New in version 13.1.
• caption (str, optional) – Caption of the video to be sent, 0-1024 characters after
entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram apps to
show bold, italic, fixed-width text or inline URLs in the media caption. See the constants
in telegram.constants.ParseMode for the available modes.
• caption_entities (List[telegram.MessageEntity], optional) – List of special en-
tities that appear in the caption, which can be specified instead of parse_mode.
• width (int, optional) – Video width.
• height (int, optional) – Video height.
type
'video'.
Type
str
media
Video file to send.
Type
str | telegram.InputFile
caption
Optional. Caption of the document to be sent.
Type
str
parse_mode
Optional. The parse mode to use for text formatting.
Type
str
caption_entities
Optional. List of special entities that appear in the caption.
Type
List[telegram.MessageEntity]
width
Optional. Video width.
Type
int
height
Optional. Video height.
Type
int
duration
Optional. Video duration in seconds.
Type
int
supports_streaming
Optional. Pass True, if the uploaded video is suitable for streaming.
Type
bool
thumb
Optional. Thumbnail of the file to send.
Type
telegram.InputFile
telegram.KeyboardButton
Note:
• Optional fields are mutually exclusive.
• request_contact and request_location options will only work in Telegram versions released
after 9 April, 2016. Older clients will display unsupported message.
• request_poll option will only work in Telegram versions released after 23 January, 2020. Older
clients will display unsupported message.
• web_app option will only work in Telegram versions released after 16 April, 2022. Older clients will
display unsupported message.
Changed in version 20.0: web_app is considered as well when comparing objects of this type in terms of
equality.
Parameters
• text (str) – Text of the button. If none of the optional fields are used, it will be sent to
the bot as a message when the button is pressed.
• request_contact (bool, optional) – If True, the user’s phone number will be sent as
a contact when the button is pressed. Available in private chats only.
• request_location (bool, optional) – If True, the user’s current location will be sent
when the button is pressed. Available in private chats only.
• request_poll (KeyboardButtonPollType, optional) – If specified, the user will be
asked to create a poll and send it to the bot when the button is pressed. Available in
private chats only.
• web_app (WebAppInfo, optional) – If specified, the described Web App will be
launched when the button is pressed. The Web App will be able to send a Message.
web_app_data service message. Available in private chats only.
New in version 20.0.
text
Text of the button.
Type
str
request_contact
Optional. The user’s phone number will be sent.
Type
bool
request_location
Optional. The user’s current location will be sent.
Type
bool
request_poll
Optional. If the user should create a poll.
Type
KeyboardButtonPollType
web_app
Optional. If the described Web App will be launched when the button is pressed.
New in version 20.0.
Type
WebAppInfo
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
telegram.KeyboardButtonPollType
telegram.Location
telegram.LoginUrl
Note: You must always check the hash of the received data to verify the authentication and the integrity of
the data as described in Checking authorization
Parameters
• url (str) – An HTTPS URL to be opened with user authorization data added to the
query string when the button is pressed. If the user refuses to provide authorization
data, the original URL without information about the user will be opened. The data
added is the same as described in Receiving authorization data
• forward_text (str, optional) – New text of the button in forwarded messages.
• bot_username (str, optional) – Username of a bot, which will be used for user au-
thorization. See Setting up a bot for more details. If not specified, the current bot’s
username will be assumed. The url’s domain must be the same as the domain linked
with the bot. See Linking your domain to the bot for more details.
• request_write_access (bool, optional) – Pass True to request the permission for
your bot to send messages to the user.
url
An HTTPS 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
telegram.MenuButton
telegram.MenuButtonCommands
telegram.MenuButtonDefault
telegram.MenuButtonWebApp
telegram.Message
Parameters
• message_id (int) – Unique message identifier inside this chat.
• from_user (telegram.User, optional) – Sender of the message; empty for messages
sent to channels. For backward compatibility, this will contain a fake sender user in
non-channel chats, if the message was sent on behalf of a chat.
• sender_chat (telegram.Chat, optional) – Sender of the message, sent on behalf of a
chat. For example, the channel itself for channel posts, the supergroup itself for messages
from anonymous group administrators, the linked channel for messages automatically
forwarded to the discussion group. For backward compatibility, from_user contains a
fake sender user in non-channel chats, if the message was sent on behalf of a chat.
• date (datetime.datetime) – Date the message was sent in Unix time. Converted to
datetime.datetime.
• chat (telegram.Chat) – Conversation the message belongs to.
• connected_website (str, optional) – The domain name of the website on which the
user has logged in.
• forward_signature (str, optional) – For messages forwarded from channels, signa-
ture of the post author if present.
• author_signature (str, optional) – Signature of the post author for messages in chan-
nels, or the custom title of an anonymous group administrator.
• passport_data (telegram.PassportData, optional) – Telegram Passport data.
• poll (telegram.Poll, optional) – Message is a native poll, information about the poll.
• dice (telegram.Dice, optional) – Message is a dice with random value from 1 to 6.
• via_bot (telegram.User, optional) – Message was sent through an inline bot.
• proximity_alert_triggered (telegram.ProximityAlertTriggered, optional)
– Service message. A user in the chat triggered another user’s proximity alert while
sharing Live Location.
• video_chat_scheduled (telegram.VideoChatScheduled, optional) – Service
message: video chat scheduled.
New in version 20.0.
• video_chat_started (telegram.VideoChatStarted, optional) – Service mes-
sage: video chat started.
New in version 20.0.
• video_chat_ended (telegram.VideoChatEnded, optional) – Service message:
video chat ended.
New in version 20.0.
• video_chat_participants_invited (telegram.
VideoChatParticipantsInvited optional) – Service message: new participants
invited to a video chat.
New in version 20.0.
• web_app_data (telegram.WebAppData, optional) – Service message: data sent by a
Web App.
New in version 20.0.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline keyboard at-
tached to the message. login_url buttons are represented as ordinary url buttons.
message_id
Unique message identifier inside this chat.
Type
int
from_user
Optional. Sender of the message; empty for messages sent to channels. For backward compatibility,
this will contain a fake sender user in non-channel chats, if the message was sent on behalf of a chat.
Type
telegram.User
sender_chat
Optional. Sender of the message, sent on behalf of a chat. For backward compatibility, from_user
contains a fake sender user in non-channel chats, if the message was sent on behalf of a chat.
Type
telegram.Chat
date
Date the message was sent.
Type
datetime.datetime
chat
Conversation the message belongs to.
Type
telegram.Chat
forward_from
Optional. Sender of the original message.
Type
telegram.User
forward_from_chat
Optional. For messages forwarded from channels or from anonymous administrators, information about
the original sender chat.
Type
telegram.Chat
forward_from_message_id
Optional. Identifier of the original message in the channel.
Type
int
forward_date
Optional. Date the original message was sent.
Type
datetime.datetime
is_automatic_forward
Optional. True, if the message is a channel post that was automatically forwarded to the connected
discussion group.
New in version 13.9.
Type
bool
reply_to_message
Optional. For replies, the original message. Note that the Message object in this field will not contain
further reply_to_message fields even if it itself is a reply.
Type
telegram.Message
edit_date
Optional. Date the message was last edited.
Type
datetime.datetime
has_protected_content
Optional. True, if the message can’t be forwarded.
New in version 13.9.
Type
bool
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
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. This list is empty if the mes-
sage does not contain entities.
Type
List[telegram.MessageEntity]
caption_entities
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. This list
is empty if the message does not contain caption entities.
Type
List[telegram.MessageEntity]
audio
Optional. Information about the file.
Type
telegram.Audio
document
Optional. Information about the file.
Type
telegram.Document
animation
For backward compatibility, when this field is set, the document field will also be set.
Type
telegram.Animation
game
Optional. Information about the game.
Type
telegram.Game
photo
Available sizes of the photo. This list is empty if the message does not contain a photo.
Type
List[telegram.PhotoSize]
sticker
Optional. Information about the sticker.
Type
telegram.Sticker
video
Optional. Information about the video.
Type
telegram.Video
voice
Optional. Information about the file.
Type
telegram.Voice
video_note
Optional. Information about the video message.
Type
telegram.VideoNote
new_chat_members
Information about new members to the chat. The bot itself may be one of these members. This list is
empty if the message does not contain new chat members.
Type
List[telegram.User]
caption
Optional. Caption for the document, photo or video, 0-1024 characters.
Type
str
contact
Optional. Information about the contact.
Type
telegram.Contact
location
Optional. Information about the location.
Type
telegram.Location
venue
Optional. Information about the venue.
Type
telegram.Venue
left_chat_member
Optional. Information about the user that left the group. (this member may be the bot itself).
Type
telegram.User
new_chat_title
Optional. A chat title was changed to this value.
Type
str
new_chat_photo
A chat photo was changed to this value. This list is empty if the message does not contain a new chat
photo.
Type
List[telegram.PhotoSize]
delete_chat_photo
Optional. The chat photo was deleted.
Type
bool
group_chat_created
Optional. The group has been created.
Type
bool
supergroup_chat_created
Optional. The supergroup has been created.
Type
bool
channel_chat_created
Optional. The channel has been created.
Type
bool
message_auto_delete_timer_changed
Optional. Service message: auto-delete timer settings changed in the chat.
New in version 13.4.
Type
telegram.MessageAutoDeleteTimerChanged
migrate_to_chat_id
Optional. The group has been migrated to a supergroup with the specified identifier.
Type
int
migrate_from_chat_id
Optional. The supergroup has been migrated from a group with the specified identifier.
Type
int
pinned_message
Optional. Specified message was pinned.
Type
telegram.Message
invoice
Optional. Information about the invoice.
Type
telegram.Invoice
successful_payment
Optional. Information about the payment.
Type
telegram.SuccessfulPayment
connected_website
Optional. The domain name of the website on which the user has logged in.
Type
str
forward_signature
Optional. Signature of the post author for messages forwarded from channels.
Type
str
forward_sender_name
Optional. Sender’s name for messages forwarded from users who disallow adding a link to their account
in forwarded messages.
Type
str
author_signature
Optional. Signature of the post author for messages in channels, or the custom title of an anonymous
group administrator.
Type
str
passport_data
Optional. Telegram Passport data.
Type
telegram.PassportData
poll
Optional. Message is a native poll, information about the poll.
Type
telegram.Poll
dice
Optional. Message is a dice.
Type
telegram.Dice
via_bot
Optional. Bot through which the message was sent.
Type
telegram.User
proximity_alert_triggered
Optional. Service message. A user in the chat triggered another user’s proximity alert while sharing
Live Location.
Type
telegram.ProximityAlertTriggered
video_chat_scheduled
Optional. Service message: video chat scheduled.
New in version 20.0.
Type
telegram.VideoChatScheduled
video_chat_started
Optional. Service message: video chat started.
New in version 20.0.
Type
telegram.VideoChatStarted
video_chat_ended
Optional. Service message: video chat ended.
New in version 20.0.
Type
telegram.VideoChatEnded
video_chat_participants_invited
Optional. Service message: new participants invited to a video chat.
New in version 20.0.
Type
telegram.VideoChatParticipantsInvited
web_app_data
Optional. Service message: data sent by a Web App.
New in version 20.0.
Type
telegram.WebAppData
reply_markup
Optional. Inline keyboard attached to the message.
Type
telegram.InlineKeyboardMarkup
property caption_html
Creates an HTML-formatted string from the markup entities found in the message’s caption.
Use this if you want to retrieve the message caption with the caption entities formatted as HTML in the
same way the original message was formatted.
Note: Custom emoji entities will currently be ignored by this function. Instead, the supplied replace-
ment for the emoji will be used.
Note: Custom emoji entities will currently be ignored by this function. Instead, the supplied replace-
ment for the emoji will be used.
Note: 'Markdown' is a legacy mode, retained by Telegram for backward compatibility. You should
use caption_markdown_v2() instead.
Custom emoji entities will currently be ignored by this function. Instead, the supplied replacement for
the emoji will be used.
Returns
Message caption with caption entities formatted as Markdown.
Return type
str
Raises
ValueError – If the message contains underline, strikethrough, spoiler or nested entities.
property caption_markdown_urled
Creates an Markdown-formatted string from the markup entities found in the message’s caption using
telegram.constants.ParseMode.MARKDOWN.
Use this if you want to retrieve the message caption with the caption entities formatted as Markdown.
This also formats telegram.MessageEntity.URL as a hyperlink.
Note: 'Markdown' is a legacy mode, retained by Telegram for backward compatibility. You should
use caption_markdown_v2_urled() instead.
Custom emoji entities will currently be ignored by this function. Instead, the supplied replacement for
the emoji will be used.
Returns
Message caption with caption entities formatted as Markdown.
Return type
str
Raises
ValueError – If the message contains underline, strikethrough, spoiler or nested entities.
property caption_markdown_v2
Creates an Markdown-formatted string from the markup entities found in the message’s caption using
telegram.constants.ParseMode.MARKDOWN_V2.
Use this if you want to retrieve the message caption with the caption entities formatted as Markdown
in the same way the original message was formatted.
Note: Custom emoji entities will currently be ignored by this function. Instead, the supplied replace-
ment for the emoji will be used.
Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.
Returns
Message caption with caption entities formatted as Markdown.
Return type
str
property caption_markdown_v2_urled
Creates an Markdown-formatted string from the markup entities found in the message’s caption using
telegram.constants.ParseMode.MARKDOWN_V2.
Use this if you want to retrieve the message caption with the caption entities formatted as Markdown.
This also formats telegram.MessageEntity.URL as a hyperlink.
Note: Custom emoji entities will currently be ignored by this function. Instead, the supplied replace-
ment for the emoji will be used.
Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.
Returns
Message caption with caption entities formatted as Markdown.
Return type
str
property chat_id
Shortcut for telegram.Chat.id for chat.
Type
int
async copy(chat_id, caption=None, parse_mode=None, caption_entities=None,
disable_notification=None, reply_to_message_id=None,
allow_sending_without_reply=None, reply_markup=None, protect_content=None, *,
read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None,
api_kwargs=None)
Shortcut for:
await bot.copy_message(
chat_id=chat_id,
from_chat_id=update.effective_message.chat_id,
message_id=update.effective_message.message_id,
*args,
**kwargs
)
await bot.delete_message(
chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)
await bot.edit_message_caption(
chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)
Note: You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods)
or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and
might be changed by Telegram.
Returns
On success, if edited message is sent by the bot, the edited Message is returned, otherwise
True is returned.
Return type
telegram.Message
await bot.edit_message_live_location(
chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)
Note: You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods)
or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and
might be changed by Telegram.
Returns
On success, if edited message is sent by the bot, the edited Message is returned, otherwise
True is returned.
Return type
telegram.Message
await bot.edit_message_media(
chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)
Note: You can only edit messages that the bot sent itself(i.e. of the bot.send_* family of methods)
or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and
might be changed by Telegram.
Returns
On success, if edited message is not an inline message, the edited Message is returned,
otherwise True is returned.
Return type
telegram.Message
await bot.edit_message_reply_markup(
chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)
Note: You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods)
or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and
might be changed by Telegram.
Returns
On success, if edited message is sent by the bot, the edited Message is returned, otherwise
True is returned.
Return type
telegram.Message
await bot.edit_message_text(
chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)
Note: You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods)
or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and
might be changed by Telegram.
Returns
On success, if edited message is sent by the bot, the edited Message is returned, otherwise
True is returned.
Return type
telegram.Message
property effective_attachment
If this message is neither a plain text message nor a status update, this gives the attachment that this
message was sent with. This may be one of
• telegram.Audio
• telegram.Dice
• telegram.Contact
• telegram.Document
• telegram.Animation
• telegram.Game
• telegram.Invoice
• telegram.Location
• telegram.PassportData
• List[telegram.PhotoSize]
• telegram.Poll
• telegram.Sticker
• telegram.SuccessfulPayment
• telegram.Venue
• telegram.Video
• telegram.VideoNote
• telegram.Voice
Changed in version 20.0: dice, passport_data and poll are now also considered to be an attach-
ment.
async forward(chat_id, disable_notification=None, protect_content=None, *, read_timeout=None,
write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)
Shortcut for:
await bot.forward_message(
from_chat_id=update.effective_message.chat_id,
message_id=update.effective_message.message_id,
*args,
**kwargs
)
Note: Since the release of Bot API 5.5 it can be impossible to forward messages from some
chats. Use the attributes telegram.Message.has_protected_content and telegram.Chat.
has_protected_content to check this.
As a workaround, it is still possible to use copy(). However, this behaviour is undocumented and
might be changed by Telegram.
Returns
On success, instance representing the message forwarded.
Return type
telegram.Message
await bot.get_game_high_scores(
chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)
Note: You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods)
or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and
might be changed by Telegram.
Returns
List[telegram.GameHighScore]
property id
Shortcut for message_id.
New in version 20.0.
Type
int
property link
Convenience property. If the chat of the message is not a private chat or normal group, returns a t.me
link of the message.
Type
str
parse_caption_entities(types=None)
Returns a dict that maps telegram.MessageEntity to str. It contains entities from this message’s
caption filtered by their telegram.MessageEntity.type attribute as the key, and the text that each
entity belongs to as the value of the dict.
Note: This method should always be used instead of the caption_entities attribute, since it cal-
culates 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 telegram.MessageEntity 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[telegram.MessageEntity, str]
parse_caption_entity(entity)
Returns the text from a given telegram.MessageEntity.
Note: This method is present because Telegram calculates the offset and length in UTF-16 codepoint
pairs, which some versions of Python don’t handle automatically. (That is, you can’t just slice Message.
caption with the offset and length.)
Parameters
entity (telegram.MessageEntity) – 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
Raises
RuntimeError – If the message has no caption.
parse_entities(types=None)
Returns a dict that maps telegram.MessageEntity to str. It contains entities from this message
filtered by their telegram.MessageEntity.type attribute as the key, and the text that each entity
belongs to as the value of the dict.
Note: This method should always be used instead of the entities attribute, since it calculates the
correct substring from the message text based on UTF-16 codepoints. See parse_entity for more
info.
Parameters
types (List[str], optional) – List of telegram.MessageEntity 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[telegram.MessageEntity, str]
parse_entity(entity)
Returns the text from a given telegram.MessageEntity.
Note: This method is present because Telegram calculates the offset and length in UTF-16 codepoint
pairs, which some versions of Python don’t handle automatically. (That is, you can’t just slice Message.
text with the offset and length.)
Parameters
entity (telegram.MessageEntity) – 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
Raises
RuntimeError – If the message has no text.
await bot.pin_chat_message(
chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)
Return type
telegram.Message
async reply_audio(audio, duration=None, performer=None, title=None, caption=None,
disable_notification=None, reply_to_message_id=None, reply_markup=None,
parse_mode=None, thumb=None, allow_sending_without_reply=None,
caption_entities=None, protect_content=None, *, filename=None, quote=None,
read_timeout=None, write_timeout=20, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Shortcut for:
await bot.copy_message(
chat_id=message.chat.id,
message_id=message_id,
*args,
**kwargs
)
Keyword Arguments
quote (bool, optional) – If set to True, the document is sent as an actual reply to this
message. If reply_to_message_id is passed, this parameter will be ignored. Default:
True in group chats and False in private chats.
Returns
On success, instance representing the message posted.
Return type
telegram.Message
async reply_game(game_short_name, disable_notification=None, reply_to_message_id=None,
reply_markup=None, allow_sending_without_reply=None, protect_content=None,
*, quote=None, read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Shortcut for:
await bot.send_message(
update.effective_message.chat_id,
parse_mode=ParseMode.HTML,
*args,
**kwargs,
)
Warning: As of API 5.2 start_parameter is an optional argument and therefore the order of
the arguments had to be changed. Use keyword arguments to make sure that the arguments are
passed correctly.
await bot.send_message(
update.effective_message.chat_id,
parse_mode=ParseMode.MARKDOWN,
*args,
**kwargs,
)
Note: 'Markdown' is a legacy mode, retained by Telegram for backward compatibility. You should
use reply_markdown_v2() instead.
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, this parameter will be ignored. Default:
True in group chats and False in private chats.
Returns
On success, instance representing the message posted.
Return type
telegram.Message
await bot.send_message(
update.effective_message.chat_id,
parse_mode=ParseMode.MARKDOWN_V2,
*args,
**kwargs,
)
Return type
telegram.Message
async reply_media_group(media, disable_notification=None, reply_to_message_id=None,
allow_sending_without_reply=None, protect_content=None, *,
quote=None, read_timeout=None, write_timeout=20,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Shortcut for:
Keyword Arguments
quote (bool, optional) – If set to True, the poll is sent as an actual reply to this message.
If reply_to_message_id is passed, this parameter will be ignored. Default: True in
group chats and False in private chats.
Returns
On success, instance representing the message posted.
Return type
telegram.Message
async reply_sticker(sticker, disable_notification=None, reply_to_message_id=None,
reply_markup=None, allow_sending_without_reply=None,
protect_content=None, *, quote=None, read_timeout=None, write_timeout=20,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Shortcut for:
await bot.set_game_score(
chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)
Note: You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods)
or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and
might be changed by Telegram.
Returns
On success, if edited message is sent by the bot, the edited Message is returned, otherwise
True is returned.
Return type
telegram.Message
await bot.stop_message_live_location(
chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)
Note: You can only edit messages that the bot sent itself (i.e. of the bot.send_* family of methods)
or channel posts, if the bot is an admin in that channel. However, this behaviour is undocumented and
Returns
On success, if edited message is sent by the bot, the edited Message is returned, otherwise
True is returned.
Return type
telegram.Message
await bot.stop_poll(
chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)
Note: Custom emoji entities will currently be ignored by this function. Instead, the supplied replace-
ment for the emoji will be used.
Note: Custom emoji entities will currently be ignored by this function. Instead, the supplied replace-
ment for the emoji will be used.
property text_markdown
Creates an Markdown-formatted string from the markup entities found in the message using
telegram.constants.ParseMode.MARKDOWN.
Use this if you want to retrieve the message text with the entities formatted as Markdown in the same
way the original message was formatted.
Note: 'Markdown' is a legacy mode, retained by Telegram for backward compatibility. You should
use text_markdown_v2() instead.
Custom emoji entities will currently be ignored by this function. Instead, the supplied replacement for
the emoji will be used.
Returns
Message text with entities formatted as Markdown.
Return type
str
Raises
ValueError – If the message contains underline, strikethrough, spoiler or nested entities.
property text_markdown_urled
Creates an Markdown-formatted string from the markup entities found in the message using
telegram.constants.ParseMode.MARKDOWN.
Use this if you want to retrieve the message text with the entities formatted as Markdown. This also
formats telegram.MessageEntity.URL as a hyperlink.
Note: 'Markdown' is a legacy mode, retained by Telegram for backward compatibility. You should
use text_markdown_v2_urled() instead.
Custom emoji entities will currently be ignored by this function. Instead, the supplied replacement for
the emoji will be used.
Returns
Message text with entities formatted as Markdown.
Return type
str
Raises
ValueError – If the message contains underline, strikethrough, spoiler or nested entities.
property text_markdown_v2
Creates an Markdown-formatted string from the markup entities found in the message using
telegram.constants.ParseMode.MARKDOWN_V2.
Use this if you want to retrieve the message text with the entities formatted as Markdown in the same
way the original message was formatted.
Note: Custom emoji entities will currently be ignored by this function. Instead, the supplied replace-
ment for the emoji will be used.
Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.
Returns
Message text with entities formatted as Markdown.
Return type
str
property text_markdown_v2_urled
Creates an Markdown-formatted string from the markup entities found in the message using
telegram.constants.ParseMode.MARKDOWN_V2.
Use this if you want to retrieve the message text with the entities formatted as Markdown. This also
formats telegram.MessageEntity.URL as a hyperlink.
Note: Custom emoji entities will currently be ignored by this function. Instead, the supplied replace-
ment for the emoji will be used.
Changed in version 13.10: Spoiler entities are now formatted as Markdown V2.
Returns
Message text with entities formatted as Markdown.
Return type
str
to_dict()
See telegram.TelegramObject.to_dict().
async unpin(*, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None,
api_kwargs=None)
Shortcut for:
await bot.unpin_chat_message(
chat_id=message.chat_id, message_id=message.message_id, *args, **kwargs
)
telegram.MessageAutoDeleteTimerChanged
telegram.MessageEntity
language
Optional. Programming language of the entity text.
Type
str
custom_emoji_id
Optional. Unique identifier of the custom emoji.
New in version 20.0.
Type
str
ALL_TYPES = [<MessageEntityType.MENTION>, <MessageEntityType.HASHTAG>,
<MessageEntityType.CASHTAG>, <MessageEntityType.PHONE_NUMBER>,
<MessageEntityType.BOT_COMMAND>, <MessageEntityType.URL>,
<MessageEntityType.EMAIL>, <MessageEntityType.BOLD>, <MessageEntityType.ITALIC>,
<MessageEntityType.CODE>, <MessageEntityType.PRE>, <MessageEntityType.TEXT_LINK>,
<MessageEntityType.TEXT_MENTION>, <MessageEntityType.UNDERLINE>,
<MessageEntityType.STRIKETHROUGH>, <MessageEntityType.SPOILER>,
<MessageEntityType.CUSTOM_EMOJI>]
A list of all available message entity types.
Type
List[str]
BOLD = 'bold'
telegram.constants.MessageEntityType.BOLD
BOT_COMMAND = 'bot_command'
telegram.constants.MessageEntityType.BOT_COMMAND
CASHTAG = 'cashtag'
telegram.constants.MessageEntityType.CASHTAG
CODE = 'code'
telegram.constants.MessageEntityType.CODE
CUSTOM_EMOJI = 'custom_emoji'
telegram.constants.MessageEntityType.CUSTOM_EMOJI
New in version 20.0.
EMAIL = 'email'
telegram.constants.MessageEntityType.EMAIL
HASHTAG = 'hashtag'
telegram.constants.MessageEntityType.HASHTAG
ITALIC = 'italic'
telegram.constants.MessageEntityType.ITALIC
MENTION = 'mention'
telegram.constants.MessageEntityType.MENTION
PHONE_NUMBER = 'phone_number'
telegram.constants.MessageEntityType.PHONE_NUMBER
PRE = 'pre'
telegram.constants.MessageEntityType.PRE
SPOILER = 'spoiler'
telegram.constants.MessageEntityType.SPOILER
New in version 13.10.
STRIKETHROUGH = 'strikethrough'
telegram.constants.MessageEntityType.STRIKETHROUGH
TEXT_LINK = 'text_link'
telegram.constants.MessageEntityType.TEXT_LINK
TEXT_MENTION = 'text_mention'
telegram.constants.MessageEntityType.TEXT_MENTION
UNDERLINE = 'underline'
telegram.constants.MessageEntityType.UNDERLINE
URL = 'url'
telegram.constants.MessageEntityType.URL
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
telegram.MessageId
telegram.PhotoSize
file_id
Identifier for this file.
Type
str
file_unique_id
Unique identifier for this file, which is supposed to be the same over time and for different bots. Can’t
be used to download or reuse the file.
Type
str
width
Photo width.
Type
int
height
Photo height.
Type
int
file_size
Optional. File size in bytes.
Type
int
async get_file(*, read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Convenience wrapper over telegram.Bot.get_file
For the documentation of the arguments, please see telegram.Bot.get_file().
Returns
telegram.File
Raises
telegram.error.TelegramError –
telegram.Poll
Parameters
• id (str) – Unique poll identifier.
• question (str) – Poll question, 1-300 characters.
id
Unique poll identifier.
Type
str
question
Poll question, 1-300 characters.
Type
str
options
List of poll options.
Type
List[PollOption]
total_voter_count
Total number of users that voted in the poll.
Type
int
is_closed
True, if the poll is closed.
Type
bool
is_anonymous
True, if the poll is anonymous.
Type
bool
type
Poll type, currently can be REGULAR or QUIZ.
Type
str
allows_multiple_answers
True, if the poll allows multiple answers.
Type
bool
correct_option_id
Optional. Identifier of the correct answer option.
Type
int
explanation
Optional. Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a
quiz-style poll.
Type
str
explanation_entities
Special entities like usernames, URLs, bot commands, etc. that appear in the explanation. This list
is empty if the message does not contain explanation entities.
Changed in version 20.0: This attribute is now always a (possibly empty) list and never None.
Type
List[telegram.MessageEntity]
open_period
Optional. Amount of time in seconds the poll will be active after creation.
Type
int
close_date
Optional. Point in time when the poll will be automatically closed.
Type
datetime.datetime
MAX_OPTION_LENGTH = 100
telegram.constants.PollLimit.OPTION_LENGTH
MAX_OPTION_NUMBER = 10
telegram.constants.PollLimit.OPTION_NUMBER
New in version 20.0.
MAX_QUESTION_LENGTH = 300
telegram.constants.PollLimit.QUESTION_LENGTH
QUIZ = 'quiz'
telegram.constants.PollType.QUIZ
REGULAR = 'regular'
telegram.constants.PollType.REGULAR
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
parse_explanation_entities(types=None)
Returns a dict that maps telegram.MessageEntity to str. It contains entities from this polls
explanation filtered by their type attribute as the key, and the text that each entity belongs to as the
value of the dict.
Note: This method should always be used instead of the explanation_entities attribute,
since it calculates the correct substring from the message text based on UTF-16 codepoints. See
parse_explanation_entity for more info.
Parameters
types (List[str], optional) – List of MessageEntity types as strings. If the type at-
tribute of an entity is contained in this list, it will be returned. Defaults to telegram.
MessageEntity.ALL_TYPES.
Returns
A dictionary of entities mapped to the text that belongs to them, calculated based on
UTF-16 codepoints.
Return type
Dict[telegram.MessageEntity, str]
parse_explanation_entity(entity)
Returns the text from a given telegram.MessageEntity.
Note: This method is present because Telegram calculates the offset and length in UTF-16 codepoint
pairs, which some versions of Python don’t handle automatically. (That is, you can’t just slice Message.
text with the offset and length.)
Parameters
entity (telegram.MessageEntity) – 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
Raises
RuntimeError – If the poll has no explanation.
to_dict()
See telegram.TelegramObject.to_dict().
telegram.PollAnswer
poll_id
Unique poll identifier.
Type
str
user
The user, who changed the answer to the poll.
Type
telegram.User
option_ids
Identifiers of answer options, chosen by the user.
Type
List[int]
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
telegram.PollOption
telegram.ProximityAlertTriggered
telegram.ReplyKeyboardMarkup
Example
A user requests to change the bot’s language, bot replies to the request with a keyboard to select the new
language. Other users in the group don’t see the keyboard.
Parameters
• keyboard (List[List[str | telegram.KeyboardButton]]) – Array of button rows,
each represented by an Array of telegram.KeyboardButton objects.
• resize_keyboard (bool, optional) – Requests clients to resize the keyboard vertically
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.
• 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 telegram.Message object.
keyboard
Array of button rows.
Type
List[List[telegram.KeyboardButton | str]]
resize_keyboard
Optional. Requests clients to resize the keyboard.
Type
bool
one_time_keyboard
Optional. Requests clients to hide the keyboard as soon as it’s been used.
Type
bool
selective
Optional. Show the keyboard to specific users only.
Type
bool
input_field_placeholder
Optional. The placeholder shown in the input field when the reply is active.
New in version 13.7.
Type
str
classmethod from_button(button, resize_keyboard=False, one_time_keyboard=False,
selective=False, input_field_placeholder=None, **kwargs)
Shortcut for:
ReplyKeyboardMarkup([[button]], **kwargs)
ReplyKeyboardMarkup([button_row], **kwargs)
telegram.ReplyKeyboardRemove
Example
A user votes in a poll, bot returns confirmation message in reply to the vote and removes the keyboard for
that user, while still showing the keyboard with poll options to users who haven’t voted yet.
Note: User will not be able to summon this keyboard; if you want to hide the keyboard from sight but keep
it accessible, use telegram.ReplyKeyboardMarkup.one_time_keyboard.
Parameters
selective (bool, optional) – Use this parameter if you want to remove the keyboard for
specific users only. Targets:
1) Users that are @mentioned in the text of the telegram.Message object.
2) If the bot’s message is a reply (has reply_to_message_id), sender of the original message.
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
telegram.SentWebAppMessage
telegram.TelegramObject
Parameters
api_kwargs (Dict[str, any], optional) – Arbitrary keyword arguments. Can be used to
store data for which there are no dedicated attributes. These arguments are also considered
by to_dict() and to_json(), i.e. when passing objects to Telegram. Passing them to
Telegram is however not guaranteed to work for all kinds of objects, e.g. this will fail for
objects that can not directly be JSON serialized.
New in version 20.0.
api_kwargs
Optional. Arbitrary keyword arguments. Used to store data for which there are no dedicated attributes.
These arguments are also considered by to_dict() and to_json(), i.e. when passing objects to
Telegram. Passing them to Telegram is however not guaranteed to work for all kinds of objects, e.g.
this will fail for objects that can not directly be JSON serialized.
Raises
RuntimeError – If no telegram.Bot instance was set for this object.
set_bot(bot)
Sets the telegram.Bot instance associated with this object.
See also:
get_bot()
Parameters
bot (telegram.Bot | None) – The bot instance.
to_dict()
Gives representation of object as dict.
Changed in version 20.0: Now includes all entries of api_kwargs.
Returns
dict
to_json()
Gives a JSON representation of object.
Changed in version 20.0: Now includes all entries of api_kwargs.
Returns
str
telegram.Update
Note: At most one of the optional parameters can be present in any given update.
Parameters
• update_id (int) – The update’s unique identifier. Update identifiers start from a cer-
tain positive number and increase sequentially. This ID becomes especially handy if
you’re using Webhooks, since it allows you to ignore repeated updates or to restore the
correct update sequence, should they get out of order. If there are no new updates for
at least a week, then identifier of the next update will be chosen randomly instead of
sequentially.
• message (telegram.Message, optional) – New incoming message of any kind - text,
photo, sticker, etc.
• edited_message (telegram.Message, optional) – New version of a message that is
known to the bot and was edited.
• channel_post (telegram.Message, optional) – New incoming channel post of any
kind - text, photo, sticker, etc.
• edited_channel_post (telegram.Message, optional) – New version of a channel
post that is known to the bot and was edited.
• inline_query (telegram.InlineQuery, optional) – New incoming inline query.
• chosen_inline_result (telegram.ChosenInlineResult, optional) – The result
of an inline query that was chosen by a user and sent to their chat partner.
• callback_query (telegram.CallbackQuery, optional) – New incoming callback
query.
• shipping_query (telegram.ShippingQuery, optional) – New incoming shipping
query. Only for invoices with flexible price.
• pre_checkout_query (telegram.PreCheckoutQuery, optional) – New incoming
pre-checkout query. Contains full information about checkout.
• poll (telegram.Poll, optional) – New poll state. Bots receive only updates about
stopped polls and polls, which are sent by the bot.
• poll_answer (telegram.PollAnswer, optional) – A user changed their answer in a
non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.
• my_chat_member (telegram.ChatMemberUpdated, optional) – The bot’s chat mem-
ber status was updated in a chat. For private chats, this update is received only when the
bot is blocked or unblocked by the user.
New in version 13.4.
update_id
The update’s unique identifier.
Type
int
message
Optional. New incoming message.
Type
telegram.Message
edited_message
Optional. New version of a message.
Type
telegram.Message
channel_post
Optional. New incoming channel post.
Type
telegram.Message
edited_channel_post
Optional. New version of a channel post.
Type
telegram.Message
inline_query
Optional. New incoming inline query.
Type
telegram.InlineQuery
chosen_inline_result
Optional. The result of an inline query that was chosen by a user.
Type
telegram.ChosenInlineResult
callback_query
Optional. New incoming callback query.
Type
telegram.CallbackQuery
shipping_query
Optional. New incoming shipping query.
Type
telegram.ShippingQuery
pre_checkout_query
Optional. New incoming pre-checkout query.
Type
telegram.PreCheckoutQuery
poll
Optional. New poll state. Bots receive only updates about stopped polls and polls, which are sent by
the bot.
Type
telegram.Poll
poll_answer
Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls
that were sent by the bot itself.
Type
telegram.PollAnswer
my_chat_member
Optional. The bot’s chat member status was updated in a chat. For private chats, this update is received
only when the bot is blocked or unblocked by the user.
New in version 13.4.
Type
telegram.ChatMemberUpdated
chat_member
Optional. A chat member’s status was updated in a chat. The bot must be an administrator in
the chat and must explicitly specify CHAT_MEMBER in the list of telegram.ext.Application.
run_polling.allowed_updates to receive these updates (see telegram.Bot.get_updates(),
telegram.Bot.set_webhook(), telegram.ext.Application.run_polling() and telegram.
ext.Application.run_webhook()).
New in version 13.4.
Type
telegram.ChatMemberUpdated
chat_join_request
Optional. A request to join the chat has been sent. The bot must have the telegram.
ChatPermissions.can_invite_users administrator right in the chat to receive these updates.
New in version 13.8.
Type
telegram.ChatJoinRequest
ALL_TYPES = [<UpdateType.MESSAGE>, <UpdateType.EDITED_MESSAGE>,
<UpdateType.CHANNEL_POST>, <UpdateType.EDITED_CHANNEL_POST>,
<UpdateType.INLINE_QUERY>, <UpdateType.CHOSEN_INLINE_RESULT>,
<UpdateType.CALLBACK_QUERY>, <UpdateType.SHIPPING_QUERY>,
<UpdateType.PRE_CHECKOUT_QUERY>, <UpdateType.POLL>, <UpdateType.POLL_ANSWER>,
<UpdateType.MY_CHAT_MEMBER>, <UpdateType.CHAT_MEMBER>,
<UpdateType.CHAT_JOIN_REQUEST>]
A list of all available update types.
New in version 13.5.
Type
List[str]
CALLBACK_QUERY = 'callback_query'
telegram.constants.UpdateType.CALLBACK_QUERY
New in version 13.5.
CHANNEL_POST = 'channel_post'
telegram.constants.UpdateType.CHANNEL_POST
New in version 13.5.
CHAT_JOIN_REQUEST = 'chat_join_request'
telegram.constants.UpdateType.CHAT_JOIN_REQUEST
New in version 13.8.
CHAT_MEMBER = 'chat_member'
telegram.constants.UpdateType.CHAT_MEMBER
New in version 13.5.
CHOSEN_INLINE_RESULT = 'chosen_inline_result'
telegram.constants.UpdateType.CHOSEN_INLINE_RESULT
New in version 13.5.
EDITED_CHANNEL_POST = 'edited_channel_post'
telegram.constants.UpdateType.EDITED_CHANNEL_POST
New in version 13.5.
EDITED_MESSAGE = 'edited_message'
telegram.constants.UpdateType.EDITED_MESSAGE
New in version 13.5.
INLINE_QUERY = 'inline_query'
telegram.constants.UpdateType.INLINE_QUERY
New in version 13.5.
MESSAGE = 'message'
telegram.constants.UpdateType.MESSAGE
New in version 13.5.
MY_CHAT_MEMBER = 'my_chat_member'
telegram.constants.UpdateType.MY_CHAT_MEMBER
New in version 13.5.
POLL = 'poll'
telegram.constants.UpdateType.POLL
New in version 13.5.
POLL_ANSWER = 'poll_answer'
telegram.constants.UpdateType.POLL_ANSWER
New in version 13.5.
PRE_CHECKOUT_QUERY = 'pre_checkout_query'
telegram.constants.UpdateType.PRE_CHECKOUT_QUERY
New in version 13.5.
SHIPPING_QUERY = 'shipping_query'
telegram.constants.UpdateType.SHIPPING_QUERY
New in version 13.5.
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
property effective_chat
The chat that this update was sent in, no matter what kind of update this is. If no chat is associ-
ated with this update, this gives None. This is the case, if inline_query, chosen_inline_result,
callback_query from inline messages, shipping_query, pre_checkout_query, poll or
poll_answer is present.
Example
If message is present, this will give telegram.Message.chat.
Type
telegram.Chat
property effective_message
The message included in this update, no matter what kind of update this is. More precisely, this will be
the message contained in message, edited_message, channel_post, edited_channel_post or
callback_query (i.e. telegram.CallbackQuery.message) or None, if none of those are present.
Type
telegram.Message
property effective_user
The user that sent this update, no matter what kind of update this is. If no user is associated with
this update, this gives None. This is the case if channel_post, edited_channel_post or poll is
present.
Example
• If message is present, this will give telegram.Message.from_user.
• If poll_answer is present, this will give telegram.PollAnswer.user.
Type
telegram.User
telegram.User
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 bots first name.
• last_name (str, optional) – User’s or bots last name.
• username (str, optional) – User’s or bots username.
• language_code (str, optional) – IETF language tag of the user’s language.
• can_join_groups (str, optional) – True, if the bot can be invited to groups. Returned
only in telegram.Bot.get_me requests.
• can_read_all_group_messages (str, optional) – True, if privacy mode is disabled
for the bot. Returned only in telegram.Bot.get_me requests.
• supports_inline_queries (str, optional) – True, if the bot supports inline queries.
Returned only in telegram.Bot.get_me requests.
• is_premium (bool, optional) – True, if this user is a Telegram Premium user.
New in version 20.0.
• added_to_attachment_menu (bool, optional) – True, if this user added the bot to
the attachment menu.
New in version 20.0.
id
Unique identifier for this user or bot.
Type
int
is_bot
True, if this user is a bot.
Type
bool
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
can_join_groups
Optional. True, if the bot can be invited to groups. Returned only in telegram.Bot.get_me requests.
Type
str
can_read_all_group_messages
Optional. True, if privacy mode is disabled for the bot. Returned only in telegram.Bot.get_me
requests.
Type
str
supports_inline_queries
Optional. True, if the bot supports inline queries. Returned only in telegram.Bot.get_me requests.
Type
str
is_premium
Optional. True, if this user is a Telegram Premium user.
New in version 20.0.
Type
bool
added_to_attachment_menu
Optional. True, if this user added the bot to the attachment menu.
New in version 20.0.
Type
bool
async approve_join_request(chat_id, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Shortcut for:
Returns
On success, instance representing the message posted.
Return type
telegram.Message
async decline_join_request(chat_id, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Shortcut for:
mention_button(name=None)
Shortcut for:
InlineKeyboardButton(text=name, url=f"tg://user?id={update.effective_user.id}
˓→")
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)
Note: 'Markdown' is a legacy mode, retained by Telegram for backward compatibility. You should
use mention_markdown_v2() instead.
Parameters
name (str) – The name used as a link for the user. Defaults to full_name.
Returns
The inline mention for the user as markdown (version 1).
Return type
str
mention_markdown_v2(name=None)
Parameters
name (str) – The name used as a link for the user. Defaults to full_name.
Returns
The inline mention for the user as markdown (version 2).
Return type
str
property name
Convenience property. If available, returns the user’s username prefixed with “@”. If username is
not available, returns full_name.
Type
str
async pin_message(message_id, disable_notification=None, *, read_timeout=None,
write_timeout=None, connect_timeout=None, pool_timeout=None,
api_kwargs=None)
Shortcut for:
Returns
On success.
Return type
True
async send_contact(phone_number=None, first_name=None, last_name=None,
disable_notification=None, reply_to_message_id=None, reply_markup=None,
vcard=None, allow_sending_without_reply=None, protect_content=None, *,
contact=None, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Shortcut for:
Shortcut for:
Warning: As of API 5.2 start_parameter is an optional argument and therefore the order of
the arguments had to be changed. Use keyword arguments to make sure that the arguments are
passed correctly.
Changed in version 13.5: As of Bot API 5.2, the parameter start_parameter is optional.
Returns
On success, instance representing the message posted.
Return type
telegram.Message
Returns
On success, instance representing the message posted.
Return type
telegram.Message
async send_poll(question, options, is_anonymous=None, type=None, allows_multiple_answers=None,
correct_option_id=None, is_closed=None, disable_notification=None,
reply_to_message_id=None, reply_markup=None, explanation=None,
explanation_parse_mode=None, open_period=None, close_date=None,
allow_sending_without_reply=None, explanation_entities=None,
protect_content=None, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Shortcut for:
telegram.UserProfilePhotos
Type
List[List[telegram.PhotoSize]]
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
to_dict()
See telegram.TelegramObject.to_dict().
telegram.Venue
Note: Foursquare details and Google Pace details are mutually exclusive. However, this behaviour is
undocumented and might be changed by Telegram.
Parameters
• location (telegram.Location) – Venue location.
• title (str) – Name of the venue.
• address (str) – Address of the venue.
• 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”.)
• google_place_id (str, optional) – Google Places identifier of the venue.
• google_place_type (str, optional) – Google Places type of the venue. (See sup-
ported types.)
location
Venue location.
Type
telegram.Location
title
Name of the venue.
Type
str
address
Address of the venue.
Type
str
foursquare_id
Optional. Foursquare identifier of the venue.
Type
str
foursquare_type
Optional. Foursquare type of the venue.
Type
str
google_place_id
Optional. Google Places identifier of the venue.
Type
str
google_place_type
Optional. Google Places type of the venue.
Type
str
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
telegram.Video
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. Video thumbnail.
Type
telegram.PhotoSize
file_name
Optional. Original filename as defined by sender.
Type
str
mime_type
Optional. MIME type of a file as defined by sender.
Type
str
file_size
Optional. File size in bytes.
Type
int
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
async get_file(*, read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Convenience wrapper over telegram.Bot.get_file
For the documentation of the arguments, please see telegram.Bot.get_file().
Returns
telegram.File
Raises
telegram.error.TelegramError –
telegram.VideoChatEnded
telegram.VideoChatParticipantsInvited
telegram.VideoChatScheduled
telegram.VideoChatStarted
telegram.VideoNote
telegram.Voice
telegram.WebAppData
telegram.WebAppInfo
telegram.WebhookInfo
ip_address
Optional. Currently used webhook IP address.
Type
str
last_error_date
Optional. Unix time for the most recent error that happened.
Type
int
last_error_message
Optional. Error message in human-readable format.
Type
str
max_connections
Optional. Maximum allowed number of simultaneous HTTPS connections.
Type
int
allowed_updates
Optional. A list of update types the bot is subscribed to. Defaults to all update types, except telegram.
Update.chat_member.
Type
List[str]
last_synchronization_error_date
Optional. Unix time of the most recent error that happened when trying to synchronize available up-
dates with Telegram datacenters.
New in version 20.0.
Type
int
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
Stickers
telegram.MaskPosition
• 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.
point
The part of the face relative to which the mask should be placed. One of FOREHEAD, EYES, MOUTH, or
CHIN.
Type
str
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
CHIN = 'chin'
telegram.constants.MaskPosition.CHIN
EYES = 'eyes'
telegram.constants.MaskPosition.EYES
FOREHEAD = 'forehead'
telegram.constants.MaskPosition.FOREHEAD
MOUTH = 'mouth'
telegram.constants.MaskPosition.MOUTH
telegram.Sticker
Note: As of v13.11 is_video is a required argument and therefore the order of the arguments had to be
changed. Use keyword arguments to make sure that the arguments are passed correctly.
Parameters
• file_id (str) – Identifier for this file, which can be used to download or reuse the file.
• file_unique_id (str) – Unique identifier for this file, which is supposed to be the
same over time and for different bots. Can’t be used to download or reuse the file.
• width (int) – Sticker width.
• height (int) – Sticker height.
• is_animated (bool) – True, if the sticker is animated.
• is_video (bool) – True, if the sticker is a video sticker.
New in version 13.11.
• type (str) – Type of the sticker. Currently one of REGULAR, MASK, CUSTOM_EMOJI.
The type of the sticker is independent from its format, which is determined by the fields
is_animated and is_video.
New in version 20.0.
• thumb (telegram.PhotoSize, optional) – Sticker thumbnail in the .WEBP or .JPG
format.
• emoji (str, optional) – Emoji associated with the sticker
• set_name (str, optional) – Name of the sticker set to which the sticker belongs.
• mask_position (telegram.MaskPosition, optional) – For mask stickers, the posi-
tion where the mask should be placed.
• file_size (int, optional) – File size in bytes.
• premium_animation (telegram.File, optional) – For premium regular stickers, pre-
mium animation for the sticker.
New in version 20.0.
• custom_emoji_id (str, optional) – For custom emoji stickers, unique identifier of the
custom emoji.
New in version 20.0.
file_id
Identifier for this file.
Type
str
file_unique_id
Unique identifier for this file, which is supposed to be the same over time and for different bots. Can’t
be used to download or reuse the file.
Type
str
width
Sticker width.
Type
int
height
Sticker height.
Type
int
is_animated
True, if the sticker is animated.
Type
bool
is_video
True, if the sticker is a video sticker.
New in version 13.11.
Type
bool
type
Type of the sticker. Currently one of REGULAR, MASK, CUSTOM_EMOJI. The type of the sticker is inde-
pendent from its format, which is determined by the fields is_animated and is_video.
New in version 20.0.
Type
str
thumb
Optional. Sticker thumbnail in the .WEBP or .JPG format.
Type
telegram.PhotoSize
emoji
Optional. Emoji associated with the sticker.
Type
str
set_name
Optional. Name of the sticker set to which the sticker belongs.
Type
str
mask_position
Optional. For mask stickers, the position where the mask should be placed.
Type
telegram.MaskPosition
file_size
Optional. File size in bytes.
Type
int
premium_animation
Optional. For premium regular stickers, premium animation for the sticker.
New in version 20.0.
Type
telegram.File
custom_emoji_id
Optional. For custom emoji stickers, unique identifier of the custom emoji.
New in version 20.0.
Type
str
CUSTOM_EMOJI = 'custom_emoji'
telegram.constants.StickerType.CUSTOM_EMOJI
MASK = 'mask'
telegram.constants.StickerType.MASK
REGULAR = 'regular'
telegram.constants.StickerType.REGULAR
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
async get_file(*, read_timeout=None, write_timeout=None, connect_timeout=None,
pool_timeout=None, api_kwargs=None)
Convenience wrapper over telegram.Bot.get_file
For the documentation of the arguments, please see telegram.Bot.get_file().
Returns
telegram.File
Raises
telegram.error.TelegramError –
telegram.StickerSet
Note: As of v13.11 is_video is a required argument and therefore the order of the arguments had to be
changed. Use keyword arguments to make sure that the arguments are passed correctly.
Changed in version 20.0:: The parameter contains_masks has been removed. Use sticker_type instead.
Parameters
• name (str) – Sticker set name.
• title (str) – Sticker set title.
• is_animated (bool) – True, if the sticker set contains animated stickers.
• is_video (bool) – True, if the sticker set contains video stickers.
New in version 13.11.
• stickers (List[telegram.Sticker]) – List of all set stickers.
• sticker_type (str) – Type of stickers in the set, currently one of telegram.
Sticker.REGULAR, telegram.Sticker.MASK, telegram.Sticker.
CUSTOM_EMOJI.
New in version 20.0.
• thumb (telegram.PhotoSize, optional) – Sticker set thumbnail in the .WEBP, .TGS,
or .WEBM format.
name
Sticker set name.
Type
str
title
Sticker set title.
Type
str
is_animated
True, if the sticker set contains animated stickers.
Type
bool
is_video
True, if the sticker set contains video stickers.
New in version 13.11.
Type
bool
stickers
List of all set stickers.
Type
List[telegram.Sticker]
sticker_type
Type of stickers in the set.
New in version 20.0.
Type
str
thumb
Optional. Sticker set thumbnail in the .WEBP, .TGS or .WEBM format.
Type
telegram.PhotoSize
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
to_dict()
See telegram.TelegramObject.to_dict().
Inline Mode
telegram.ChosenInlineResult
Note:
• In Python from is a reserved word use from_user instead.
• It is necessary to enable inline feedback via @Botfather in order to receive these objects in updates.
Parameters
• result_id (str) – The unique identifier for the result that was chosen.
• from_user (telegram.User) – The user that chose the result.
• location (telegram.Location, optional) – Sender location, only for bots that require
user location.
• inline_message_id (str, optional) – Identifier of the sent inline message. Available
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.
result_id
The unique identifier for the result that was chosen.
Type
str
from_user
The user that chose the result.
Type
telegram.User
location
Optional. Sender location.
Type
telegram.Location
inline_message_id
Optional. Identifier of the sent inline message.
Type
str
query
The query that was used to obtain the result.
Type
str
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
telegram.InlineQuery
Changed in version 20.0: The following are now keyword-only arguments in Bot methods: {read, write,
connect, pool}_timeout, answer.api_kwargs, auto_pagination. Use a named argument for those,
and notice that some positional arguments changed position as a result.
Parameters
• id (str) – Unique identifier for this query.
• from_user (telegram.User) – Sender.
• query (str) – Text of the query (up to 256 characters).
• offset (str) – Offset of the results to be returned, can be controlled by the bot.
• chat_type (str, optional) – Type of the chat, from which the inline query was sent. Can
be either 'sender' for a private chat with the inline query sender, 'private', 'group',
'supergroup' or 'channel'. The chat type should be always known for requests sent
from official clients and most third-party clients, unless the request was sent from a
secret chat.
New in version 13.5.
• location (telegram.Location, optional) – Sender location, only for bots that re-
quest user location.
id
Unique identifier for this query.
Type
str
from_user
Sender.
Type
telegram.User
query
Text of the query (up to 256 characters).
Type
str
offset
Offset of the results to be returned, can be controlled by the bot.
Type
str
location
Optional. Sender location, only for bots that request user location.
Type
telegram.Location
chat_type
Type of the chat, from which the inline query was sent.
New in version 13.5.
Type
str, optional
MAX_RESULTS = 50
telegram.constants.InlineQueryLimit.RESULTS
New in version 13.2.
MAX_SWITCH_PM_TEXT_LENGTH = 64
telegram.constants.InlineQueryLimit.SWITCH_PM_TEXT_LENGTH
New in version 20.0.
async answer(results, cache_time=None, is_personal=None, next_offset=None, switch_pm_text=None,
switch_pm_parameter=None, *, current_offset=None, auto_pagination=False,
read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None,
api_kwargs=None)
Shortcut for:
await bot.answer_inline_query(
update.inline_query.id,
*args,
current_offset=self.offset if auto_pagination else None,
**kwargs
)
telegram.InlineQueryResult
Note: All URLs passed in inline query results will be available to end users and therefore must be assumed
to be public.
Parameters
• type (str) – Type of the result.
• id (str) – Unique identifier for this result, 1-64 Bytes.
type
Type of the result.
Type
str
id
Unique identifier for this result, 1-64 Bytes.
Type
str
to_dict()
See telegram.TelegramObject.to_dict().
telegram.InlineQueryResultArticle
Parameters
• id (str) – Unique identifier for this result, 1-64 Bytes.
• title (str) – Title of the result.
• input_message_content (telegram.InputMessageContent) – Content of the
message to be sent.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline keyboard at-
tached 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.
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
telegram.InputMessageContent
reply_markup
Optional. Inline keyboard attached to the message.
Type
telegram.InlineKeyboardMarkup
url
Optional. URL of the result.
Type
str
hide_url
Optional. Pass True, if you don’t want the URL to be shown in the message.
Type
bool
description
Optional. Short description of the result.
Type
str
thumb_url
Optional. Url of the thumbnail for the result.
Type
str
thumb_width
Optional. Thumbnail width.
Type
int
thumb_height
Optional. Thumbnail height.
Type
int
telegram.InlineQueryResultAudio
audio_duration
Optional. Audio duration in seconds.
Type
str
caption
Optional. Caption, 0-1024 characters after entities parsing.
Type
str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.constants.ParseMode for the
available modes.
Type
str
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type
List[telegram.MessageEntity]
reply_markup
Optional. Inline keyboard attached to the message.
Type
telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the audio.
Type
telegram.InputMessageContent
telegram.InlineQueryResultCachedAudio
telegram.InlineQueryResultCachedDocument
caption
Optional. Caption of the document to be sent, 0-1024 characters after entities parsing.
Type
str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption.. See the constants in telegram.constants.ParseMode for the
available modes.
Type
str
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type
List[telegram.MessageEntity]
reply_markup
Optional. Inline keyboard attached to the message.
Type
telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the file.
Type
telegram.InputMessageContent
telegram.InlineQueryResultCachedGif
telegram.InlineQueryResultCachedMpeg4Gif
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.constants.ParseMode for the
available modes.
Type
str
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type
List[telegram.MessageEntity]
reply_markup
Optional. Inline keyboard attached to the message.
Type
telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the MPEG-4 file.
Type
telegram.InputMessageContent
telegram.InlineQueryResultCachedPhoto
type
'photo'.
Type
str
id
Unique identifier for this result, 1-64 bytes.
Type
str
photo_file_id
A valid file identifier of the photo.
Type
str
title
Optional. Title for the result.
Type
str
description
Optional. Short description of the result.
Type
str
caption
Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing.
Type
str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.constants.ParseMode for the
available modes.
Type
str
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type
List[telegram.MessageEntity]
reply_markup
Optional. Inline keyboard attached to the message.
Type
telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the photo.
Type
telegram.InputMessageContent
telegram.InlineQueryResultCachedSticker
telegram.InlineQueryResultCachedVideo
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• video_file_id (str) – A valid file identifier for the video file.
• title (str) – Title for the result.
• description (str, optional) – Short description of the result.
• caption (str, optional) – Caption of the video to be sent, 0-1024 characters after
entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram apps to
show bold, italic, fixed-width text or inline URLs in the media caption. See the constants
in telegram.constants.ParseMode for the available modes.
• caption_entities (List[telegram.MessageEntity], optional) – List of special en-
tities that appear in the caption, which can be specified instead of parse_mode.
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline keyboard at-
tached to the message.
• input_message_content (telegram.InputMessageContent, optional) – Content
of the message to be sent 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 of the video to be sent, 0-1024 characters after entities parsing.
Type
str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.constants.ParseMode for the
available modes.
Type
str
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type
List[telegram.MessageEntity]
reply_markup
Optional. Inline keyboard attached to the message.
Type
telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the video.
Type
telegram.InputMessageContent
telegram.InlineQueryResultCachedVoice
id
Unique identifier for this result, 1-64 bytes.
Type
str
voice_file_id
A valid file identifier for the voice message.
Type
str
title
Voice message title.
Type
str
caption
Optional. Caption, 0-1024 characters after entities parsing.
Type
str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.constants.ParseMode for the
available modes.
Type
str
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type
List[telegram.MessageEntity]
reply_markup
Optional. Inline keyboard attached to the message.
Type
telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the voice message.
Type
telegram.InputMessageContent
telegram.InlineQueryResultContact
input_message_content
Optional. Content of the message to be sent instead of the contact.
Type
telegram.InputMessageContent
thumb_url
Optional. Url of the thumbnail for the result.
Type
str
thumb_width
Optional. Thumbnail width.
Type
int
thumb_height
Optional. Thumbnail height.
Type
int
telegram.InlineQueryResultDocument
reply_markup
Optional. Inline keyboard attached to the message.
Type
telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the file.
Type
telegram.InputMessageContent
thumb_url
Optional. URL of the thumbnail (JPEG only) for the file.
Type
str
thumb_width
Optional. Thumbnail width.
Type
int
thumb_height
Optional. Thumbnail height.
Type
int
telegram.InlineQueryResultGame
reply_markup
Optional. Inline keyboard attached to the message.
Type
telegram.InlineKeyboardMarkup
telegram.InlineQueryResultGif
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 in seconds.
Type
int
thumb_url
URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result.
Type
str
thumb_mime_type
Optional. MIME type of the thumbnail.
Type
str
title
Optional. Title for the result.
Type
str
caption
Optional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing.
Type
str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.constants.ParseMode for the
available modes.
Type
str
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type
List[telegram.MessageEntity]
reply_markup
Optional. Inline keyboard attached to the message.
Type
telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the GIF animation.
Type
telegram.InputMessageContent
telegram.InlineQueryResultLocation
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
horizontal_accuracy
Optional. The radius of uncertainty for the location, measured in meters.
Type
float
live_period
Optional. Period in seconds for which the location can be updated, should be between 60 and 86400.
Type
int
heading
Optional. For live locations, a direction in which the user is moving, in degrees.
Type
int
proximity_alert_radius
Optional. For live locations, a maximum distance for proximity alerts about approaching another chat
member, in meters.
Type
int
reply_markup
Optional. Inline keyboard attached to the message.
Type
telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the location.
Type
telegram.InputMessageContent
thumb_url
Optional. Url of the thumbnail for the result.
Type
str
thumb_width
Optional. Thumbnail width.
Type
int
thumb_height
Optional. Thumbnail height.
Type
int
telegram.InlineQueryResultMpeg4Gif
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 in seconds.
Type
int
thumb_url
URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result.
Type
str
thumb_mime_type
Optional. MIME type of the thumbnail.
Type
str
title
Optional. Title for the result.
Type
str
caption
Optional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing.
Type
str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.constants.ParseMode for the
available modes.
Type
str
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type
List[telegram.MessageEntity]
reply_markup
Optional. Inline keyboard attached to the message.
Type
telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the video animation.
Type
telegram.InputMessageContent
telegram.InlineQueryResultPhoto
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
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 of the photo to be sent, 0-1024 characters after entities parsing.
Type
str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.constants.ParseMode for the
available modes.
Type
str
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type
List[telegram.MessageEntity]
reply_markup
Optional. Inline keyboard attached to the message.
Type
telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the photo.
Type
telegram.InputMessageContent
telegram.InlineQueryResultVenue
Note: Foursquare details and Google Pace details are mutually exclusive. However, this behaviour is
undocumented and might be changed by Telegram.
Parameters
• id (str) – Unique identifier for this result, 1-64 Bytes.
• latitude (float) – Latitude of the venue location in degrees.
• longitude (float) – Longitude of the venue location in degrees.
• title (str) – Title of the venue.
• address (str) – Address of the venue.
• foursquare_id (str, optional) – Foursquare identifier of the venue if known.
• foursquare_type (str, optional) – Foursquare type of the venue, if known.
(For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or
“food/icecream”.)
• google_place_id (str, optional) – Google Places identifier of the venue.
• google_place_type (str, optional) – Google Places type of the venue. (See sup-
ported types.)
• reply_markup (telegram.InlineKeyboardMarkup, optional) – Inline keyboard at-
tached to the message.
• input_message_content (telegram.InputMessageContent, optional) – Content
of the message to be sent instead of the location.
• thumb_url (str, optional) – Url of the thumbnail for the result.
• thumb_width (int, optional) – Thumbnail width.
• thumb_height (int, optional) – Thumbnail height.
type
'venue'.
Type
str
id
Unique identifier for this result, 1-64 Bytes.
Type
str
latitude
Latitude of the venue location in degrees.
Type
float
longitude
Longitude of the venue location in degrees.
Type
float
title
Title of the venue.
Type
str
address
Address of the venue.
Type
str
foursquare_id
Optional. Foursquare identifier of the venue if known.
Type
str
foursquare_type
Optional. Foursquare type of the venue, if known.
Type
str
google_place_id
Optional. Google Places identifier of the venue.
Type
str
google_place_type
Optional. Google Places type of the venue.
Type
str
reply_markup
Optional. Inline keyboard attached to the message.
Type
telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the venue.
Type
telegram.InputMessageContent
thumb_url
Optional. Url of the thumbnail for the result.
Type
str
thumb_width
Optional. Thumbnail width.
Type
int
thumb_height
Optional. Thumbnail height.
Type
int
telegram.InlineQueryResultVideo
Note: If an InlineQueryResultVideo message contains an embedded video (e.g., YouTube), you must replace
its content using input_message_content.
Parameters
• id (str) – Unique identifier for this result, 1-64 bytes.
• video_url (str) – A valid URL for the embedded video player or video file.
• mime_type (str) – Mime type of the content of video url, “text/html” or “video/mp4”.
• thumb_url (str) – URL of the thumbnail (JPEG only) for the video.
• title (str) – Title for the result.
• caption (str, optional) – Caption, 0-1024 characters after entities parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram apps to
show bold, italic, fixed-width text or inline URLs in the media caption. See the constants
in telegram.constants.ParseMode for the available modes.
• caption_entities (List[telegram.MessageEntity], optional) – List of special en-
tities that appear in the caption, which can be specified instead of parse_mode.
• video_width (int, optional) – Video width.
type
'video'.
Type
str
id
Unique identifier for this result, 1-64 bytes.
Type
str
video_url
A valid URL for the embedded video player or video file.
Type
str
mime_type
Mime type of the content of video url, “text/html” or “video/mp4”.
Type
str
thumb_url
URL of the thumbnail (JPEG only) for the video.
Type
str
title
Title for the result.
Type
str
caption
Optional. Caption of the video to be sent, 0-1024 characters after entities parsing.
Type
str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in the media caption. See the constants in telegram.constants.ParseMode for the
available modes.
Type
str
caption_entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type
List[telegram.MessageEntity]
video_width
Optional. Video width.
Type
int
video_height
Optional. Video height.
Type
int
video_duration
Optional. Video duration in seconds.
Type
int
description
Optional. Short description of the result.
Type
str
reply_markup
Optional. Inline keyboard attached to the message.
Type
telegram.InlineKeyboardMarkup
input_message_content
Optional. Content of the message to be sent instead of the video. This field is required if Inline-
QueryResultVideo is used to send an HTML-page as a result (e.g., a YouTube video).
Type
telegram.InputMessageContent
telegram.InlineQueryResultVoice
input_message_content
Optional. Content of the message to be sent instead of the voice recording.
Type
telegram.InputMessageContent
telegram.InputMessageContent
telegram.InputTextMessageContent
Parameters
• message_text (str) – Text of the message to be sent, 1-4096 characters after entities
parsing.
• parse_mode (str, optional) – Send Markdown or HTML, if you want Telegram apps
to show bold, italic, fixed-width text or inline URLs in your bot’s message. See the
constants in telegram.constants.ParseMode for the available modes.
• entities (List[telegram.MessageEntity], optional) – List of special entities that
appear in the caption, which can be specified instead of parse_mode.
• disable_web_page_preview (bool, optional) – Disables link previews for links in
the sent message.
message_text
Text of the message to be sent, 1-4096 characters after entities parsing.
Type
str
parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or inline URLs in your bot’s message. See the constants in telegram.constants.ParseMode for
the available modes.
Type
str
entities
Optional. List of special entities that appear in the caption, which can be specified instead of
parse_mode.
Type
List[telegram.MessageEntity]
disable_web_page_preview
Optional. Disables link previews for links in the sent message.
Type
bool
to_dict()
See telegram.TelegramObject.to_dict().
telegram.InputLocationMessageContent
live_period
Optional. Period in seconds for which the location can be updated.
Type
int
heading
Optional. For live locations, a direction in which the user is moving, in degrees.
Type
int
proximity_alert_radius
Optional. For live locations, a maximum distance for proximity alerts about approaching another chat
member, in meters.
Type
int
telegram.InputVenueMessageContent
Note: Foursquare details and Google Pace details are mutually exclusive. However, this behaviour is
undocumented and might be changed by Telegram.
Parameters
• latitude (float) – Latitude of the location in degrees.
• longitude (float) – Longitude of the location in degrees.
• title (str) – Name of the venue.
• address (str) – Address of the venue.
• foursquare_id (str, optional) – Foursquare identifier of the venue, if known.
• foursquare_type (str, optional) – Foursquare type of the venue, if known.
(For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or
“food/icecream”.)
• google_place_id (str, optional) – Google Places identifier of the venue.
• google_place_type (str, optional) – Google Places type of the venue. (See sup-
ported types.)
latitude
Latitude of the location in degrees.
Type
float
longitude
Longitude of the location in degrees.
Type
float
title
Name of the venue.
Type
str
address
Address of the venue.
Type
str
foursquare_id
Optional. Foursquare identifier of the venue, if known.
Type
str
foursquare_type
Optional. Foursquare type of the venue, if known.
Type
str
google_place_id
Optional. Google Places identifier of the venue.
Type
str
google_place_type
Optional. Google Places type of the venue.
Type
str
telegram.InputContactMessageContent
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
telegram.InputInvoiceMessageContent
rencies.json, it shows the number of digits past the decimal point for each currency (2
for the majority of currencies). Defaults to 0.
• suggested_tip_amounts (List[int], optional) – An array of suggested amounts of
tip in the smallest units of the currency (integer, not float/double). At most 4 suggested
tip amounts can be specified. The suggested tip amounts must be positive, passed in a
strictly increased order and must not exceed max_tip_amount.
• provider_data (str, optional) – An object for data about the invoice, which will be
shared with the payment provider. A detailed description of the required fields should
be provided by the payment provider.
• 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 (int, 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 address to
complete the order.
• need_shipping_address (bool, optional) – Pass True, if you require the user’s ship-
ping address to complete the order
• send_phone_number_to_provider (bool, optional) – Pass True, if user’s phone
number should be sent to provider.
• send_email_to_provider (bool, optional) – Pass True, if user’s email address
should be sent to provider.
• is_flexible (bool, optional) – Pass True, if the final price depends on the shipping
method.
title
Product name. 1- 32 characters.
Type
str
description
Product description. 1- 255 characters.
Type
str
payload
Bot-defined invoice payload. 1- 128 bytes. This will not be displayed to the user, use for your internal
processes.
Type
str
provider_token
Payment provider token, obtained via @Botfather.
Type
str
currency
Three-letter ISO 4217 currency code, see more on currencies
Type
str
prices
Price breakdown, a list of components.
Type
List[telegram.LabeledPrice]
max_tip_amount
Optional. The maximum accepted amount for tips in the smallest units of the currency (integer, not
float/double).
Type
int
suggested_tip_amounts
Optional. An array of suggested amounts of tip in the smallest units of the currency (integer, not
float/double).
Type
List[int]
provider_data
Optional. An object for data about the invoice, which will be shared with the payment provider.
Type
str
photo_url
Optional. URL of the product photo for the invoice.
Type
str
photo_size
Optional. Photo size.
Type
int
photo_width
Optional. Photo width.
Type
int
photo_height
Optional. Photo height.
Type
int
need_name
Optional. Pass True, if you require the user’s full name to complete the order.
Type
bool
need_phone_number
Optional. Pass True, if you require the user’s phone number to complete the order
Type
bool
need_email
Optional. Pass True, if you require the user’s email address to complete the order.
Type
bool
need_shipping_address
Optional. Pass True, if you require the user’s shipping address to complete the order
Type
bool
send_phone_number_to_provider
Optional. Pass True, if user’s phone number should be sent to provider.
Type
bool
send_email_to_provider
Optional. Pass True, if user’s email address should be sent to provider.
Type
bool
is_flexible
Optional. Pass True, if the final price depends on the shipping method.
Type
bool
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
to_dict()
See telegram.TelegramObject.to_dict().
Payments
telegram.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
MAX_DESCRIPTION_LENGTH = 255
telegram.constants.InvoiceLimit.MAX_DESCRIPTION_LENGTH
New in version 20.0.
MAX_PAYLOAD_LENGTH = 128
telegram.constants.InvoiceLimit.MAX_PAYLOAD_LENGTH
New in version 20.0.
MAX_TITLE_LENGTH = 32
telegram.constants.InvoiceLimit.MAX_TITLE_LENGTH
New in version 20.0.
MIN_DESCRIPTION_LENGTH = 1
telegram.constants.InvoiceLimit.MIN_DESCRIPTION_LENGTH
New in version 20.0.
MIN_PAYLOAD_LENGTH = 1
telegram.constants.InvoiceLimit.MIN_PAYLOAD_LENGTH
New in version 20.0.
MIN_TITLE_LENGTH = 1
telegram.constants.InvoiceLimit.MIN_TITLE_LENGTH
New in version 20.0.
telegram.LabeledPrice
Parameters
• label (str) – Portion label.
• amount (int) – Price of the product in the smallest units of the currency (integer, not
float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp
parameter in currencies.json, it shows the number of digits past the decimal point for
each currency (2 for the majority of currencies).
label
Portion label.
Type
str
amount
Price of the product in the smallest units of the currency.
Type
int
telegram.OrderInfo
phone_number
Optional. User’s phone number.
Type
str
email
Optional. User email.
Type
str
shipping_address
Optional. User shipping address.
Type
telegram.ShippingAddress
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
telegram.PreCheckoutQuery
Parameters
• id (str) – Unique query identifier.
• from_user (telegram.User) – User who sent the query.
• currency (str) – Three-letter ISO 4217 currency code.
• total_amount (int) – Total price in the smallest units of the currency (integer, not
float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp
parameter in currencies.json, it shows the number of digits past the decimal point for
each currency (2 for the majority of currencies).
• invoice_payload (str) – Bot specified invoice payload.
• shipping_option_id (str, optional) – Identifier of the shipping option chosen by the
user.
• order_info (telegram.OrderInfo, optional) – Order info provided by the user.
id
Unique query identifier.
Type
str
from_user
User who sent the query.
Type
telegram.User
currency
Three-letter ISO 4217 currency code.
Type
str
total_amount
Total price in the smallest units of the currency.
Type
int
invoice_payload
Bot specified invoice payload.
Type
str
shipping_option_id
Optional. Identifier of the shipping option chosen by the user.
Type
str
order_info
Optional. Order info provided by the user.
Type
telegram.OrderInfo
async answer(ok, error_message=None, *, read_timeout=None, write_timeout=None,
connect_timeout=None, pool_timeout=None, api_kwargs=None)
Shortcut for:
telegram.ShippingAddress
telegram.ShippingOption
Parameters
• id (str) – Shipping option identifier.
• title (str) – Option title.
• prices (List[telegram.LabeledPrice]) – List of price portions.
id
Shipping option identifier.
Type
str
title
Option title.
Type
str
prices
List of price portions.
Type
List[telegram.LabeledPrice]
to_dict()
See telegram.TelegramObject.to_dict().
telegram.ShippingQuery
Parameters
• id (str) – Unique query identifier.
• from_user (telegram.User) – User who sent the query.
• invoice_payload (str) – Bot specified invoice payload.
• shipping_address (telegram.ShippingAddress) – User specified shipping ad-
dress.
id
Unique query identifier.
Type
str
from_user
User who sent the query.
Type
telegram.User
invoice_payload
Bot specified invoice payload.
Type
str
shipping_address
User specified shipping address.
Type
telegram.ShippingAddress
async answer(ok, shipping_options=None, error_message=None, *, read_timeout=None,
write_timeout=None, connect_timeout=None, pool_timeout=None, api_kwargs=None)
Shortcut for:
telegram.SuccessfulPayment
Type
str
shipping_option_id
Optional. Identifier of the shipping option chosen by the user.
Type
str
order_info
Optional. Order info provided by the user.
Type
telegram.OrderInfo
telegram_payment_charge_id
Telegram payment identifier.
Type
str
provider_payment_charge_id
Provider payment identifier.
Type
str
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
Games
telegram.Callbackgame
telegram.Game
• 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 telegram.Bot.set_game_score(), or manually edited us-
ing telegram.Bot.edit_message_text(). 0-4096 characters.
• text_entities (List[telegram.MessageEntity], optional) – Special entities that
appear in text, such as usernames, URLs, bot commands, etc.
• animation (telegram.Animation, optional) – Animation that will be displayed in
the game message in chats. Upload via BotFather.
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[telegram.PhotoSize]
text
Optional. Brief description of the game or high scores included in the game message. Can be au-
tomatically edited to include current high scores for the game when the bot calls telegram.Bot.
set_game_score(), or manually edited using telegram.Bot.edit_message_text().
Type
str
text_entities
Special entities that appear in text, such as usernames, URLs, bot commands, etc. This list is empty if
the message does not contain text entities.
Type
List[telegram.MessageEntity]
animation
Optional. Animation that will be displayed in the game message in chats. Upload via BotFather.
Type
telegram.Animation
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
parse_text_entities(types=None)
Returns a dict that maps telegram.MessageEntity to str. It contains entities from this message
filtered by their type attribute as the key, and the text that each entity belongs to as the value of the
dict.
Note: This method should always be used instead of the text_entities attribute, since it calculates
the correct substring from the message text based on UTF-16 codepoints. See parse_text_entity
for more info.
Parameters
types (List[str], optional) – List of telegram.MessageEntity types as strings. If
the type attribute of an entity is contained in this list, it will be returned. Defaults to
telegram.MessageEntity.ALL_TYPES.
Returns
A dictionary of entities mapped to the text that belongs to them, calculated based on
UTF-16 codepoints.
Return type
Dict[telegram.MessageEntity, str]
parse_text_entity(entity)
Returns the text from a given telegram.MessageEntity.
Note: This method is present because Telegram calculates the offset and length in UTF-16 codepoint
pairs, which some versions of Python don’t handle automatically. (That is, you can’t just slice Message.
text with the offset and length.)
Parameters
entity (telegram.MessageEntity) – 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
Raises
RuntimeError – If this game has no text.
to_dict()
See telegram.TelegramObject.to_dict().
telegram.GameHighScore
user
User.
Type
telegram.User
score
Score.
Type
int
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
Passport
telegram.Credentials
telegram.DataCredentials
to_dict()
See telegram.TelegramObject.to_dict().
telegram.EncryptedCredentials
Parameters
• data (telegram.Credentials or str) – Decrypted data with unique user’s nonce,
data hashes and secrets used for EncryptedPassportElement decryption and authentica-
tion or base64 encrypted data.
• hash (str) – Base64-encoded data hash for data authentication.
• secret (str) – Decrypted or encrypted secret used for decryption.
data
Decrypted data with unique user’s nonce, data hashes and secrets used for EncryptedPassportElement
decryption and authentication or base64 encrypted data.
Type
telegram.Credentials or str
hash
Base64-encoded data hash for data authentication.
Type
str
secret
Decrypted or encrypted secret used for decryption.
Type
str
property decrypted_data
Raises
telegram.error.PassportDecryptionError – Decryption failed. Usually due to
bad private/public key but can also suggest malformed/tampered data.
Type
telegram.Credentials
property decrypted_secret
Lazily decrypt and return secret.
Raises
telegram.error.PassportDecryptionError – Decryption failed. Usually due to
bad private/public key but can also suggest malformed/tampered data.
Type
str
telegram.EncryptedPassportElement
Parameters
• type (str) – Element type. One of “personal_details”, “passport”, “driver_license”,
“identity_card”, “internal_passport”, “address”, “utility_bill”, “bank_statement”,
“rental_agreement”, “passport_registration”, “temporary_registration”,
“phone_number”, “email”.
• hash (str) – Base64-encoded element hash for using in telegram.
PassportElementErrorUnspecified.
• data (telegram.PersonalDetails | telegram.IdDocumentData | telegram.
ResidentialAddress | str, optional) – Decrypted or encrypted data, available for
“personal_details”, “passport”, “driver_license”, “identity_card”, “identity_passport”
and “address” types.
• phone_number (str, optional) – User’s verified phone number, available only for
“phone_number” type.
• email (str, optional) – User’s verified email address, available only for “email” type.
• files (List[telegram.PassportFile], optional) – Array of encrypted/decrypted
files with documents provided by the user, available for “utility_bill”, “bank_statement”,
“rental_agreement”, “passport_registration” and “temporary_registration” types.
• front_side (telegram.PassportFile, optional) – Encrypted/decrypted file with
the front side of the document, provided by the user. Available for “passport”,
“driver_license”, “identity_card” and “internal_passport”.
• reverse_side (telegram.PassportFile, optional) – Encrypted/decrypted file with
the reverse side of the document, provided by the user. Available for “driver_license”
and “identity_card”.
• selfie (telegram.PassportFile, 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
Element type. One of “personal_details”, “passport”, “driver_license”, “identity_card”, “in-
ternal_passport”, “address”, “utility_bill”, “bank_statement”, “rental_agreement”, “pass-
port_registration”, “temporary_registration”, “phone_number”, “email”.
Type
str
hash
Base64-encoded element hash for using in telegram.PassportElementErrorUnspecified.
Type
str
data
Optional. Decrypted or encrypted data, available for “personal_details”, “passport”, “driver_license”,
“identity_card”, “identity_passport” and “address” types.
Type
telegram.PersonalDetails | telegram.IdDocumentData | telegram.
ResidentialAddress | str
phone_number
Optional. User’s verified phone number, available only for “phone_number” type.
Type
str
email
Optional. User’s verified email address, available only for “email” type.
Type
str
files
Optional. Array of encrypted/decrypted files with documents provided by the user, avail-
able for “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and “tempo-
rary_registration” types.
Type
List[telegram.PassportFile]
front_side
Optional. Encrypted/decrypted file with the front side of the document, provided by the user. Available
for “passport”, “driver_license”, “identity_card” and “internal_passport”.
Type
telegram.PassportFile
reverse_side
Optional. Encrypted/decrypted file with the reverse side of the document, provided by the user. Avail-
able for “driver_license” and “identity_card”.
Type
telegram.PassportFile
selfie
Optional. Encrypted/decrypted file with the selfie of the user holding a document, provided by the
user; available for “passport”, “driver_license”, “identity_card” and “internal_passport”.
Type
telegram.PassportFile
translation
Optional. Array of encrypted/decrypted files with translated versions of documents provided
by the user. Available if requested for “passport”, “driver_license”, “identity_card”, “inter-
nal_passport”, “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and
“temporary_registration” types.
Type
List[telegram.PassportFile]
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
classmethod de_json_decrypted(data, bot, credentials)
Variant of telegram.TelegramObject.de_json() that also takes into account passport credentials.
Parameters
• data (Dict[str, . . . ]) – The JSON data.
• bot (telegram.Bot) – The bot associated with this object.
• credentials (telegram.FileCredentials) – The credentials
Return type
telegram.EncryptedPassportElement
to_dict()
See telegram.TelegramObject.to_dict().
telegram.FileCredentials
telegram.IdDocumentData
telegram.PassportData
Note: To be able to decrypt this object, you must pass your private_key to either telegram.ext.
Updater or telegram.Bot. Decrypted data is then found in decrypted_data and the payload can be
found in decrypted_credentials’s attribute telegram.Credentials.nonce.
Parameters
• data (List[telegram.EncryptedPassportElement]) – Array with encrypted infor-
mation about documents and other Telegram Passport elements that was shared with the
bot.
• credentials (telegram.EncryptedCredentials)) – Encrypted credentials.
data
Array with encrypted information about documents and other Telegram Passport elements that was
shared with the bot.
Type
List[telegram.EncryptedPassportElement]
credentials
Encrypted credentials.
Type
telegram.EncryptedCredentials
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
property decrypted_credentials
Raises
telegram.error.PassportDecryptionError – Decryption failed. Usually due to
bad private/public key but can also suggest malformed/tampered data.
Type
telegram.Credentials
property decrypted_data
Raises
telegram.error.PassportDecryptionError – Decryption failed. Usually due to
bad private/public key but can also suggest malformed/tampered data.
Type
List[telegram.EncryptedPassportElement]
to_dict()
See telegram.TelegramObject.to_dict().
telegram.PassportElementError
telegram.PassportElementErrorDataField
telegram.PassportElementErrorFile
telegram.PassportElementErrorFiles
telegram.PassportElementErrorFrontSide
telegram.PassportElementErrorReverseSide
Type
str
file_hash
Base64-encoded hash of the file with the reverse side of the document.
Type
str
message
Error message.
Type
str
telegram.PassportElementErrorSelfie
telegram.PassportElementErrorTranslationFile
telegram.PassportElementErrorTranslationFiles
telegram.PassportElementErrorUnspecified
telegram.PassportFile
telegram.PersonalDetails
residence_country_code
Country of residence (ISO 3166-1 alpha-2 country code).
Type
str
first_name_native
First Name in the language of the user’s country of residence.
Type
str
middle_name_native
Optional. Middle Name in the language of the user’s country of residence.
Type
str
last_name_native
Last Name in the language of the user’s country of residence.
Type
str
telegram.ResidentialAddress
post_code
Address post code.
Type
str
telegram.SecureData
rental_agreement
Credentials for encrypted rental agreement.
Type
telegram.SecureValue, optional
passport_registration
Credentials for encrypted registration from internal passport.
Type
telegram.SecureValue, optional
temporary_registration
Credentials for encrypted temporary registration.
Type
telegram.SecureValue, optional
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
telegram.SecureValue
Type
List[telegram.FileCredentials], optional
files
Credentials for encrypted files. Available for “utility_bill”, “bank_statement”, “rental_agreement”,
“passport_registration” and “temporary_registration” types.
Type
List[telegram.FileCredentials], optional
classmethod de_json(data, bot)
See telegram.TelegramObject.de_json().
to_dict()
See telegram.TelegramObject.to_dict().
10.2.1 telegram.ext.Application
Tip: This class may not be initialized directly. Use telegram.ext.ApplicationBuilder or builder()
(for convenience).
is roughly equivalent to
try:
await application.initialize()
# code
finally:
await application.shutdown()
updater
Optional. The updater used by this application.
Type
telegram.ext.Updater
job_queue
Optional. The telegram.ext.JobQueue instance to pass onto handler callbacks.
Type
telegram.ext.JobQueue
chat_data
A dictionary handlers can use to store data for the chat.
Changed in version 20.0: chat_data is now read-only
Type
types.MappingProxyType
user_data
A dictionary handlers can use to store data for the user.
Changed in version 20.0: user_data is now read-only
Type
types.MappingProxyType
bot_data
A dictionary handlers can use to store data for the bot.
Type
dict
persistence
The persistence class to store data that should be persistent over restarts.
Type
telegram.ext.BasePersistence
handlers
A dictionary mapping each handler group to the list of handlers registered to that group.
See also:
add_handler(), add_handlers().
Type
Dict[int, List[telegram.ext.BaseHandler]]
error_handlers
A dictionary where the keys are error handlers and the values indicate whether they are to be run
blocking.
See also:
add_error_handler()
Type
Dict[coroutine function, bool]
context_types
Specifies the types used by this dispatcher for the context argument of handler and job callbacks.
Type
telegram.ext.ContextTypes
post_init
Optional. A callback that will be executed by Application.run_polling() and Application.
run_webhook() after initializing the application via initialize().
Type
coroutine function
post_shutdown
Optional. A callback that will be executed by Application.run_polling() and Application.
run_webhook() after shutting down the application via shutdown().
Type
coroutine function
add_error_handler(callback, block=True)
Registers an error handler in the Application. This handler will receive every error which happens in
your bot. See the docs of process_error() for more details on how errors are handled.
Note: Attempts to add the same callback multiple times will be ignored.
See also:
Errorhandler Example
Parameters
• callback (coroutine function) – The callback function for this error handler. Will be
called when an error is raised. Callback signature:
add_handler(handler, group=0)
Register a handler.
TL;DR: Order and priority counts. 0 or 1 handlers per group will be used. End handling of update
with telegram.ext.ApplicationHandlerStop.
A handler must be an instance of a subclass of telegram.ext.BaseHandler. All handlers are
organized in groups with a numeric value. The default group is 0. All groups will be evalu-
ated for handling an update, but only 0 or 1 handler per group will be used. If telegram.ext.
ApplicationHandlerStop 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 can handle an update (see telegram.ext.BaseHandler.
check_update) will be used. Other handlers from the group will not be used. The order in which
handlers were added to the group defines the priority.
Parameters
• handler (telegram.ext.BaseHandler) – A BaseHandler instance.
• group (int, optional) – The group identifier. Default is 0.
add_handlers(handlers, group=0)
Registers multiple handlers at once. The order of the handlers in the passed sequence(s) matters. See
add_handler() for details.
New in version 20.0.
Parameters
• handlers (List[telegram.ext.BaseHandler] | Dict[int, List[telegram.ext.
BaseHandler]]) – Specify a sequence of handlers or a dictionary where the keys are
groups and values are handlers.
• group (int, optional) – Specify which group the sequence of handlers should be
added to. Defaults to 0.
Example:
app.add_handlers(handlers={
-1: [MessageHandler(...)],
1: [CallbackQueryHandler(...), CommandHandler(...)]
}
static builder()
Convenience method. Returns a new telegram.ext.ApplicationBuilder.
New in version 20.0.
property concurrent_updates
The number of concurrent updates that will be processed in parallel. A value of 0 indicates updates
are not being processed concurrently.
Type
int
create_task(coroutine, update=None)
Thin wrapper around asyncio.create_task() that handles exceptions raised by the coroutine
with process_error().
Note:
• If coroutine raises an exception, it will be set on the task created by this method even though it’s
handled by process_error().
• If the application is currently running, tasks created by this method will be awaited with stop().
Parameters
• coroutine (coroutine function) – The coroutine to run as task.
• update (object, optional) – If set, will be passed to process_error() as addi-
tional information for the error handlers. Moreover, the corresponding chat_data
and user_data entries will be updated in the next run of update_persistence()
after the coroutine is finished.
Returns
The created task.
Return type
asyncio.Task
drop_chat_data(chat_id)
Drops the corresponding entry from the chat_data. Will also be deleted from the persistence on the
next run of update_persistence(), if applicable.
Warning:
• Any data stored in chat_data at key new_chat_id will be overridden
• The key old_chat_id of chat_data will be deleted
• This does not update the chat_id attribute of any scheduled telegram.ext.Job.
Parameters
• message (telegram.Message, optional) – A message with either
migrate_from_chat_id or migrate_to_chat_id. Mutually exclusive with
passing old_chat_id and new_chat_id.
See also:
telegram.ext.filters.StatusUpdate.MIGRATE
• old_chat_id (int, optional) – The old chat ID. Mutually exclusive with passing
message
• new_chat_id (int, optional) – The new chat ID. Mutually exclusive with passing
message
Raises
ValueError – Raised if the input is invalid.
Parameters
• update (object | telegram.Update) – The update that caused the error.
• error (Exception) – The error that was raised.
• job (telegram.ext.Job, optional) – The job that caused the error.
New in version 20.0.
• coroutine (coroutine function, optional) – The coroutine that caused the error.
Returns
True, if one of the error handlers raised telegram.ext.ApplicationHandlerStop.
False, otherwise.
Return type
bool
async process_update(update)
Processes a single update and marks the update to be updated by the persistence later. Exceptions raised
by handler callbacks will be processed by process_update().
Changed in version 20.0: Persistence is now updated in an interval set by telegram.ext.
BasePersistence.update_interval.
Parameters
update (telegram.Update | object | telegram.error.TelegramError) – The up-
date to process.
Raises
RuntimeError – If the application was not initialized.
remove_error_handler(callback)
Removes an error handler.
Parameters
callback (coroutine function) – The error handler to remove.
remove_handler(handler, group=0)
Remove a handler from the specified group.
Parameters
• handler (telegram.ext.BaseHandler) – A telegram.ext.BaseHandler in-
stance.
• group (object, optional) – The group identifier. Default is 0.
run_polling(poll_interval=0.0, timeout=10, bootstrap_retries=-1, read_timeout=2,
write_timeout=None, connect_timeout=None, pool_timeout=None,
allowed_updates=None, drop_pending_updates=None, close_loop=True,
stop_signals=None)
Convenience method that takes care of initializing and starting the app, polling updates from Telegram
using telegram.ext.Updater.start_polling() and a graceful shutdown of the app on exit.
The app will shut down when KeyboardInterrupt or SystemExit is raised. On unix, the app will
also shut down on receiving the signals specified by stop_signals.
If post_init is set, it will be called between initialize() and telegram.ext.Updater.
start_polling().
If post_shutdown is set, it will be called after both shutdown() and telegram.ext.Updater.
shutdown().
See also:
initialize(), start(), stop(), shutdown() telegram.ext.Updater.start_polling(),
run_webhook()
Parameters
• poll_interval (float, optional) – Time to wait between polling updates from Tele-
gram in seconds. Default is 0.0.
• timeout (float, optional) – Passed to telegram.Bot.get_updates.timeout.
Default is 10 seconds.
• bootstrap_retries (int, optional) – Whether the bootstrapping phase of the
telegram.ext.Updater will retry on failures on the Telegram server.
– < 0 - retry indefinitely (default)
– 0 - no retries
– > 0 - retry up to X times
Raises
RuntimeError – If the Application does not have an telegram.ext.Updater.
Parameters
property running
Indicates if this application is running.
See also:
start(), stop()
Type
bool
async shutdown()
Shuts down the Application by shutting down:
• bot by calling telegram.Bot.shutdown()
• updater by calling telegram.ext.Updater.shutdown()
• persistence by calling update_persistence() and BasePersistence.flush()
Does not call post_shutdown - that is only done by run_polling() and run_webhook().
See also:
initialize()
Raises
RuntimeError – If the application is still running.
async start()
Starts
• a background task that fetches updates from update_queue and processes them.
• job_queue, if set.
• a background task that calls update_persistence() in regular intervals, if persistence is set.
Note: This does not start fetching updates from Telegram. To fetch updates, you need to either start
updater manually or use one of run_polling() or run_webhook().
See also:
stop()
Raises
RuntimeError – If the application is already running or was not initialized.
async stop()
Stops the process after processing any pending updates or tasks created by create_task(). Also
stops job_queue, if set. Finally, calls update_persistence() and BasePersistence.flush()
on persistence, if set.
Warning: Once this method is called, no more updates will be fetched from update_queue, even
if it’s not empty.
See also:
start()
Note: This does not stop updater. You need to either manually call telegram.ext.Updater.
stop() or use one of run_polling() or run_webhook().
Raises
RuntimeError – If the application is not running.
async update_persistence()
Updates user_data, chat_data, bot_data in persistence along with callback_data_cache
and the conversation states of any persistent ConversationHandler registered for this application.
For user_data, chat_data, only entries used since the last run of this method are updated.
Tip: This method will be called in regular intervals by the application. There is usually no need to
call it manually.
Note: Any data is deep copied with copy.deepcopy() before handing it over to the persistence in
order to avoid race conditions, so all persisted data must be copyable.
See also:
telegram.ext.BasePersistence.update_interval.
10.2.2 telegram.ext.ApplicationBuilder
class telegram.ext.ApplicationBuilder
This class serves as initializer for telegram.ext.Application via the so called builder pattern. To build a
telegram.ext.Application, one first initializes an instance of this class. Arguments for the telegram.
ext.Application to build are then added by subsequently calling the methods of the builder. Finally,
the telegram.ext.Application is built by calling build(). In the simplest case this can look like the
following example.
Example
application = ApplicationBuilder().token("TOKEN").build()
Please see the description of the individual methods for information on which arguments can be set and what
the defaults are when not called. When no default is mentioned, the argument will not be used by default.
Note:
• Some arguments are mutually exclusive. E.g. after calling token(), you can’t set a custom bot with
bot() and vice versa.
• Unless a custom telegram.Bot instance is set via bot(), build() will use telegram.ext.ExtBot
for the bot.
application_class(application_class, kwargs=None)
Sets a custom subclass instead of telegram.ext.Application. The subclass’s __init__ should
look like this
Parameters
arbitrary_callback_data(arbitrary_callback_data)
Specifies whether telegram.ext.Application.bot should allow arbitrary objects as callback data
for telegram.InlineKeyboardButton and how many keyboards should be cached in memory. If
not called, only strings can be used as callback data and no data will be stored in memory.
See also:
Arbitrary callback_data, arbitrarycallbackdatabot.py
Parameters
arbitrary_callback_data (bool | int) – If True is passed, the default cache size of
1024 will be used. Pass an integer to specify a different cache size.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
base_file_url(base_file_url)
Sets the base file URL for telegram.ext.Application.bot. If not called, will default to 'https:/
/api.telegram.org/file/bot'.
See also:
telegram.Bot.base_file_url, Local Bot API Server, base_url()
Parameters
base_file_url (str) – The URL.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
base_url(base_url)
Sets the base URL for telegram.ext.Application.bot. If not called, will default to 'https://
api.telegram.org/bot'.
See also:
telegram.Bot.base_url, Local Bot API Server, base_file_url()
Parameters
base_url (str) – The URL.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
bot(bot)
Sets a telegram.Bot instance for telegram.ext.Application.bot. Instances of subclasses like
telegram.ext.ExtBot are also valid.
Parameters
bot (telegram.Bot) – The bot.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
build()
Builds a telegram.ext.Application with the provided arguments.
Calls telegram.ext.JobQueue.set_application() and telegram.ext.BasePersistence.
set_bot() if appropriate.
Returns
telegram.ext.Application
concurrent_updates(concurrent_updates)
Specifies if and how many updates may be processed concurrently instead of one by one.
Warning: Processing updates concurrently is not recommended when stateful handlers like
telegram.ext.ConversationHandler are used. Only use this if you are sure that your bot
does not (explicitly or implicitly) rely on updates being processed sequentially.
Tip: When making requests to the Bot API in an asynchronous fashion (e.g. via block=False,
Application.create_task, concurrent_updates() or the JobQueue), it can happen that more
requests are being made in parallel than there are connections in the pool. If the number of requests
is much higher than the number of connections, even setting pool_timeout() to a larger value may
not always be enough to prevent pool timeouts. You should therefore set concurrent_updates(),
connection_pool_size() and pool_timeout() to values that make sense for your setup.
See also:
telegram.ext.Application.concurrent_updates
Parameters
concurrent_updates (bool | int) – Passing True will allow for 256 updates to be
processed concurrently. Pass an integer to specify a different number of updates that may
be processed concurrently.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
connect_timeout(connect_timeout)
Sets the connection attempt timeout for the connect_timeout parameter of telegram.Bot.
request. Defaults to 5.0.
Parameters
connect_timeout (float) – See telegram.request.HTTPXRequest.
connect_timeout for more information.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
connection_pool_size(connection_pool_size)
Sets the size of the connection pool for the connection_pool_size parameter of telegram.Bot.
request. Defaults to 256.
Tip: When making requests to the Bot API in an asynchronous fashion (e.g. via block=False,
Application.create_task, concurrent_updates() or the JobQueue), it can happen that more
requests are being made in parallel than there are connections in the pool. If the number of requests
is much higher than the number of connections, even setting pool_timeout() to a larger value may
not always be enough to prevent pool timeouts. You should therefore set concurrent_updates(),
connection_pool_size() and pool_timeout() to values that make sense for your setup.
Parameters
connection_pool_size (int) – The size of the connection pool.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
context_types(context_types)
Sets a telegram.ext.ContextTypes instance for telegram.ext.Application.
context_types.
See also:
contexttypesbot.py
Parameters
context_types (telegram.ext.ContextTypes) – The context types.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
defaults(defaults)
Sets the telegram.ext.Defaults instance for telegram.ext.Application.bot.
See also:
Adding Defaults
Parameters
defaults (telegram.ext.Defaults) – The defaults instance.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
get_updates_connect_timeout(get_updates_connect_timeout)
Sets the connection attempt timeout for the telegram.request.HTTPXRequest.connect_timeout
parameter which is used for the telegram.Bot.get_updates() request. Defaults to 5.0.
Parameters
get_updates_connect_timeout (float) – See telegram.request.
HTTPXRequest.connect_timeout for more information.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
get_updates_connection_pool_size(get_updates_connection_pool_size)
Sets the size of the connection pool for the telegram.request.HTTPXRequest.
connection_pool_size parameter which is used for the telegram.Bot.get_updates()
request. Defaults to 1.
Parameters
get_updates_connection_pool_size (int) – The size of the connection pool.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
get_updates_pool_timeout(get_updates_pool_timeout)
Sets the connection pool’s connection freeing timeout for the pool_timeout parameter which is used
for the telegram.Bot.get_updates() request. Defaults to None.
Parameters
get_updates_pool_timeout (float) – See telegram.request.HTTPXRequest.
pool_timeout for more information.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
get_updates_proxy_url(get_updates_proxy_url)
Sets the proxy for the telegram.request.HTTPXRequest.proxy_url parameter which is used for
telegram.Bot.get_updates(). Defaults to None.
Parameters
get_updates_proxy_url (str) – The URL to the proxy server. See telegram.
request.HTTPXRequest.proxy_url for more information.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
get_updates_read_timeout(get_updates_read_timeout)
Sets the waiting timeout for the telegram.request.HTTPXRequest.read_timeout parameter
which is used for the telegram.Bot.get_updates() request. Defaults to 5.0.
Parameters
get_updates_read_timeout (float) – See telegram.request.HTTPXRequest.
read_timeout for more information.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
get_updates_request(get_updates_request)
Sets a telegram.request.BaseRequest instance for the get_updates_request parameter of
telegram.ext.Application.bot.
See also:
request()
Parameters
get_updates_request (telegram.request.BaseRequest) – The request instance.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
get_updates_write_timeout(get_updates_write_timeout)
Sets the write operation timeout for the telegram.request.HTTPXRequest.write_timeout pa-
rameter which is used for the telegram.Bot.get_updates() request. Defaults to 5.0.
Parameters
get_updates_write_timeout (float) – See telegram.request.HTTPXRequest.
write_timeout for more information.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
job_queue(job_queue)
Sets a telegram.ext.JobQueue instance for telegram.ext.Application.job_queue. If not
called, a job queue will be instantiated.
See also:
JobQueue, timerbot.py
Note:
• telegram.ext.JobQueue.set_application() will be called automatically by build().
• The job queue will be automatically started and stopped by telegram.ext.Application.
start() and telegram.ext.Application.stop(), respectively.
• When passing None, telegram.ext.ConversationHandler.conversation_timeout can
not be used, as this uses telegram.ext.Application.job_queue internally.
Parameters
job_queue (telegram.ext.JobQueue) – The job queue. Pass None if you don’t want
to use a job queue.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
local_mode(local_mode)
Parameters
local_mode (bool) – Whether the bot should run in local mode.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
persistence(persistence)
Sets a telegram.ext.BasePersistence instance for telegram.ext.Application.
persistence.
Note: When using a persistence, note that all data stored in context.user_data, context.
chat_data, context.bot_data and in telegram.ext.ExtBot.callback_data_cache must be
copyable with copy.deepcopy(). This is due to the data being deep copied before handing it over to
the persistence in order to avoid race conditions.
See also:
Making your bot persistent, persistentconversationbot.py
Parameters
persistence (telegram.ext.BasePersistence) – The persistence instance.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
pool_timeout(pool_timeout)
Sets the connection pool’s connection freeing timeout for the pool_timeout parameter of telegram.
Bot.request. Defaults to None.
Tip: When making requests to the Bot API in an asynchronous fashion (e.g. via block=False,
Application.create_task, concurrent_updates() or the JobQueue), it can happen that more
requests are being made in parallel than there are connections in the pool. If the number of requests
is much higher than the number of connections, even setting pool_timeout() to a larger value may
not always be enough to prevent pool timeouts. You should therefore set concurrent_updates(),
connection_pool_size() and pool_timeout() to values that make sense for your setup.
Parameters
pool_timeout (float) – See telegram.request.HTTPXRequest.pool_timeout
for more information.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
post_init(post_init)
Sets a callback to be executed by Application.run_polling() and Application.
run_webhook() after executing Application.initialize() but before executing Updater.
start_polling() or Updater.start_webhook(), respectively.
Tip: This can be used for custom startup logic that requires to await coroutines, e.g. setting up the
bots commands via set_my_commands().
Example
application = Application.builder().token("TOKEN").post_init(post_init).
˓→build()
Parameters
post_init (coroutine function) – The custom callback. Must be a coroutine function
and must accept exactly one positional argument, which is the Application:
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
post_shutdown(post_shutdown)
Sets a callback to be executed by Application.run_polling() and Application.
run_webhook() after executing Updater.shutdown() and Application.shutdown().
Tip: This can be used for custom shutdown logic that requires to await coroutines, e.g. closing a
database connection
Example
application = Application.builder()
.token("TOKEN")
.post_shutdown(post_shutdown)
.build()
Parameters
post_shutdown (coroutine function) – The custom callback. Must be a coroutine func-
tion and must accept exactly one positional argument, which is the Application:
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
private_key(private_key, password=None)
Sets the private key and corresponding password for decryption of telegram passport data for
telegram.ext.Application.bot.
See also:
passportbot.py, Telegram Passports
Parameters
• private_key (bytes | str | pathlib.Path) – The private key or the file path of a
file that contains the key. In the latter case, the file’s content will be read automatically.
• password (bytes | str | pathlib.Path, optional) – The corresponding password or
the file path of a file that contains the password. In the latter case, the file’s content
will be read automatically.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
proxy_url(proxy_url)
Sets the proxy for the proxy_url parameter of telegram.Bot.request. Defaults to None.
Parameters
proxy_url (str) – The URL to the proxy server. See telegram.request.
HTTPXRequest.proxy_url for more information.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
rate_limiter(rate_limiter)
Sets a telegram.ext.BaseRateLimiter instance for the telegram.ext.ExtBot.rate_limiter
parameter of telegram.ext.Application.bot.
Parameters
rate_limiter (telegram.ext.BaseRateLimiter) – The rate limiter.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
read_timeout(read_timeout)
Sets the waiting timeout for the read_timeout parameter of telegram.Bot.request. Defaults to
5.0.
Parameters
read_timeout (float) – See telegram.request.HTTPXRequest.read_timeout
for more information.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
request(request)
Sets a telegram.request.BaseRequest instance for the telegram.Bot.request parameter of
telegram.ext.Application.bot.
See also:
get_updates_request()
Parameters
request (telegram.request.BaseRequest) – The request instance.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
token(token)
Sets the token for telegram.ext.Application.bot.
Parameters
token (str) – The token.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
update_queue(update_queue)
Sets a asyncio.Queue instance for telegram.ext.Application.update_queue, i.e. the queue
that the application will fetch updates from. Will also be used for the telegram.ext.Application.
updater. If not called, a queue will be instantiated.
See also:
telegram.ext.Updater.update_queue
Parameters
update_queue (asyncio.Queue) – The queue.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
updater(updater)
Sets a telegram.ext.Updater instance for telegram.ext.Application.updater. The
telegram.ext.Updater.bot and telegram.ext.Updater.update_queue will be used for
telegram.ext.Application.bot and telegram.ext.Application.update_queue, respec-
tively.
Parameters
updater (telegram.ext.Updater | None) – The updater instance or None if no updater
should be used.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
write_timeout(write_timeout)
Sets the write operation timeout for the write_timeout parameter of telegram.Bot.request. De-
faults to 5.0.
Parameters
write_timeout (float) – See telegram.request.HTTPXRequest.
write_timeout for more information.
Returns
The same builder with the updated argument.
Return type
ApplicationBuilder
10.2.3 telegram.ext.ApplicationHandlerStop
class telegram.ext.ApplicationHandlerStop(state=None)
Bases: Exception
Raise this in a handler or an error handler to prevent execution of any other handler (even in different groups).
In order to use this exception in a telegram.ext.ConversationHandler, pass the optional state pa-
rameter instead of returning the next state:
Note: Has no effect, if the handler or error handler is run in a non-blocking way.
Parameters
state (object, optional) – The next state of the conversation.
state
Optional. The next state of the conversation.
Type
object
10.2.4 telegram.ext.CallbackContext
Note: telegram.ext.Application 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 receive the same CallbackContext
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 handler 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.
Parameters
• application (telegram.ext.Application) – The application associated with this
context.
• chat_id (int, optional) – The ID of the chat associated with this object. Used to
provide chat_data.
New in version 20.0.
• user_id (int, optional) – The ID of the user associated with this object. Used to
provide user_data.
New in version 20.0.
coroutine
Optional. Only present in error handlers if the error was caused by a coroutine run with Application.
create_task() or a handler callback with block=False.
Type
coroutine function
matches
Optional. If the associated update originated from a filters.Regex, this will contain a list of match
objects for every pattern where re.search(pattern, string) returned a match. Note that filters
short circuit, so combined regex filters will not always be evaluated.
Type
List[re.Match]
args
Optional. Arguments passed to a command if the associated update is handled by telegram.ext.
CommandHandler, telegram.ext.PrefixHandler or telegram.ext.StringCommandHandler.
It contains a list of the words in the text after the command, using any whitespace string as a delimiter.
Type
List[str]
error
Optional. The error that was raised. Only present when passed to an error handler registered with
telegram.ext.Application.add_error_handler.
Type
Exception
job
Optional. The job which originated this callback. Only present when passed to the callback of
telegram.ext.Job or in error handlers if the error is caused by a job.
Changed in version 20.0: job is now also present in error handlers if the error is caused by a job.
Type
telegram.ext.Job
property application
The application associated with this context.
Type
telegram.ext.Application
property bot
The bot associated with this context.
Type
telegram.Bot
property bot_data
Optional. An object that can be used to keep any data in. For each update it will be the same
ContextTypes.bot_data. Defaults to dict.
Type
ContextTypes.bot_data
property chat_data
Optional. An object that can be used to keep any data in. For each update from the same chat id it will
be the same ContextTypes.chat_data. Defaults to dict.
Warning: When a group chat migrates to a supergroup, its chat id will change and the chat_data
needs to be transferred. For details see our wiki page.
Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a
job.
Type
ContextTypes.chat_data
drop_callback_data(callback_query)
Deletes the cached data for the specified callback query.
New in version 13.6.
Note: Will not raise exceptions in case the data is not found in the cache. Will raise KeyError in case
the callback query can not be found in the cache.
Parameters
callback_query (telegram.CallbackQuery) – The callback query.
Raises
KeyError | RuntimeError – KeyError, if the callback query can not be found in the
cache and RuntimeError, if the bot doesn’t allow for arbitrary callback data.
Parameters
• job (telegram.ext.Job) – The job.
• application (telegram.ext.Application) – The application associated with
this context.
Returns
telegram.ext.CallbackContext
Parameters
• update (object | telegram.Update) – The update.
• application (telegram.ext.Application) – The application associated with
this context.
Returns
telegram.ext.CallbackContext
property job_queue
The JobQueue used by the telegram.ext.Application.
Type
telegram.ext.JobQueue
property match
The first match from matches. Useful if you are only filtering using a single regex filter. Returns None
if matches is empty.
Type
re.Match
async refresh_data()
If application uses persistence, calls telegram.ext.BasePersistence.refresh_bot_data()
on bot_data, telegram.ext.BasePersistence.refresh_chat_data() on chat_data and
telegram.ext.BasePersistence.refresh_user_data() on user_data, if appropriate.
Will be called by telegram.ext.Application.process_update() and telegram.ext.Job.
run().
New in version 13.6.
update(data)
Updates self.__slots__ with the passed data.
Parameters
data (Dict[str, object]) – The data.
property update_queue
The asyncio.Queue instance used by the telegram.ext.Application and (usually) the
telegram.ext.Updater associated with this context.
Type
asyncio.Queue
property user_data
Optional. An object that can be used to keep any data in. For each update from the same user it will
be the same ContextTypes.user_data. Defaults to dict.
Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a
job.
Type
ContextTypes.user_data
10.2.5 telegram.ext.ContextTypes
Example
10.2.6 telegram.ext.Defaults
Type
bool
property explanation_parse_mode
Optional. Alias for parse_mode, used for the corresponding parameter of telegram.Bot.
send_poll().
Type
str
property parse_mode
Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text
or URLs in your bot’s message.
Type
str
property protect_content
Optional. Protects the contents of the sent message from forwarding and saving.
New in version 20.0.
Type
bool
property quote
Optional. If set to True, the reply is sent as an actual reply to the message. If reply_to_message_id
is passed, this parameter will be ignored. Default: True in group chats and False in private chats.
Type
bool
property tzinfo
A timezone to be used for all date(time) objects appearing throughout PTB.
Type
tzinfo
10.2.7 telegram.ext.ExtBot
For the documentation of the arguments, methods and attributes, please see telegram.Bot.
All API methods of this class have an additional keyword argument rate_limit_args. This can be
used to pass additional information to the rate limiter, specifically to telegram.ext.BaseRateLimiter.
process_request.rate_limit_args.
Warning:
• The keyword argument rate_limit_args can not be used, if rate_limiter is None.
• The method get_updates() is the only method that does not have the additional argument, as
this method will never be rate limited.
See also:
Arbitrary Callback Example, Arbitrary callback_data
New in version 13.6.
Changed in version 20.0: Removed the attribute arbitrary_callback_data. You can instead use bot.
callback_data_cache.maxsize to access the size of the cache.
Parameters
• defaults (telegram.ext.Defaults, optional) – An object containing default values
to be used if not set explicitly in the bot methods.
• arbitrary_callback_data (bool | int, optional) – Whether to allow arbitrary ob-
jects as callback data for telegram.InlineKeyboardButton. Pass an integer to spec-
ify the maximum number of objects cached in memory. For more details, please see our
wiki. Defaults to False.
• rate_limiter (telegram.ext.BaseRateLimiter, optional) – A rate limiter to use
for limiting the number of requests made by the bot per time interval.
New in version 20.0.
property callback_data_cache
Optional. The cache for objects passed as callback data for telegram.InlineKeyboardButton.
Changed in version 20.0: * This property is now read-only. * This property is now optional and can be
None if arbitrary_callback_data is set to False.
Type
telegram.ext.CallbackDataCache
property defaults
The telegram.ext.Defaults used by this bot, if any.
async initialize()
See telegram.Bot.initialize(). Also initializes the ExtBot.rate_limiter (if set) by calling
telegram.ext.BaseRateLimiter.initialize().
insert_callback_data(update)
If this bot allows for arbitrary callback data, this inserts the cached data into all corresponding buttons
within this update.
Parameters
update (telegram.Update) – The update.
property rate_limiter
The telegram.ext.BaseRateLimiter used by this bot, if any.
New in version 20.0.
async shutdown()
See telegram.Bot.shutdown(). Also shuts down the ExtBot.rate_limiter (if set) by calling
telegram.ext.BaseRateLimiter.shutdown().
10.2.8 telegram.ext.Job
Note: All attributes and instance methods of job are also directly available as attributes/methods of the
corresponding telegram.ext.Job object.
Warning: This class should not be instantiated manually. Use the methods of telegram.ext.
JobQueue to schedule jobs.
Parameters
• callback (coroutine function) – The callback function that should be executed by the
new job. Callback signature:
• data (object, optional) – Additional data needed for the callback function. Can be
accessed through Job.data in the callback. Defaults to None.
• name (str, optional) – The name of the new job. Defaults to callback.__name__.
• chat_id (int, optional) – Chat id of the chat that this job is associated with.
New in version 20.0.
• user_id (int, optional) – User id of the user that this job is associated with.
New in version 20.0.
callback
The callback function that should be executed by the new job.
Type
coroutine function
data
Optional. Additional data needed for the callback function.
Type
object
name
Optional. The name of the new job.
Type
str
chat_id
Optional. Chat id of the chat that this job is associated with.
New in version 20.0.
Type
int
user_id
Optional. User id of the user that this job is associated with.
New in version 20.0.
Type
int
property enabled
Whether this job is enabled.
Type
bool
property job
The APS Job this job is a wrapper for.
Changed in version 20.0: This property is now read-only.
Type
apscheduler.job.Job
property next_t
Datetime for the next job execution. Datetime is localized according to datetime.datetime.tzinfo.
If job is removed or already ran it equals to None.
Warning: This attribute is only available, if the telegram.ext.JobQueue this job belongs to is
already started. Otherwise APScheduler raises an AttributeError.
Type
datetime.datetime
property removed
Whether this job is due to be removed.
Type
bool
async run(application)
Executes the callback function independently of the jobs schedule. Also calls telegram.ext.
Application.update_persistence().
Changed in version 20.0: Calls telegram.ext.Application.update_persistence().
Parameters
application (telegram.ext.Application) – The application this job is associated
with.
schedule_removal()
Schedules this job for removal from the JobQueue. It will be removed without executing its callback
function again.
10.2.9 telegram.ext.JobQueue
class telegram.ext.JobQueue
Bases: object
This class allows you to periodically perform tasks with the bot. It is a convenience wrapper for the AP-
Scheduler library.
See also:
telegram.ext.Application.job_queue, telegram.ext.CallbackContext.job_queue, Timerbot
Example, Job Queue
scheduler
The scheduler.
Changed in version 20.0: Uses AsyncIOScheduler instead of BackgroundScheduler
Type
apscheduler.schedulers.asyncio.AsyncIOScheduler
property application
The application this JobQueue is associated with.
get_jobs_by_name(name)
Returns a tuple of all pending/scheduled jobs with the given name that are currently in the JobQueue.
Returns
Tuple of all pending or scheduled jobs matching the name.
Return type
Tuple[Job]
jobs()
Returns a tuple of all scheduled jobs that are currently in the JobQueue.
Returns
Tuple of all scheduled jobs.
Return type
Tuple[Job]
run_custom(callback, job_kwargs, data=None, name=None, chat_id=None, user_id=None)
Creates a new custom defined Job.
Parameters
• callback (coroutine function) – The callback function that should be executed by the
new job. Callback signature:
• data (object, optional) – Additional data needed for the callback function. Can be
accessed through Job.data in the callback. Defaults to None.
Changed in version 20.0: Renamed the parameter context to data.
• name (str, optional) – The name of the new job. Defaults to callback.__name__.
• chat_id (int, optional) – Chat id of the chat associated with this job. If passed, the
corresponding chat_data will be available in the callback.
New in version 20.0.
• user_id (int, optional) – User id of the user associated with this job. If passed, the
corresponding user_data will be available in the callback.
New in version 20.0.
Returns
The new Job instance that has been added to the job queue.
Return type
telegram.ext.Job
run_daily(callback, time, days=(0, 1, 2, 3, 4, 5, 6), data=None, name=None, chat_id=None,
user_id=None, job_kwargs=None)
Creates a new Job that runs on a daily basis and adds it to the queue.
Note: For a note about DST, please see the documentation of APScheduler.
Parameters
• callback (coroutine function) – The callback function that should be executed by the
new job. Callback signature:
• time (datetime.time) – Time of day at which the job should run. If the time-
zone (datetime.time.tzinfo) is None, the default timezone of the bot will be used,
which is UTC unless telegram.ext.Defaults.tzinfo is used.
• days (Tuple[int], optional) – Defines on which days of the week the job should run
(where 0-6 correspond to sunday - saturday). By default, the job will run every day.
Changed in version 20.0: Changed day of the week mapping of 0-6 from monday-
sunday to sunday-saturday.
• data (object, optional) – Additional data needed for the callback function. Can be
accessed through Job.data in the callback. Defaults to None.
Changed in version 20.0: Renamed the parameter context to data.
• name (str, optional) – The name of the new job. Defaults to callback.__name__.
• chat_id (int, optional) – Chat id of the chat associated with this job. If passed, the
corresponding chat_data will be available in the callback.
New in version 20.0.
• user_id (int, optional) – User id of the user associated with this job. If passed, the
corresponding user_data will be available in the callback.
New in version 20.0.
• job_kwargs (dict, optional) – Arbitrary keyword arguments to pass to the
apscheduler.schedulers.base.BaseScheduler.add_job().
Returns
The new Job instance that has been added to the job queue.
Return type
telegram.ext.Job
• when (datetime.time) – Time of day at which the job should run. If the timezone
(when.tzinfo) is None, the default timezone of the bot will be used, which is UTC
unless telegram.ext.Defaults.tzinfo is used.
• day (int) – Defines the day of the month whereby the job would run. It should be
within the range of 1 and 31, inclusive. If a month has fewer days than this number,
the job will not run in this month. Passing -1 leads to the job running on the last day
of the month.
• data (object, optional) – Additional data needed for the callback function. Can be
accessed through Job.data in the callback. Defaults to None.
Changed in version 20.0: Renamed the parameter context to data.
• name (str, optional) – The name of the new job. Defaults to callback.__name__.
• chat_id (int, optional) – Chat id of the chat associated with this job. If passed, the
corresponding chat_data will be available in the callback.
New in version 20.0.
• user_id (int, optional) – User id of the user associated with this job. If passed, the
corresponding user_data will be available in the callback.
New in version 20.0.
• job_kwargs (dict, optional) – Arbitrary keyword arguments to pass to the
apscheduler.schedulers.base.BaseScheduler.add_job().
Returns
The new Job instance that has been added to the job queue.
Return type
telegram.ext.Job
run_once(callback, when, data=None, name=None, chat_id=None, user_id=None, job_kwargs=None)
Creates a new Job instance that runs once and adds it to the queue.
Parameters
• callback (coroutine function) – The callback function that should be executed by the
new job. Callback signature:
Note: For a note about DST, please see the documentation of APScheduler.
Parameters
• callback (coroutine function) – The callback function that should be executed by the
new job. Callback signature:
• interval (int | float | datetime.timedelta) – The interval in which the job will
run. If it is an int or a float, it will be interpreted as seconds.
• first (int | float | datetime.timedelta | datetime.datetime | datetime.
time, optional) – Time in or at which the job should run. This parameter will be
interpreted depending on its type.
– int or float will be interpreted as “seconds from now” in which the job should
run.
– datetime.timedelta will be interpreted as “time from now” in which the job
should run.
– datetime.datetime will be interpreted as a specific date and time at which the job
should run. If the timezone (datetime.datetime.tzinfo) is None, the default
timezone of the bot will be used.
– datetime.time will be interpreted as a specific time of day at which the job should
run. This could be either today or, if the time has already passed, tomorrow. If the
timezone (datetime.time.tzinfo) is None, the default timezone of the bot will
be used, which is UTC unless telegram.ext.Defaults.tzinfo is used.
Defaults to interval
• last (int | float | datetime.timedelta | datetime.datetime | datetime.
time, optional) – Latest possible time for the job to run. This parameter will be inter-
preted depending on its type. See first for details.
If last is datetime.datetime or datetime.time type and last.tzinfo is None,
the default timezone of the bot will be assumed, which is UTC unless telegram.ext.
Defaults.tzinfo is used.
Defaults to None.
• data (object, optional) – Additional data needed for the callback function. Can be
accessed through Job.data in the callback. Defaults to None.
Changed in version 20.0: Renamed the parameter context to data.
• name (str, optional) – The name of the new job. Defaults to callback.__name__.
• chat_id (int, optional) – Chat id of the chat associated with this job. If passed, the
corresponding chat_data will be available in the callback.
New in version 20.0.
• user_id (int, optional) – User id of the user associated with this job. If passed, the
corresponding user_data will be available in the callback.
New in version 20.0.
• job_kwargs (dict, optional) – Arbitrary keyword arguments to pass to the
apscheduler.schedulers.base.BaseScheduler.add_job().
Returns
The new Job instance that has been added to the job queue.
Return type
telegram.ext.Job
set_application(application)
Set the application to be used by this JobQueue.
Parameters
application (telegram.ext.Application) – The application.
async start()
Starts the JobQueue.
async stop(wait=True)
Shuts down the JobQueue.
Parameters
wait (bool, optional) – Whether to wait until all currently running jobs have finished.
Defaults to True.
10.2.10 telegram.ext.Updater
is roughly equivalent to
try:
await updater.initialize()
# code
finally:
await updater.shutdown()
Parameters
• bot (telegram.Bot) – The bot used with this Updater.
• update_queue (asyncio.Queue) – Queue for the updates.
bot
The bot used with this Updater.
Type
telegram.Bot
update_queue
Queue for the updates.
Type
asyncio.Queue
async initialize()
Initializes the Updater & the associated bot by calling telegram.Bot.initialize().
See also:
shutdown()
async shutdown()
Shutdown the Updater & the associated bot by calling telegram.Bot.shutdown().
See also:
initialize()
Raises
RuntimeError – If the updater is still running.
Returns
The update queue that can be filled from the main thread.
Return type
asyncio.Queue
Raises
RuntimeError – If the updater is already running or was not initialized.
async start_webhook(listen='127.0.0.1', port=80, url_path='', cert=None, key=None,
bootstrap_retries=0, webhook_url=None, allowed_updates=None,
drop_pending_updates=None, ip_address=None, max_connections=40,
secret_token=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 http://listen:port/url_path, so SSL can be handled by
another application. Else, the webhook will be started on https://listen:port/url_path. Also
calls telegram.Bot.set_webhook() as required.
Changed in version 13.4: start_webhook() now always calls telegram.Bot.set_webhook(), so
pass webhook_url instead of calling updater.bot.set_webhook(webhook_url) manually.
Changed in version 20.0: Removed the clean argument in favor of drop_pending_updates and
removed the deprecated argument force_event_loop.
Parameters
• listen (str, optional) – IP-Address to listen on. Defaults to 127.0.0.1.
• port (int, optional) – Port the bot should be listening on. Must be one of telegram.
constants.SUPPORTED_WEBHOOK_PORTS unless the bot is running behind a proxy.
Defaults to 80.
• url_path (str, optional) – Path inside url (http(s)://listen:port/<url_path>). Defaults
to ''.
• cert (pathlib.Path | str, optional) – Path to the SSL certificate file.
• key (pathlib.Path | str, optional) – Path to the SSL key file.
• drop_pending_updates (bool, optional) – Whether to clean any pending updates
on Telegram servers before actually starting to poll. Default is False.
New in version 13.4.
• bootstrap_retries (int, optional) – Whether the bootstrapping phase of the
telegram.ext.Updater will retry on failures on the Telegram server.
– < 0 - retry indefinitely
– 0 - no retries (default)
– > 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 , cert,
and key.
• ip_address (str, optional) – Passed to telegram.Bot.set_webhook(). Defaults
to None.
New in version 13.4.
• allowed_updates (List[str], optional) – Passed to telegram.Bot.
set_webhook(). Defaults to None.
• max_connections (int, optional) – Passed to telegram.Bot.set_webhook().
Defaults to 40.
New in version 13.6.
• secret_token (str, optional) – Passed to telegram.Bot.set_webhook(). De-
faults to None.
When added, the web server started by this call will expect the token to be set in the
X-Telegram-Bot-Api-Secret-Token header of an incoming request and will raise
a http.HTTPStatus.FORBIDDEN error if either the header isn’t set or it is set to a
wrong token.
New in version 20.0.
Returns
The update queue that can be filled from the main thread.
Return type
queue.Queue
Raises
RuntimeError – If the updater is already running or was not initialized.
async stop()
Stops the polling/webhook.
See also:
start_polling(), start_webhook()
Raises
RuntimeError – If the updater is not running.
10.2.11 Handlers
telegram.ext.BaseHandler
Warning: When setting block to False, you cannot rely on adding custom attributes to telegram.
ext.CallbackContext. See its docs for more info.
Tip: For this type variable, one should usually provide a TypeVar that is also used for the mentioned
method arguments. That way, a type checker can check whether this handler fits the definition of the
Application.
Parameters
• callback (coroutine function) – The callback function for this handler. Will be called
when check_update() has determined that an update should be processed by this han-
dler. Callback signature:
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• block (bool, optional) – Determines whether the return value of the callback should
be awaited before processing the next handler in telegram.ext.Application.
process_update(). Defaults to True.
callback
The callback function for this handler.
Type
coroutine function
block
Determines whether the callback will run in a blocking way..
Type
bool
abstract check_update(update)
This method is called to determine if an update should be handled by this handler instance. It should
always be overridden.
Note: Custom updates types can be handled by the application. Therefore, an implementation of this
method should always check the type of update.
Parameters
update (object | telegram.Update) – The update to be tested.
Returns
Either None or False if the update should not be handled. Otherwise an object that
will be passed to handle_update() and collect_additional_context() when the
update gets handled.
telegram.ext.CallbackQueryHandler
Note:
• If your bot allows arbitrary objects as callback_data, it may happen that the original
callback_data for the incoming telegram.CallbackQuery can not be found. This is the case
when either a malicious client tempered with the telegram.CallbackQuery.data or the data
was simply dropped from cache or not persisted. In these cases, an instance of telegram.ext.
InvalidCallbackData will be set as telegram.CallbackQuery.data.
New in version 13.6.
Warning: When setting block to False, you cannot rely on adding custom attributes to telegram.
ext.CallbackContext. See its docs for more info.
Parameters
• callback (coroutine function) – The callback function for this handler. Will be called
when check_update() has determined that an update should be processed by this han-
dler. Callback signature:
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• pattern (str | re.Pattern | callable | type, optional) – Pattern to test telegram.
CallbackQuery.data against. If a string or a regex pattern is passed, re.match() is
used on telegram.CallbackQuery.data to determine if an update should be handled
by this handler. If your bot allows arbitrary objects as callback_data, non-strings will
be accepted. To filter arbitrary objects you may pass:
– a callable, accepting exactly one argument, namely the telegram.CallbackQuery.
data. It must return True or False/None to indicate, whether the update should be
handled.
– a type. If telegram.CallbackQuery.data is an instance of that type (or a sub-
class), the update will be handled.
If telegram.CallbackQuery.data is None, the telegram.CallbackQuery update
will not be handled.
Changed in version 13.6: Added support for arbitrary callback data.
• block (bool, optional) – Determines whether the return value of the callback should
be awaited before processing the next handler in telegram.ext.Application.
process_update(). Defaults to True.
callback
The callback function for this handler.
Type
coroutine function
pattern
Optional. Regex pattern, callback or type to test telegram.CallbackQuery.data against.
Changed in version 13.6: Added support for arbitrary callback data.
Type
re.Pattern | callable | type
block
Determines whether the return value of the callback should be awaited before processing the next
handler in telegram.ext.Application.process_update().
Type
bool
check_update(update)
Determines whether an update should be passed to this handler’s callback.
Parameters
update (telegram.Update | object) – Incoming update.
Returns
bool
collect_additional_context(context, update, application, check_result)
Add the result of re.match(pattern, update.callback_query.data) to CallbackContext.
matches as list with one element.
telegram.ext.ChatJoinRequestHandler
Note: If neither of username and the chat_id are passed, this handler accepts any join request. Otherwise,
this handler accepts all requests to join chats for which the chat ID is listed in chat_id or the username is
listed in username, or both.
New in version 20.0.
Warning: When setting block to False, you cannot rely on adding custom attributes to telegram.
ext.CallbackContext. See its docs for more info.
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• chat_id (int | Collection[int], optional) – Filters requests to allow only those which
are asking to join the specified chat ID(s).
New in version 20.0.
• username (str | Collection[str], optional) – Filters requests to allow only those which
are asking to join the specified username(s).
New in version 20.0.
• block (bool, optional) – Determines whether the return value of the callback should
be awaited before processing the next handler in telegram.ext.Application.
process_update(). Defaults to True.
callback
The callback function for this handler.
Type
coroutine function
block
Determines whether the callback will run in a blocking way..
Type
bool
check_update(update)
Determines whether an update should be passed to this handler’s callback.
Parameters
update (telegram.Update | object) – Incoming update.
Returns
bool
telegram.ext.ChatMemberHandler
Warning: When setting block to False, you cannot rely on adding custom attributes to telegram.
ext.CallbackContext. See its docs for more info.
See also:
Chat Member Example
New in version 13.4.
Parameters
• callback (coroutine function) – The callback function for this handler. Will be called
when check_update() has determined that an update should be processed by this han-
dler. Callback signature:
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• chat_member_types (int, optional) – Pass one of MY_CHAT_MEMBER, CHAT_MEMBER
or ANY_CHAT_MEMBER to specify if this handler should handle only updates with
telegram.Update.my_chat_member, telegram.Update.chat_member or both.
Defaults to MY_CHAT_MEMBER.
• block (bool, optional) – Determines whether the return value of the callback should
be awaited before processing the next handler in telegram.ext.Application.
process_update(). Defaults to True.
callback
The callback function for this handler.
Type
coroutine function
chat_member_types
Specifies if this handler should handle only updates with telegram.Update.my_chat_member,
telegram.Update.chat_member or both.
Type
int, optional
block
Determines whether the return value of the callback should be awaited before processing the next
handler in telegram.ext.Application.process_update().
Type
bool
ANY_CHAT_MEMBER = 1
Used as a constant to handle both telegram.Update.my_chat_member and telegram.Update.
chat_member.
Type
int
CHAT_MEMBER = 0
Used as a constant to handle only telegram.Update.chat_member.
Type
int
MY_CHAT_MEMBER = -1
Used as a constant to handle only telegram.Update.my_chat_member.
Type
int
check_update(update)
Determines whether an update should be passed to this handler’s callback.
Parameters
update (telegram.Update | object) – Incoming update.
Returns
bool
telegram.ext.ChosenInlineResultHandler
Warning: When setting block to False, you cannot rely on adding custom attributes to telegram.
ext.CallbackContext. See its docs for more info.
Parameters
• callback (coroutine function) – The callback function for this handler. Will be called
when check_update() has determined that an update should be processed by this han-
dler. Callback signature:
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• block (bool, optional) – Determines whether the return value of the callback should
be awaited before processing the next handler in telegram.ext.Application.
process_update(). Defaults to True.
• pattern (str | re.Pattern, optional) – Regex pattern. If not None, re.match()
is used on telegram.ChosenInlineResult.result_id to determine if an update
should be handled by this handler. This is accessible in the callback as telegram.ext.
CallbackContext.matches.
New in version 13.6.
callback
The callback function for this handler.
Type
coroutine function
block
Determines whether the return value of the callback should be awaited before processing the next
handler in telegram.ext.Application.process_update().
Type
bool
pattern
Optional. Regex pattern to test telegram.ChosenInlineResult.result_id against.
New in version 13.6.
Type
Pattern
check_update(update)
Determines whether an update should be passed to this handler’s callback.
Parameters
update (telegram.Update | object) – Incoming update.
Returns
bool | re.match
collect_additional_context(context, update, application, check_result)
This function adds the matched regex pattern result to telegram.ext.CallbackContext.matches.
telegram.ext.CommandHandler
Note: CommandHandler does not handle (edited) channel posts and does not handle commands that are
part of a caption. Please use MessageHandler with a suitable combination of filters (e.g. telegram.
ext.filters.UpdateType.CHANNEL_POSTS, telegram.ext.filters.CAPTION and telegram.ext.
filters.Regex) to handle those messages.
Warning: When setting block to False, you cannot rely on adding custom attributes to telegram.
ext.CallbackContext. See its docs for more info.
Parameters
• command (str | Collection[str]) – The command or list of commands this handler
should listen for. Case-insensitive. Limitations are the same as described here
• callback (coroutine function) – The callback function for this handler. Will be called
when check_update() has determined that an update should be processed by this han-
dler. Callback signature:
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• filters (telegram.ext.filters.BaseFilter, optional) – A filter inheriting from
telegram.ext.filters.BaseFilter. Standard filters can be found in telegram.
ext.filters. Filters can be combined using bitwise operators (& for and, | for or, ~
for not)
• block (bool, optional) – Determines whether the return value of the callback should
be awaited before processing the next handler in telegram.ext.Application.
process_update(). Defaults to True.
Raises
ValueError – When the command is too long or has illegal chars.
commands
The set of commands this handler should listen for.
Type
FrozenSet[str]
callback
The callback function for this handler.
Type
coroutine function
filters
Optional. Only allow updates with these Filters.
Type
telegram.ext.filters.BaseFilter
block
Determines whether the return value of the callback should be awaited before processing the next
handler in telegram.ext.Application.process_update().
Type
bool
check_update(update)
Determines whether an update should be passed to this handler’s callback.
Parameters
update (telegram.Update | object) – Incoming update.
Returns
The list of args for the handler.
Return type
list
collect_additional_context(context, update, application, check_result)
Add text after the command to CallbackContext.args as list, split on single whitespaces and add
output of data filters to CallbackContext as well.
telegram.ext.ConversationHandler
Warning: ConversationHandler heavily relies on incoming updates being processed one by one.
When using this handler, telegram.ext.Application.concurrent_updates should be False.
Note: ConversationHandler will only accept updates that are (subclass-)instances of telegram.
Update. This is, because depending on the per_user and per_chat, ConversationHandler
relies on telegram.Update.effective_user and/or telegram.Update.effective_chat in or-
der to determine which conversation an update should belong to. For per_message=True,
ConversationHandler uses update.callback_query.message.message_id when per_chat=True
and update.callback_query.inline_message_id when per_chat=False. For a more detailed ex-
planation, please see our FAQ.
Finally, ConversationHandler, does not handle (edited) channel posts.
The first collection, a list named entry_points, is used to initiate the conversation, for example with a
telegram.ext.CommandHandler or telegram.ext.MessageHandler.
The second collection, a dict named states, contains the different conversation steps and one or more
associated handlers that should be used if the user sends a message when the conversation with them
is currently in that state. Here you can also define a state for TIMEOUT to define the behavior when
conversation_timeout is exceeded, and a state for WAITING to define behavior when a new update is
received while the previous block=False 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 re-
sponding to the user. If it does not return anything (returning None by default), the state will not change.
If an entry point callback function returns None, the conversation ends immediately after the execution of
this callback function. To end the conversation, the callback function must return END or -1. To handle the
conversation timeout, use handler TIMEOUT or -2. Finally, telegram.ext.ApplicationHandlerStop
can be used in conversations as described in its documentation.
Note: In each of the described collections of handlers, a handler may in turn be a ConversationHandler.
In that case, the child ConversationHandler should have the attribute map_to_parent which allows
returning to the parent conversation at specified states within the child conversation.
Note that the keys in map_to_parent must not appear as keys in states attribute or else the latter will be
ignored. You may map END to one of the parents states to continue the parent conversation after the child
conversation has ended or even map a state to END to end the parent conversation from within the child
conversation. For an example on nested ConversationHandler s, see nestedconversationbot.py.
See also:
Conversation Example, Conversation Example 2, Nested Conversation Example, Persistent Conversation
Example
Parameters
• entry_points (List[telegram.ext.BaseHandler]) – A list of BaseHandler ob-
jects that can trigger the start of the conversation. The first handler whose
check_update() method returns True will be used. If all return False, the update
is not handled.
• states (Dict[object, List[telegram.ext.BaseHandler]]) – A dict that defines the
different states of conversation a user can be in and one or more associated BaseHandler
objects that should be used in that state. The first handler whose check_update()
method returns True will be used.
• fallbacks (List[telegram.ext.BaseHandler]) – 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 conver-
sation can restart the conversation by triggering one of the entry points.
• per_chat (bool, optional) – If the conversation key should contain the Chat’s ID. De-
fault is True.
• per_user (bool, optional) – If the conversation key should contain the User’s ID. De-
fault is True.
• per_message (bool, optional) – If the conversation key should contain the Message’s
ID. Default is False.
• name (str, optional) – The name for this conversation handler. Required for persistence.
• persistent (bool, optional) – If the conversation’s dict for this handler should be
saved. name is required and persistence has to be set in Application.
Changed in version 20.0: Was previously named as persistence.
• map_to_parent (Dict[object, object], optional) – A dict that can be used to instruct
a child conversation handler to transition into a mapped state on its parent conversation
handler in place of a specified nested state.
• block (bool, optional) – Pass False or True to set a default value for the
BaseHandler.block setting of all handlers (in entry_points, states and
fallbacks). The resolution order for checking if a handler should be run non-blocking
is:
1. telegram.ext.BaseHandler.block (if set)
2. the value passed to this parameter (if any)
3. telegram.ext.Defaults.block (if defaults are used)
Changed in version 20.0: No longer overrides the handlers settings. Resolution order
was changed.
Raises
ValueError – If persistent is used but name was not set, or when per_message,
per_chat, per_user are all False.
block
Determines whether the callback will run in a blocking way.. Always True since conversation handlers
handle any non-blocking callbacks internally.
Type
bool
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 (exceeded
conversation_timeout).
Type
int
WAITING = -3
Used as a constant to handle state when a conversation is still waiting on the previous block=False
handler to finish.
Type
int
property allow_reentry
Determines if a user can restart a conversation with an entry point.
Type
bool
check_update(update)
Determines whether an update should be handled by this conversation handler, and if so in which state
the conversation currently is.
Parameters
update (telegram.Update | object) – Incoming update.
Returns
bool
property conversation_timeout
Optional. When this handler is inactive more than this timeout (in seconds), it will be automatically
ended.
Type
float | datetime.timedelta
property entry_points
A list of BaseHandler objects that can trigger the start of the conversation.
Type
List[telegram.ext.BaseHandler]
property fallbacks
A list of handlers that might be used if the user is in a conversation, but every handler for their current
state returned False on check_update().
Type
List[telegram.ext.BaseHandler]
async handle_update(update, application, check_result, context)
Send the update to the callback for the current state and BaseHandler
Parameters
• check_result – The result from check_update(). For this handler it’s a tuple of
the conversation state, key, handler, and the handler’s check result.
• update (telegram.Update) – Incoming telegram update.
• application (telegram.ext.Application) – Application that originated the up-
date.
• context (telegram.ext.CallbackContext) – The context as provided by the ap-
plication.
property map_to_parent
Optional. A dict that can be used to instruct a nested ConversationHandler to transition into a
mapped state on its parent ConversationHandler in place of a specified nested state.
Type
Dict[object, object]
property name
Optional. The name for this ConversationHandler.
Type
str
property per_chat
If the conversation key should contain the Chat’s ID.
Type
bool
property per_message
If the conversation key should contain the message’s ID.
Type
bool
property per_user
If the conversation key should contain the User’s ID.
Type
bool
property persistent
Optional. If the conversations dict for this handler should be saved. name is required and persistence
has to be set in Application.
Type
bool
property states
A dict that defines the different states of conversation a user can be in and one or more associated
BaseHandler objects that should be used in that state.
Type
Dict[object, List[telegram.ext.BaseHandler]]
telegram.ext.filters Module
telegram.ext.filters.AUDIO = filters.AUDIO
Messages that contain telegram.Message.audio.
class telegram.ext.filters.BaseFilter(name=None, data_filter=False)
Bases: object
Base class for all Filters.
Filters subclassing from this class can combined using bitwise operators:
And:
Or:
filters.AUDIO | filters.VIDEO
Exclusive Or:
Not:
~ filters.COMMAND
Note: Filters use the same short circuiting logic as python’s and, or and not. This means that for example:
filters.Regex(r'(a?x)') | filters.Regex(r'(b?x)')
With message.text == 'x', will only ever return the matches for the first filter, since the second one is
never evaluated.
If you want to create your own filters create a class inheriting from either MessageFilter or UpdateFilter
and implement a filter() method that returns a boolean: True if the message should be handled, False
otherwise. Note that the filters work only as class instances, not actual class objects (so remember to initialize
your filter classes).
By default, the filters name (what will get printed when converted to a string for display) will be the class
name. If you want to overwrite this assign a better name to the name class variable.
New in version 20.0: Added the arguments name and data_filter.
Parameters
• name (str) – Name for this filter. Defaults to the type of filter.
• data_filter (bool) – Whether this filter is a data filter. A data filter should return
a dict with lists. The dict will be merged with telegram.ext.CallbackContext’s
internal dict in most cases (depends on the handler).
name
Name for this filter.
Type
str
data_filter
Whether this filter is a data filter.
Type
bool
check_update(update)
Checks if the specified update is a message.
telegram.ext.filters.CAPTION = filters.CAPTION
Shortcut for telegram.ext.filters.Caption().
Examples
To allow any caption, simply use MessageHandler(filters.CAPTION, callback_method).
telegram.ext.filters.CHAT = filters.CHAT
This filter filters any message that has a telegram.Message.chat.
telegram.ext.filters.COMMAND = filters.COMMAND
Shortcut for telegram.ext.filters.Command().
Examples
To allow messages starting with a command use MessageHandler(filters.COMMAND,
command_at_start_callback).
telegram.ext.filters.CONTACT = filters.CONTACT
Messages that contain telegram.Message.contact.
class telegram.ext.filters.Caption(strings=None)
Bases: telegram.ext.filters.MessageFilter
Messages with a caption. If a list of strings is passed, it filters messages to only allow those whose caption
is appearing in the given list.
Examples
MessageHandler(filters.Caption(['PTB rocks!', 'PTB'], callback_method_2)
See also:
telegram.ext.filters.CAPTION
Parameters
strings (List[str] | Tuple[str], optional) – Which captions to allow. Only exact matches
are allowed. If not specified, will allow any message with a caption.
class telegram.ext.filters.CaptionEntity(entity_type)
Bases: telegram.ext.filters.MessageFilter
Filters media messages to only allow those which have a telegram.MessageEntity where their type
matches entity_type.
Examples
MessageHandler(filters.CaptionEntity("hashtag"), callback_method)
Parameters
entity_type (str) – Caption Entity type to check for. All types can be found as constants
in telegram.MessageEntity.
class telegram.ext.filters.CaptionRegex(pattern)
Bases: telegram.ext.filters.MessageFilter
Filters updates by searching for an occurrence of pattern in the message caption.
This filter works similarly to Regex, with the only exception being that it applies to the message caption
instead of the text.
Examples
Use MessageHandler(filters.PHOTO & filters.CaptionRegex(r'help'), callback) to cap-
ture all photos with caption containing the word ‘help’.
Note: This filter will not work on simple text messages, but only on media with caption.
Parameters
pattern (str | re.Pattern) – The regex pattern.
Examples
MessageHandler(filters.Chat(-1234), callback_method)
Warning: chat_ids will give a copy of the saved chat ids as frozenset. This is to ensure thread
safety. To add/remove a chat, you should use add_chat_ids(), and remove_chat_ids(). Only up-
date the entire set by filter.chat_ids = new_set, if you are entirely sure that it is not causing race
conditions, as this will complete replace the current set of allowed chats.
Parameters
• chat_id (int | Collection[int], optional) – Which chat ID(s) to allow through.
• username (str | Collection[str], optional) – Which username(s) to allow through.
Leading '@' s in usernames will be discarded.
• allow_empty (bool, optional) – Whether updates should be processed, if no chat is
specified in chat_ids and usernames. Defaults to False.
chat_ids
Which chat ID(s) to allow through.
Type
set(int)
allow_empty
Whether updates should be processed, if no chat is specified in chat_ids and usernames.
Type
bool
Raises
RuntimeError – If chat_id and username are both present.
add_chat_ids(chat_id)
Add one or more chats to the allowed chat ids.
Parameters
chat_id (int | Collection[int]) – Which chat ID(s) to allow through.
remove_chat_ids(chat_id)
Remove one or more chats from allowed chat ids.
Parameters
chat_id (int | Collection[int]) – Which chat ID(s) to disallow through.
add_usernames(username)
Add one or more chats to the allowed usernames.
Parameters
username (str | Collection[str]) – Which username(s) to allow through. Leading '@'
s in usernames will be discarded.
remove_usernames(username)
Remove one or more chats from allowed usernames.
Parameters
username (str | Collection[str]) – Which username(s) to disallow through. Leading
'@' s in usernames will be discarded.
property usernames
Which username(s) to allow through.
Warning: usernames will give a copy of the saved usernames as frozenset. This
is to ensure thread safety. To add/remove a user, you should use add_usernames(), and
remove_usernames(). Only update the entire set by filter.usernames = new_set, if you
are entirely sure that it is not causing race conditions, as this will complete replace the current set
of allowed users.
Returns
frozenset(str)
class telegram.ext.filters.ChatType
Bases: object
Subset for filtering the type of chat.
Examples
Use these filters like: filters.ChatType.CHANNEL or filters.ChatType.SUPERGROUP etc.
CHANNEL = filters.ChatType.CHANNEL
Updates from channel.
GROUP = filters.ChatType.GROUP
Updates from group.
GROUPS = filters.ChatType.GROUPS
Update from group or supergroup.
PRIVATE = filters.ChatType.PRIVATE
Update from private chats.
SUPERGROUP = filters.ChatType.SUPERGROUP
Updates from supergroup.
class telegram.ext.filters.Command(only_start=True)
Bases: telegram.ext.filters.MessageFilter
Messages with a telegram.MessageEntity.BOT_COMMAND. By default, only allows messages starting
with a bot command. Pass False to also allow messages that contain a bot command anywhere in the text.
Examples
MessageHandler(filters.Command(False), command_anywhere_callback)
See also:
telegram.ext.filters.COMMAND.
Parameters
only_start (bool, optional) – Whether to only allow messages that start with a bot com-
mand. Defaults to True.
Examples
To allow any dice message, simply use MessageHandler(filters.Dice.ALL, callback_method).
To allow any dice message, but with value 3 or 4, use MessageHandler(filters.Dice([3, 4]),
callback_method)
To allow only dice messages with the emoji , but any value, use MessageHandler(filters.Dice.DICE,
callback_method).
To allow only dice messages with the emoji and with value 6, use MessageHandler(filters.Dice.
Darts(6), callback_method).
To allow only dice messages with the emoji and with value 5 or 6, use MessageHandler(filters.Dice.
Football([5, 6]), callback_method).
Note: Dice messages don’t have text. If you want to filter either text or dice messages, use filters.TEXT
| filters.Dice.ALL.
Parameters
values (int | Collection[int], optional) – Which values to allow. If not specified, will
allow the specified dice message.
ALL = filters.Dice.ALL
Dice messages with any value and any emoji.
class Basketball(values)
Bases: telegram.ext.filters.MessageFilter
Dice messages with the emoji . Supports passing a list of integers.
Parameters
values (int | Collection[int]) – Which values to allow.
BASKETBALL = filters.Dice.BASKETBALL
Dice messages with the emoji . Matches any dice value.
class Bowling(values)
Bases: telegram.ext.filters.MessageFilter
Dice messages with the emoji . Supports passing a list of integers.
Parameters
values (int | Collection[int]) – Which values to allow.
BOWLING = filters.Dice.BOWLING
Dice messages with the emoji . Matches any dice value.
class Darts(values)
Bases: telegram.ext.filters.MessageFilter
Dice messages with the emoji . Supports passing a list of integers.
Parameters
values (int | Collection[int]) – Which values to allow.
DARTS = filters.Dice.DARTS
Dice messages with the emoji . Matches any dice value.
class Dice(values)
Bases: telegram.ext.filters.MessageFilter
Dice messages with the emoji . Supports passing a list of integers.
Parameters
values (int | Collection[int]) – Which values to allow.
DICE = filters.Dice.DICE
Dice messages with the emoji . Matches any dice value.
class Football(values)
Bases: telegram.ext.filters.MessageFilter
Dice messages with the emoji . Supports passing a list of integers.
Parameters
values (int | Collection[int]) – Which values to allow.
FOOTBALL = filters.Dice.FOOTBALL
Dice messages with the emoji . Matches any dice value.
class SlotMachine(values)
Bases: telegram.ext.filters.MessageFilter
Dice messages with the emoji . Supports passing a list of integers.
Parameters
values (int | Collection[int]) – Which values to allow.
SLOT_MACHINE = filters.Dice.SLOT_MACHINE
Dice messages with the emoji . Matches any dice value.
class telegram.ext.filters.Document
Bases: object
Subset for messages containing a document/file.
Examples
Use these filters like: filters.Document.MP3, filters.Document.MimeType("text/plain") etc. Or
just use filters.Document.ALL for all document messages.
ALL = filters.Document.ALL
Messages that contain a telegram.Message.document.
class Category(category)
Bases: telegram.ext.filters.MessageFilter
Filters documents by their category in the mime-type attribute.
Parameters
category (str) – Category of the media you want to filter.
Example
filters.Document.Category('audio/') returns True for all types of audio sent as a file, for
example 'audio/mpeg' or 'audio/x-wav'.
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.
APPLICATION = filters.Document.Category('application/')
Use as filters.Document.APPLICATION.
AUDIO = filters.Document.Category('audio/')
Use as filters.Document.AUDIO.
IMAGE = filters.Document.Category('image/')
Use as filters.Document.IMAGE.
VIDEO = filters.Document.Category('video/')
Use as filters.Document.VIDEO.
TEXT = filters.Document.Category('text/')
Use as filters.Document.TEXT.
class FileExtension(file_extension, case_sensitive=False)
Bases: telegram.ext.filters.MessageFilter
This filter filters documents by their file ending/extension.
Parameters
• file_extension (str | None) – Media file extension you want to filter.
• case_sensitive (bool, optional) – Pass True to make the filter case sensitive. De-
fault: False.
Example
• filters.Document.FileExtension("jpg") filters files with extension ".jpg".
• filters.Document.FileExtension(".jpg") filters files with extension "..jpg".
• filters.Document.FileExtension("Dockerfile", case_sensitive=True) filters files
with extension ".Dockerfile" minding the case.
• filters.Document.FileExtension(None) filters files without a dot in the filename.
Note:
• This Filter only filters by the file ending/extension of the document, it doesn’t check the validity
of document.
• The user can manipulate the file extension of a document and send media with wrong types that
don’t fit to this handler.
• Case insensitive by default, you may change this with the flag case_sensitive=True.
• Extension should be passed without leading dot unless it’s a part of the extension.
• Pass None to filter files with no extension, i.e. without a dot in the filename.
class MimeType(mimetype)
Bases: telegram.ext.filters.MessageFilter
This Filter filters documents by their mime-type attribute.
Parameters
mimetype (str) – The mimetype to filter.
Example
filters.Document.MimeType('audio/mpeg') filters all audio in .mp3 format.
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.
APK = filters.Document.MimeType('application/vnd.android.package-archive')
Use as filters.Document.APK.
DOC = filters.Document.MimeType('application/msword')
Use as filters.Document.DOC.
DOCX = filters.Document.MimeType('application/vnd.openxmlformats-officedocument.
wordprocessingml.document')
Use as filters.Document.DOCX.
EXE = filters.Document.MimeType('application/octet-stream')
Use as filters.Document.EXE.
MP4 = filters.Document.MimeType('video/mp4')
Use as filters.Document.MP4.
GIF = filters.Document.MimeType('image/gif')
Use as filters.Document.GIF.
JPG = filters.Document.MimeType('image/jpeg')
Use as filters.Document.JPG.
MP3 = filters.Document.MimeType('audio/mpeg')
Use as filters.Document.MP3.
PDF = filters.Document.MimeType('application/pdf')
Use as filters.Document.PDF.
PY = filters.Document.MimeType('text/x-python')
Use as filters.Document.PY.
SVG = filters.Document.MimeType('image/svg+xml')
Use as filters.Document.SVG.
TXT = filters.Document.MimeType('text/plain')
Use as filters.Document.TXT.
TARGZ = filters.Document.MimeType('application/x-compressed-tar')
Use as filters.Document.TARGZ.
WAV = filters.Document.MimeType('audio/x-wav')
Use as filters.Document.WAV.
XML = filters.Document.MimeType('text/xml')
Use as filters.Document.XML.
ZIP = filters.Document.MimeType('application/zip')
Use as filters.Document.ZIP.
class telegram.ext.filters.Entity(entity_type)
Bases: telegram.ext.filters.MessageFilter
Filters messages to only allow those which have a telegram.MessageEntity where their type matches
entity_type.
Examples
MessageHandler(filters.Entity("hashtag"), callback_method)
Parameters
entity_type (str) – Entity type to check for. All types can be found as constants in
telegram.MessageEntity.
telegram.ext.filters.FORWARDED = filters.FORWARDED
Messages that contain telegram.Message.forward_date.
class telegram.ext.filters.ForwardedFrom(chat_id=None, username=None, allow_empty=False)
Bases: telegram.ext.filters.MessageFilter
Filters messages to allow only those which are forwarded from the specified chat ID(s) or username(s) based
on telegram.Message.forward_from and telegram.Message.forward_from_chat.
New in version 13.5.
Examples
MessageHandler(filters.ForwardedFrom(chat_id=1234), callback_method)
Note: When a user has disallowed adding a link to their account while forwarding their mes-
sages, this filter will not work since both telegram.Message.forward_from and telegram.Message.
forward_from_chat are None. However, this behaviour is undocumented and might be changed by Tele-
gram.
Warning: chat_ids will give a copy of the saved chat ids as frozenset. This is to ensure thread
safety. To add/remove a chat, you should use add_chat_ids(), and remove_chat_ids(). Only up-
date the entire set by filter.chat_ids = new_set, if you are entirely sure that it is not causing race
conditions, as this will complete replace the current set of allowed chats.
Parameters
• chat_id (int | Collection[int], optional) – Which chat/user ID(s) to allow through.
• username (str | Collection[str], optional) – Which username(s) to allow through.
Leading '@' s in usernames will be discarded.
• allow_empty (bool, optional) – Whether updates should be processed, if no chat is
specified in chat_ids and usernames. Defaults to False.
chat_ids
Which chat/user ID(s) to allow through.
Type
set(int)
allow_empty
Whether updates should be processed, if no chat is specified in chat_ids and usernames.
Type
bool
Raises
RuntimeError – If both chat_id and username are present.
add_chat_ids(chat_id)
Add one or more chats to the allowed chat ids.
Parameters
chat_id (int | Collection[int]) – Which chat/user ID(s) to allow through.
remove_chat_ids(chat_id)
Remove one or more chats from allowed chat ids.
Parameters
chat_id (int | Collection[int]) – Which chat/user ID(s) to disallow through.
add_usernames(username)
Add one or more chats to the allowed usernames.
Parameters
username (str | Collection[str]) – Which username(s) to allow through. Leading '@'
s in usernames will be discarded.
remove_usernames(username)
Remove one or more chats from allowed usernames.
Parameters
username (str | Collection[str]) – Which username(s) to disallow through. Leading
'@' s in usernames will be discarded.
property usernames
Which username(s) to allow through.
Warning: usernames will give a copy of the saved usernames as frozenset. This
is to ensure thread safety. To add/remove a user, you should use add_usernames(), and
remove_usernames(). Only update the entire set by filter.usernames = new_set, if you
are entirely sure that it is not causing race conditions, as this will complete replace the current set
of allowed users.
Returns
frozenset(str)
telegram.ext.filters.GAME = filters.GAME
Messages that contain telegram.Message.game.
telegram.ext.filters.HAS_PROTECTED_CONTENT = filters.HAS_PROTECTED_CONTENT
Messages that contain telegram.Message.has_protected_content.
New in version 13.9.
telegram.ext.filters.INVOICE = filters.INVOICE
Messages that contain telegram.Message.invoice.
telegram.ext.filters.IS_AUTOMATIC_FORWARD = filters.IS_AUTOMATIC_FORWARD
Messages that contain telegram.Message.is_automatic_forward.
New in version 13.9.
telegram.ext.filters.LOCATION = filters.LOCATION
Messages that contain telegram.Message.location.
class telegram.ext.filters.Language(lang)
Bases: telegram.ext.filters.MessageFilter
Filters messages to only allow those which are from users with a certain language code.
Note: According to official Telegram Bot API documentation, not every single user has the language_code
attribute. Do not count on this filter working on all users.
Examples
MessageHandler(filters.Language("en"), callback_method)
Parameters
lang (str | Collection[str]) – Which language code(s) to allow through. This will be
matched using str.startswith meaning that ‘en’ will match both ‘en_US’ and ‘en_GB’.
Examples
Use MessageHandler(filters.Regex(r'help'), callback) to capture all messages that contain
the word ‘help’. You can also use MessageHandler(filters.Regex(re.compile(r'help', re.
IGNORECASE)), callback) if you want your pattern to be case insensitive. This approach is recommended
if you need to specify flags on your pattern.
Note: Filters use the same short circuiting logic as python’s and, or and not. This means that for example:
With a telegram.Message.text of x, will only ever return the matches for the first filter, since the second
one is never evaluated.
Parameters
pattern (str | re.Pattern) – The regex pattern.
class telegram.ext.filters.Sticker
Bases: object
Filters messages which contain a sticker.
Examples
Use this filter like: filters.Sticker.VIDEO. Or, just use filters.Sticker.ALL for any type of sticker.
ALL = filters.Sticker.ALL
Messages that contain telegram.Message.sticker.
ANIMATED = filters.Sticker.ANIMATED
Messages that contain telegram.Message.sticker and is animated.
New in version 20.0.
STATIC = filters.Sticker.STATIC
Messages that contain telegram.Message.sticker and is a static sticker, i.e. does not contain
telegram.Sticker.is_animated or telegram.Sticker.is_video.
New in version 20.0.
VIDEO = filters.Sticker.VIDEO
Messages that contain telegram.Message.sticker and is a video sticker.
New in version 20.0.
PREMIUM = filters.Sticker.PREMIUM
Messages that contain telegram.Message.sticker and have a premium animation.
New in version 20.0.
telegram.ext.filters.SUCCESSFUL_PAYMENT = filters.SUCCESSFUL_PAYMENT
Messages that contain telegram.Message.successful_payment.
class telegram.ext.filters.SenderChat(chat_id=None, username=None, allow_empty=False)
Bases: telegram.ext.filters.MessageFilter
Filters messages to allow only those which are from a specified sender chat’s chat ID or username.
Examples
• To filter for messages sent to a group by a channel with ID -1234, use MessageHandler(filters.
SenderChat(-1234), callback_method).
• To filter for messages of anonymous admins in a super group with username @anonymous, use
MessageHandler(filters.SenderChat(username='anonymous'), callback_method).
Note: Remember, sender_chat is also set for messages in a channel as the channel itself, so when your
bot is an admin in a channel and the linked discussion group, you would receive the message twice (once
from inside the channel, once inside the discussion group). Since v13.9, the field telegram.Message.
is_automatic_forward will be True for the discussion group message.
See also:
telegram.ext.filters.IS_AUTOMATIC_FORWARD
Warning: chat_ids will return a copy of the saved chat ids as frozenset. This is to ensure thread
safety. To add/remove a chat, you should use add_chat_ids(), and remove_chat_ids(). Only up-
date the entire set by filter.chat_ids = new_set, if you are entirely sure that it is not causing race
conditions, as this will complete replace the current set of allowed chats.
Parameters
• chat_id (int | Collection[int], optional) – Which sender chat chat ID(s) to allow
through.
• username (str | Collection[str], optional) – Which sender chat username(s) to allow
through. Leading '@' s in usernames will be discarded.
• allow_empty (bool, optional) – Whether updates should be processed, if no sender
chat is specified in chat_ids and usernames. Defaults to False.
chat_ids
Which sender chat chat ID(s) to allow through.
Type
set(int)
allow_empty
Whether updates should be processed, if no sender chat is specified in chat_ids and usernames.
Type
bool
Raises
RuntimeError – If both chat_id and username are present.
ALL = filters.SenderChat.ALL
All messages with a telegram.Message.sender_chat.
SUPER_GROUP = filters.SenderChat.SUPER_GROUP
Messages whose sender chat is a super group.
CHANNEL = filters.SenderChat.CHANNEL
Messages whose sender chat is a channel.
add_chat_ids(chat_id)
Add one or more sender chats to the allowed chat ids.
Parameters
chat_id (int | Collection[int]) – Which sender chat ID(s) to allow through.
remove_chat_ids(chat_id)
Remove one or more sender chats from allowed chat ids.
Parameters
chat_id (int | Collection[int]) – Which sender chat ID(s) to disallow through.
add_usernames(username)
Add one or more chats to the allowed usernames.
Parameters
username (str | Collection[str]) – Which username(s) to allow through. Leading '@'
s in usernames will be discarded.
remove_usernames(username)
Remove one or more chats from allowed usernames.
Parameters
username (str | Collection[str]) – Which username(s) to disallow through. Leading
'@' s in usernames will be discarded.
property usernames
Which username(s) to allow through.
Warning: usernames will give a copy of the saved usernames as frozenset. This
is to ensure thread safety. To add/remove a user, you should use add_usernames(), and
remove_usernames(). Only update the entire set by filter.usernames = new_set, if you
are entirely sure that it is not causing race conditions, as this will complete replace the current set
of allowed users.
Returns
frozenset(str)
class telegram.ext.filters.StatusUpdate
Bases: object
Subset for messages containing a status update.
Examples
Use these filters like: filters.StatusUpdate.NEW_CHAT_MEMBERS etc. Or use just filters.
StatusUpdate.ALL for all status update messages.
ALL = filters.StatusUpdate.ALL
Messages that contain any of the below.
CHAT_CREATED = filters.StatusUpdate.CHAT_CREATED
Messages that contain telegram.Message.group_chat_created, telegram.Message.
supergroup_chat_created or telegram.Message.channel_chat_created.
CONNECTED_WEBSITE = filters.StatusUpdate.CONNECTED_WEBSITE
Messages that contain telegram.Message.connected_website.
DELETE_CHAT_PHOTO = filters.StatusUpdate.DELETE_CHAT_PHOTO
Messages that contain telegram.Message.delete_chat_photo.
LEFT_CHAT_MEMBER = filters.StatusUpdate.LEFT_CHAT_MEMBER
Messages that contain telegram.Message.left_chat_member.
MESSAGE_AUTO_DELETE_TIMER_CHANGED =
filters.StatusUpdate.MESSAGE_AUTO_DELETE_TIMER_CHANGED
Messages that contain telegram.Message.message_auto_delete_timer_changed
New in version 13.4.
MIGRATE = filters.StatusUpdate.MIGRATE
Messages that contain telegram.Message.migrate_from_chat_id or telegram.Message.
migrate_to_chat_id.
NEW_CHAT_MEMBERS = filters.StatusUpdate.NEW_CHAT_MEMBERS
Messages that contain telegram.Message.new_chat_members.
NEW_CHAT_PHOTO = filters.StatusUpdate.NEW_CHAT_PHOTO
Messages that contain telegram.Message.new_chat_photo.
NEW_CHAT_TITLE = filters.StatusUpdate.NEW_CHAT_TITLE
Messages that contain telegram.Message.new_chat_title.
PINNED_MESSAGE = filters.StatusUpdate.PINNED_MESSAGE
Messages that contain telegram.Message.pinned_message.
PROXIMITY_ALERT_TRIGGERED = filters.StatusUpdate.PROXIMITY_ALERT_TRIGGERED
Messages that contain telegram.Message.proximity_alert_triggered.
VIDEO_CHAT_ENDED = filters.StatusUpdate.VIDEO_CHAT_ENDED
Messages that contain telegram.Message.video_chat_ended.
New in version 13.4.
Changed in version 20.0: This filter was formerly named VOICE_CHAT_ENDED
VIDEO_CHAT_SCHEDULED = filters.StatusUpdate.VIDEO_CHAT_SCHEDULED
Messages that contain telegram.Message.video_chat_scheduled.
New in version 13.5.
Changed in version 20.0: This filter was formerly named VOICE_CHAT_SCHEDULED
VIDEO_CHAT_STARTED = filters.StatusUpdate.VIDEO_CHAT_STARTED
Messages that contain telegram.Message.video_chat_started.
New in version 13.4.
Changed in version 20.0: This filter was formerly named VOICE_CHAT_STARTED
VIDEO_CHAT_PARTICIPANTS_INVITED =
filters.StatusUpdate.VIDEO_CHAT_PARTICIPANTS_INVITED
Messages that contain telegram.Message.video_chat_participants_invited.
New in version 13.4.
Changed in version 20.0: This filter was formerly named VOICE_CHAT_PARTICIPANTS_INVITED
WEB_APP_DATA = filters.StatusUpdate.WEB_APP_DATA
Messages that contain telegram.Message.web_app_data.
New in version 20.0.
telegram.ext.filters.TEXT = filters.TEXT
Shortcut for telegram.ext.filters.Text().
Examples
To allow any text message, simply use MessageHandler(filters.TEXT, callback_method).
class telegram.ext.filters.Text(strings=None)
Bases: telegram.ext.filters.MessageFilter
Text Messages. If a list of strings is passed, it filters messages to only allow those whose text is appearing in
the given list.
Examples
A simple use case for passing a list is to allow only messages that were sent by a custom telegram.
ReplyKeyboardMarkup:
See also:
telegram.ext.filters.TEXT
Note:
• Dice messages don’t have text. If you want to filter either text or dice messages, use filters.TEXT |
filters.Dice.ALL.
• Messages containing a command are accepted by this filter. Use filters.TEXT & (~filters.
COMMAND), if you want to filter only text messages without commands.
Parameters
strings (List[str] | Tuple[str], optional) – Which messages to allow. Only exact matches
are allowed. If not specified, will allow any text message.
telegram.ext.filters.USER = filters.USER
This filter filters any message that has a telegram.Message.from_user.
telegram.ext.filters.USER_ATTACHMENT = filters.USER_ATTACHMENT
This filter filters any message that have a user who added the bot to their attachment menu as telegram.
Update.effective_user.
New in version 20.0.
telegram.ext.filters.PREMIUM_USER = filters.PREMIUM_USER
This filter filters any message from a Telegram Premium user as telegram.Update.effective_user.
New in version 20.0.
Examples
Use these filters like: filters.UpdateType.MESSAGE or filters.UpdateType.CHANNEL_POSTS etc.
CHANNEL_POST = filters.UpdateType.CHANNEL_POST
Updates with telegram.Update.channel_post.
CHANNEL_POSTS = filters.UpdateType.CHANNEL_POSTS
Updates with either telegram.Update.channel_post or telegram.Update.
edited_channel_post.
EDITED = filters.UpdateType.EDITED
Updates with either telegram.Update.edited_message or telegram.Update.
edited_channel_post.
New in version 20.0.
EDITED_CHANNEL_POST = filters.UpdateType.EDITED_CHANNEL_POST
Updates with telegram.Update.edited_channel_post.
EDITED_MESSAGE = filters.UpdateType.EDITED_MESSAGE
Updates with telegram.Update.edited_message.
MESSAGE = filters.UpdateType.MESSAGE
Updates with telegram.Update.message.
MESSAGES = filters.UpdateType.MESSAGES
Updates with either telegram.Update.message or telegram.Update.edited_message.
class telegram.ext.filters.User(user_id=None, username=None, allow_empty=False)
Bases: telegram.ext.filters.MessageFilter
Filters messages to allow only those which are from specified user ID(s) or username(s).
Examples
MessageHandler(filters.User(1234), callback_method)
Parameters
• user_id (int | Collection[int], optional) – Which user ID(s) to allow through.
• username (str | Collection[str], optional) – Which username(s) to allow through.
Leading '@' s in usernames will be discarded.
• allow_empty (bool, optional) – Whether updates should be processed, if no user is
specified in user_ids and usernames. Defaults to False.
Raises
RuntimeError – If user_id and username are both present.
allow_empty
Whether updates should be processed, if no user is specified in user_ids and usernames.
Type
bool
add_usernames(username)
Add one or more chats to the allowed usernames.
Parameters
username (str | Collection[str]) – Which username(s) to allow through. Leading '@'
s in usernames will be discarded.
remove_usernames(username)
Remove one or more chats from allowed usernames.
Parameters
username (str | Collection[str]) – Which username(s) to disallow through. Leading
'@' s in usernames will be discarded.
property usernames
Which username(s) to allow through.
Warning: usernames will give a copy of the saved usernames as frozenset. This
is to ensure thread safety. To add/remove a user, you should use add_usernames(), and
remove_usernames(). Only update the entire set by filter.usernames = new_set, if you
are entirely sure that it is not causing race conditions, as this will complete replace the current set
of allowed users.
Returns
frozenset(str)
property user_ids
Which user ID(s) to allow through.
Warning: user_ids will give a copy of the saved user ids as frozenset. This is to ensure
thread safety. To add/remove a user, you should use add_user_ids(), and remove_user_ids().
Only update the entire set by filter.user_ids = new_set, if you are entirely sure that it is not
causing race conditions, as this will complete replace the current set of allowed users.
Returns
frozenset(int)
add_user_ids(user_id)
Add one or more users to the allowed user ids.
Parameters
user_id (int | Collection[int]) – Which user ID(s) to allow through.
remove_user_ids(user_id)
Remove one or more users from allowed user ids.
Parameters
user_id (int | Collection[int]) – Which user ID(s) to disallow through.
telegram.ext.filters.VENUE = filters.VENUE
Messages that contain telegram.Message.venue.
telegram.ext.filters.VIA_BOT = filters.VIA_BOT
This filter filters for message that were sent via any bot.
telegram.ext.filters.VIDEO = filters.VIDEO
Messages that contain telegram.Message.video.
telegram.ext.filters.VIDEO_NOTE = filters.VIDEO_NOTE
Messages that contain telegram.Message.video_note.
telegram.ext.filters.VOICE = filters.VOICE
Messages that contain telegram.Message.voice.
class telegram.ext.filters.ViaBot(bot_id=None, username=None, allow_empty=False)
Bases: telegram.ext.filters.MessageFilter
Filters messages to allow only those which are from specified via_bot ID(s) or username(s).
Examples
MessageHandler(filters.ViaBot(1234), callback_method)
Parameters
• bot_id (int | Collection[int], optional) – Which bot ID(s) to allow through.
• username (str | Collection[str], optional) – Which username(s) to allow through.
Leading '@' s in usernames will be discarded.
• allow_empty (bool, optional) – Whether updates should be processed, if no user is
specified in bot_ids and usernames. Defaults to False.
Raises
RuntimeError – If bot_id and username are both present.
allow_empty
Whether updates should be processed, if no bot is specified in bot_ids and usernames.
Type
bool
add_usernames(username)
Add one or more chats to the allowed usernames.
Parameters
username (str | Collection[str]) – Which username(s) to allow through. Leading '@'
s in usernames will be discarded.
remove_usernames(username)
Remove one or more chats from allowed usernames.
Parameters
username (str | Collection[str]) – Which username(s) to disallow through. Leading
'@' s in usernames will be discarded.
property usernames
Which username(s) to allow through.
Warning: usernames will give a copy of the saved usernames as frozenset. This
is to ensure thread safety. To add/remove a user, you should use add_usernames(), and
remove_usernames(). Only update the entire set by filter.usernames = new_set, if you
are entirely sure that it is not causing race conditions, as this will complete replace the current set
of allowed users.
Returns
frozenset(str)
property bot_ids
Which bot ID(s) to allow through.
Warning: bot_ids will give a copy of the saved bot ids as frozenset. This is to ensure thread
safety. To add/remove a bot, you should use add_bot_ids(), and remove_bot_ids(). Only
update the entire set by filter.bot_ids = new_set, if you are entirely sure that it is not causing
race conditions, as this will complete replace the current set of allowed bots.
Returns
frozenset(int)
add_bot_ids(bot_id)
Add one or more bots to the allowed bot ids.
Parameters
bot_id (int | Collection[int]) – Which bot ID(s) to allow through.
remove_bot_ids(bot_id)
Remove one or more bots from allowed bot ids.
Parameters
bot_id (int | Collection[int], optional) – Which bot ID(s) to disallow through.
telegram.ext.InlineQueryHandler
Warning:
• When setting block to False, you cannot rely on adding custom attributes to telegram.ext.
CallbackContext. See its docs for more info.
• telegram.InlineQuery.chat_type will not be set for inline queries from secret chats and may
not be set for inline queries coming from third-party clients. These updates won’t be handled, if
chat_types is passed.
See also:
Inlinebot Example
Parameters
• callback (coroutine function) – The callback function for this handler. Will be called
when check_update() has determined that an update should be processed by this han-
dler. Callback signature:
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• pattern (str | re.Pattern, optional) – Regex pattern. If not None, re.match() is
used on telegram.InlineQuery.query to determine if an update should be handled
by this handler.
• block (bool, optional) – Determines whether the return value of the callback should
be awaited before processing the next handler in telegram.ext.Application.
process_update(). Defaults to True.
• chat_types (List[str], optional) – List of allowed chat types. If passed, will only
handle inline queries with the appropriate telegram.InlineQuery.chat_type.
New in version 13.5.
callback
The callback function for this handler.
Type
coroutine function
pattern
Optional. Regex pattern to test telegram.InlineQuery.query against.
Type
str | re.Pattern
chat_types
Optional. List of allowed chat types.
New in version 13.5.
Type
List[str]
block
Determines whether the return value of the callback should be awaited before processing the next
handler in telegram.ext.Application.process_update().
Type
bool
check_update(update)
Determines whether an update should be passed to this handler’s callback.
Parameters
update (telegram.Update | object) – Incoming update.
Returns
bool | re.match
collect_additional_context(context, update, application, check_result)
Add the result of re.match(pattern, update.inline_query.query) to CallbackContext.
matches as list with one element.
telegram.ext.MessageHandler
Warning: When setting block to False, you cannot rely on adding custom attributes to telegram.
ext.CallbackContext. See its docs for more info.
Parameters
• filters (telegram.ext.filters.BaseFilter) – A filter inheriting from
telegram.ext.filters.BaseFilter. Standard filters can be found in telegram.
ext.filters. Filters can be combined using bitwise operators (& for and, | for or, ~
for not). This defaults to all message updates being: telegram.Update.message,
telegram.Update.edited_message, telegram.Update.channel_post and
telegram.Update.edited_channel_post. If you don’t want or need any of those
pass ~filters.UpdateType.* in the filter argument.
• callback (coroutine function) – The callback function for this handler. Will be called
when check_update() has determined that an update should be processed by this han-
dler. Callback signature:
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• block (bool, optional) – Determines whether the return value of the callback should
be awaited before processing the next handler in telegram.ext.Application.
process_update(). Defaults to True.
filters
Only allow updates with these Filters. See telegram.ext.filters for a full list of all available
filters.
Type
telegram.ext.filters.BaseFilter
callback
The callback function for this handler.
Type
coroutine function
block
Determines whether the return value of the callback should be awaited before processing the next
handler in telegram.ext.Application.process_update().
Type
bool
check_update(update)
Determines whether an update should be passed to this handler’s callback.
Parameters
update (telegram.Update | object) – Incoming update.
Returns
bool
collect_additional_context(context, update, application, check_result)
Adds possible output of data filters to the CallbackContext.
telegram.ext.PollAnswerHandler
Warning: When setting block to False, you cannot rely on adding custom attributes to telegram.
ext.CallbackContext. See its docs for more info.
See also:
Pollbot EXample
Parameters
• callback (coroutine function) – The callback function for this handler. Will be called
when check_update() has determined that an update should be processed by this han-
dler. Callback signature:
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• block (bool, optional) – Determines whether the return value of the callback should
be awaited before processing the next handler in telegram.ext.Application.
process_update(). Defaults to True.
callback
The callback function for this handler.
Type
coroutine function
block
Determines whether the callback will run in a blocking way..
Type
bool
check_update(update)
Determines whether an update should be passed to this handler’s callback.
Parameters
update (telegram.Update | object) – Incoming update.
Returns
bool
telegram.ext.PollHandler
Warning: When setting block to False, you cannot rely on adding custom attributes to telegram.
ext.CallbackContext. See its docs for more info.
See also:
Pollbot Example
Parameters
• callback (coroutine function) – The callback function for this handler. Will be called
when check_update() has determined that an update should be processed by this han-
dler. Callback signature:
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• block (bool, optional) – Determines whether the return value of the callback should
be awaited before processing the next handler in telegram.ext.Application.
process_update(). Defaults to True.
callback
The callback function for this handler.
Type
coroutine function
block
Determines whether the callback will run in a blocking way..
Type
bool
check_update(update)
Determines whether an update should be passed to this handler’s callback.
Parameters
update (telegram.Update | object) – Incoming update.
Returns
bool
telegram.ext.PreCheckoutQueryHandler
Warning: When setting block to False, you cannot rely on adding custom attributes to telegram.
ext.CallbackContext. See its docs for more info.
See also:
Paymentbot Example
Parameters
• callback (coroutine function) – The callback function for this handler. Will be called
when check_update() has determined that an update should be processed by this han-
dler. Callback signature:
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• block (bool, optional) – Determines whether the return value of the callback should
be awaited before processing the next handler in telegram.ext.Application.
process_update(). Defaults to True.
callback
The callback function for this handler.
Type
coroutine function
block
Determines whether the callback will run in a blocking way..
Type
bool
check_update(update)
Determines whether an update should be passed to this handler’s callback.
Parameters
update (telegram.Update | object) – Incoming update.
Returns
bool
telegram.ext.PrefixHandler
Examples
Single prefix and command:
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
~filters.UpdateType.EDITED_MESSAGE
Note:
• PrefixHandler does not handle (edited) channel posts.
Warning: When setting block to False, you cannot rely on adding custom attributes to telegram.
ext.CallbackContext. See its docs for more info.
Parameters
• prefix (str | Collection[str]) – The prefix(es) that will precede command.
• command (str | Collection[str]) – The command or list of commands this handler
should listen for. Case-insensitive.
• callback (coroutine function) – The callback function for this handler. Will be called
when check_update() has determined that an update should be processed by this han-
dler. Callback signature:
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• filters (telegram.ext.filters.BaseFilter, optional) – A filter inheriting from
telegram.ext.filters.BaseFilter. Standard filters can be found in telegram.
ext.filters. Filters can be combined using bitwise operators (& for and, | for or, ~
for not)
• block (bool, optional) – Determines whether the return value of the callback should
be awaited before processing the next handler in telegram.ext.Application.
process_update(). Defaults to True.
commands
The commands that this handler will listen for, i.e. the combinations of prefix and command.
Type
FrozenSet[str]
callback
The callback function for this handler.
Type
coroutine function
filters
Optional. Only allow updates with these Filters.
Type
telegram.ext.filters.BaseFilter
block
Determines whether the return value of the callback should be awaited before processing the next
handler in telegram.ext.Application.process_update().
Type
bool
check_update(update)
Determines whether an update should be passed to this handler’s callback.
Parameters
update (telegram.Update | object) – Incoming update.
Returns
The list of args for the handler.
Return type
list
collect_additional_context(context, update, application, check_result)
Add text after the command to CallbackContext.args as list, split on single whitespaces and add
output of data filters to CallbackContext as well.
telegram.ext.ShippingQueryHandler
Warning: When setting block to False, you cannot rely on adding custom attributes to telegram.
ext.CallbackContext. See its docs for more info.
See also:
Paymentbot Example
Parameters
• callback (coroutine function) – The callback function for this handler. Will be called
when check_update() has determined that an update should be processed by this han-
dler. Callback signature:
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• block (bool, optional) – Determines whether the return value of the callback should
be awaited before processing the next handler in telegram.ext.Application.
process_update(). Defaults to True.
callback
The callback function for this handler.
Type
coroutine function
block
Determines whether the callback will run in a blocking way..
Type
bool
check_update(update)
Determines whether an update should be passed to this handler’s callback.
Parameters
update (telegram.Update | object) – Incoming update.
Returns
bool
telegram.ext.StringCommandHandler
Note: This handler is not used to handle Telegram telegram.Update, but strings manually put in the
queue. For example to send messages with the bot using command line or API.
Warning: When setting block to False, you cannot rely on adding custom attributes to telegram.
ext.CallbackContext. See its docs for more info.
Parameters
• command (str) – The command this handler should listen for.
• callback (coroutine function) – The callback function for this handler. Will be called
when check_update() has determined that an update should be processed by this han-
dler. Callback signature:
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• block (bool, optional) – Determines whether the return value of the callback should
be awaited before processing the next handler in telegram.ext.Application.
process_update(). Defaults to True.
command
The command this handler should listen for.
Type
str
callback
The callback function for this handler.
Type
coroutine function
block
Determines whether the return value of the callback should be awaited before processing the next
handler in telegram.ext.Application.process_update().
Type
bool
check_update(update)
Determines whether an update should be passed to this handler’s callback.
Parameters
update (object) – The incoming update.
Returns
List containing the text command split on whitespace.
Return type
List[str]
collect_additional_context(context, update, application, check_result)
Add text after the command to CallbackContext.args as list, split on single whitespaces.
telegram.ext.StringRegexHandler
Note: This handler is not used to handle Telegram telegram.Update, but strings manually put in the
queue. For example to send messages with the bot using command line or API.
Warning: When setting block to False, you cannot rely on adding custom attributes to telegram.
ext.CallbackContext. See its docs for more info.
Parameters
• pattern (str | re.Pattern) – The regex pattern.
• callback (coroutine function) – The callback function for this handler. Will be called
when check_update() has determined that an update should be processed by this han-
dler. Callback signature:
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• block (bool, optional) – Determines whether the return value of the callback should
be awaited before processing the next handler in telegram.ext.Application.
process_update(). Defaults to True.
pattern
The regex pattern.
Type
str | re.Pattern
callback
The callback function for this handler.
Type
coroutine function
block
Determines whether the return value of the callback should be awaited before processing the next
handler in telegram.ext.Application.process_update().
Type
bool
check_update(update)
Determines whether an update should be passed to this handler’s callback.
Parameters
update (object) – The incoming update.
Returns
None | re.match
telegram.ext.TypeHandler
Warning: When setting block to False, you cannot rely on adding custom attributes to telegram.
ext.CallbackContext. See its docs for more info.
Parameters
• type (type) – The type of updates this handler should process, as determined by
isinstance
• callback (coroutine function) – The callback function for this handler. Will be called
when check_update() has determined that an update should be processed by this han-
dler. Callback signature:
The return value of the callback is usually ignored except for the special case of
telegram.ext.ConversationHandler.
• strict (bool, optional) – Use type instead of isinstance. Default is False.
• block (bool, optional) – Determines whether the return value of the callback should
be awaited before processing the next handler in telegram.ext.Application.
process_update(). Defaults to True.
type
The type of updates this handler should process.
Type
type
callback
The callback function for this handler.
Type
coroutine function
strict
Use type instead of isinstance. Default is False.
Type
bool
block
Determines whether the return value of the callback should be awaited before processing the next
handler in telegram.ext.Application.process_update().
Type
bool
check_update(update)
Determines whether an update should be passed to this handler’s callback.
Parameters
update (object) – Incoming update.
Returns
bool
10.2.12 Persistence
telegram.ext.BasePersistence
Attention: The interface provided by this class is intended to be accessed exclusively by Application.
Calling any of the methods below manually might interfere with the integration of persistence into
Application.
Note: You should avoid saving telegram.Bot instances. This is because if you change e.g. the bots token,
this won’t propagate to the serialized instances and may lead to exceptions.
To prevent this, the implementation may use bot to replace bot instances with a placeholder before serial-
ization and insert bot back when loading the data. Since bot will be set when the process starts, this will
be the up-to-date bot instance.
If the persistence implementation does not take care of this, you should make sure not to store any bot
instances in the data that will be persisted. E.g. in case of telegram.TelegramObject, one may call
set_bot() to ensure that shortcuts like telegram.Message.reply_text() are available.
Parameters
• store_data (PersistenceInput, optional) – Specifies which kinds of data will be
saved by this persistence instance. By default, all available kinds of data will be saved.
• update_interval (int | float, optional) – The Application will update the persis-
tence in regular intervals. This parameter specifies the time (in seconds) to wait between
two consecutive runs of updating the persistence. Defaults to 60 seconds.
New in version 20.0.
store_data
Specifies which kinds of data will be saved by this persistence instance.
Type
PersistenceInput
bot
The bot associated with the persistence.
Type
telegram.Bot
abstract async drop_chat_data(chat_id)
Will be called by the telegram.ext.Application, when using drop_chat_data().
New in version 20.0.
Parameters
chat_id (int) – The chat id to delete from the persistence.
abstract async drop_user_data(user_id)
Will be called by the telegram.ext.Application, when using drop_user_data().
New in version 20.0.
Parameters
user_id (int) – The user id to delete from the persistence.
Returns
The restored bot data.
Return type
Dict[int, dict | telegram.ext.ContextTypes.bot_data]
telegram.ext.DictPersistence
Attention: The interface provided by this class is intended to be accessed exclusively by Application.
Calling any of the methods below manually might interfere with the integration of persistence into
Application.
Note:
• Data managed by DictPersistence is in-memory only and will be lost when the bot shuts down.
This is, because DictPersistence is mainly intended as starting point for custom persistence classes
that need to JSON-serialize the stored data before writing them to file/database.
• This implementation of BasePersistence does not handle data that cannot be serialized by json.
dumps().
Changed in version 20.0: The parameters and attributes store_*_data were replaced by store_data.
Parameters
• store_data (PersistenceInput, optional) – Specifies which kinds of data will be
saved by this persistence instance. By default, all available kinds of data will be saved.
• user_data_json (str, optional) – JSON string that will be used to reconstruct
user_data on creating this persistence. Default is "".
• chat_data_json (str, optional) – JSON string that will be used to reconstruct
chat_data on creating this persistence. Default is "".
• bot_data_json (str, optional) – JSON string that will be used to reconstruct bot_data
on creating this persistence. Default is "".
• conversations_json (str, optional) – JSON string that will be used to reconstruct
conversation on creating this persistence. Default is "".
• callback_data_json (str, optional) – JSON string that will be used to reconstruct
callback_data on creating this persistence. Default is "".
New in version 13.6.
• update_interval (int | float, optional) – The Application will update the persis-
tence in regular intervals. This parameter specifies the time (in seconds) to wait between
two consecutive runs of updating the persistence. Defaults to 60 seconds.
New in version 20.0.
store_data
Specifies which kinds of data will be saved by this persistence instance.
Type
PersistenceInput
property bot_data
The bot_data as a dict.
Type
dict
property bot_data_json
The bot_data serialized as a JSON-string.
Type
str
property callback_data
The metadata on the stored callback data.
New in version 13.6.
Type
Tuple[List[Tuple[str, float, Dict[str, object]]], Dict[str, str]]
property callback_data_json
The metadata on the stored callback data as a JSON-string.
New in version 13.6.
Type
str
property chat_data
The chat_data as a dict.
Type
dict
property chat_data_json
The chat_data serialized as a JSON-string.
Type
str
property conversations
The conversations as a dict.
Type
dict
property conversations_json
The conversations serialized as a JSON-string.
Type
str
async drop_chat_data(chat_id)
Will delete the specified key from the chat_data.
New in version 20.0.
Parameters
chat_id (int) – The chat id to delete from the persistence.
async drop_user_data(user_id)
Will delete the specified key from the user_data.
New in version 20.0.
Parameters
user_id (int) – The user id to delete from the persistence.
async flush()
Does nothing.
New in version 20.0.
See also:
telegram.ext.BasePersistence.flush()
async get_bot_data()
Returns the bot_data created from the bot_data_json or an empty dict.
Returns
The restored bot data.
Return type
dict
async get_callback_data()
Returns the callback_data created from the callback_data_json or None.
New in version 13.6.
Returns
The restored metadata or None, if no data was stored.
Return type
Tuple[List[Tuple[str, float, Dict[str, object]]], Dict[str, str]]
async get_chat_data()
Returns the chat_data created from the chat_data_json or an empty dict.
Returns
The restored chat data.
Return type
dict
async get_conversations(name)
Returns the conversations created from the conversations_json or an empty dict.
Returns
The restored conversations data.
Return type
dict
async get_user_data()
Returns the user_data created from the user_data_json or an empty dict.
Returns
The restored user data.
Return type
dict
async refresh_bot_data(bot_data)
Does nothing.
New in version 13.6.
See also:
telegram.ext.BasePersistence.refresh_bot_data()
async refresh_chat_data(chat_id, chat_data)
Does nothing.
New in version 13.6.
See also:
telegram.ext.BasePersistence.refresh_chat_data()
telegram.ext.PersistenceInput
telegram.ext.PicklePersistence
Attention: The interface provided by this class is intended to be accessed exclusively by Application.
Calling any of the methods below manually might interfere with the integration of persistence into
Application.
Note: This implementation of BasePersistence uses the functionality of the pickle module to support
serialization of bot instances. Specifically any reference to bot will be replaced by a placeholder before
pickling and bot will be inserted back when loading the data.
Parameters
• filepath (str | pathlib.Path) – The filepath for storing the pickle files. When
single_file is False this will be used as a prefix.
• store_data (PersistenceInput, optional) – Specifies which kinds of data will be
saved by this persistence instance. By default, all available kinds of data will be saved.
• single_file (bool, optional) – When False will store 5 separate files of file-
name_user_data, filename_bot_data, filename_chat_data, filename_callback_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 trans-
action and on call to flush(). Default is False.
• context_types (telegram.ext.ContextTypes, optional) – Pass an instance of
telegram.ext.ContextTypes to customize the types used in the context interface.
If not passed, the defaults documented in telegram.ext.ContextTypes will be used.
New in version 13.6.
• update_interval (int | float, optional) – The Application will update the persis-
tence in regular intervals. This parameter specifies the time (in seconds) to wait between
two consecutive runs of updating the persistence. Defaults to 60 seconds.
New in version 20.0.
filepath
The filepath for storing the pickle files. When single_file is False this will be used as a prefix.
Type
str | pathlib.Path
store_data
Specifies which kinds of data will be saved by this persistence instance.
Type
PersistenceInput
single_file
Optional. When False will store 5 separate files of filename_user_data, filename_bot_data, file-
name_chat_data, filename_callback_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 happens.
When False will store data on any transaction and on call to flush(). Default is False.
Type
bool, optional
context_types
Container for the types used in the context interface.
New in version 13.6.
Type
telegram.ext.ContextTypes
async drop_chat_data(chat_id)
Will delete the specified key from the chat_data and depending on on_flush save the pickle file.
New in version 20.0.
Parameters
chat_id (int) – The chat id to delete from the persistence.
async drop_user_data(user_id)
Will delete the specified key from the user_data and depending on on_flush save the pickle file.
New in version 20.0.
Parameters
user_id (int) – The user id to delete from the persistence.
async flush()
Will save all data in memory to pickle file(s).
async get_bot_data()
Returns the bot_data from the pickle file if it exists or an empty object of type dict | telegram.ext.
ContextTypes.bot_data.
Returns
The restored bot data.
Return type
dict | telegram.ext.ContextTypes.bot_data
async get_callback_data()
Returns the callback data from the pickle file if it exists or None.
New in version 13.6.
Returns
Tuple[List[Tuple[str, float, Dict[str, object]]], Dict[str, str]] | None: The re-
stored metadata or None, if no data was stored.
async get_chat_data()
Returns the chat_data from the pickle file if it exists or an empty dict.
Returns
The restored chat data.
Return type
Dict[int, dict]
async get_conversations(name)
Returns the conversations from the pickle file if it exists or an empty dict.
Parameters
name (str) – The handlers name.
Returns
The restored conversations for the handler.
Return type
dict
async get_user_data()
Returns the user_data from the pickle file if it exists or an empty dict.
Returns
The restored user data.
Return type
Dict[int, dict]
async refresh_bot_data(bot_data)
Does nothing.
New in version 13.6.
See also:
telegram.ext.BasePersistence.refresh_bot_data()
async refresh_chat_data(chat_id, chat_data)
Does nothing.
New in version 13.6.
See also:
telegram.ext.BasePersistence.refresh_chat_data()
async refresh_user_data(user_id, user_data)
Does nothing.
New in version 13.6.
See also:
telegram.ext.BasePersistence.refresh_user_data()
async update_bot_data(data)
Will update the bot_data and depending on on_flush save the pickle file.
Parameters
data (dict | telegram.ext.ContextTypes.bot_data) – The telegram.ext.
Application.bot_data.
async update_callback_data(data)
Will update the callback_data (if changed) and depending on on_flush save the pickle file.
New in version 13.6.
Parameters
data (Tuple[List[Tuple[str, float, Dict[str, object]]], Dict[str, str]]) – The rele-
vant data to restore telegram.ext.CallbackDataCache.
async update_chat_data(chat_id, data)
Will update the chat_data and depending on on_flush save the pickle file.
Parameters
• chat_id (int) – The chat the data might have been changed for.
• data (dict) – The telegram.ext.Application.chat_data [chat_id].
async update_conversation(name, key, new_state)
Will update the conversations for the given handler and depending on on_flush save the pickle file.
Parameters
• name (str) – The handler’s name.
• key (tuple) – The key the state is changed for.
telegram.ext.CallbackDataCache
drop_data(callback_query)
Deletes the data for the specified callback query.
Note: Will not raise exceptions in case the callback data is not found in the cache. Will raise KeyError
in case the callback query can not be found in the cache.
Parameters
callback_query (telegram.CallbackQuery) – The callback query.
Raises
KeyError – If the callback query can not be found in the cache
static extract_uuids(callback_data)
Extracts the keyboard uuid and the button uuid from the given callback_data.
Parameters
callback_data (str) – The callback_data as present in the button.
Returns
Tuple of keyboard and button uuid
Return type
(str, str)
load_persistence_data(persistent_data)
Loads data into the cache.
Note: Also considers inserts data into the buttons of telegram.Message.reply_to_message and
telegram.Message.pinned_message if necessary.
Parameters
callback_query (telegram.CallbackQuery) – The callback query.
process_keyboard(reply_markup)
Registers the reply markup to the cache. If any of the buttons have callback_data, stores that data
and builds a new keyboard with the correspondingly replaced buttons. Otherwise, does nothing and
returns the original reply markup.
Parameters
reply_markup (telegram.InlineKeyboardMarkup) – The keyboard.
Returns
The keyboard to be passed to Telegram.
Return type
telegram.InlineKeyboardMarkup
process_message(message)
Replaces the data in the inline keyboard attached to the message with the cached objects, if necessary.
If the data could not be found, telegram.ext.InvalidCallbackData will be inserted.
Warning:
• Does not consider telegram.Message.reply_to_message and telegram.Message.
pinned_message. Pass them to this method separately.
• In place, i.e. the passed telegram.Message will be changed!
Parameters
message (telegram.Message) – The message.
telegram.ext.InvalidCallbackData
class telegram.ext.InvalidCallbackData(callback_data=None)
Bases: telegram.error.TelegramError
Raised when the received callback data has been tempered with or deleted from cache.
New in version 13.6.
Parameters
callback_data (int, optional) – The button data of which the callback data could not be
found.
callback_data
Optional. The button data of which the callback data could not be found.
Type
int
telegram.ext.BaseRateLimiter
class telegram.ext.BaseRateLimiter
Bases: ABC, typing.Generic
Abstract interface class that allows to rate limit the requests that python-telegram-bot sends to the Telegram
Bot API. An implementation of this class must implement all abstract methods and properties.
This class is a Generic class and accepts one type variable that specifies the type of the argument
rate_limit_args of process_request() and the methods of ExtBot.
Important: This method must only return once the result of callback is known!
If a RetryAfter error is raised, this method may try to make a new request by calling the callback
again.
Warning: This method should not handle any other exception raised by callback!
There are basically two different approaches how a rate limiter can be implemented:
1. React only if necessary. In this case, the callback is called without any precautions. If a
RetryAfter error is raised, processing requests is halted for the retry_after and finally the
callback is called again. This approach is often amendable for bots that don’t have a large user
base and/or don’t send more messages than they get updates.
2. Throttle all outgoing requests. In this case the implementation makes sure that the requests are
spread out over a longer time interval in order to stay below the rate limits. This approach is often
amendable for bots that have a large user base and/or send more messages than they get updates.
An implementation can use the information provided by data, endpoint and rate_limit_args to
handle each request differently.
Examples
• It is usually desirable to call telegram.Bot.answer_inline_query() as quickly as possible,
while delaying telegram.Bot.send_message() is acceptable.
• There are different rate limits for group chats and private chats.
• When sending broadcast messages to a large number of users, these requests can typically be
delayed for a longer time than messages that are direct replies to a user input.
Parameters
• callback (Callable[. . . , coroutine]) – The coroutine function that must be called to
make the request.
• args (Tuple[object]) – The positional arguments for the callback function.
• kwargs (Dict[str, object]) – The keyword arguments for the callback function.
• endpoint (str) – The endpoint that the request is made for, e.g. "sendMessage".
• data (Dict[str, object]) – The parameters that were passed to the method of
ExtBot. Any api_kwargs are included in this and any defaults are already ap-
plied.
Example
When calling:
await ext_bot.send_message(
chat_id=1,
text="Hello world!",
api_kwargs={"custom": "arg"}
)
telegram.ext.AIORateLimiter
Important: If you want to use this class, you must install PTB with the optional requirement
rate-limiter, i.e.
The rate limiting is applied by combining two levels of throttling and process_request() roughly boils
down to:
Here, group_id is determined by checking if there is a chat_id parameter in the data. The
overall_limiter is applied only if a chat_id argument is present at all.
Attention:
• Some bot methods accept a chat_id parameter in form of a @username for supergroups and
channels. As we can’t know which @username corresponds to which integer chat_id, these will
be treated as different groups, which may lead to exceeding the rate limit.
• As channels can’t be differentiated from supergroups by the @username or integer chat_id, this
also applies the group related rate limits to channels.
• A RetryAfter exception will halt all requests for retry_after + 0.1 seconds. This may be
stricter than necessary in some cases, e.g. the bot may hit a rate limit in one group but might still
be allowed to send messages in another group.
Note: This class is to be understood as minimal effort reference implementation. If you would like to handle
rate limiting in a more sophisticated, fine-tuned way, we welcome you to implement your own subclass of
BaseRateLimiter. Feel free to check out the source code of this class for inspiration.
Parameters
rate_limit_args (None | int) – If set, specifies the maximum number of retries to be
made in case of a RetryAfter exception. Defaults to AIORateLimiter.max_retries.
async shutdown()
Does nothing.
This module contains several constants that are relevant for working with the Bot API.
Unless noted otherwise, all constants in this module were extracted from the Telegram Bots FAQ and Telegram
Bots API.
Most of the following constants are related to specific classes or topics and are grouped into enums. If they are
related to a specific class, then they are also available as attributes of those classes.
Changed in version 20.0:
• Most of the constants in this module are grouped into enums.
telegram.constants.BOT_API_VERSION = '6.2'
Telegram Bot API version supported by this version of python-telegram-bot. Also available as telegram.
__bot_api_version__.
New in version 13.4.
Type
str
telegram.constants.BOT_API_VERSION_INFO = BotAPIVersion(major=6, minor=2)
The components can also be accessed by name, so BOT_API_VERSION_INFO[0] is equivalent to
BOT_API_VERSION_INFO.major and so on. Also available as telegram.__bot_api_version_info__.
New in version 20.0.
class telegram.constants.BotCommandScopeType(value)
Bases: str, enum.Enum
This enum contains the available types of telegram.BotCommandScope. The enum members of this enu-
meration are instances of str and can be treated as such.
New in version 20.0.
ALL_CHAT_ADMINISTRATORS = 'all_chat_administrators'
The type of telegram.BotCommandScopeAllChatAdministrators.
Type
str
ALL_GROUP_CHATS = 'all_group_chats'
The type of telegram.BotCommandScopeAllGroupChats.
Type
str
ALL_PRIVATE_CHATS = 'all_private_chats'
The type of telegram.BotCommandScopeAllPrivateChats.
Type
str
CHAT = 'chat'
The type of telegram.BotCommandScopeChat.
Type
str
CHAT_ADMINISTRATORS = 'chat_administrators'
The type of telegram.BotCommandScopeChatAdministrators.
Type
str
CHAT_MEMBER = 'chat_member'
The type of telegram.BotCommandScopeChatMember.
Type
str
DEFAULT = 'default'
The type of telegram.BotCommandScopeDefault.
Type
str
class telegram.constants.CallbackQueryLimit(value)
Bases: enum.IntEnum
This enum contains limitations for telegram.CallbackQuery/ telegram.Bot.
answer_callback_query(). The enum members of this enumeration are instances of int and can
be treated as such.
New in version 20.0.
ANSWER_CALLBACK_QUERY_TEXT_LENGTH = 200
Maximum number of characters for the text parameter of telegram.Bot.
answer_callback_query().
Type
int
class telegram.constants.ChatAction(value)
Bases: str, enum.Enum
This enum contains the available chat actions for telegram.Bot.send_chat_action(). The enum mem-
bers of this enumeration are instances of str and can be treated as such.
New in version 20.0.
CHOOSE_STICKER = 'choose_sticker'
Chat action indicating that the bot is selecting a sticker.
Type
str
FIND_LOCATION = 'find_location'
Chat action indicating that the bot is selecting a location.
Type
str
RECORD_VIDEO = 'record_video'
Chat action indicating that the bot is recording a video.
Type
str
RECORD_VIDEO_NOTE = 'record_video_note'
Chat action indicating that the bot is recording a video note.
Type
str
RECORD_VOICE = 'record_voice'
Chat action indicating that the bot is recording a voice message.
Type
str
TYPING = 'typing'
A chat indicating the bot is typing.
Type
str
UPLOAD_DOCUMENT = 'upload_document'
Chat action indicating that the bot is uploading a document.
Type
str
UPLOAD_PHOTO = 'upload_photo'
Chat action indicating that the bot is uploading a photo.
Type
str
UPLOAD_VIDEO = 'upload_video'
Chat action indicating that the bot is uploading a video.
Type
str
UPLOAD_VIDEO_NOTE = 'upload_video_note'
Chat action indicating that the bot is uploading a video note.
Type
str
UPLOAD_VOICE = 'upload_voice'
Chat action indicating that the bot is uploading a voice message.
Type
str
class telegram.constants.ChatID(value)
Bases: enum.IntEnum
This enum contains some special chat IDs. The enum members of this enumeration are instances of int and
can be treated as such.
New in version 20.0.
ANONYMOUS_ADMIN = 1087968824
User ID in groups for messages sent by anonymous admins.
Note: telegram.Message.from_user will contain this ID for backwards compatibility only. It’s
recommended to use telegram.Message.sender_chat instead.
Type
int
FAKE_CHANNEL = 136817688
User ID in groups when message is sent on behalf of a channel.
Note:
• telegram.Message.from_user will contain this ID for backwards compatibility only. It’s rec-
ommended to use telegram.Message.sender_chat instead.
• This value is undocumented and might be changed by Telegram.
Type
int
SERVICE_CHAT = 777000
Telegram service chat, that also acts as sender of channel posts forwarded to discussion groups.
Note: telegram.Message.from_user will contain this ID for backwards compatibility only. It’s
recommended to use telegram.Message.sender_chat instead.
Type
int
class telegram.constants.ChatInviteLinkLimit(value)
Bases: enum.IntEnum
This enum contains limitations for telegram.ChatInviteLink/ telegram.Bot.
create_chat_invite_link()/telegram.Bot.edit_chat_invite_link(). The enum members
of this enumeration are instances of int and can be treated as such.
New in version 20.0.
MEMBER_LIMIT = 99999
Maximum value allowed for the member_limit parameter of telegram.Bot.
create_chat_invite_link() and telegram.Bot.edit_chat_invite_link().
Type
int
NAME_LENGTH = 32
Maximum number of characters allowed for the name parameter of telegram.Bot.
create_chat_invite_link() and telegram.Bot.edit_chat_invite_link().
Type
int
class telegram.constants.ChatMemberStatus(value)
Bases: str, enum.Enum
This enum contains the available states for telegram.ChatMember. The enum members of this enumeration
are instances of str and can be treated as such.
New in version 20.0.
ADMINISTRATOR = 'administrator'
A telegram.ChatMember who is administrator of the chat.
Type
str
BANNED = 'kicked'
A telegram.ChatMember who was banned in the chat.
Type
str
LEFT = 'left'
A telegram.ChatMember who has left the chat.
Type
str
MEMBER = 'member'
A telegram.ChatMember who is a member of the chat.
Type
str
OWNER = 'creator'
A telegram.ChatMember who is the owner of the chat.
Type
str
RESTRICTED = 'restricted'
A telegram.ChatMember who was restricted in this chat.
Type
str
class telegram.constants.ChatType(value)
Bases: str, enum.Enum
This enum contains the available types of telegram.Chat. The enum members of this enumeration are
instances of str and can be treated as such.
New in version 20.0.
CHANNEL = 'channel'
A telegram.Chat that is a channel.
Type
str
GROUP = 'group'
A telegram.Chat that is a group.
Type
str
PRIVATE = 'private'
A telegram.Chat that is private.
Type
str
SENDER = 'sender'
A telegram.Chat that represents the chat of a telegram.User sending an telegram.
InlineQuery.
Type
str
SUPERGROUP = 'supergroup'
A telegram.Chat that is a supergroup.
Type
str
class telegram.constants.CustomEmojiStickerLimit(value)
Bases: enum.IntEnum
This enum contains limitations for telegram.Bot.get_custom_emoji_stickers(). The enum mem-
bers of this enumeration are instances of int and can be treated as such.
New in version 20.0.
CUSTOM_EMOJI_IDENTIFIER_LIMIT = 200
Maximum amount of custom emoji identifiers which can be specified for the custom_emoji_ids
parameter of telegram.Bot.get_custom_emoji_stickers().
Type
int
class telegram.constants.DiceEmoji(value)
Bases: str, enum.Enum
This enum contains the available emoji for telegram.Dice/ telegram.Bot.send_dice(). The enum
members of this enumeration are instances of str and can be treated as such.
New in version 20.0.
BASKETBALL = ''
A telegram.Dice with the emoji .
Type
str
BOWLING = ''
A telegram.Dice with the emoji .
Type
str
DARTS = ''
A telegram.Dice with the emoji .
Type
str
DICE = ''
A telegram.Dice with the emoji .
Type
str
FOOTBALL = ''
A telegram.Dice with the emoji .
Type
str
SLOT_MACHINE = ''
A telegram.Dice with the emoji .
Type
str
class telegram.constants.FileSizeLimit(value)
Bases: enum.IntEnum
This enum contains limitations regarding the upload and download of files. The enum members of this
enumeration are instances of int and can be treated as such.
Type
int
TOTAL_BUTTON_NUMBER = 100
Maximum number of buttons that can be attached to a message.
Type
int
class telegram.constants.InlineQueryLimit(value)
Bases: enum.IntEnum
This enum contains limitations for telegram.InlineQuery/ telegram.Bot.answer_inline_query().
The enum members of this enumeration are instances of int and can be treated as such.
New in version 20.0.
RESULTS = 50
Maximum number of results that can be passed to telegram.Bot.answer_inline_query().
Type
int
SWITCH_PM_TEXT_LENGTH = 64
Maximum number of characters for the switch_pm_text parameter of telegram.Bot.
answer_inline_query().
Type
int
class telegram.constants.InlineQueryResultType(value)
Bases: str, enum.Enum
This enum contains the available types of telegram.InlineQueryResult. The enum members of this
enumeration are instances of str and can be treated as such.
New in version 20.0.
ARTICLE = 'article'
Type of telegram.InlineQueryResultArticle.
Type
str
AUDIO = 'audio'
Type of telegram.InlineQueryResultAudio and telegram.
InlineQueryResultCachedAudio.
Type
str
CONTACT = 'contact'
Type of telegram.InlineQueryResultContact.
Type
str
DOCUMENT = 'document'
Type of telegram.InlineQueryResultDocument and telegram.
InlineQueryResultCachedDocument.
Type
str
GAME = 'game'
Type of telegram.InlineQueryResultGame.
Type
str
GIF = 'gif'
Type of telegram.InlineQueryResultGif and telegram.InlineQueryResultCachedGif .
Type
str
LOCATION = 'location'
Type of telegram.InlineQueryResultLocation.
Type
str
MPEG4GIF = 'mpeg4_gif'
Type of telegram.InlineQueryResultMpeg4Gif and telegram.
InlineQueryResultCachedMpeg4Gif .
Type
str
PHOTO = 'photo'
Type of telegram.InlineQueryResultPhoto and telegram.
InlineQueryResultCachedPhoto.
Type
str
STICKER = 'sticker'
Type of and telegram.InlineQueryResultCachedSticker.
Type
str
VENUE = 'venue'
Type of telegram.InlineQueryResultVenue.
Type
str
VIDEO = 'video'
Type of telegram.InlineQueryResultVideo and telegram.
InlineQueryResultCachedVideo.
Type
str
VOICE = 'voice'
Type of telegram.InlineQueryResultVoice and telegram.
InlineQueryResultCachedVoice.
Type
str
class telegram.constants.InputMediaType(value)
Bases: str, enum.Enum
This enum contains the available types of telegram.InputMedia. The enum members of this enumeration
are instances of str and can be treated as such.
New in version 20.0.
ANIMATION = 'animation'
Type of telegram.InputMediaAnimation.
Type
str
AUDIO = 'audio'
Type of telegram.InputMediaAudio.
Type
str
DOCUMENT = 'document'
Type of telegram.InputMediaDocument.
Type
str
PHOTO = 'photo'
Type of telegram.InputMediaPhoto.
Type
str
VIDEO = 'video'
Type of telegram.InputMediaVideo.
Type
str
class telegram.constants.InvoiceLimit(value)
Bases: enum.IntEnum
This enum contains limitations for telegram.Bot.create_invoice_link(). The enum members of this
enumeration are instances of int and can be treated as such.
New in version 20.0.
MAX_DESCRIPTION_LENGTH = 255
Maximum number of characters of the invoice description.
Type
int
MAX_PAYLOAD_LENGTH = 128
Maximum amount of bytes for the internal payload.
Type
int
MAX_TITLE_LENGTH = 32
Maximum number of characters of the invoice title.
Type
int
MIN_DESCRIPTION_LENGTH = 1
Minimum number of characters of the invoice description.
Type
int
MIN_PAYLOAD_LENGTH = 1
Minimum amount of bytes for the internal payload.
Type
int
MIN_TITLE_LENGTH = 1
Minimum number of characters of the invoice title.
Type
int
class telegram.constants.LocationLimit(value)
Bases: enum.IntEnum
This enum contains limitations for telegram.Location/ telegram.Bot.send_location(). The enum
members of this enumeration are instances of int and can be treated as such.
New in version 20.0.
HEADING = 360
Maximum value allowed for the direction in which the user is moving, in degrees.
Type
int
HORIZONTAL_ACCURACY = 1500
Maximum radius of uncertainty for the location, measured in meters.
Type
int
PROXIMITY_ALERT_RADIUS = 100000
Maximum distance for proximity alerts about approaching another chat member, in meters.
Type
int
class telegram.constants.MaskPosition(value)
Bases: str, enum.Enum
This enum contains the available positions for telegram.MaskPosition. The enum members of this enu-
meration are instances of str and can be treated as such.
New in version 20.0.
CHIN = 'chin'
Mask position for a sticker on the chin.
Type
str
EYES = 'eyes'
Mask position for a sticker on the eyes.
Type
str
FOREHEAD = 'forehead'
Mask position for a sticker on the forehead.
Type
str
MOUTH = 'mouth'
Mask position for a sticker on the mouth.
Type
str
class telegram.constants.MenuButtonType(value)
Bases: str, enum.Enum
This enum contains the available types of telegram.MenuButton. The enum members of this enumeration
are instances of str and can be treated as such.
New in version 20.0.
COMMANDS = 'commands'
The type of telegram.MenuButtonCommands.
Type
str
DEFAULT = 'default'
The type of telegram.MenuButtonDefault.
Type
str
WEB_APP = 'web_app'
The type of telegram.MenuButtonWebApp.
Type
str
class telegram.constants.MessageAttachmentType(value)
Bases: str, enum.Enum
This enum contains the available types of telegram.Message that can be seen as attachment. The enum
members of this enumeration are instances of str and can be treated as such.
New in version 20.0.
ANIMATION = 'animation'
Messages with telegram.Message.animation.
Type
str
AUDIO = 'audio'
Messages with telegram.Message.audio.
Type
str
CONTACT = 'contact'
Messages with telegram.Message.contact.
Type
str
DICE = 'dice'
Messages with telegram.Message.dice.
Type
str
DOCUMENT = 'document'
Messages with telegram.Message.document.
Type
str
GAME = 'game'
Messages with telegram.Message.game.
Type
str
INVOICE = 'invoice'
Messages with telegram.Message.invoice.
Type
str
LOCATION = 'location'
Messages with telegram.Message.location.
Type
str
PASSPORT_DATA = 'passport_data'
Messages with telegram.Message.passport_data.
Type
str
PHOTO = 'photo'
Messages with telegram.Message.photo.
Type
str
POLL = 'poll'
Messages with telegram.Message.poll.
Type
str
STICKER = 'sticker'
Messages with telegram.Message.sticker.
Type
str
SUCCESSFUL_PAYMENT = 'successful_payment'
Messages with telegram.Message.successful_payment.
Type
str
VENUE = 'venue'
Messages with telegram.Message.venue.
Type
str
VIDEO = 'video'
Messages with telegram.Message.video.
Type
str
VIDEO_NOTE = 'video_note'
Messages with telegram.Message.video_note.
Type
str
VOICE = 'voice'
Messages with telegram.Message.voice.
Type
str
class telegram.constants.MessageEntityType(value)
Bases: str, enum.Enum
This enum contains the available types of telegram.MessageEntity. The enum members of this enumer-
ation are instances of str and can be treated as such.
New in version 20.0.
BOLD = 'bold'
Message entities representing bold text.
Type
str
BOT_COMMAND = 'bot_command'
Message entities representing a bot command.
Type
str
CASHTAG = 'cashtag'
Message entities representing a cashtag.
Type
str
CODE = 'code'
Message entities representing monowidth string.
Type
str
CUSTOM_EMOJI = 'custom_emoji'
Message entities representing inline custom emoji stickers.
New in version 20.0.
Type
str
EMAIL = 'email'
Message entities representing a email.
Type
str
HASHTAG = 'hashtag'
Message entities representing a hashtag.
Type
str
ITALIC = 'italic'
Message entities representing italic text.
Type
str
MENTION = 'mention'
Message entities representing a mention.
Type
str
PHONE_NUMBER = 'phone_number'
Message entities representing a phone number.
Type
str
PRE = 'pre'
Message entities representing monowidth block.
Type
str
SPOILER = 'spoiler'
Message entities representing spoiler text.
Type
str
STRIKETHROUGH = 'strikethrough'
Message entities representing strikethrough text.
Type
str
TEXT_LINK = 'text_link'
Message entities representing clickable text URLs.
Type
str
TEXT_MENTION = 'text_mention'
Message entities representing text mention for users without usernames.
Type
str
UNDERLINE = 'underline'
Message entities representing underline text.
Type
str
URL = 'url'
Message entities representing a url.
Type
str
class telegram.constants.MessageLimit(value)
Bases: enum.IntEnum
This enum contains limitations for telegram.Message/ telegram.Bot.send_message() & friends. The
enum members of this enumeration are instances of int and can be treated as such.
New in version 20.0.
CAPTION_LENGTH = 1024
Maximum number of characters for a message caption.
Type
int
MESSAGE_ENTITIES = 100
Maximum number of entities that can be displayed in a message. Further entities will simply be ignored
by Telegram.
Type
int
TEXT_LENGTH = 4096
Maximum number of characters for a text message.
Type
int
class telegram.constants.MessageType(value)
Bases: str, enum.Enum
This enum contains the available types of telegram.Message that can be seen as attachment. The enum
members of this enumeration are instances of str and can be treated as such.
New in version 20.0.
ANIMATION = 'animation'
Messages with telegram.Message.animation.
Type
str
AUDIO = 'audio'
Messages with telegram.Message.audio.
Type
str
CHANNEL_CHAT_CREATED = 'channel_chat_created'
Messages with telegram.Message.channel_chat_created.
Type
str
CONTACT = 'contact'
Messages with telegram.Message.contact.
Type
str
DELETE_CHAT_PHOTO = 'delete_chat_photo'
Messages with telegram.Message.delete_chat_photo.
Type
str
DICE = 'dice'
Messages with telegram.Message.dice.
Type
str
DOCUMENT = 'document'
Messages with telegram.Message.document.
Type
str
GAME = 'game'
Messages with telegram.Message.game.
Type
str
GROUP_CHAT_CREATED = 'group_chat_created'
Messages with telegram.Message.group_chat_created.
Type
str
INVOICE = 'invoice'
Messages with telegram.Message.invoice.
Type
str
LEFT_CHAT_MEMBER = 'left_chat_member'
Messages with telegram.Message.left_chat_member.
Type
str
LOCATION = 'location'
Messages with telegram.Message.location.
Type
str
MESSAGE_AUTO_DELETE_TIMER_CHANGED = 'message_auto_delete_timer_changed'
Messages with telegram.Message.message_auto_delete_timer_changed.
Type
str
MIGRATE_FROM_CHAT_ID = 'migrate_from_chat_id'
Messages with telegram.Message.migrate_from_chat_id.
Type
str
MIGRATE_TO_CHAT_ID = 'migrate_to_chat_id'
Messages with telegram.Message.migrate_to_chat_id.
Type
str
NEW_CHAT_MEMBERS = 'new_chat_members'
Messages with telegram.Message.new_chat_members.
Type
str
NEW_CHAT_PHOTO = 'new_chat_photo'
Messages with telegram.Message.new_chat_photo.
Type
str
NEW_CHAT_TITLE = 'new_chat_title'
Messages with telegram.Message.new_chat_title.
Type
str
PASSPORT_DATA = 'passport_data'
Messages with telegram.Message.passport_data.
Type
str
PHOTO = 'photo'
Messages with telegram.Message.photo.
Type
str
PINNED_MESSAGE = 'pinned_message'
Messages with telegram.Message.pinned_message.
Type
str
POLL = 'poll'
Messages with telegram.Message.poll.
Type
str
PROXIMITY_ALERT_TRIGGERED = 'proximity_alert_triggered'
Messages with telegram.Message.proximity_alert_triggered.
Type
str
STICKER = 'sticker'
Messages with telegram.Message.sticker.
Type
str
SUCCESSFUL_PAYMENT = 'successful_payment'
Messages with telegram.Message.successful_payment.
Type
str
SUPERGROUP_CHAT_CREATED = 'supergroup_chat_created'
Messages with telegram.Message.supergroup_chat_created.
Type
str
TEXT = 'text'
Messages with telegram.Message.text.
Type
str
VENUE = 'venue'
Messages with telegram.Message.venue.
Type
str
VIDEO = 'video'
Messages with telegram.Message.video.
Type
str
VIDEO_CHAT_ENDED = 'video_chat_ended'
Messages with telegram.Message.video_chat_ended.
Type
str
VIDEO_CHAT_PARTICIPANTS_INVITED = 'video_chat_participants_invited'
Messages with telegram.Message.video_chat_participants_invited.
Type
str
VIDEO_CHAT_SCHEDULED = 'video_chat_scheduled'
Messages with telegram.Message.video_chat_scheduled.
Type
str
VIDEO_CHAT_STARTED = 'video_chat_started'
Messages with telegram.Message.video_chat_started.
Type
str
VIDEO_NOTE = 'video_note'
Messages with telegram.Message.video_note.
Type
str
VOICE = 'voice'
Messages with telegram.Message.voice.
Type
str
class telegram.constants.ParseMode(value)
Bases: str, enum.Enum
This enum contains the available parse modes. The enum members of this enumeration are instances of str
and can be treated as such.
New in version 20.0.
HTML = 'HTML'
HTML parse mode.
Type
str
MARKDOWN = 'Markdown'
Markdown parse mode.
Note: MARKDOWN is a legacy mode, retained by Telegram for backward compatibility. You should use
MARKDOWN_V2 instead.
Type
str
MARKDOWN_V2 = 'MarkdownV2'
Markdown parse mode version 2.
Type
str
class telegram.constants.PollLimit(value)
Bases: enum.IntEnum
This enum contains limitations for telegram.Poll/ telegram.Bot.send_poll(). The enum members
of this enumeration are instances of int and can be treated as such.
New in version 20.0.
OPTION_LENGTH = 100
Maximum number of characters for each option for the poll.
Type
str
OPTION_NUMBER = 10
Maximum number of available options for the poll.
Type
str
QUESTION_LENGTH = 300
Maximum number of characters of the polls question.
Type
str
class telegram.constants.PollType(value)
Bases: str, enum.Enum
This enum contains the available types for telegram.Poll/ telegram.Bot.send_poll(). The enum
members of this enumeration are instances of str and can be treated as such.
New in version 20.0.
QUIZ = 'quiz'
quiz polls.
Type
str
REGULAR = 'regular'
regular polls.
Type
str
telegram.constants.SUPPORTED_WEBHOOK_PORTS = [443, 80, 88, 8443]
Ports supported by telegram.Bot.set_webhook.url.
Type
List[int]
class telegram.constants.StickerType(value)
Bases: str, enum.Enum
This enum contains the available types of telegram.Sticker. The enum members of this enumeration are
instances of str and can be treated as such.
New in version 20.0.
CUSTOM_EMOJI = 'custom_emoji'
Custom emoji sticker.
Type
str
MASK = 'mask'
Mask sticker.
Type
str
REGULAR = 'regular'
Regular sticker.
Type
str
class telegram.constants.UpdateType(value)
Bases: str, enum.Enum
This enum contains the available types of telegram.Update. The enum members of this enumeration are
instances of str and can be treated as such.
New in version 20.0.
CALLBACK_QUERY = 'callback_query'
Updates with telegram.Update.callback_query.
Type
str
CHANNEL_POST = 'channel_post'
Updates with telegram.Update.channel_post.
Type
str
CHAT_JOIN_REQUEST = 'chat_join_request'
Updates with telegram.Update.chat_join_request.
Type
str
CHAT_MEMBER = 'chat_member'
Updates with telegram.Update.chat_member.
Type
str
CHOSEN_INLINE_RESULT = 'chosen_inline_result'
Updates with telegram.Update.chosen_inline_result.
Type
str
EDITED_CHANNEL_POST = 'edited_channel_post'
Updates with telegram.Update.edited_channel_post.
Type
str
EDITED_MESSAGE = 'edited_message'
Updates with telegram.Update.edited_message.
Type
str
INLINE_QUERY = 'inline_query'
Updates with telegram.Update.inline_query.
Type
str
MESSAGE = 'message'
Updates with telegram.Update.message.
Type
str
MY_CHAT_MEMBER = 'my_chat_member'
Updates with telegram.Update.my_chat_member.
Type
str
POLL = 'poll'
Updates with telegram.Update.poll.
Type
str
POLL_ANSWER = 'poll_answer'
Updates with telegram.Update.poll_answer.
Type
str
PRE_CHECKOUT_QUERY = 'pre_checkout_query'
Updates with telegram.Update.pre_checkout_query.
Type
str
SHIPPING_QUERY = 'shipping_query'
Updates with telegram.Update.shipping_query.
Type
str
class telegram.constants.WebhookLimit(value)
Bases: enum.IntEnum
This enum contains limitations for telegram.Bot.set_webhook.secret_token. The enum members of
this enumeration are instances of int and can be treated as such.
New in version 20.0.
MAX_SECRET_TOKEN_LENGTH = 256
Maximum length of the secret token.
Type
int
MIN_SECRET_TOKEN_LENGTH = 1
Minimum length of the secret token.
Type
int
retry_after
Time in seconds, after which the bot can retry the request.
Type
int
exception telegram.error.TelegramError(message)
Bases: Exception
Base class for Telegram errors.
exception telegram.error.TimedOut(message=None)
Bases: telegram.error.NetworkError
Raised when a request took too long to finish.
Parameters
message (str, optional) – Any additional information about the exception.
New in version 20.0.
Examples
create_deep_linked_url(bot.get_me().username, "some-params")
See also:
Deeplinking Example
Parameters
• bot_username (str) – The username to link to
• payload (str, optional) – Parameters to encode in the created URL
• group (bool, optional) – If True the user is prompted to select a group to add the bot
to. If False, opens a one-on-one conversation with the bot. Defaults to False.
Returns
An URL to start the bot with specific parameters
Return type
str
telegram.helpers.effective_message_type(entity)
Extracts the type of message as a string identifier from a telegram.Message or a telegram.Update.
Parameters
entity (telegram.Update | telegram.Message) – The update or message to extract
from.
Returns
One of telegram.constants.MessageType if the entity
contains a message that matches one of those types. None otherwise.
Return type
str | None
telegram.helpers.escape_markdown(text, version=1, entity_type=None)
Helper function to escape telegram markup symbols.
Parameters
• text (str) – The text.
• version (int | str) – Use to specify the version of telegrams Markdown. Either 1 or
2. Defaults to 1.
• entity_type (str, optional) – For the entity types 'pre', 'code' and the link part of
'text_link', only certain characters need to be escaped in 'MarkdownV2'. See the offi-
cial API documentation for details. Only valid in combination with version=2, will be
ignored else.
telegram.helpers.mention_html(user_id, name)
Parameters
• user_id (int) – The user’s id which you want to mention.
• name (str) – The name the mention is showing.
Returns
The inline mention for the user as HTML.
Return type
str
telegram.helpers.mention_markdown(user_id, name, version=1)
Parameters
• user_id (int) – The user’s id which you want to mention.
• name (str) – The name the mention is showing.
• version (int | str) – Use to specify the version of Telegram’s Markdown. Either 1 or
2. Defaults to 1.
Returns
The inline mention for the user as Markdown.
Return type
str
telegram.request.BaseRequest
class telegram.request.BaseRequest
Bases: AbstractAsyncContextManager, ABC
Abstract interface class that allows python-telegram-bot to make requests to the Bot API. Can be imple-
mented via different asyncio HTTP libraries. An implementation of this class must implement all abstract
methods and properties.
Instances of this class can be used as asyncio context managers, where
is roughly equivalent to
try:
await request_object.initialize()
# code
finally:
await request_object.shutdown()
Tip: JSON encoding and decoding is done with the standard library’s json by default. To use a custom
library for this, you can override parse_json_payload() and implement custom logic to encode the keys
of telegram.request.RequestData.parameters.
Example
When calling request.post(url), request should use the default timeouts set on initializa-
tion. When calling request.post(url, connect_timeout=5, read_timeout=None), request
should use 5 for the connect timeout and None for the read timeout.
Use if parameter is (not) BaseRequest.DEFAULT_NONE: to check if the parameter was set.
Type
object
Warning: This method will be called by post() and retrieve(). It should not be called man-
ually.
Parameters
• url (str) – The URL to request.
• method (str) – HTTP method (i.e. 'POST', 'GET', etc.).
• request_data (telegram.request.RequestData, optional) – An object contain-
ing information about parameters and files to upload for the request.
• read_timeout (float | None, optional) – If passed, specifies the maximum amount
of time (in seconds) to wait for a response from Telegram’s server instead of the time
specified during creating of this object. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – If passed, specifies the maximum amount
of time (in seconds) to wait for a write operation to complete (in terms of a network
socket; i.e. POSTing a request or uploading a file) instead of the time specified during
creating of this object. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – If passed, specifies the maximum
amount of time (in seconds) to wait for a connection attempt to a server to succeed
instead of the time specified during creating of this object. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – If passed, specifies the maximum amount
of time (in seconds) to wait for a connection to become available instead of the time
specified during creating of this object. Defaults to DEFAULT_NONE.
Returns
The HTTP return code & the payload part of the server response.
Return type
Tuple[int, bytes]
Tip: By default, this method uses the standard library’s json.loads() and errors="replace" in
bytes.decode(). You can override it to customize either of these behaviors.
Parameters
payload (bytes) – The UTF-8 encoded JSON payload as returned by Telegram.
Returns
A JSON parsed as Python dict with results.
Return type
dict
Raises
TelegramError – If loading the JSON data failed
Warning: This method will be called by the methods of telegram.Bot and should not be called
manually.
Parameters
• url (str) – The URL to request.
• request_data (telegram.request.RequestData, optional) – An object contain-
ing information about parameters and files to upload for the request.
• read_timeout (float | None, optional) – If passed, specifies the maximum amount
of time (in seconds) to wait for a response from Telegram’s server instead of the time
specified during creating of this object. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – If passed, specifies the maximum amount
of time (in seconds) to wait for a write operation to complete (in terms of a network
socket; i.e. POSTing a request or uploading a file) instead of the time specified during
creating of this object. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – If passed, specifies the maximum
amount of time (in seconds) to wait for a connection attempt to a server to succeed
instead of the time specified during creating of this object. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – If passed, specifies the maximum amount
of time (in seconds) to wait for a connection to become available instead of the time
specified during creating of this object. Defaults to DEFAULT_NONE.
Returns
The JSON response of the Bot API.
Return type
Dict[str, . . . ]
Warning: This method will be called by the methods of telegram.Bot and should not be called
manually.
Parameters
• url (str) – The web location we want to retrieve.
• read_timeout (float | None, optional) – If passed, specifies the maximum amount
of time (in seconds) to wait for a response from Telegram’s server instead of the time
specified during creating of this object. Defaults to DEFAULT_NONE.
• write_timeout (float | None, optional) – If passed, specifies the maximum amount
of time (in seconds) to wait for a write operation to complete (in terms of a network
socket; i.e. POSTing a request or uploading a file) instead of the time specified during
creating of this object. Defaults to DEFAULT_NONE.
• connect_timeout (float | None, optional) – If passed, specifies the maximum
amount of time (in seconds) to wait for a connection attempt to a server to succeed
instead of the time specified during creating of this object. Defaults to DEFAULT_NONE.
• pool_timeout (float | None, optional) – If passed, specifies the maximum amount
of time (in seconds) to wait for a connection to become available instead of the time
specified during creating of this object. Defaults to DEFAULT_NONE.
Returns
The files contents.
Return type
bytes
telegram.request.RequestData
class telegram.request.RequestData(parameters=None)
Bases: object
Instances of this class collect the data needed for one request to the Bot API, including all parameters and
files to be sent along with the request.
New in version 20.0.
Warning: How exactly instances of this will are created should be considered an implementation detail
and not part of PTBs public API. Users should exclusively rely on the documented attributes, properties
and methods.
contains_files
Whether this object contains files to be uploaded via multipart/form-data.
Type
bool
property json_parameters
Gives the parameters as mapping of parameter name to the respective JSON encoded value.
Tip: By default, this property uses the standard library’s json.dumps(). To use a custom library for
JSON encoding, you can directly encode the keys of parameters - note that string valued keys should
not be JSON encoded.
property json_payload
The parameters as UTF-8 encoded JSON payload.
Tip: By default, this property uses the standard library’s json.dumps(). To use a custom library for
JSON encoding, you can directly encode the keys of parameters - note that string valued keys should
not be JSON encoded.
property multipart_data
Gives the files contained in this object as mapping of part name to encoded content.
property parameters
Gives the parameters as mapping of parameter name to the parameter value, which can be a single object
of type int, float, str or bool or any (possibly nested) composition of lists, tuples and dictionaries,
where each entry, key and value is of one of the mentioned types.
parametrized_url(url, encode_kwargs=None)
Shortcut for attaching the return value of url_encoded_parameters() to the url.
Parameters
• url (str) – The URL the parameters will be attached to.
telegram.request.HTTPXRequest
Note: Independent of the value, one additional connection will be reserved for
telegram.Bot.get_updates().
• proxy_url (str, optional) – The URL to the proxy server. For example 'http://
127.0.0.1:3128' or 'socks5://127.0.0.1:3128'. Defaults to None.
Note:
– The proxy URL can also be set via the environment variables HTTPS_PROXY or
ALL_PROXY. See the docs of httpx for more info.
– For Socks5 support, additional dependencies are required. Make sure to install PTB
via pip install python-telegram-bot[socks] in this case.
– Socks5 proxies can not be set via environment variables.
This module contains classes used for warnings issued by this library.
New in version 20.0.
exception telegram.warnings.PTBDeprecationWarning
Bases: telegram.warnings.PTBUserWarning, DeprecationWarning
Custom warning class for deprecations in this library.
Changed in version 20.0: Renamed TelegramDeprecationWarning to PTBDeprecationWarning.
exception telegram.warnings.PTBRuntimeWarning
Bases: telegram.warnings.PTBUserWarning, RuntimeWarning
Custom runtime warning class used for warnings in this library.
New in version 20.0.
exception telegram.warnings.PTBUserWarning
Bases: UserWarning
Custom user warning class used for warnings in this library.
New in version 20.0.
10.4 Examples
In this section we display small examples to show what a bot written with python-telegram-bot looks like.
Some bots focus on one specific aspect of the Telegram Bot API while others focus on one of the mechanics of this
library. Except for the rawapibot.py example, they all use the high-level framework this library provides with the
telegram.ext submodule.
All examples are licensed under the CC0 License and are therefore fully dedicated to the public domain. You can
use them as the base for your own bots without worrying about copyrights.
Do note that we ignore one pythonic convention. Best practice would dictate, in many handler callbacks function
signatures, to replace the argument context with an underscore, since context is an unused local variable in
those callbacks. However, since these are examples and not having a name for that argument confuses beginners,
we decided to have it present.
10.4.1 echobot.py
This is probably the base for most of the bots made with python-telegram-bot. It simply replies to each text
message with a message that contains the same text.
10.4.2 timerbot.py
This bot uses the telegram.ext.JobQueue class to send timed messages. The user sets a timer by using /set
command with a specific time, for example /set 30. The bot then sets up a job to send a message to that user
after 30 seconds. The user can also cancel the timer by sending /unset. To learn more about the JobQueue, read
this wiki article.
10.4.3 conversationbot.py
A common task for a bot is to ask information from the user. In v5.0 of this library, we introduced the telegram.
ext.ConversationHandler for that exact purpose. This example uses it to retrieve user-information in a
conversation-like style. To get a better understanding, take a look at the state diagram.
10.4.4 conversationbot2.py
A more complex example of a bot that uses the ConversationHandler. It is also more confusing. Good thing
there is a fancy state diagram. for this one, too!
10.4.5 nestedconversationbot.py
A even more complex example of a bot that uses the nested ConversationHandlers. While it’s certainly not that
complex that you couldn’t built it without nested ConversationHanldlers, it gives a good impression on how to
work with them. Of course, there is a fancy state diagram for this example, too!
10.4.6 persistentconversationbot.py
A basic example of a bot store conversation state and user_data over multiple restarts.
10.4.7 inlinekeyboard.py
This example sheds some light on inline keyboards, callback queries and message editing. A wiki site explaining
this examples lives here.
10.4.8 inlinekeyboard2.py
A more complex example about inline keyboards, callback queries and message editing. This example showcases
how an interactive menu could be build using inline keyboards.
10.4.9 deeplinking.py
10.4.10 inlinebot.py
A basic example of an inline bot. Don’t forget to enable inline mode with @BotFather.
10.4.11 pollbot.py
This example sheds some light on polls, poll answers and the corresponding handlers.
10.4.12 passportbot.py
A basic example of a bot that can accept passports. Use in combination with the HTML page. Don’t forget to
enable and configure payments with @BotFather. Check out this guide on Telegram passports in PTB.
10.4.13 paymentbot.py
A basic example of a bot that can accept payments. Don’t forget to enable and configure payments with @BotFather.
10.4.14 errorhandlerbot.py
10.4.15 chatmemberbot.py
10.4.16 webappbot.py
A basic example of how Telegram WebApps can be used. Use in combination with the HTML page. For your
convenience, this file is hosted by the PTB team such that you don’t need to host it yourself. Uses the iro.js
JavaScript library to showcase a user interface that is hard to achieve with native Telegram functionality.
10.4.17 contexttypesbot.py
This example showcases how telegram.ext.ContextTypes can be used to customize the context argument
of handler and job callbacks.
10.4.18 customwebhookbot.py
This example showcases how a custom webhook setup can be used in combination with telegram.ext.
Application.
10.4.19 arbitrarycallbackdatabot.py
This example showcases how PTBs “arbitrary callback data” feature can be used.
The rawapibot.py example example uses only the pure, “bare-metal” API wrapper.
arbitrarycallbackdatabot.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
5 """This example showcases how PTBs "arbitrary callback data" feature can be used.
6
7 For detailed info on arbitrary callback data, see the wiki page at
8 https://github.com/python-telegram-bot/python-telegram-bot/wiki/Arbitrary-callback_
˓→data
9 """
10 import logging
11 from typing import List, Tuple, cast
12
15 try:
16 from telegram import __version_info__
17 except ImportError:
18 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
19
36 # Enable logging
37 logging.basicConfig(
38 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
39 )
40 logger = logging.getLogger(__name__)
41
42
47
48
56
63
68 )
69
70
82 await query.edit_message_text(
83 text=f"So far you've selected {number_list}. Choose the next item:",
84 reply_markup=build_keyboard(number_list),
85 )
86
87 # we can delete the data stored for the query, because we've replaced the buttons
88 context.drop_callback_data(query)
89
90
98
123
chatmemberbot.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
5 """
6 Simple Bot to handle '(my_)chat_member' updates.
7 Greets new users & keeps track of which chats the bot is in.
8
9 Usage:
10 Press Ctrl-C on the command line or send a signal to the process to stop the
11 bot.
12 """
13
14 import logging
15 from typing import Optional, Tuple
16
19 try:
20 from telegram import __version_info__
(continues on next page)
34 # Enable logging
35
36 logging.basicConfig(
37 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
38 )
39
40 logger = logging.getLogger(__name__)
41
42
45 of the chat and whether the 'new_chat_member' is a member of the chat. Returns␣
˓→None, if
50
51 if status_change is None:
52 return None
53
68
94 context.bot_data.setdefault("group_ids", set()).discard(chat.id)
95 else:
96 if not was_member and is_member:
97 logger.info("%s added the bot to the channel %s", cause_name, chat.title)
98 context.bot_data.setdefault("channel_ids", set()).add(chat.id)
99 elif was_member and not is_member:
100 logger.info("%s removed the bot from the channel %s", cause_name, chat.
˓→title)
103
109 text = (
110 f"@{context.bot.username} is currently in a conversation with the user IDs
˓→{user_ids}."
111 f" Moreover it is a member of the groups with IDs {group_ids} "
112 f"and administrator in the channels with IDs {channel_ids}."
113 )
114 await update.effective_message.reply_text(text)
115
116
118 """Greets new users in chats and announces when someone leaves"""
119 result = extract_status_change(update.chat_member)
120 if result is None:
(continues on next page)
138
150
156
contexttypesbot.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
5 """
6 Simple Bot to showcase `telegram.ext.ContextTypes`.
7
8 Usage:
9 Press Ctrl-C on the command line or send a signal to the process to stop the
10 bot.
11 """
12
19 try:
20 from telegram import __version_info__
21 except ImportError:
22 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
23
42 # Enable logging
43 logging.basicConfig(
44 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
45 )
46 logger = logging.getLogger(__name__)
47
48
49 class ChatData:
50 """Custom class for chat_data. Here we store data per message."""
51
55
56 # The [ExtBot, dict, ChatData, dict] is for type checkers like mypy
57 class CustomContext(CallbackContext[ExtBot, dict, ChatData, dict]):
58 """Custom class for context."""
59
64 @property
65 def bot_user_ids(self) -> Set[int]:
66 """Custom shortcut to access a value stored in the bot_data dict"""
(continues on next page)
69 @property
70 def message_clicks(self) -> Optional[int]:
71 """Access the number of clicks for the message this context object was built␣
˓→for."""
72 if self._message_id:
73 return self.chat_data.clicks_per_message[self._message_id]
74 return None
75
76 @message_clicks.setter
77 def message_clicks(self, value: int) -> None:
78 """Allow to change the count"""
79 if not self._message_id:
80 raise RuntimeError("There is no message associated with this context␣
˓→object.")
81 self.chat_data.clicks_per_message[self._message_id] = value
82
83 @classmethod
84 def from_update(cls, update: object, application: "Application") -> "CustomContext
˓→":
85 """Override from_update to set _message_id."""
86 # Make sure to call super()
87 context = super().from_update(update, application)
88
96
106
127
133
138
139 # run track_users in its own group to not interfere with the user handlers
140 application.add_handler(TypeHandler(Update, track_users), group=-1)
141 application.add_handler(CommandHandler("start", start))
142 application.add_handler(CallbackQueryHandler(count_click))
143 application.add_handler(CommandHandler("print_users", print_users))
144
145 application.run_polling()
146
147
conversationbot.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
5 """
6 First, a few callback functions are defined. Then, those functions are passed to
7 the Application and registered at their respective places.
8 Then, the bot is started and runs until we press Ctrl-C on the command line.
9
10 Usage:
11 Example of a bot-user conversation using ConversationHandler.
12 Send /start to initiate the conversation.
13 Press Ctrl-C on the command line or send a signal to the process to stop the
14 bot.
15 """
16
17 import logging
18
42 # Enable logging
43 logging.basicConfig(
44 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
45 )
46 logger = logging.getLogger(__name__)
47
50
55 await update.message.reply_text(
56 "Hi! My name is Professor Bot. I will hold a conversation with you. "
57 "Send /cancel to stop talking to me.\n\n"
58 "Are you a boy or a girl?",
59 reply_markup=ReplyKeyboardMarkup(
60 reply_keyboard, one_time_keyboard=True, input_field_placeholder="Boy or␣
˓→Girl?"
61 ),
62 )
63
64 return GENDER
65
66
77 return PHOTO
78
79
88 )
89
90 return LOCATION
91
92
103
110 )
111 await update.message.reply_text(
112 "Maybe I can visit you sometime! At last, tell me something about yourself."
113 )
114
117
128
137
148
154 # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
155 conv_handler = ConversationHandler(
156 entry_points=[CommandHandler("start", start)],
157 states={
158 GENDER: [MessageHandler(filters.Regex("^(Boy|Girl|Other)$"), gender)],
159 PHOTO: [MessageHandler(filters.PHOTO, photo), CommandHandler("skip", skip_
˓→photo)],
160 LOCATION: [
161 MessageHandler(filters.LOCATION, location),
162 CommandHandler("skip", skip_location),
163 ],
164 BIO: [MessageHandler(filters.TEXT & ~filters.COMMAND, bio)],
165 },
166 fallbacks=[CommandHandler("cancel", cancel)],
167 )
168
169 application.add_handler(conv_handler)
170
174
State Diagram
conversationbot2.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
5 """
6 First, a few callback functions are defined. Then, those functions are passed to
7 the Application and registered at their respective places.
8 Then, the bot is started and runs until we press Ctrl-C on the command line.
9
10 Usage:
11 Example of a bot-user conversation using ConversationHandler.
12 Send /start to initiate the conversation.
13 Press Ctrl-C on the command line or send a signal to the process to stop the
14 bot.
15 """
16
17 import logging
18 from typing import Dict
19
22 try:
23 from telegram import __version_info__
24 except ImportError:
25 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
26
43 # Enable logging
44 logging.basicConfig(
45 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
46 )
47 logger = logging.getLogger(__name__)
48
51 reply_keyboard = [
52 ["Age", "Favourite colour"],
(continues on next page)
58
64
73 return CHOOSING
74
75
81
82 return TYPING_REPLY
83
84
89 )
90
91 return TYPING_CHOICE
92
93
95 """Store info provided by user and ask for the next category."""
96 user_data = context.user_data
97 text = update.message.text
98 category = user_data["choice"]
99 user_data[category] = text
100 del user_data["choice"]
101
111
123 user_data.clear()
124 return ConversationHandler.END
125
126
132 # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_
˓→REPLY
133 conv_handler = ConversationHandler(
134 entry_points=[CommandHandler("start", start)],
135 states={
136 CHOOSING: [
137 MessageHandler(
138 filters.Regex("^(Age|Favourite colour|Number of siblings)$"),␣
˓→regular_choice
139 ),
140 MessageHandler(filters.Regex("^Something else...$"), custom_choice),
141 ],
142 TYPING_CHOICE: [
143 MessageHandler(
144 filters.TEXT & ~(filters.COMMAND | filters.Regex("^Done$")),␣
˓→regular_choice
145 )
146 ],
147 TYPING_REPLY: [
148 MessageHandler(
149 filters.TEXT & ~(filters.COMMAND | filters.Regex("^Done$")),
150 received_information,
151 )
152 ],
153 },
154 fallbacks=[MessageHandler(filters.Regex("^Done$"), done)],
155 )
156
157 application.add_handler(conv_handler)
(continues on next page)
162
State Diagram
customwebhookbot.py
1 #!/usr/bin/env python
2 # This program is dedicated to the public domain under the CC0 license.
3 # pylint: disable=import-error,wrong-import-position
4 """
5 Simple example of a bot that uses a custom webhook setup and handles custom updates.
6 For the custom webhook setup, the libraries `starlette` and `uvicorn` are used. Please␣
˓→install
9 just as well.
10
11 Usage:
12 Set bot token, url, admin chat_id and port at the start of the `main` function.
13 You may also need to change the `listen` value in the uvicorn configuration to match␣
˓→your setup.
14 Press Ctrl-C on the command line or send a signal to the process to stop the bot.
15 """
16 import asyncio
17 import html
18 import logging
19 from dataclasses import dataclass
20 from http import HTTPStatus
21
22 import uvicorn
23 from starlette.applications import Starlette
24 from starlette.requests import Request
25 from starlette.responses import PlainTextResponse, Response
26 from starlette.routing import Route
27
30 try:
31 from telegram import __version_info__
32 except ImportError:
33 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
34
53 # Enable logging
54 logging.basicConfig(
55 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
56 )
57 logger = logging.getLogger(__name__)
58
59
60 @dataclass
61 class WebhookUpdate:
62 """Simple dataclass to wrap a custom update type"""
63
64 user_id: int
65 payload: str
66
67
74 @classmethod
75 def from_update(
76 cls,
77 update: object,
78 application: "Application",
79 ) -> "CustomContext":
80 if isinstance(update, WebhookUpdate):
81 return cls(application=application, user_id=update.user_id)
82 return super().from_update(update, application)
83
84
89 text = (
90 f"To check if the bot is still running, call <code>{url}/healthcheck</code>.\
˓→n\n"
95
105 )
106 await context.bot.send_message(
107 chat_id=context.bot_data["admin_chat_id"], text=text, parse_mode=ParseMode.
˓→HTML
108 )
109
110
122 )
123 # save the values in `bot_data` such that we may easily access them in the␣
˓→callbacks
154 )
155 except ValueError:
156 return PlainTextResponse(
157 status_code=HTTPStatus.BAD_REQUEST,
158 content="The `user_id` must be a string!",
159 )
160
163
190
deeplinking.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
7 This program is dedicated to the public domain under the CC0 license.
8
11 First, a few handler functions are defined. Then, those functions are passed to
12 the Application and registered at their respective places.
13 Then, the bot is started and runs until we press Ctrl-C on the command line.
14
15 Usage:
16 Deep Linking example. Send /start to get the link.
17 Press Ctrl-C on the command line or send a signal to the process to stop the
18 bot.
19 """
20
21 import logging
22
25 try:
26 from telegram import __version_info__
27 except ImportError:
28 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
29
39
40 # Enable logging
41 logging.basicConfig(
42 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
43 )
44
45 logger = logging.getLogger(__name__)
46
56
64
78
85
86
93 ),
94 )
95
96
111
117 # More info on what deep linking actually is (read this first if it's unclear to␣
˓→you):
118 # https://core.telegram.org/bots#deep-linking
119
127
141 )
142
143 # Make sure the deep-linking handlers occur *before* the normal /start handler.
144 application.add_handler(CommandHandler("start", start))
145
149
echobot.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
5 """
6 Simple Bot to reply to Telegram messages.
7
8 First, a few handler functions are defined. Then, those functions are passed to
9 the Application and registered at their respective places.
10 Then, the bot is started and runs until we press Ctrl-C on the command line.
11
12 Usage:
13 Basic Echobot example, repeats messages.
14 Press Ctrl-C on the command line or send a signal to the process to stop the
15 bot.
16 """
17
18 import logging
19
22 try:
23 from telegram import __version_info__
24 except ImportError:
25 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
26
35
36 # Enable logging
37 logging.basicConfig(
38 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
39 )
40 logger = logging.getLogger(__name__)
41
42
43 # Define a few command handlers. These usually take the two arguments update and
44 # context.
45 async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
46 """Send a message when the command /start is issued."""
47 user = update.effective_user
48 await update.message.reply_html(
49 rf"Hi {user.mention_html()}!",
50 reply_markup=ForceReply(selective=True),
51 )
52
53
58
63
79
80 if __name__ == "__main__":
81 main()
errorhandlerbot.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
5 """This is a very simple example on how one could implement a custom error handler."""
6 import html
7 import json
8 import logging
9 import traceback
10
13 try:
14 from telegram import __version_info__
15 except ImportError:
16 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
17
28 # Enable logging
29 logging.basicConfig(
30 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
31 )
32 logger = logging.getLogger(__name__)
33
38
47 tb_string = "".join(tb_list)
48
49 # Build the message with some markup and additional information about what␣
˓→happened.
50 # You might need to add some logic to deal with messages longer than the 4096␣
˓→character limit.
55 "</pre>\n\n"
56 f"<pre>context.chat_data = {html.escape(str(context.chat_data))}</pre>\n\n"
57 f"<pre>context.user_data = {html.escape(str(context.user_data))}</pre>\n\n"
58 f"<pre>{html.escape(tb_string)}</pre>"
59 )
60
66
71
79
95
96 if __name__ == "__main__":
97 main()
inlinebot.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
5 """
6 Don't forget to enable inline mode with @BotFather
7
8 First, a few handler functions are defined. Then, those functions are passed to
9 the Application and registered at their respective places.
10 Then, the bot is started and runs until we press Ctrl-C on the command line.
11
12 Usage:
13 Basic inline bot example. Applies different text transformations.
14 Press Ctrl-C on the command line or send a signal to the process to stop the
15 bot.
16 """
17 import logging
18 from html import escape
19 from uuid import uuid4
20
23 try:
24 from telegram import __version_info__
25 except ImportError:
26 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
27
38 # Enable logging
39 logging.basicConfig(
40 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
41 )
42 logger = logging.getLogger(__name__)
43
44
45 # Define a few command handlers. These usually take the two arguments update and
46 # context.
47 async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
48 """Send a message when the command /start is issued."""
49 await update.message.reply_text("Hi!")
50
51
56
61 if query == "":
62 return
63
64 results = [
65 InlineQueryResultArticle(
66 id=str(uuid4()),
67 title="Caps",
68 input_message_content=InputTextMessageContent(query.upper()),
69 ),
70 InlineQueryResultArticle(
71 id=str(uuid4()),
72 title="Bold",
73 input_message_content=InputTextMessageContent(
74 f"<b>{escape(query)}</b>", parse_mode=ParseMode.HTML
75 ),
76 ),
77 InlineQueryResultArticle(
78 id=str(uuid4()),
79 title="Italic",
80 input_message_content=InputTextMessageContent(
81 f"<i>{escape(query)}</i>", parse_mode=ParseMode.HTML
82 ),
83 ),
(continues on next page)
86 await update.inline_query.answer(results)
87
88
104
inlinekeyboard.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
5 """
6 Basic example for a bot that uses inline keyboards. For an in-depth explanation,␣
˓→check out
7 https://github.com/python-telegram-bot/python-telegram-bot/wiki/InlineKeyboard-
˓→Example.
8 """
9 import logging
10
13 try:
14 from telegram import __version_info__
15 except ImportError:
16 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
17
27 # Enable logging
28 logging.basicConfig(
29 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
30 )
31 logger = logging.getLogger(__name__)
32
33
44 reply_markup = InlineKeyboardMarkup(keyboard)
45
48
55 await query.answer()
56
59
64
70 application.add_handler(CommandHandler("start", start))
71 application.add_handler(CallbackQueryHandler(button))
72 application.add_handler(CommandHandler("help", help_command))
73
77
78 if __name__ == "__main__":
79 main()
inlinekeyboard2.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
13 ConversationHandler.
14 Send /start to initiate the conversation.
15 Press Ctrl-C on the command line to stop the bot.
16 """
17 import logging
18
21 try:
22 from telegram import __version_info__
23 except ImportError:
24 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
25
41 # Enable logging
42 logging.basicConfig(
43 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
44 )
45 logger = logging.getLogger(__name__)
46
47 # Stages
48 START_ROUTES, END_ROUTES = range(2)
49 # Callback data
50 ONE, TWO, THREE, FOUR = range(4)
51
52
74
81 await query.answer()
82 keyboard = [
83 [
84 InlineKeyboardButton("1", callback_data=str(ONE)),
85 InlineKeyboardButton("2", callback_data=str(TWO)),
86 ]
87 ]
88 reply_markup = InlineKeyboardMarkup(keyboard)
89 # Instead of sending a new message, edit the message that
90 # originated the CallbackQuery. This gives the feeling of an
91 # interactive menu.
92 await query.edit_message_text(text="Start handler, Choose a route", reply_
˓→markup=reply_markup)
93 return START_ROUTES
94
95
112
129
143 )
144 # Transfer to conversation state `SECOND`
145 return END_ROUTES
146
147
164
174
180 # Setup conversation handler with the states FIRST and SECOND
181 # Use the pattern parameter to pass CallbackQueries with specific
182 # data pattern to the corresponding handlers.
183 # ^ means "start of line/string"
184 # $ means "end of line/string"
185 # So ^ABC$ will only allow 'ABC'
186 conv_handler = ConversationHandler(
187 entry_points=[CommandHandler("start", start)],
188 states={
189 START_ROUTES: [
190 CallbackQueryHandler(one, pattern="^" + str(ONE) + "$"),
191 CallbackQueryHandler(two, pattern="^" + str(TWO) + "$"),
192 CallbackQueryHandler(three, pattern="^" + str(THREE) + "$"),
193 CallbackQueryHandler(four, pattern="^" + str(FOUR) + "$"),
194 ],
195 END_ROUTES: [
196 CallbackQueryHandler(start_over, pattern="^" + str(ONE) + "$"),
197 CallbackQueryHandler(end, pattern="^" + str(TWO) + "$"),
198 ],
199 },
200 fallbacks=[CommandHandler("start", start)],
201 )
202
203 # Add ConversationHandler to application that will be used for handling updates
204 application.add_handler(conv_handler)
205
209
nestedconversationbot.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
5 """
6 First, a few callback functions are defined. Then, those functions are passed to
7 the Application and registered at their respective places.
8 Then, the bot is started and runs until we press Ctrl-C on the command line.
9
10 Usage:
11 Example of a bot-user conversation using nested ConversationHandlers.
12 Send /start to initiate the conversation.
13 Press Ctrl-C on the command line or send a signal to the process to stop the
14 bot.
15 """
16
17 import logging
18 from typing import Any, Dict, Tuple
19
22 try:
23 from telegram import __version_info__
24 except ImportError:
25 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
26
44 # Enable logging
45 logging.basicConfig(
46 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
47 )
48 logger = logging.getLogger(__name__)
49
77
78 # Helper
79 def _name_switcher(level: str) -> Tuple[str, str]:
80 if level == PARENTS:
81 return "Father", "Mother"
82 return "Brother", "Sister"
83
84
93 buttons = [
94 [
95 InlineKeyboardButton(text="Add family member", callback_data=str(ADDING_
˓→MEMBER)),
112 )
113 await update.message.reply_text(text=text, reply_markup=keyboard)
114
118
131
168
175
185
190 buttons = [
191 [
192 InlineKeyboardButton(text="Add parent", callback_data=str(PARENTS)),
193 InlineKeyboardButton(text="Add child", callback_data=str(CHILDREN)),
194 ],
195 [
196 InlineKeyboardButton(text="Show data", callback_data=str(SHOWING)),
197 InlineKeyboardButton(text="Back", callback_data=str(END)),
198 ],
199 ]
200 keyboard = InlineKeyboardMarkup(buttons)
201
207
217 buttons = [
218 [
219 InlineKeyboardButton(text=f"Add {male}", callback_data=str(MALE)),
220 InlineKeyboardButton(text=f"Add {female}", callback_data=str(FEMALE)),
221 ],
222 [
223 InlineKeyboardButton(text="Show data", callback_data=str(SHOWING)),
224 InlineKeyboardButton(text="Back", callback_data=str(END)),
225 ],
226 ]
227 keyboard = InlineKeyboardMarkup(buttons)
228
234
242
255 # If we collect features for a new person, clear the cache and save the gender
256 if not context.user_data.get(START_OVER):
257 context.user_data[FEATURES] = {GENDER: update.callback_query.data}
258 text = "Please select a feature to update."
259
270
281
291
309
316
350 states={
351 SELECTING_LEVEL: [
352 CallbackQueryHandler(select_gender, pattern=f"^{PARENTS}$|^{CHILDREN}$
˓→")
353 ],
354 SELECTING_GENDER: [description_conv],
355 },
356 fallbacks=[
357 CallbackQueryHandler(show_data, pattern="^" + str(SHOWING) + "$"),
358 CallbackQueryHandler(end_second_level, pattern="^" + str(END) + "$"),
359 CommandHandler("stop", stop_nested),
360 ],
361 map_to_parent={
362 # After showing data return to top level menu
363 SHOWING: SHOWING,
364 # Return to top level menu
365 END: SELECTING_ACTION,
366 # End conversation altogether
367 STOPPING: END,
368 },
369 )
370
373 # conversation, we need to make sure the top level conversation can also handle␣
˓→them
374 selection_handlers = [
375 add_member_conv,
376 CallbackQueryHandler(show_data, pattern="^" + str(SHOWING) + "$"),
377 CallbackQueryHandler(adding_self, pattern="^" + str(ADDING_SELF) + "$"),
(continues on next page)
392 application.add_handler(conv_handler)
393
397
State Diagram
passportbot.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
5 """
6 Simple Bot to print/download all incoming passport data
7
10 See https://github.com/python-telegram-bot/python-telegram-bot/wiki/Telegram-Passport
11 for how to use Telegram Passport properly with python-telegram-bot.
12
13 """
14 import logging
15 from pathlib import Path
16
19 try:
20 from telegram import __version_info__
21 except ImportError:
22 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
23
33 # Enable logging
34
35 logging.basicConfig(
36 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
37 )
38
39 logger = logging.getLogger(__name__)
40
41
94 and data.selfie
95 ):
96 selfie_file = await data.selfie.get_file()
97 print(data.type, selfie_file)
98 await selfie_file.download()
99 if data.translation and data.type in (
100 "passport",
101 "driver_license",
102 "identity_card",
103 "internal_passport",
104 "utility_bill",
105 "bank_statement",
106 "rental_agreement",
107 "passport_registration",
108 "temporary_registration",
109 ):
110 print(data.type, len(data.translation), "translation")
111 for file in data.translation:
112 actual_file = await file.get_file()
113 print(actual_file)
114 await actual_file.download()
115
116
123 )
124
131
HTML Page
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <title>Telegram passport test!</title>
5 <meta charset="utf-8">
6 <meta content="IE=edge" http-equiv="X-UA-Compatible">
7 <meta content="width=device-width, initial-scale=1" name="viewport">
8 </head>
9 <body>
10 <h1>Telegram passport test</h1>
11
12 <div id="telegram_passport_auth"></div>
13 </body>
14
16 <script src="telegram-passport.js"></script>
17 <script>
18 "use strict";
19
20 Telegram.Passport.createAuthButton('telegram_passport_auth', {
21 bot_id: 1234567890, // YOUR BOT ID
22 scope: {
23 data: [{
24 type: 'id_document',
25 selfie: true
26 }, 'address_document', 'phone_number', 'email'], v: 1
27 }, // WHAT DATA YOU WANT TO RECEIVE
28 public_key: '-----BEGIN PUBLIC KEY-----\n', // YOUR PUBLIC KEY
29 nonce: 'thisisatest', // YOUR BOT WILL RECEIVE THIS DATA WITH THE REQUEST
30 callback_url: 'https://example.org' // TELEGRAM WILL SEND YOUR USER BACK TO␣
˓→THIS URL
31 });
32
33 </script>
34 </html>
paymentbot.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
5 """Basic example for a bot that can receive payment from user."""
6
7 import logging
8
11 try:
12 from telegram import __version_info__
13 except ImportError:
14 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
(continues on next page)
33 # Enable logging
34 logging.basicConfig(
35 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
36 )
37 logger = logging.getLogger(__name__)
38
39 PAYMENT_PROVIDER_TOKEN = "PAYMENT_PROVIDER_TOKEN"
40
41
49 await update.message.reply_text(msg)
50
51
60 currency = "USD"
61 # price in dollars
62 price = 1
63 # price * 100 so as to include 2 decimal points
64 # check https://core.telegram.org/bots/payments#supported-currencies for more␣
˓→details
84
95 currency = "USD"
96 # price in dollars
97 price = 1
98 # price * 100 so as to include 2 decimal points
99 prices = [LabeledPrice("Test", price * 100)]
100
107
124
136
143
155
170
persistentconversationbot.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
5 """
6 First, a few callback functions are defined. Then, those functions are passed to
7 the Application and registered at their respective places.
8 Then, the bot is started and runs until we press Ctrl-C on the command line.
9
10 Usage:
11 Example of a bot-user conversation using ConversationHandler.
12 Send /start to initiate the conversation.
13 Press Ctrl-C on the command line or send a signal to the process to stop the
14 bot.
15 """
16
17 import logging
18 from typing import Dict
19
22 try:
23 from telegram import __version_info__
24 except ImportError:
25 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
26
44 # Enable logging
45 logging.basicConfig(
46 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
47 )
48 logger = logging.getLogger(__name__)
49
52 reply_keyboard = [
53 ["Age", "Favourite colour"],
54 ["Number of siblings", "Something else..."],
(continues on next page)
59
65
73 )
74 else:
75 reply_text += (
76 " I will hold a more complex conversation with you. Why don't you tell me
˓→"
81 return CHOOSING
82
83
91 )
92 else:
93 reply_text = f"Your {text}? Yes, I would love to hear about that!"
94 await update.message.reply_text(reply_text)
95
96 return TYPING_REPLY
97
98
103 )
104
107
109 """Store info provided by user and ask for the next category."""
110 text = update.message.text
111 category = context.user_data["choice"]
112 context.user_data[category] = text.lower()
113 del context.user_data["choice"]
114
124
131
139 reply_markup=ReplyKeyboardRemove(),
140 )
141 return ConversationHandler.END
142
143
149
150 # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_
˓→REPLY
151 conv_handler = ConversationHandler(
152 entry_points=[CommandHandler("start", start)],
153 states={
154 CHOOSING: [
155 MessageHandler(
156 filters.Regex("^(Age|Favourite colour|Number of siblings)$"),␣
˓→regular_choice
163 )
164 ],
165 TYPING_REPLY: [
166 MessageHandler(
167 filters.TEXT & ~(filters.COMMAND | filters.Regex("^Done$")),
168 received_information,
169 )
170 ],
171 },
172 fallbacks=[MessageHandler(filters.Regex("^Done$"), done)],
173 name="my_conversation",
174 persistent=True,
175 )
176
177 application.add_handler(conv_handler)
178
185
pollbot.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
5 """
6 Basic example for a bot that works with polls. Only 3 people are allowed to interact␣
˓→with each
7 poll/quiz the bot generates. The preview command generates a closed poll/quiz,␣
˓→exactly like the
14 try:
15 from telegram import __version_info__
16 except ImportError:
17 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
18
44 # Enable logging
45 logging.basicConfig(
46 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
47 )
48 logger = logging.getLogger(__name__)
49
50
58
80
88 except KeyError:
89 return
90 selected_options = answer.option_ids
91 answer_string = ""
92 for question_id in selected_options:
93 if question_id != selected_options[-1]:
94 answer_string += questions[question_id] + " and "
95 else:
96 answer_string += questions[question_id]
97 await context.bot.send_message(
98 answered_poll["chat_id"],
99 f"{update.effective_user.mention_html()} feels {answer_string}!",
100 parse_mode=ParseMode.HTML,
101 )
102 answered_poll["answers"] += 1
103 # Close poll after three participants voted
104 if answered_poll["answers"] == 3:
105 await context.bot.stop_poll(answered_poll["chat_id"], answered_poll["message_
˓→id"])
106
107
113 )
114 # Save some info about the poll the bot_data for later use in receive_quiz_answer
115 payload = {
116 message.poll.id: {"chat_id": update.effective_chat.id, "message_id": message.
˓→message_id}
117 }
118 context.bot_data.update(payload)
119
120
134
145
159
164
181
rawapibot.py
1 #!/usr/bin/env python
2 # pylint: disable=wrong-import-position
3 """Simple Bot to reply to Telegram messages.
4
5 This is built on the API wrapper, see echobot.py to see the same example built
6 on the telegram.ext bot framework.
7 This program is dedicated to the public domain under the CC0 license.
8 """
9 import asyncio
10 import logging
11 from typing import NoReturn
12
15 try:
16 from telegram import __version_info__
17 except ImportError:
18 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment] # type:␣
˓→ignore[assignment]
19
29 logging.basicConfig(
30 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
31 )
32 logger = logging.getLogger(__name__)
33
34
56
73
74 if __name__ == "__main__":
75 try:
76 asyncio.run(main())
77 except KeyboardInterrupt: # Ignore exception when Ctrl-C is pressed
78 pass
timerbot.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument, wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
5 """
6 Simple Bot to send timed Telegram messages.
7
8 This Bot uses the Application class to handle the bot and the JobQueue to send
9 timed messages.
10
11 First, a few handler functions are defined. Then, those functions are passed to
12 the Application and registered at their respective places.
13 Then, the bot is started and runs until we press Ctrl-C on the command line.
14
15 Usage:
(continues on next page)
21 import logging
22
25 try:
26 from telegram import __version_info__
27 except ImportError:
28 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
29
39 # Enable logging
40 logging.basicConfig(
41 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
42 )
43
44
45 # Define a few command handlers. These usually take the two arguments update and
46 # context.
47 # Best practice would be to replace context with an underscore,
48 # since context is an unused local variable.
49 # This being an example and not having context present confusing beginners,
50 # we decided to have it present as context.
51 async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
52 """Sends explanation on how to use the bot."""
53 await update.message.reply_text("Hi! Use /set <seconds> to set a timer")
54
55
60
61
71
80 return
81
84
93
99 await update.message.reply_text(text)
100
101
115
webappbot.py
1 #!/usr/bin/env python
2 # pylint: disable=unused-argument,wrong-import-position
3 # This program is dedicated to the public domain under the CC0 license.
4
5 """
6 Simple example of a Telegram WebApp which displays a color picker.
7 The static website for this website is hosted by the PTB team for your convenience.
8 Currently only showcases starting the WebApp via a KeyboardButton, as all other␣
˓→methods would
16 try:
17 from telegram import __version_info__
18 except ImportError:
19 __version_info__ = (0, 0, 0, 0, 0) # type: ignore[assignment]
20
29
30 # Enable logging
31 logging.basicConfig(
32 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
33 )
34 logger = logging.getLogger(__name__)
35
36
46 )
47 ),
48 )
49
50
63
69 application.add_handler(CommandHandler("start", start))
70 application.add_handler(MessageHandler(filters.StatusUpdate.WEB_APP_DATA, web_app_
˓→data))
71
75
76 if __name__ == "__main__":
77 main()
HTML Page
1 <!--
2 Simple static Telegram WebApp. Does not verify the WebAppInitData, as a bot token␣
˓→would be needed for that.
3 -->
4 <!DOCTYPE html>
5 <html lang="en">
6 <head>
7 <meta charset="UTF-8">
8 <title>python-telegram-bot Example WebApp</title>
9 <script src="https://telegram.org/js/telegram-web-app.js"></script>
10 <script src="https://cdn.jsdelivr.net/npm/@jaames/iro@5"></script>
11 </head>
12 <script type="text/javascript">
13 const colorPicker = new iro.ColorPicker('#picker', {
14 borderColor: "#ffffff",
15 borderWidth: 1,
16 width: Math.round(document.documentElement.clientWidth / 2),
17 });
18 colorPicker.on('color:change', function (color) {
19 document.body.style.background = color.hexString;
20 });
21
25 Telegram.WebApp.sendData(data);
26 Telegram.WebApp.close();
27 });
28 </script>
29 <body style="background-color: #ffffff">
30 <div style="position: absolute; margin-top: 5vh; margin-left: 5vw; height: 90vh;␣
˓→width: 90vw; border-radius: 5vh; background-color: var(--tg-theme-bg-color); box-
˓→shadow: 0 0 2vw
31 #000000;">
32 <div id="picker"
33 style="display: flex; justify-content: center; align-items: center; height:␣
˓→100%; width: 100%"></div>
34 </div>
35 </body>
36 <script type="text/javascript">
37 Telegram.WebApp.expand();
38 </script>
39 </html>
10.5 Changelog
Released 2022-08-27
This is the technical changelog for version 20.0a4. More elaborate release notes can be found in the news channel
@pythontelegrambotchannel.
Hot Fixes
Released 2022-08-27
This is the technical changelog for version 20.0a3. More elaborate release notes can be found in the news channel
@pythontelegrambotchannel.
Major Changes
New Features
Bug Fixes
• Fix helpers.mention_markdown for Markdown V1 and Improve Related Unit Tests (#3155)
• Add api_kwargs Parameter to Bot.log_out and Improve Related Unit Tests (#3147)
• Make Bot.delete_my_commands a Coroutine Function (#3136)
• Fix ConversationHandler.check_update not respecting per_user (#3128)
• Add Python 3.11 to Test Suite & Adapt Enum Behaviour (#3168)
• Drop Manual Token Validation (#3167)
• Simplify Unit Tests for Bot.send_chat_action (#3151)
• Drop pre-commit Dependencies from requirements-dev.txt (#3120)
• Change Default Values for concurrent_updates and connection_pool_size (#3127)
• Documentation Improvements (#3139, #3153, #3135)
• Type Hinting Fixes (#3202)
Dependencies
Released 2022-06-27
This is the technical changelog for version 20.0a2. More elaborate release notes can be found in the news channel
@pythontelegrambotchannel.
Major Changes
New Features
Released 2022-06-09
This is the technical changelog for version 20.0a1. More elaborate release notes can be found in the news channel
@pythontelegrambotchannel.
Major Changes:
New Features:
Bug Fixes:
Dependencies:
Released 2022-05-06
This is the technical changelog for version 20.0a0. More elaborate release notes can be found in the news channel
@pythontelegrambotchannel.
Major Changes:
New Features:
• Add User Friendly Type Check For Init Of {Inline, Reply}KeyboardMarkup (#2657)
• Warnings Overhaul (#2662)
• Clear Up Import Policy (#2671)
• Mark Internal Modules As Private (#2687 by kencx)
• Handle Filepaths via the pathlib Module (#2688 by eldbud)
• Refactor MRO of InputMedia* and Some File-Like Classes (#2717 by eldbud)
• Update Exceptions for Immutable Attributes (#2749)
• Refactor Warnings in ConversationHandler (#2755, #2784)
• Use __all__ Consistently (#2805)
Documentation Improvements:
Released 2022-02-02
This is the technical changelog for version 13.11. More elaborate release notes can be found in the news channel
@pythontelegrambotchannel.
Major Changes:
• Full Support for Bot API 5.7 (#2881)
Released 2022-01-03
This is the technical changelog for version 13.10. More elaborate release notes can be found in the news channel
@pythontelegrambotchannel.
Major Changes:
• Full Support for API 5.6 (#2835)
Minor Changes & Doc fixes:
• Update Copyright to 2022 (#2836)
• Update Documentation of BotCommand (#2820)
Released 2021-12-11
This is the technical changelog for version 13.9. More elaborate release notes can be found in the news channel
@pythontelegrambotchannel.
Major Changes:
• Full Support for Api 5.5 (#2809)
Minor Changes
• Adjust Automated Locking of Inactive Issues (#2775)
Released 2021-11-08
This is the technical changelog for version 13.8.1. More elaborate release notes can be found in the news channel
@pythontelegrambotchannel.
Doc fixes:
• Add ChatJoinRequest(Handler) to Docs (#2771)
Released 2021-11-08
This is the technical changelog for version 13.8. More elaborate release notes can be found in the news channel
@pythontelegrambotchannel.
Major Changes:
• Full support for API 5.4 (#2767)
Minor changes, CI improvements, Doc fixes and Type hinting:
• Create Issue Template Forms (#2689)
• Fix camelCase Functions in ExtBot (#2659)
• Fix Empty Captions not Being Passed by Bot.copy_message (#2651)
• Fix Setting Thumbs When Uploading A Single File (#2583)
• Fix Bug in BasePersistence.insert/replace_bot for Objects with __dict__ not in __slots__
(#2603)
Released 2021-07-01
This is the technical changelog for version 13.7. More elaborate release notes can be found in the news channel
@pythontelegrambotchannel.
Major Changes:
• Full support for Bot API 5.3 (#2572)
Bug Fixes:
• Fix Bug in BasePersistence.insert/replace_bot for Objects with __dict__ in their slots (#2561)
• Remove Incorrect Warning About Defaults and ExtBot (#2553)
Minor changes, CI improvements, Doc fixes and Type hinting:
• Type Hinting Fixes (#2552)
• Doc Fixes (#2551)
• Improve Deprecation Warning for __slots__ (#2574)
• Stabilize CI (#2575)
• Fix Coverage Configuration (#2571)
• Better Exception-Handling for BasePersistence.replace/insert_bot (#2564)
• Remove Deprecated pass_args from Deeplinking Example (#2550)
Released 2021-06-06
New Features:
• Arbitrary callback_data (#1844)
• Add ContextTypes & BasePersistence.refresh_user/chat/bot_data (#2262)
• Add Filters.attachment (#2528)
• Add pattern Argument to ChosenInlineResultHandler (#2517)
Major Changes:
• Add slots (#2345)
Minor changes, CI improvements, Doc fixes and Type hinting:
• Doc Fixes (#2495, #2510)
• Add max_connections Parameter to Updater.start_webhook (#2547)
• Fix for Promise.done_callback (#2544)
• Improve Code Quality (#2536, #2454)
• Increase Test Coverage of CallbackQueryHandler (#2520)
• Stabilize CI (#2522, #2537, #2541)
• Fix send_phone_number_to_provider argument for Bot.send_invoice (#2527)
• Handle Classes as Input for BasePersistence.replace/insert_bot (#2523)
• Bump Tornado Version and Remove Workaround from #2067 (#2494)
Released 2021-04-30
Major Changes:
• Full support of Bot API 5.2 (#2489).
Note: The start_parameter argument of Bot.send_invoice and the corresponding shortcuts is now
optional, so the order of parameters had to be changed. Make sure to update your method calls accordingly.
Released 2021-03-14
Hot fix release:
• Fixed a bug in setup.py (#2431)
Released 2021-03-14
Major Changes:
• Full support of Bot API 5.1 (#2424)
Minor changes, CI improvements, doc fixes and type hinting:
• Improve Updater.set_webhook (#2419)
• Doc Fixes (#2404)
• Type Hinting Fixes (#2425)
• Update pre-commit Settings (#2415)
• Fix Logging for Vendored urllib3 (#2427)
• Stabilize Tests (#2409)
Released 2021-02-19
Major Changes:
• Make cryptography Dependency Optional & Refactor Some Tests (#2386, #2370)
• Deprecate MessageQueue (#2393)
Bug Fixes:
• Refactor Defaults Integration (#2363)
• Add Missing telegram.SecureValue to init and Docs (#2398)
Minor changes:
• Doc Fixes (#2359)
Released 2021-02-02
Major Changes:
• Introduce python-telegram-bot-raw (#2324)
• Explicit Signatures for Shortcuts (#2240)
New Features:
• Add Missing Shortcuts to Message (#2330)
Released 2020-11-29
Major Changes:
• Full support of Bot API 5.0 (#2181, #2186, #2190, #2189, #2183, #2184, #2188, #2185, #2192, #2196,
#2193, #2223, #2199, #2187, #2147, #2205)
New Features:
• Add Defaults.run_async (#2210)
• Improve and Expand CallbackQuery Shortcuts (#2172)
• Add XOR Filters and make Filters.name a Property (#2179)
• Add Filters.document.file_extension (#2169)
• Add Filters.caption_regex (#2163)
• Add Filters.chat_type (#2128)
• Handle Non-Binary File Input (#2202)
Bug Fixes:
• Improve Handling of Custom Objects in BasePersistence.insert/replace_bot (#2151)
Released 2020-10-07
For a detailed guide on how to migrate from v12 to v13, see this wiki page.
Major Changes:
• Deprecate old-style callbacks, i.e. set use_context=True by default (#2050)
• Refactor Handling of Message VS Update Filters (#2032)
• Deprecate Message.default_quote (#1965)
• Refactor persistence of Bot instances (#1994)
• Refactor JobQueue (#1981)
• Refactor handling of kwargs in Bot methods (#1924)
• Refactor Dispatcher.run_async, deprecating the @run_async decorator (#2051)
New Features:
• Type Hinting (#1920)
• Automatic Pagination for answer_inline_query (#2072)
• Defaults.tzinfo (#2042)
• Extend rich comparison of objects (#1724)
• Add Filters.via_bot (#2009)
• Add missing shortcuts (#2043)
• Allow DispatcherHandlerStop in ConversationHandler (#2059)
• Make Errors picklable (#2106)
Minor changes, CI improvements, doc fixes or bug fixes:
• Fix Webhook not working on Windows with Python 3.8+ (#2067)
• Fix setting thumbs with send_media_group (#2093)
Released 2020-06-22
Major Changes:
• Remove Python 2 support (#1715)
• Bot API 4.9 support (#1980)
• IDs/Usernames of Filters.user and Filters.chat can now be updated (#1757)
Minor changes, CI improvements, doc fixes or bug fixes:
• Update contribution guide and stale bot (#1937)
• Remove NullHandlers (#1913)
• Improve and expand examples (#1943, #1995, #1983, #1997)
• Doc fixes (#1940, #1962)
• Add User.send_poll() shortcut (#1968)
• Ignore private attributes en TelegramObject.to_dict() (#1989)
• Stabilize CI (#2000)
Released 2020-05-02
Major Changes:
• Bot API 4.8 support. Note: The Dice object now has a second positional argument emoji. This is relevant,
if you instantiate Dice objects manually. (#1917)
• Added tzinfo argument to helpers.from_timestamp. It now returns an timezone aware object.
This is relevant for Message.{date,forward_date,edit_date}, Poll.close_date and ChatMember.
until_date (#1621)
New Features:
• New method run_monthly for the JobQueue (#1705)
• Job.next_t now gives the datetime of the jobs next execution (#1685)
Minor changes, CI improvements, doc fixes or bug fixes:
• Stabalize CI (#1919, #1931)
• Use ABCs @abstractmethod instead of raising NotImplementedError for Handler, BasePersistence
and BaseFilter (#1905)
Released 2020-04-11
Bug fixes:
• Fix serialization of reply_markup in media messages (#1889)
Released 2020-04-10
Major Changes:
• Bot API 4.7 support. Note: In Bot.create_new_sticker_set and Bot.add_sticker_to_set, the
order of the parameters had be changed, as the png_sticker parameter is now optional. (#1858)
Minor changes, CI improvements or bug fixes:
• Add tests for swtich_inline_query(_current_chat) with empty string (#1635)
• Doc fixes (#1854, #1874, #1884)
• Update issue templates (#1880)
• Favor concrete types over “Iterable” (#1882)
• Pass last valid CallbackContext to TIMEOUT handlers of ConversationHandler (#1826)
• Tweak handling of persistence and update persistence after job calls (#1827)
• Use checkout@v2 for GitHub actions (#1887)
Released 2020-03-30
Minor changes, doc fixes or bug fixes:
• Add missing docs for PollHandler and PollAnswerHandler (#1853)
• Fix wording in Filters docs (#1855)
• Reorder tests to make them more stable (#1835)
• Make ConversationHandler attributes immutable (#1756)
• Make PrefixHandler attributes command and prefix editable (#1636)
• Fix UTC as default tzinfo for Job (#1696)
Released 2020-03-29
New Features:
• Bot.link gives the t.me link of the bot (#1770)
Major Changes:
• Bot API 4.5 and 4.6 support. (#1508, #1723)
Minor changes, CI improvements or bug fixes:
Released 2020-02-10
Bug Fixes
• Pass correct parse_mode to InlineResults if bot.defaults is None (#1763)
• Make sure PP can read files that dont have bot_data (#1760)
Released 2020-02-08
This is a quick release for #1744 which was accidently left out of v12.4.0 though mentioned in the release notes.
Released 2020-02-08
New features:
• Set default values for arguments appearing repeatedly. We also have a wiki page for the new defaults. (#1490)
• Store data in CallbackContext.bot_data to access it in every callback. Also persists. (#1325)
• Filters.poll allows only messages containing a poll (#1673)
Major changes:
• Filters.text now accepts messages that start with a slash, because CommandHandler checks for
MessageEntity.BOT_COMMAND since v12. This might lead to your MessageHandlers receiving more up-
dates than before (#1680).
• Filters.command new checks for MessageEntity.BOT_COMMAND instead of just a leading slash. Also by
Filters.command(False) you can now filters for messages containing a command anywhere in the text
(#1744).
Minor changes, CI improvements or bug fixes:
• Add disptacher argument to Updater to allow passing a customized Dispatcher (#1484)
• Add missing names for Filters (#1632)
• Documentation fixes (#1624, #1647, #1669, #1703, #1718, #1734, #1740, #1642, #1739, #1746)
• CI improvements (#1716, #1731, #1738, #1748, #1749, #1750, #1752)
Released 2020-01-11
New features:
• Filters.caption allows only messages with caption (#1631).
• Filter for exact messages/captions with new capability of Filters.text and Filters.caption. Especially useful
in combination with ReplyKeyboardMarkup. (#1631).
Major changes:
• Fix inconsistent handling of naive datetimes (#1506).
Minor changes, CI improvements or bug fixes:
• Documentation fixes (#1558, #1569, #1579, #1572, #1566, #1577, #1656).
• Add mutex protection on ConversationHandler (#1533).
• Add MAX_PHOTOSIZE_UPLOAD constant (#1560).
• Add args and kwargs to Message.forward() (#1574).
• Transfer to GitHub Actions CI (#1555, #1556, #1605, #1606, #1607, #1612, #1615, #1645).
• Fix deprecation warning with Py3.8 by vendored urllib3 (#1618).
• Simplify assignements for optional arguments (#1600)
• Allow private groups for Message.link (#1619).
• Fix wrong signature call for ConversationHandler.TIMEOUT handlers (#1653).
Released 2019-10-14
New features:
• Nested ConversationHandlers (#1512).
Minor changes, CI improvments or bug fixes:
• Fix CI failures due to non-backward compat attrs depndency (#1540).
• travis.yaml: TEST_OFFICIAL removed from allowed_failures.
• Fix typos in examples (#1537).
Released 2019-09-18
Hot fix release
Fixed regression in the vendored urllib3 (#1517).
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)
Released 2019-08-29
Well. . . This felt like decades. But here we are with a new release.
Expect minor releases soon (mainly complete Bot API 4.4 support)
Major and/or breaking changes:
• Context based callbacks
• Persistence
• PrefixHandler added (Handler overhaul)
• Deprecation of RegexHandler and edited_messages, channel_post, etc. arguments (Filter overhaul)
• Various ConversationHandler changes and fixes
• Bot API 4.1, 4.2, 4.3 support
• Python 3.4 is no longer supported
• Error Handler now handles all types of exceptions (#1485)
• Return UTC from from_timestamp() (#1485)
See the wiki page at https://github.com/python-telegram-bot/python-telegram-bot/wiki/Transition-guide-to-
Version-12.0 for a detailed guide on how to migrate from version 11 to version 12.
Persistence (#1017)
• CommandHandler now only triggers on actual commands as defined by telegram servers (everything that
the clients mark as a tabable link).
• PrefixHandler can be used if you need to trigger on prefixes (like all messages starting with a “/” (old Com-
mandHandler behaviour) or even custom prefixes like “#” or “!”).
• RegexHandler is deprecated and should be replaced with a MessageHandler with a regex filter.
• Use update filters to filter update types instead of arguments (message_updates, channel_post_updates and
edited_updates) on the handlers.
• Completely remove allow_edited argument - it has been deprecated for a while.
• data_filters now exist which allows filters that return data into the callback function. This is how the regex
filter is implemented.
• All this means that it no longer possible to use a list of filters in a handler. Use bitwise operators instead!
ConversationHandler
Internal improvements
• Finally fix our CI builds mostly (too many commits and PRs to list)
• Use multiple bots for CI to improve testing times significantly.
• Allow pypy to fail in CI.
• Remove the last CamelCase CheckUpdate methods from the handlers we missed earlier.
• test_official is now executed in a different job
Released 2018-09-01
Fixes and updates for Telegram Passport: (#1198)
• Fix passport decryption failing at random times
• Added support for middle names.
• Added support for translations for documents
• Add errors for translations for documents
• Added support for requesting names in the language of the user’s country of residence
• Replaced the payload parameter with the new parameter nonce
• Add hash to EncryptedPassportElement
Released 2018-08-29
Fully support Bot API version 4.0! (also some bugfixes :))
Telegram Passport (#1174):
•Add full support for telegram passport.
– New types: PassportData, PassportFile, EncryptedPassportElement, EncryptedCredentials,
PassportElementError, PassportElementErrorDataField, PassportElementErrorFrontSide, Pass-
portElementErrorReverseSide, PassportElementErrorSelfie, PassportElementErrorFile and Pass-
portElementErrorFiles.
– New bot method: set_passport_data_errors
– New filter: Filters.passport_data
– Field passport_data field on Message
– PassportData can be easily decrypted.
– PassportFiles are automatically decrypted if originating from decrypted PassportData.
• See new passportbot.py example for details on how to use, or go to our telegram passport wiki page for more
info
• NOTE: Passport decryption requires new dependency cryptography.
Inputfile rework (#1184):
• Change how Inputfile is handled internally
• This allows support for specifying the thumbnails of photos and videos using the thumb= argument in the
different send_ methods.
• Also allows Bot.send_media_group to actually finally send more than one media.
Released 2018-05-02
Fixes changing previous behaviour:
• Add urllib3 fix for socks5h support (#1085)
• Fix send_sticker() timeout=20 (#1088)
Fixes:
• Add a caption_entity filter for filtering caption entities (#1068)
• Inputfile encode filenames (#1086)
• InputFile: Fix proper naming of file when reading from subprocess.PIPE (#1079)
• Remove pytest-catchlog from requirements (#1099)
• Documentation fixes (#1061, #1078, #1081, #1096)
Released 2018-04-17
Important fix:
• Handle utf8 decoding errors (#1076)
New features:
• Added Filter.regex (#1028)
• Filters for Category and file types (#1046)
• Added video note filter (#1067)
Fixes:
• Fix in telegram.Message (#1042)
• Make chat_id a positional argument inside shortcut methods of Chat and User classes (#1050)
• Make Bot.full_name return a unicode object. (#1063)
• CommandHandler faster check (#1074)
• Correct documentation of Dispatcher.add_handler (#1071)
• Various small fixes to documentation.
Released 2018-03-05
Fixes:
• Fix conversationhandler timeout (PR #1032)
• Add missing docs utils (PR #912)
Released 2018-03-02
Non backward compatabile changes and changed defaults
• JobQueue: Remove deprecated prevent_autostart & put() (PR #1012)
• Bot, Updater: Remove deprecated network_delay (PR #1012)
• Remove deprecated Message.new_chat_member (PR #1012)
• Retry bootstrap phase indefinitely (by default) on network errors (PR #1018)
New Features
• Support v3.6 API (PR #1006)
• User.full_name convinience property (PR #949)
• Add send_phone_number_to_provider and send_email_to_provider arguments to send_invoice (PR #986)
• Bot: Add shortcut methods reply_{markdown,html} (PR #827)
• Bot: Add shortcut method reply_media_group (PR #994)
• Added utils.helpers.effective_message_type (PR #826)
• Bot.get_file now allows passing a file in addition to file_id (PR #963)
• Add .get_file() to Audio, Document, PhotoSize, Sticker, Video, VideoNote and Voice (PR #963)
• 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)
• File.download(): Now returns a meaningful return value (PR #1019)
• Added conversation timeout in ConversationHandler (PR #895)
Changes
• Store bot in PreCheckoutQuery (PR #953)
Released 2017-12-08
Breaking changes (possibly)
• Drop support for python 3.3 (PR #930)
New Features
• Support Bot API 3.5 (PR #920)
Changes
• Fix race condition in dispatcher start/stop (#887)
• Log error trace if there is no error handler registered (#694)
• Update examples with consistent string formatting (#870)
• Various changes and improvements to the docs.
Released 2017-10-15
• Fix Commandhandler crashing on single character messages (PR #873).
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.
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.
Released 2017-07-28
• Fix TypeError exception in RegexHandler (PR #751).
• Small documentation fix (PR #749).
Released 2017-07-25
• Fully support Bot API 3.2.
• New filters for handling messages from specific chat/user id (PR #677).
• Add the possibility to add objects as arguments to send_* methods (PR #742).
• Fixed download of URLs with UTF-8 chars in path (PR #688).
• Fixed URL parsing for Message text properties (PR #689).
• Fixed args dispatching in MessageQueue’s decorator (PR #705).
• Fixed regression preventing IPv6 only hosts from connnecting to Telegram servers (Issue #720).
• ConvesationHandler - check if a user exist before using it (PR #699).
• Removed deprecated telegram.Emoji.
• Removed deprecated Botan import from utils (Botan is still available through contrib).
2017-06-18
Released 6.1.0
• Fully support Bot API 3.0
• Add more fine-grained filters for status updates
• Bug fixes and other improvements
2017-05-29
Released 6.0.3
• Faulty PyPI release
2017-05-29
Released 6.0.2
• Avoid confusion with user’s urllib3 by renaming vendored urllib3 to ptb_urllib3
2017-05-19
Released 6.0.1
• Add support for User.language_code
• Fix Message.text_html and Message.text_markdown for messages with emoji
2017-05-19
Released 6.0.0
• Add support for Bot API 2.3.1
• Add support for deleteMessage API method
• New, simpler API for JobQueue - https://github.com/python-telegram-bot/python-telegram-bot/pull/484
• Download files into file-like objects - https://github.com/python-telegram-bot/python-telegram-bot/pull/
459
• Use vendor urllib3 to address issues with timeouts - The default timeout for messages is now 5 seconds.
For sending media, the default timeout is now 20 seconds.
• String attributes that are not set are now None by default, instead of empty strings
• Add text_markdown and text_html properties to Message - https://github.com/python-telegram-bot/
python-telegram-bot/pull/507
• Add support for Socks5 proxy - https://github.com/python-telegram-bot/python-telegram-bot/pull/518
• Add support for filters in CommandHandler - https://github.com/python-telegram-bot/python-telegram-bot/
pull/536
• Add the ability to invert (not) filters - https://github.com/python-telegram-bot/python-telegram-bot/pull/552
• Add Filters.group and Filters.private
• Introduce ConversationHandler
• Introduce telegram.constants - https://github.com/python-telegram-bot/python-telegram-bot/pull/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 urllib3.PoolManager for connection re-use
• Rewrite run_async decorator to re-use threads
• New requirements: urllib3 and certifi
2016-06-10
Released 4.2.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 telegram.contrib
• 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 telegram.Bot.send_message is the same as
telegram.Bot.sendMessage
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
• Please read the Transistion Guide to 4.0
2016-03-22
Released 3.4
• Move Updater, Dispatcher and JobQueue to new telegram.ext 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 botan.io (thanks to @ollmer)
• HTML Parsemode (thanks to @jlmadurga)
• Bugfixes and under-the-hood improvements
Very special thanks to Noam Meltzer (@tsnoam) for all of his work!
2016-01-09
Released 3.3b1
• Implement inline bots (beta)
2016-01-05
Released 3.2.0
• Introducing JobQueue (original author: @franciscod)
• Streamlining all exceptions to TelegramError (Special thanks to @tsnoam)
• Proper locking of Updater and Dispatcher start and stop methods
• Small bugfixes
2015-12-29
Released 3.1.2
• Fix custom path for file downloads
• Don’t stop the dispatcher thread on uncaught errors in handlers
2015-12-21
Released 3.1.1
• Fix a bug where asynchronous handlers could not have additional arguments
• Add groups and groupdict as additional arguments for regex-based handlers
2015-12-16
Released 3.1.0
• The chat-field in Message is now of type Chat. (API update Oct 8 2015)
• Message now contains the optional fields supergroup_chat_created, migrate_to_chat_id,
migrate_from_chat_id and channel_chat_created. (API update Nov 2015)
2015-12-08
Released 3.0.0
• Introducing the Updater and Dispatcher classes
2015-11-11
Released 2.9.2
• Error handling on request timeouts has been improved
2015-11-10
Released 2.9.1
• Add parameter network_delay to Bot.getUpdates 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
2015-08-19
Released 2.7.1
• Fixed JSON serialization for message
2015-08-17
Released 2.7
• Added support for Voice object and sendVoice method
• Due backward compatibility performer or/and title will be required for sendAudio
• Fixed JSON serialization when forwarded message
2015-08-15
Released 2.6.1
• Fixed parsing image header issue on < Python 2.7.3
2015-08-14
Released 2.6.0
• Depreciation of require_authentication and clearCredentials methods
• Giving AUTHORS the proper credits for their contribution for this project
• Message.date and Message.forward_date are now datetime objects
2015-08-12
Released 2.5.3
• telegram.Bot now supports to be unpickled
2015-08-11
Released 2.5.2
• New changes from Telegram Bot API have been applied
• telegram.Bot now supports to be pickled
• Return empty str instead None when message.text is empty
2015-08-10
Released 2.5.1
• Moved from GPLv2 to LGPLv3
2015-08-09
Released 2.5
• 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 logging.basicConfig from library
2015-07-25
Released 2.2
• Allows debug=True when initializing telegram.Bot
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
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
Every open source project lives from the generous help by contributors that sacrifice their time and
python-telegram-bot is no different. To make participation as pleasant as possible, this project adheres to
the Code of Conduct by the Python Software Foundation.
4. Install dependencies:
$ pre-commit install
If you already know what you’d like to work on, you can skip this section.
If you have an idea for something to do, first check if it’s already been filed on the issue tracker. If so, add a
comment to the issue saying you’d like to work on it, and we’ll help you get started! Otherwise, please file a new
issue and assign yourself to it.
Another great way to start contributing is by writing tests. Tests are really important because they help prevent
developers from accidentally breaking existing code, allowing them to build cool things faster. If you’re interested
in helping out, let the development team know by posting to the Telegram group, and we’ll help you get started.
That being said, we want to mention that we are very hesitant about adding new requirements to our projects. If
you intend to do this, please state this in an issue and get a verification from one of the maintainers.
The central development branch is master, which should be clean and ready for release at any time. In general,
all changes should be done as feature branches based off of master.
If you want to do solely documentation changes, base them and PR to the branch doc-fixes. This branch also
has its own RTD build.
Here’s how to make a one-off code change.
1. Choose a descriptive branch name. It should be lowercase, hyphen-separated, and a noun describing the
change (so, fuzzy-rules, but not implement-fuzzy-rules). Also, it shouldn’t start with hotfix or
release.
2. Create a new branch with this name, starting from master. In other words, run:
3. Make a commit to your feature branch. Each commit should be self-contained and have a descriptive
commit message that helps other developers understand why the changes were made.
• You can refer to relevant issues in the commit message by writing, e.g., “#105”.
• Your code should adhere to the PEP 8 Style Guide, with the exception that we have a maximum line
length of 99.
• Provide static typing with signature annotations. The documentation of MyPy will be a good start, the
cheat sheet is here. We also have some custom type aliases in telegram._utils.types.
• Document your code. This step is pretty important to us, so it has its own section.
• For consistency, please conform to Google Python Style Guide and Google Python Style Docstrings.
• The following exceptions to the above (Google’s) style guides applies:
– Documenting types of global variables and complex types of class members can be done using the
Sphinx docstring convention.
• In addition, PTB uses some formatting/styling and linting tools in the pre-commit setup. Some of those
tools also have command line tools that can help to run these tools outside of the pre-commit step. If
you’d like to leverage that, please have a look at the pre-commit config file for an overview of which
tools (and which versions of them) are used. For example, we use Black for code formatting. Plugins
for Black exist for some popular editors. You can use those instead of manually formatting everything.
• Please ensure that the code you write is well-tested.
– In addition to that, we provide the dev marker for pytest. If you write one or multiple tests and
want to run only those, you can decorate them via @pytest.mark.dev and then run it with minimal
overhead with pytest ./path/to/test_file.py -m dev.
• Don’t break backward compatibility.
• Add yourself to the AUTHORS.rst file in an alphabetical fashion.
• Before making a commit ensure that all automated tests still pass:
$ pytest -v
$ export TEST_OFFICIAL=true
$ pre-commit run -a
• To actually make the commit (this will trigger tests style & type checks automatically):
10.6.4 Documenting
The documentation of this project is separated in two sections: User facing and dev facing.
User facing docs are hosted at RTD. They are the main way the users of our library are supposed to get information
about the objects. They don’t care about the internals, they just want to know what they have to pass to make it
work, what it actually does. You can/should provide examples for non obvious cases (like the Filter module), and
notes/warnings.
Dev facing, on the other side, is for the devs/maintainers of this project. These doc strings don’t have a separate
documentation site they generate, instead, they document the actual code.
We use sphinx to generate static HTML docs. To build them, first make sure you have the required dependencies:
Once the process terminates, you can view the built documentation by opening docs/build/html/index.html
with a browser.
• Add .. versionadded:: version, .. versionchanged:: version or .. deprecated::
version to the associated documentation of your changes, depending on what kind of change you made.
This only applies if the change you made is visible to an end user. The directives should be added to
class/method descriptions if their general behaviour changed and to the description of all arguments &
attributes that changed.
We adhere to the CSI standard. This documentation is not fully implemented in the project, yet, but new code
changes should comply with the CSI standard. The idea behind this is to make it very easy for you/a random
maintainer or even a totally foreign person to drop anywhere into the code and more or less immediately understand
what a particular line does. This will make it easier for new to make relevant changes if said lines don’t do what
they are supposed to.
Assert statements should compare in actual == expected order. For example (assuming test_call is the thing
being tested):
# GOOD
assert test_call() == 5
# BAD
assert 5 == test_call()
Methods, functions and classes can specify optional parameters (with default values) using Python’s keyword arg
syntax. When providing a value to such a callable we prefer that the call also uses keyword arg syntax. For example:
# GOOD
f(0, optional=True)
# BAD
f(0, True)
This gives us the flexibility to re-order arguments and more importantly to add new required arguments. It’s also
more explicit and easier to read.
It’s always good to not initialize optional arguments at class creation, instead use **kwargs to get them. It’s well
known Telegram API can change without notice, in that case if a new argument is added it won’t break the API
classes. For example:
# GOOD
def __init__(self, id, name, last_name=None, **kwargs):
self.last_name = last_name
# BAD
def __init__(self, id, name, last_name=None):
self.last_name = last_name
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to
making participation in our project and our community a harassment-free experience for everyone, regardless
of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal
appearance, race, religion, or sexual identity and orientation.
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take
appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits,
issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently
any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
10.7.4 Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing
the project or its community. Examples of representing a project or community include using an official project
e-mail address, posting via an official social media account, or acting as an appointed representative at an online
or offline event. Representation of a project may be further defined and clarified by project maintainers.
10.7.5 Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team
at devs@python-telegram-bot.org. The project team will review and investigate all complaints, and will respond in
a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with
regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or per-
manent repercussions as determined by other members of the project’s leadership.
10.7.6 Attribution
This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-
covenant.org/version/1/4.
t
telegram, 21
telegram.constants, 440
telegram.error, 462
telegram.ext.filters, 388
telegram.helpers, 463
telegram.warnings, 470
571
python-telegram-bot Documentation, Release 20.0a4
573
python-telegram-bot Documentation, Release 20.0a4
574 Index
python-telegram-bot Documentation, Release 20.0a4
Index 575
python-telegram-bot Documentation, Release 20.0a4
576 Index
python-telegram-bot Documentation, Release 20.0a4
Index 577
python-telegram-bot Documentation, Release 20.0a4
578 Index
python-telegram-bot Documentation, Release 20.0a4
Index 579
python-telegram-bot Documentation, Release 20.0a4
580 Index
python-telegram-bot Documentation, Release 20.0a4
Index 581
python-telegram-bot Documentation, Release 20.0a4
582 Index
python-telegram-bot Documentation, Release 20.0a4
Index 583
python-telegram-bot Documentation, Release 20.0a4
584 Index
python-telegram-bot Documentation, Release 20.0a4
Index 585
python-telegram-bot Documentation, Release 20.0a4
586 Index
python-telegram-bot Documentation, Release 20.0a4
Index 587
python-telegram-bot Documentation, Release 20.0a4
588 Index
python-telegram-bot Documentation, Release 20.0a4
Index 589
python-telegram-bot Documentation, Release 20.0a4
590 Index
python-telegram-bot Documentation, Release 20.0a4
Index 591
python-telegram-bot Documentation, Release 20.0a4
592 Index
python-telegram-bot Documentation, Release 20.0a4
Index 593
python-telegram-bot Documentation, Release 20.0a4
594 Index
python-telegram-bot Documentation, Release 20.0a4
Index 595
python-telegram-bot Documentation, Release 20.0a4
596 Index
python-telegram-bot Documentation, Release 20.0a4
Index 597
python-telegram-bot Documentation, Release 20.0a4
598 Index
python-telegram-bot Documentation, Release 20.0a4
Index 599
python-telegram-bot Documentation, Release 20.0a4
600 Index
python-telegram-bot Documentation, Release 20.0a4
Index 601
python-telegram-bot Documentation, Release 20.0a4
602 Index
python-telegram-bot Documentation, Release 20.0a4
Index 603
python-telegram-bot Documentation, Release 20.0a4
604 Index
python-telegram-bot Documentation, Release 20.0a4
W
WAITING (telegram.ext.ConversationHandler at-
tribute), 386
watcher (telegram.ProximityAlertTriggered attribute),
228
WAV (telegram.ext.filters.Document attribute), 397
WEB_APP (telegram.constants.MenuButtonType at-
tribute), 451
Index 605