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

Extensions JobQueue

MoHamMad edited this pageAug 20, 2024 ·6 revisions

Introduction

The extension classtelegram.ext.JobQueue allows you to perform tasks with a delay or even periodically, at a set interval. Among many other things, you can use it to send regular updates to your subscribers.

When working withJobQueue, 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 as of v13 a third party library is used
  • If you need highly customized scheduling thingies, youcan use advanced features of the third party library
  • We can't guarantee that the backend will stay the same forever. For example, if the third party library is discontinued, we will have to look for alternatives.

Example

In addition to the tutorial below, there is also thetimerbot.py example at theexamples directory.

Usage

Warning

Since v20, you must install PTB with the optional requirementjob-queue, i.e.

pip install python-telegram-bot[job-queue]

TheJobQueue class is tightly integrated with othertelegram.ext classes.

To use theJobQueue, you don't have to do much. When you build theApplication, it will create aJobQueue for you:

fromtelegram.extimportApplicationapplication=Application.builder().token('TOKEN').build()job_queue=application.job_queue

Just know that unless you have a good reason to do so, you should not instantiateJobQueue yourself.

Tasks in the job queue are encapsulated by theJob class. It takes acallback function as a parameter, which will be executed when the time comes. This callback function always takes exactly one parameter:context, atelegram.ext.CallbackContext. Like in the case of handler callbacks used by theApplication, through this object you can access

  • context.bot, theApplication'stelegram.Bot instance
  • context.job_queue, the same object asapplication.job_queue above
  • and for this particular case you can also accesscontext.job, which is theJob instance of the task that triggered the callback (more on that later).

You can use the following methods to create jobs with different frequency and time:job_queue.run_once,job_queue.run_repeating,job_queue.run_daily andjob_queue.run_monthly. (As before, you do not usually need to instantiate theJob class directly.)

Tutorial

Add your first job to the queue by defining a callback function and adding it to the job queue. For this tutorial, you can replace'@examplechannel' with a channel where your bot is an admin, or by your user id (use@userinfobot to find out your user id):

fromtelegram.extimportContextTypes,Applicationasyncdefcallback_minute(context:ContextTypes.DEFAULT_TYPE):awaitcontext.bot.send_message(chat_id='@examplechannel',text='One message every minute')application=Application.builder().token('TOKEN').build()job_queue=application.job_queuejob_minute=job_queue.run_repeating(callback_minute,interval=60,first=10)application.run_polling()

Thecallback_minute function will be executed every60.0 seconds, the first time being after 10 seconds (because offirst=10). Theinterval andfirst parameters are in seconds if they areint orfloat. They can also bedatetime objects. See thedocs for detailed explanation.The return value of these functions are theJob objects being created. You don't need to store the result ofrun_repeating (which is the newly instantiatedJob) if you don't need it; we will make use of it later in this tutorial.

You can also add a job that will be executed only once, with a delay:

fromtelegram.extimportContextTypes,Applicationasyncdefcallback_30(context:ContextTypes.DEFAULT_TYPE):awaitcontext.bot.send_message(chat_id='@examplechannel',text='A single message with 30s delay')application=Application.builder().token('TOKEN').build()job_queue=application.job_queuejob_queue.run_once(callback_30,30)application.run_polling()

In thirty seconds, you should receive the message fromcallback_30.

If you are tired of receiving a message every minute, you can temporarily disable a job or even completely remove it from the queue:

job_minute.enabled=False# Temporarily disable this jobjob_minute.schedule_removal()# Remove this job completely

Caution

schedule_removal does not immediately remove the job from the queue. Instead, it is marked for removal and will be removed as soon as its current interval is over (it will not run again after being marked for removal).

You might want to add jobs in response to certain user input, and there is a convenient way to do that. Thecontext argument of yourHandler callbacks has theJobQueue attached ascontext.job_queue ready to be used. Another feature you can use here are thedata,chat_id oruser_id keyword arguments ofJob. You can pass any object as adata parameter when you launch aJob and retrieve it at a later stage as long as theJob exists. Thechat_id/user_id parameter allows for an easy way to let theJob know which chat we're talking about. This way, we can accesscontext.chat_data/context.user_data in the job'scallback. Let's see how it looks in code:

fromtelegramimportUpdatefromtelegram.extimportCommandHandler,Application,ContextTypesasyncdefcallback_alarm(context:ContextTypes.DEFAULT_TYPE):# Beep the person who called this alarm:awaitcontext.bot.send_message(chat_id=context.job.chat_id,text=f'BEEP{context.job.data}!')asyncdefcallback_timer(update:Update,context:ContextTypes.DEFAULT_TYPE):chat_id=update.message.chat_idname=update.effective_chat.full_nameawaitcontext.bot.send_message(chat_id=chat_id,text='Setting a timer for 1 minute!')# Set the alarm:context.job_queue.run_once(callback_alarm,60,data=name,chat_id=chat_id)application=Application.builder().token('TOKEN').build()timer_handler=CommandHandler('timer',callback_timer)application.add_handler(timer_handler)application.run_polling()

By placing thechat_id in theJob object, the callback function knows where it should send the message.

All good things must come to an end, so when you stop the Application, the related job queue will be stopped as well.

Persistent Job Queues

PTBsPersistence Setup currently does not support serialization of jobs.However, the current backend of theJobQueue, namely theAPScheduler library has a mechanism for that, which you can leverage.Check out e.g.ptbcontrib/ptb_jobstores for an example implementation.

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