【问题标题】:How to write the callback function of a telegram bot for the job queue?如何为作业队列编写电报机器人的回调函数?
【发布时间】:2017-11-06 13:30:20
【问题描述】:

我对 job queue 这件事感到困惑。在回调函数中,我想访问用户消息并对其进行处理,但在文章中说回调只接受机器人和作业参数。与那些在手的我无法访问update.message.text。因此,例如,我想将以下函数重写为我无法弄清楚的回调函数:

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

我在这里缺少什么?

【问题讨论】:

    标签: python telegram-bot python-telegram-bot job-queue


    【解决方案1】:

    您必须在创建作业时传递上下文。

    您可以阅读页面底部附近的示例here

    >>> 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)
    

    当您使用run_oncerun_dailyrun_repeating 函数时,您可以将任何内容(包括电报对象、列表/字典等)传递到作业的context。然后在你的回调函数中你必须按照你说的传递2个参数,botjob,然后通过访问job.context获取你需要的数据。

    【讨论】:

    • 在示例中仅传递了 chat_id。如何将多个项目传递给它?
    • 你可以传递任何东西,例如整个更新:context=update,或者你创建的字典:context={"chat_id": update.message.chat_id, "text": update.message.text, "custom_stuff": "some other text"},或者实际上你想传递的任何东西,把它们当作普通的python变量是可以的;然后你可以在你的回调函数中得到它:update = job.contextstuff = job.context["custom_stuff"],等等。
    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 2017-08-18
    • 2020-07-23
    相关资源
    最近更新 更多