pythontelegram-botpython-telegram-botjob-queue

How to write the callback function of a telegram bot for the job queue?


I'm confused about this job queue thing. In the callback function I want to get access to the users message and work on it but in the article says that the call back accepts only bot and job parameters. with those in hand I can not get access to the update.message.text. So for example I want to rewrite the following function as a callback one which I can't figure it out:

def echo(bot,update):
    if tldextract.extract(update.message.text).registered_domain:
        bot.send_message(chat_id= update.message.chat_id, text="OK")

What am I missing here?


Solution

  • You have to pass the context when you create the job.

    You can read from the example here near the bottom of the page:

    >>> from telegram.ext import CommandHandler
    >>> def callback_alarm(bot, job):
    ...     bot.send_message(chat_id=job.context, text='BEEP')
    ...
    >>> def callback_timer(bot, update, job_queue):
    ...     bot.send_message(chat_id=update.message.chat_id,
    ...                      text='Setting a timer for 1 minute!')
    ... 
    ...     job_queue.run_once(callback_alarm, 60, context=update.message.chat_id)
    ...
    >>> timer_handler = CommandHandler('timer', callback_timer, pass_job_queue=True)
    >>> u.dispatcher.add_handler(timer_handler)
    

    You can pass anything (including telegram objects, list/dicts, etc) into the job's context when you use the run_once, run_daily and run_repeating functions. Then in your callback function you must pass 2 parameters as you said, bot and job, then get the data you need by accessing job.context.