无法将参数传递给 Python Telegram bot API 中的 context.job_queue.run_once
Unable to pass args to context.job_queue.run_once in Python Telegram bot API
在下面的代码中,我们如何将 context.args
和 context
传递给另一个函数,在本例中为 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()
一些注意事项:
- 作业回调只接受一个
CallbackContext
类型的参数。不是两个。
job_kwargs
参数用于将 keywoard 参数传递给 APScheduler 后端,JobQueue
建立在该后端上。您尝试使用它的方式不起作用。
- 如果您只想知道作业中的
chat_id
,则不必传递 search_msgs
的整个 context
参数。只要做 context.job_queue.run_once(..., context=chat_id,...)
- 如果你想同时传递
chat_id
和 context.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
的维护者
在下面的代码中,我们如何将 context.args
和 context
传递给另一个函数,在本例中为 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()
一些注意事项:
- 作业回调只接受一个
CallbackContext
类型的参数。不是两个。 job_kwargs
参数用于将 keywoard 参数传递给 APScheduler 后端,JobQueue
建立在该后端上。您尝试使用它的方式不起作用。- 如果您只想知道作业中的
chat_id
,则不必传递search_msgs
的整个context
参数。只要做context.job_queue.run_once(..., context=chat_id,...)
- 如果你想同时传递
chat_id
和context.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