CONTEX.JOB_QUEUE.RUN_ONCE不能在Python Telegram bot API中工作 [英] context.job_queue.run_once not working in Python Telegram BOT API
本文介绍了CONTEX.JOB_QUEUE.RUN_ONCE不能在Python Telegram bot API中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试设置一个机器人,它:
- 从TG组接收
/search_msgs userkey
命令中的关键字 - 在数据库中搜索
userkey
并发回相应文本
我收到两个错误
- 无类型对象没有属性参数,在
callback_search_msgs(context)
中,请参阅代码片段 - AttributeError:‘int’对象没有‘JOB_QUEUE’属性,
in search_msgs(update, 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的文件。然而,Updater
、CommandHandler
和context
是python-telegram-bot
的概念,python-telegram-bot
是为bot API提供包装器的(众多)python库之一。python-telegram-bot
提供了tutorial、examples、wiki和documentation。
现在到您的代码:
在
context.job_queue.run_once(callback_search_msgs, context=update.message.chat_id)
中,您没有告诉job_queue
何时运行作业。必须将整数或datetime.(date)time
对象作为第二个参数传递。中
您正在将def callback_search_msgs(context): print('In TG, args', context.args) chat_id = context.job.context search_msgs(context, chat_id)
context
和chat_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屋!
查看全文