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 13.0

Harshil edited this pageMar 25, 2023 ·20 revisions

Table of contents

Deprecations

Old handler API

The context-based API introduced in v12 is now the default, i.e. theuse_context argument of theDispatcher/Updater now defaults toTrue.

Python 3.5

As Python 3.5 reached its end of life on 2020-09-05, v13 drops support for Python 3.5. More precisely, some Python 3.6+-only features are introduced, making PTB incompatible with Python 3.5 as of v13.

Message.default_quote

Message objects no longer have adefault_quote attribute. Instead,Message.bot.defaults.quote is used. This happened in accordance with the refactoring of persistence of Bots.

@run_async

It has been a long-standing issue that methods decorated with@run_async have not received proper error handling. We therefore decided todeprecate the decorator. To run functions asynchronously, you now have two options, both of which support error handling:

  1. All theHandler classes have a new parameterrun_async. By instantiating your handler as e.g.CommandHandler('start', start, run_async=True), the callback (herestart) will be run asynchronously.

  2. To run custom functions asynchronously, you can useDispatcher.run_async. Here is a small example:

    defcustom_function(a,b=None):passdefmy_callback(update,context):a=7b='b'context.dispatcher.run_async(custom_function,a,update=update,b=b)

    Of course the use ofDispatcher.run_async is not limited to handler callbacks and you don't have to pass anupdate in that case. Passing theupdate when possible is just preferable because that way it's available in the error handlers.

While@run_async will still work, we recommend switching to the new syntax, as the decorator will be deprecated over the course of the next releases.

Persistence of Bots

StoringBot objects (directly or e.g. as attributes of an PTB object) may lead to problems. For example, if you changetheDefaults object passed to yourUpdater, you would expect the loadedBot instances to use the new defaults.For that reason, v13 makes two changes:

  1. Bot instances are no longer picklable
  2. Instead, all subclasses ofBasePersistence will replace all*Bot instances with a placeholder. When loading the data again,the newBot instance will be inserted.

Note that changing the used bot token may lead to e.g.Chat not found errors.

*Alright, almost all instances. For the limitations, seereplace_bot andinsert_bot.

Converting existing pickle files

In order for v13sPicklePersistence to be able to read your pickle files, you need to convert them oncebefore upgrading to v13.* We have prepared aGist for that. Usethis version, if you're upgrading directly to v13.1. This is of course only needed if you storeBot instances somewhere. But if you're not sure, just run the Gist ;)

If you have a custom implementation ofBasePersistence and you currently storeBot instances (or any PTB object that has abot attribute, e.g.Message), you may need to do something similar. The above Gist is a good starting point in that case.

*This is due to the fact thatPicklePersistence usesdeepcopy, which in turn uses the same interface aspickle andBots are no longer pickable in v13…

API Keyword Arguments

Pre v13, the Bot methods accepted arbitrary keyword arguments via the**kwargs parameter. This was implemented in order to allow for minor API updates to be patched into PTB calls while there was no release of the library just yet. However, this also lead to editors not highlighting typos. For this reason, the**kwargs parameter was replaced by theapi_kwargs parameter. This means that function calls like

bot.send_message(...,custom_kwarg=42)

need to be changed to

bot.send_message(...,api_kwargs={'custom_kwarg':42})

As PTB is currently up to date with the Telegram API, this shouldn't affect your code. If it does, it probably means that you had a typo somewhere ;)

JobQueue Refactored

Previously, PTB implemented the scheduling of tasks inside theJobQueue manually. As timing logic is not always straightforward, maintaining theJobQueue was not easy and new features were only reluctantly added. To decrease development effort in that area, we refactored theJobQueue in v13. Now, it relies on the third party libraryAPScheduler behind the scenes.

But what does this mean for you in detail? If you're scheduling tasks vanilla style as e.g.

context.job_queue.run_once(callback,when)

you will only have to change the handling of time zones, or likely nothing at all. In fact, everything covered in thiswiki article will work unchanged except for time zones. So before bothering to read on, just try to run you bot - in most cases it will still work. However, there are some more advanced things which changed.

Handling of time zones

TheAPScheduler library only accepts time zones provided by thepytz library. If you pass time zone aware objects for job creating, you will need to take that into account.

Changes in advanced scheduling

Leveraging the APScheduler library brings both some perks in terms of new features as well as some breaking changes. Please keep in mind:

  • PTBsJobQueue provides an easy and ready to use way of scheduling tasks which ties in with the PTB architecture
  • Managing scheduling logic is not the main intend of PTB and hence a third party library is used for that now
  • If you need highly customized scheduling, youcan use these advanced features of the third party library
  • We can't guarantee that the back end will stay the same forever. For example, if APScheduler is discontinued, we will have to look for alternatives.

That said, here are the perks and changes:

New features

  • run_repeating now has alast parameter as originally proposed in #1333
  • JobQueue.run_custom allows you to run a job with a custom scheduling logic. See the APSUser Guide and the page onhow to combine triggers for more details.
  • All methodsJobQueue.run_* now have ajob_kwargs argument that accepts a dictionary. Use this to specify additional kwargs forJobQueue.scheduler.add_job().
  • Persistence of jobs: APScheduler has it's own logic of persisting jobs. Because of the aforementioned reasons, we decided to not integrate this logic with PTBs own persistence logic (at least for now). You may however set up persistence for jobs yourself. See the APSUser Guide for details.

Changes

Most importantly, theJob class is now a wrapper for APSchedulers ownJob class, i.e.job.job is anapscheduler.job (don't get confused here!). In particular, attributes likedays,interval andis_monthly were removed. Some of those could previously be used to alter the scheduling of the job. You will now have to usejob.job.modify for that. Please see theAPScheduler docs for details.

There are some other minor changes, most of which will likely not affect you. For details, please see the documentation ofJobQueue andJob.

Setting up aJobQueue

Passing aBot instance to theJobQueue has been deprecated for a while now. v13 removes this completely. UseJobQueue.set_dispatcher() instead.

Rich Comparison

v13 adds rich comparison to more Telegram objects. This means that e.g.inline_keyboard_1 == inline_keyboard_2 is not equivalent toinline_keyboard_1 is inline_keyboard_2, but all the buttons will be compared. For each class supporting rich comparison, the documentation now explicitly states how equality of the class objects is determined. Warnings will be raised when trying to compare Telegram objects that don't support rich comparison.

Special note onMessage

Pre-v13, comparingMessage objects only compared themessage_id. As those are not globally unique, as of v13,message.chat is compared as well, i.e. messages with the samemessage_id sent in different chats are no longer evaluated as equal. While strictly speaking this is a breaking change, it shouldn't affect your code.

Refactoring of Filters

In order to reduce confusion over the arguments of thefilter() method, the handling of message filters vs update filters was refined. v13 brings two classes

  • telegram.ext.MessageFilter, whereMessageFilter.filter() accepts atelegram.Message object (theupdate.effective_message)

and

  • telegram.ext.UpdateFilter, whereUpdateFilter.filter() accepts atelegram.Update object (theupdate),

both inheriting fromBaseFilter.

If you have custom filters inheriting fromBaseFilter, you will need to change their parent class toMessageFilter or, if you're currently settingupdate_filter = True, toUpdateFilter. In that case, you can remove theupdate_filter = True.

Special Note onUpdater.start_webhook

If you're upgrading directly to v13.4+ and use something like

updater.start_webhook(…)updater.bot.set_webhook(my_url)

you will have to change that to

updater.start_webhook(…,webhook_url=my_url)

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