【问题标题】:context.job_queue.run_once not working in Python Telegram BOT APIcontext.job_queue.run_once 在 Python Telegram BOT API 中不起作用
【发布时间】:2021-08-24 11:07:09
【问题描述】:

我正在尝试设置一个机器人:

  1. 从 TG 组接收/search_msgs userkey 命令中的关键字
  2. 在 DB 中搜索 userkey 并将相应的文本发回

我遇到了两个错误

  1. None类型对象没有属性args,在callback_search_msgs(context),见代码sn-p
  2. AttributeError: 'int' object has no attribute 'job_queue', in search_msgs(update, context),见代码 sn-p。

Telegram 的官方文档对我来说太难阅读和理解了。连一个地方都找不到 Updater、update、Commandhandler、context 都用例子来解释的地方。

如何修复此代码?

import telegram
from telegram.ext import Updater,CommandHandler, JobQueue

token = "Token"
bot = telegram.Bot(token=token)

# Search specific msgs on user request
def search_msgs(update, context):
    context.job_queue.run_once(callback_search_msgs, context=update.message.chat_id)


def callback_search_msgs(context):
    print('In TG, args', context.args)
    chat_id = context.job.context
    search_msgs(context, 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()

【问题讨论】:

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


    【解决方案1】:

    让我先试着澄清一下:

    Telegram 的官方文档对我来说太难阅读和理解了。连一个地方都找不到 Updater、update、Commandhandler、context 都用例子来解释的地方。

    我猜“Telegram 的官方文档”是指https://core.telegram.org/bots/api 的文档。然而,UpdaterCommandHandlercontextpython-telegram-bot 的概念,python-telegram-bot 是(众多)python 库之一,它为机器人 api 提供了一个包装器。 python-telegram-bot 提供了tutorialexampleswiki,其中解释了许多功能和documentation


    现在到你的代码:

    1. context.job_queue.run_once(callback_search_msgs, context=update.message.chat_id) 中,您没有告诉job_queue 何时运行该作业。您必须传递一个整数或 datetime.(date)time 对象作为 second 参数。

    2. def callback_search_msgs(context):
          print('In TG, args', context.args)
          chat_id = context.job.context
          search_msgs(context, chat_id)
      

      您将contextchat_id 传递给search_msgs。但是,该函数将context 视为telegram.ext.CallbackContext 的一个实例,而您传递的是一个整数。此外,即使这样可行,也只会在无限循环中安排另一个作业。

    最后,我不明白调度作业与在数据库中查找键有什么关系。你所要做的就是像

    def search_msgs(update, context):
        userkey = context.args[0]
        result = look_up_key_in_db(userkey)
        # this assumes that result is a string:
        update.effective_message.reply_text(result)
    

    要更好地了解context.args,请查看此wiki page


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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-07
      • 2016-04-10
      • 1970-01-01
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      相关资源
      最近更新 更多