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

v13#1982

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Bibo-Joshi merged 9 commits intomasterfromv13
Oct 7, 2020
Merged

v13#1982

Bibo-Joshi merged 9 commits intomasterfromv13
Oct 7, 2020

Conversation

Bibo-Joshi
Copy link
Member

@Bibo-JoshiBibo-Joshi commentedJun 6, 2020
edited
Loading

For the moment I'm just here so that PRs to v13 can be properly checked by Codacy and Codecov.
When v13 is ready, I can be merged. For now, comment here to gather info for the coming v13 transition guide.

The PRs merged into v13:

@Bibo-JoshiBibo-Joshi added ⚙️ testsaffected functionality: tests 📋 do-not-merge-yetwork status: do-not-merge-yet labelsJun 6, 2020
@Bibo-JoshiBibo-Joshiforce-pushed thev13 branch 4 times, most recently from2a9a5b0 to1fdc197CompareJune 16, 2020 15:08
@Bibo-JoshiBibo-Joshiforce-pushed thev13 branch 2 times, most recently fromb3e9be1 tob7e635bCompareJune 25, 2020 05:56
@Bibo-Joshi
Copy link
MemberAuthor

API Keyword Arguments

Pre-v12 the Bot methods accepted arbitrarty keyword argument via the**kwargs parameter. This was to allow for minor API updates to work, while they were not implemented in PTB. However, this also lead to editors not highlighting typos. This is, why the**kwargs parameter was replaced byapi_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 wtih the Telegram API, this shouldn't affect your code in the most cases. If it does, it means that you had a typo somewhere.

@Bibo-Joshi
Copy link
MemberAuthor

Bibo-Joshi commentedJul 13, 2020
edited
Loading

  • Remove the job-storing snippet/add a note that it's outdated
  • Maybe add the "keep in mind" bullet points to the extensions page

JobQueue Refactored

Previously, PTB implemented the scheduling of tasks in theJobQueue manually. As timing logic is not always straightforward, maintaining theJobQueue was not easy and new features were added only reluctantly. This is, why in v13 theJobQueue was refactored to realy on the third pary libraryAPScheduler.

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

context.job_queue.run_once(callback,when)

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

Handling of timezones

TheAPScheduler library only accepts timezones provided by thepytz library. If you pass timezone 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 to use and ready to use way of scheduling tasks in a way that 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 thingies, youcan use these advanced features of the third party library
  • We can't guarantee that the backend 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 inlast kwarg forJobQueue.run_repeating method #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 most likely not affect you. For details, please see the documentation ofJobQueue andJob.

Setting up aJobQueue

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

@Bibo-JoshiBibo-Joshi mentioned this pull requestJul 13, 2020
@Bibo-Joshi
Copy link
MemberAuthor

Update wiki:

  • Add table of contents
  • Add the following note:

Storing Bots

As of v13, persistence will try to replacetelegram.Bot instances byREPLACED_BOT and
insert the bot set withset_bot upon loading of the data. This is to ensure that
changes to the bot apply to the saved objects, too. For example, you might change thedefault values used by the bot. If you change the bots token, this may
lead to e.g.Chat not found errors. For the limitations on replacing bots see
replace_bot andinsert_bot.

Persistence of Bots

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

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

In most cases, this won't directly affect you. Note however, that changing the used bot token may lead to e.g.Chat not found errors.

*Okay, almost all, For the limitations, seereplace_bot andinsert_bot.

@Bibo-Joshi
Copy link
MemberAuthor

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 alsomessage.chat is compared, 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, in most cases it shouldn't affect your code.

@Bibo-JoshiBibo-Joshiforce-pushed thev13 branch 2 times, most recently from1e29c1a to7867b9bCompareJuly 19, 2020 15:25
@Bibo-Joshi
Copy link
MemberAuthor

Deprecation ofMessage.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.

@Bibo-Joshi
Copy link
MemberAuthor

Bibo-Joshi commentedJul 28, 2020
edited
Loading

Update Wiki

Thispart on custom filters must be updated.

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)
  • telegram.ext.UpdateFilter, whereUpdateFilter.filter() accepts atelegram.Update object (theupdate),

both inheriting fromBaseFilter.

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

@Bibo-JoshiBibo-Joshiforce-pushed thev13 branch 2 times, most recently fromdcf7328 toad30a8fCompareAugust 16, 2020 17:43
@Bibo-Joshi
Copy link
MemberAuthor

Deprecation of old handler API

The context-based API introduced in v12 is now the default, i.e. theuse_context now defaults toTrue.

@Bibo-Joshi
Copy link
MemberAuthor

Dropping support for Python 3.5

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

@Bibo-Joshi
Copy link
MemberAuthor

Defaults.tzinfo

Update example in wiki:

importpytzimportdatetimeasdtmfromtelegramimportParseModefromtelegram.extimportUpdater,MessageHandler,Filters,Defaultsdefjob(context):chat_id=context.job.contextlocal_now=dtm.datetime.now(context.bot.defaults.tzinfo)utc_now=dtm.datetime.utcnow()text='Running job at {} in timezone {}, which equals {} UTC.'.format(local_now,context.bot.defaults.tzinfo,utc_now    )context.bot.send_message(chat_id=chat_id,text=text)defecho(update,context):# Send with default parse modeupdate.message.reply_text('<b>{}</b>'.format(update.message.text))# Override default parse mode locallyupdate.message.reply_text('*{}*'.format(update.message.text),parse_mode=ParseMode.MARKDOWN)update.message.reply_text('*{}*'.format(update.message.text),parse_mode=None)# Schedule jobcontext.job_queue.run_once(job,dtm.datetime.now()+dtm.timedelta(seconds=1),context=update.effective_chat.id)defmain():"""Instantiate a Defaults object"""defaults=Defaults(parse_mode=ParseMode.HTML,tzinfo=pytz.timezone('Europe/Berlin'))"""Start the bot."""updater=Updater("TOKEN",use_context=True,defaults=defaults)# Get the dispatcher to register handlersdp=updater.dispatcher# on non command text message - echo the message on Telegramdp.add_handler(MessageHandler(Filters.text&~Filters.command,echo))# Start the Botupdater.start_polling()updater.idle()if__name__=='__main__':main()

@Bibo-JoshiBibo-Joshiforce-pushed thev13 branch 2 times, most recently from3247477 tob7293a4CompareSeptember 27, 2020 15:32
@Bibo-Joshi
Copy link
MemberAuthor

  • Update the Performance optimization page to useDipsatcher.run_async instead

Deprecation of@run_async

It has been a long stanting issue that methods decorated with@run_async will not get 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 asychronously, 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,custom_function,a,update=update,b=b)

    Of course the use ofDispatcher.run_async is not limited to within 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_asyn will still work, we recommand to switch to the new syntax.

@Bibo-JoshiBibo-Joshi marked this pull request as ready for reviewOctober 6, 2020 16:07
@Bibo-JoshiBibo-Joshiforce-pushed thev13 branch 2 times, most recently from9252b0f tobce39ccCompareOctober 6, 2020 17:32
@Bibo-Joshi
Copy link
MemberAuthor

pytest fail is unrelated and codecov was expected. ready for merge 🕺

@Bibo-JoshiBibo-Joshi changed the titlev13 - Ignore mev13Oct 7, 2020
* Unify kwargs handling in Bot methods* Remove Request.get, make api_kwargs an explicit argument, move note to head of Bot class* Fix test_official* Update get_file methods
* First go on refactoring JobQueue* Temporarily enable tests for the v13 branch* Work on tests* Temporarily enable tests for the v13 branch* Increase coverage* Remove JobQueue.tick()* Address review* Temporarily enable tests for the v13 branch* Address review* Dispatch errors* Fix handling of job_kwargs* Remove possibility to pass a Bot to JobQueue
* Refactor persistence of bots* Use BP.set_bot in Dispatcher* Add documentation
* Make most objects comparable* ID attrs for PollAnswer* fix test_game* fix test_userprofilephotos* update for API 4.7* Warn on meaningless comparisons* Update for API 4.8* Address review* Get started on docs, update Message._id_attrs* Change PollOption & InputLocation* Some more changes* Even more changes
* Refactor handling of `default_quote`* Make it a breaking change* Pickle a bots defaults* Temporarily enable tests for the v13 branch* Temporarily enable tests for the v13 branch* Refactor handling of kwargs in Bot methods (#1924)* Unify kwargs handling in Bot methods* Remove Request.get, make api_kwargs an explicit argument, move note to head of Bot class* Fix test_official* Update get_file methods* Refactor JobQueue (#1981)* First go on refactoring JobQueue* Temporarily enable tests for the v13 branch* Work on tests* Temporarily enable tests for the v13 branch* Increase coverage* Remove JobQueue.tick()* Address review* Temporarily enable tests for the v13 branch* Address review* Dispatch errors* Fix handling of job_kwargs* Remove possibility to pass a Bot to JobQueue* Refactor persistence of Bot instances (#1994)* Refactor persistence of bots* User BP.set_bot in Dispatcher* Temporarily enable tests for the v13 branch* Add documentation* Add warning to Updater for passing both defaults and bot* Address review* Fix test
* Refactor handling of message vs update filters* address review
@Bibo-JoshiBibo-Joshi removed 📋 do-not-merge-yetwork status: do-not-merge-yet ⚙️ testsaffected functionality: tests labelsOct 7, 2020
@Bibo-JoshiBibo-Joshi merged commit5fd7606 intomasterOct 7, 2020
@Bibo-JoshiBibo-Joshi deleted the v13 branchOctober 7, 2020 18:30
@github-actionsgithub-actionsbot locked and limited conversation to collaboratorsOct 9, 2020
Sign up for freeto subscribe to this conversation on GitHub. Already have an account?Sign in.
Reviewers
No reviews
Assignees
No one assigned
Labels
None yet
Projects
None yet
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

[BUG] Errors in Job callbacks are not passed to error handler Refactor JobQueue [BUG] Behaviour of kwargs in bot methods
1 participant
@Bibo-Joshi

[8]ページ先頭

©2009-2025 Movatter.jp