CONTEX.JOB_QUEUE.RUN_ONCE不能在Python Telegram bot API中工作 [英] context.job_queue.run_once not working in Python Telegram BOT API

查看:24
本文介绍了CONTEX.JOB_QUEUE.RUN_ONCE不能在Python Telegram bot API中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我收到两个错误

  1. 无类型对象没有属性参数,在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()

推荐答案

让我先试一试&&A&C清理一下:

Telegram的官方文件对我来说太难读和理解了。找不到将Updater、UPDATE、CommandHandler、Context全部与示例一起解释的位置。

我猜您所说的Telegram的官方文件是指https://core.telegram.org/bots/api的文件。然而,UpdaterCommandHandlercontextpython-telegram-bot的概念,python-telegram-bot是为bot API提供包装器的(众多)python库之一。python-telegram-bot提供了tutorialexampleswikidocumentation


现在到您的代码:

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

  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的维护者。

这篇关于CONTEX.JOB_QUEUE.RUN_ONCE不能在Python Telegram bot API中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆