context.job_queue.run_once 无法在 Python Telegram BOT API 中工作

context.job_queue.run_once not working in Python Telegram BOT API

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

  1. 从 TG 组接收 /search_msgs userkey 命令中的关键字
  2. 在数据库中搜索 userkey 并发回适当的文本

我遇到了两个错误

  1. None 类型对象没有属性参数,在 callback_search_msgs(context) 中,参见代码片段
  2. AttributeError:'int' 对象没有属性 'job_queue'、in search_msgs(update, context),请参阅代码片段。

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

让我先尝试清理一下:

Telegram's official documents is way too difficult for me to read and understand. Couldn't find even one place where Updater, update, Commandhandler, context are all explained together with examples.

我猜你说的“Telegram 的官方文档”是指 https://core.telegram.org/bots/api. However, Updater, CommandHandler and context are concepts of python-telegram-bot, which is one (of many) python libraries that provides a wrapper for the bot api. python-telegram-bot provides a tutorial, examples, a wiki where a lots of the features are explained and 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.

的维护者