Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Transition guide to Version 20.0

ezugwuernesttoc edited this pageDec 4, 2024 ·30 revisions

Introduction

This transition guide aims to easy transitions from v13.x to v20.0 by listing relevant changes between these versions.It's important to note that this transition guide will not cover every last one of the many smaller changes that came along with the bigger structural changes.If you notice that some non trivial change is missing in here, feel free to add it.

Table of contents

Transition Script

We have prepared a script that is aimed at easing the transition for you.Note that this script currently just does some regex-based search & replace take some of the transition work off your shoulders.It is no way a substitute for reading this transition guide and manually adjusting your code base.In addition to the script, we recommend using a language interpreter (e.g.pylint) and a static type checker (e.g.mypy) on your code base to minimize the trial-and-error time during transitioning at a minimum.You can find the scripthere.

Contributions that fine tune or extend the script are welcome (you must clone the wiki repo to make changes)!

Structural changes & Deprecations

Overall architecture

ext.Updater is no longer the entry point to a PTB program and we have replaced theext.Dispatcher class with the new classext.Application.

TheApplication is the new entry point to a PTB program and binds all its components together. The following diagram gives you an overview.

Click to show the diagram

When initializing anApplication, many settings can be configured for the individual components.In an effort to make this instantiation both clear and clean, we adopted the so-calledbuilder pattern.This means that instead of passing arguments directly toApplication, one creates a builder viaApplication.builder() and then specifies all required arguments via that builder.Finally, theApplication is created by callingbuilder.build(). A simple example is

fromtelegram.extimportApplication,CommandHandlerapplication=Application.builder().token('TOKEN').build()application.add_handler(CommandHandler('start',start_callback))application.run_polling()

We hope that this design makes it easier for you to understand what goes where and also simplifies setups of customized solutions, e.g. if you want to use a custom webhook.

There is also astandalone wiki page just about this topic.

asyncio

The deepest structural change is introducing theasyncio module intopython-telegram-bot.

asyncio is a library to write concurrent code using theasync/await syntax.

What does this mean and why do we care?

python-telegram-bot is a library with the main purpose of communicating with the Telegram Bot API via web requests.When making web requests, your code usually spends alot of time with - waiting.Namely, waiting for a response from Telegram.The same holds for many so-called input-output (I/O) tasks.Instead of sitting around, your program could already do other stuff in that time.

So far, PTB has build on thethreading library to overcome this issue.

asyncio is a modern alternative tothreading that comes with multiple advantages.Covering those or an introduction to how usingasyncio works, is sadly beyond the scope of this transition guide or the PTB resources in general.Searching forpython asyncio introduction orpython asyncio vs threading in your favorite search engine will yield numerous results that will help you get up to speed.

The main points of whatasyncio changed in PTB are:

  • PTB doesn't use threads anymore. It is also not thread safe!
  • All API methods oftelegram.Bot are now coroutine functions, i.e. you have toawait them
  • All handler & job callbacks must be coroutine functions, i.e. you need to changedef callback(update, context) toasync def callback(update, context).
  • therun_async parameter of the handlers was replaced by theblock parameter, which has a similar functionality. More details on this can be found onthis page.
  • The methodDispatcher.run_async doesn't exist anymore. Something that comes close to its functionality isApplication.create_task (more onApplication below). More details on this can be found onthis page.
  • All methods that make calls to coroutines or perform any I/O bound tasks are now coroutine functions.This includes all abstract methods ofBasePersistence. Listing them all here would be too long. When in doubt, please consult the documentation atReadTheDocs.

Optional Dependencies

Some of the functionality of thetelegram andtelegram.ext modules rely on 3rd party dependencies.Since these features are optional to use and we aim to keep the footprint ofpython-telegram-bot small, we have reduced the number of 3rd party dependencies that automatically get's installed along withpython-telegram-bot to a minimum.As of v20.0a5, only the 3rd party libraryhttpx is installed, which is used for the default networking backendHTTPXRequest.If you wish to use any of the optional features of thetelegram andtelegram.ext modules, you will have to specify that while installingpython-telegram-bot from now on.Please have a look atthe readme for further details.

Refinement of the public API

We've made an effort to make it clearer which parts ofpython-telegram-bot can be considered to be part of the public interface that users are allowed to use. To phrase it the other way around: Which parts are internals ofpython-telegram-bot are implementation details that might change without notice. Notably this means:

  1. Only non-private modules are part of the public API and you should import classes & functions the way they are described in the docs. E.g.from telegram.error import TelegramError is fine, butfrom telegram._message import Message is strongly discouraged - usefrom telegram import Message instead.
  2. We have removed the moduletelegram.utils. The parts of this module that we consider to be part of the public API have been moved into the modulestelegram.{helpers, request, warnings}.

__slots__

We introduced the usage of__slots__ in v13.6, which can reduce memory usage and improve performance. In v20 we removed the ability to set custom attributes on all objects except forext.CallbackContext. To store data, we recommend to use PTB's built-in mechanism forstoring data instead. If you want to add additional functionality to some class, we suggest subclassing it.

Keyword-Only arguments

Since v20.0a1, all arguments of bot methods that were added by PTB are now keyword-only arguments.Most importantly, this covers the*_timeout andapi_kwargs arguments.

Initialization of Telegram Classes

Since v20.0a5,TelegramObject and it's subclasses no longer accept arbitrary keyword arguments (**kwargs). These were formerly used to ensure that PTB wouldn't break when Telegram added new fields to existing classes.Instead,TelegramObject and it's subclasses now have an argumentapi_kwargs that will be used to store fields that are passed by Telegram and that PTB did not yet incorporate. These fields will also be available via theapi_kwargsattribute.

Immutability

Any data objects received by Telegram represent a current state on the Telegram servers, that only be changed by making a request to Telegram (or even not at all).We hence decided to makeTelegramObject and all of its subclasses immutable, meaning:

  • Attributes of these classes can neither be changed nor deleted. For exampleupdate.message = new_message ordel update.message will both raiseAttributeErrors
  • Any attributes that contain a list/an array of items are now of the immutable typetuple. For example,Message.photo is now atuple instead of alist
  • All API methods of thetelegram.Bot class that return a list/an array of items now return an immutabletuple. For example, the return value ofget_chat_administrators is now atuple instead of alist

If these changes have an effect on your current code, we highly recommend to overthink your code design.Keep in mind that for storing data in memory, PTB provides a handybuilt-in solution.

These changes were introduced in v20.0b0.

Removed features

We made a cut and dropped all deprecated functionality. Most importantly, this includes the old-style handler API, which was deprecated inVersion 12, and theMessageQueue. As replacement for theMessageQueue,telegram.ext.{Base, AIO}RateLimiter where introduced in v20.0a3 (see alsothis wiki page).

Changes for specific modules, classes & functions

telegram

Previously some parts oftelegram.{error, constants} where available directly via thetelegram package - e.g.from telegram import TelegramError. These imports will no longer work. Only classes that directly reflect the official Bot API are now available directly via thetelegram package. Constants and errors are available via the modulestelegram.{error, constants} - e.g.from telegram.error import TelegramError.

Several classes

Previously, some classes (liketelegram.{Message, User, Chat}) had an attributebot that was used for the shortcuts (e.g.Message.reply_text). This attribute was removed.Instead, the new methodTelegramObject.{set, get}_bot() are used.

Networking backend

Previously, the classtelegram.utils.request.Request formed the networking backend of PTB.This class has been removed.Instead, there is the new moduletelegram.request, which contains an interface classBaseRequest as well as an implementationHTTPXRequest of that class via thehttpx library.By default, theHTTPXRequest class is used for the networking backend.Advanced users may use a custom backend by implementing a custom subclass ofBaseRequest.Seethis page for more information on that.

telegram.ChatAction

This class was removed as it is not part of the official Bot API. Usetelegram.constants.ChatAction instead.

telegram.constants

This module was rewritten from scratch. The constants are now grouped with the help ofEnums.

telegram.Bot

  • The class has a new argumentget_updates_request in addition torequest and the corresponding request instance will be used exclusively for callinggetUpdates.
  • The argumentmedia ofBot.edit_message_media is now the first positional argument as specified by the Bot API.
  • The argumenturl ofBot.set_webhook is now required as specified by the Bot API.
  • The argumentdescription ofBot.set_chat_description is now optional as specified by the Bot API.

telegram.EncryptedPassportElement

The argumenthash is now the second positional argument as specified by the Bot API.

telegram.error

telegram.error.Unauthorized was replaced bytelegram.error.Forbidden.Moreover,telegram.error.Forbidden is now only raised if your bot tries to perform actions that it doesn't have enough rights for.In case your bot token is invalid,telegram.error.InvalidToken is raised.

telegram.File

The methodFile.download was split into the two methodsFile.download_to_drive andFile.download_to_memory.Fordownload_to_drive, thecustom_path parameter now also acceptspathlib.Path objects.Moreover instead of returning the file path as string, it's now returned aspathlib.Path object.

telegram.ForceReply

The argumentforce_reply was removed, since italways must beTrue anyway.

telegram.InlineQuery.answer

If both parameterscurrent_offset andauto_pagination are supplied, the method now raises aValueError rather than aTypeError.

telegram.InputFile.is_image

This method was removed in v20.0a1.

telegram.ParseMode

This class was removed as it is not part of the official Bot API. Usetelegram.constants.ParseMode instead.

telegram.PassportFile

The argumentfile_size is now optional as specified by the Bot API.

telegram.ReplyMarkup

This class was removed as it is not part of the official Bot API.

telegram.VideoChat

The argumentusers is now optional as specified by the Bot API.

telegram.ext

BasePersistence

asyncio

All abstract methods are now coroutine functions as implementations should be able to perform I/O tasks in a non-blocking way.

Data must be copyable

Any data passed to persistence will be copied withcopy.deepcopy.This requirement is in place to avoid race conditions.

Persistingtelegram.Bot instances.

InVersion 13, we introduced a mechanism that replaces anytelegram.Bot instance with a placeholder automaticallybeforeupdate_*_data was called and inserts the instance back into the return value ofget_*_data. Unfortunately, this mechanism has proven to be unstable and also slow.

We have therefore decided to remove this functionality.Bot instances should still not be serialized, but handling this is now the responsibility of the specific implementation ofBasePersistence. For example,ext.PicklePersistence uses the built-in functionality of thepickle module to achieve the same effect in a more reliable way.

More detailed information on this can be found in the documentation of{Base, Pickle}Persistence.

Return value ofget_{user, chat}_data

BasePersistence.get_{user, chat}_data are no longer expected to returncollections.defaultdict. Instead, they may return plaindicts.

Abstract methods

BasePersistence made a full transition to an abstract base class. This means that now all methods that a subclass should implement are marked asabc.abstractmethod. If e.g. you don't needupdate_bot_data because your persistence class is not supposed to storebot_data, you will still have to override that method, but you can simply make itpass.

store_*_data

The parameters & attributesstore_{user,chat,bot}_data were removed. Instead, these settings were combined into the argument/attributestore_data, which accepts an instance of the new helper classtelegram.ext.PersistenceInput.

Note thatcallback_data is now persisted by default.

CallbackContext

  • CallbackContext.from_error has a new optional argumentjob. When an exception happens inside aext.Job callback, this parameter will be passed.
  • Accordingly, the attributeCallbackContext.job will now also be present in error handlers if the error was caused by aext.Job.
  • v20.0a1 removed the constantCallbackContext.DEFAULT_TYPE. That constant can now be found asContextTypes.DEFAULT_TYPE.

CommandHandler

The attributecommands was made immutable in v20.0a1.

ConversationHandler

ConversationHandler now raises warnings for more handlers which are added in the wrong context/shouldn't be in the handler at all.

filters

Theext.filters module was rewritten almost from scratch and uses a new namespace policy. The changes are roughly as follows:

  1. telegram.ext.Filters no longer exists. Instead, use the moduletelegram.ext.filters directly. For example,Filters.text has to be replaced byfilters.TEXT
  2. Already instantiated filters that don't need arguments are now inSCREAMING_SNAKE_CASE, e.g.filters.TEXT. Filterclasses that do need arguments to be used are now inCamelCase, e.g.filters.User.
  3. For filters that are closely related, we now use a namespace class to group them. For example,filters.Document can not be used inMessageHandler. To filter for messages withany document attached, usefilters.Document.ALL instead.

Moreover, filters are no longer callable. To check if a filter accepts an update, use the new syntaxmy_filter.check_update(update) instead.

Handler

v20.0a1 renamed the classHandler toBaseHandler in an effort to emphasize that this class is an abstract base class.

PrefixHandler

Since v20.0a1, this is no longer a subclass ofCommandHandler.Moreover, the prefixes and commands are no longer mutable.

JobQueue

New arguments{chat, user}_id

All scheduling methods (JobQueue.run_*) have two new arguments{chat, user}_id, which allows to easily associate a user/chat with a job. By specifying these arguments, the corresponding ID will be available in the job callback viacontext.job.{chat, user}_id.

Moreover,context.{chat, user}_data will be available. This has some subtle advantages over the previous workaroundjob_queue.run_*(..., context=context.chat_data) and we recommend using this new feature instead.

context argument

To address the frequent confusion aboutcontext vscontext.job.context, v20.0a1 renamed the argumentcontext of allJobQueue.run_* methods todata.This also covers the corresponding attribute ofJob.

Job.run_daily

Since v20.0a1, the behavior of this method is aligned withcron, i.e. 0 is Sunday and 6 is Saturday.

JobQueue.run_monthly

Unfortunately, theday_is_strict argument was not working correctly (see#2627) and was therefore removed. Instead, you can now passday='last' to make the job run on the last day of the month.

Job

Removed the attributejob_queue

This was removed because if you have access to a job, then you also have access to either theJobQueue directly or at least aCallbackContext instance, which already contains thejob_queue.

AttributeJob.context

To address the frequent confusion aboutcontext vscontext.job.context, v20.0a1 renamed the argumentcontext of allJobQueue.run_* methods todata and renamedJob.context toJob.data.

PicklePersistence

  • The argumentfilename was renamed tofilepath and now also accepts apathlib.Path object
  • Changes toBasePersistence also affect this class.

We have prepared a script that will help you convert your v13 pickle-files into v20 pickle files.Note that this script is a best-effort solution for a conversion - for some special cases, a conversion may not be possible without adjusting the v13 data before.You can find the scripthere.

Updater

The sole purpose of this class now is to fetch updates from Telegram. It now only accepts the argumentsbot andupdate_queue and only has those attributes.

Application/Dispatcher

user/chat_data

If you were modifying theuser/chat_data ofDispatcher directly e.g. by doingcontext.dispatcher.chat_data[id] = ..., then this will now not work.Application.user/chat_data is now read only. Note thatcontext.chat/user_data[key] = ... will still work.

Wiki ofpython-telegram-bot © Copyright 2015-2025 – Licensed byCreative Commons

Must read

  1. Introduction to the API
  2. Tutorial: Your first bot
  3. FAQ
  4. How to ask good questions
  5. How to write an MWE

Concepts & Important Elements

  1. Architecture Overview
  2. Builder Pattern forApplication
  3. Types of Handlers
  4. Working with Files and Media
  5. Exceptions, Warnings and Logging
  6. Concurrency in PTB

Notable Features

  1. Advanced Filters
  2. Storing data
  3. Making your bot persistent
  4. Adding Defaults
  5. Job Queue
  6. Arbitrarycallback_data
  7. Avoiding flood limits
  8. Webhooks
  9. Bot API Forward Compatiblity

Code Resources

  1. Frequently requested design patterns
  2. Code snippets
  3. Performance Optimizations
  4. Telegram Passport
  5. Bots built with PTB
  6. Automated Bot Tests

Examples explained

  1. InlineKeyboard Example

Networking

  1. Working Behind a Proxy
  2. Handling network errors

Other resources

  1. Where to host Telegram Bots
  2. How to host your bot
  3. Local API Server
  4. Type Checking with PTB
  5. Press
  6. Notes on GAE
  7. Related Projects
  8. Emoji

Transition Guides

Administration

Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp