【问题标题】:Unable to pass args to context.job_queue.run_once in Python Telegram bot API无法在 Python Telegram bot API 中将参数传递给 context.job_queue.run_once
【发布时间】:2021-06-15 15:45:21
【问题描述】:

在下面的代码中,我们如何将context.argscontext 传递给另一个函数,在本例中为callback_search_msgs

def search_msgs(update, context):
    print('In TG, args', context.args)
    context.job_queue.run_once(callback_search_msgs, 1, context=context, job_kwargs={'keys': context.args})

def callback_search_msgs(context, keys):
    print('Args', keys)
    chat_id = context.job.context
    print('Chat ID ', chat_id)

def main():
    updater = Updater(token, use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("search_msgs",search_msgs, pass_job_queue=True,
                                  pass_user_data=True))

    updater.start_polling()
    updater.idle()


if __name__ == '__main__':
    main()

【问题讨论】:

    标签: telegram telegram-bot python-telegram-bot


    【解决方案1】:

    几点说明:

    • 作业回调只接受一个CallbackContext 类型的参数。不是两个。
    • job_kwargs 参数用于将关键字参数传递给 APScheduler 后端,JobQueue 是在该后端构建的。您尝试使用它的方式不起作用。
    • 如果您只想知道作业中的chat_id,则不必传递search_msgs 的整个context 参数。就做context.job_queue.run_once(..., context=chat_id,...)
    • 如果你想通过chat_idcontext.args你可以例如将它们作为元组传递:
      job_queue.run_once(..., context=(chat_id, context.args), ...)
      
      然后通过chat_id, args = context.job.context 在作业中检索它们。
    • 由于您使用的是 use_context=True(这是 v13+ 中的默认设置,顺便说一句),CommandHandler(或任何其他处理程序)的 pass_* 参数根本没有任何效果。

    建议仔细阅读


    免责声明:我目前是python-telegram-bot的维护者

    【讨论】:

      猜你喜欢
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 2011-08-31
      • 2016-02-23
      • 1970-01-01
      相关资源
      最近更新 更多