【问题标题】:Telegram python check key value from JSON来自JSON的电报python检查键值
【发布时间】:2021-03-08 08:56:39
【问题描述】:

我正在使用 pyhton 创建一个电报机器人,特别是以下模块

https://github.com/python-telegram-bot/python-telegram-bot

我想做的是:

  • 向机器人发送输入
  • 读取更新对象以分析每个字段
  • 检查“文本”键是否存在
  • 如果是的话就做点什么

我目前的python实现:

def echo(update: Update, context: CallbackContext) -> None:
    if 'text' in update.message:
        update.message.reply_text('I found your key value you are looking for')
    else:
        update.message.reply_text('Key not found')

def main():
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    updater = Updater(MY_TOKEN)

    # Get the dispatcher to register handlers
    dispatcher = updater.dispatcher
    dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))

    updater.start_polling()
    updater.idle()


if __name__ == '__main__':
    main()

update对象的结构:

{
   "update_id":id_update,
   "message":{
      "message_id":1579,
      "date":1615193338,
      "chat":{
         "id":id_chat,
         "type":"private",
         "username":"XXX",
         "first_name":"XXX"
      },
      "text":"Hello Bot",
      "entities":[
         
      ],
      "caption_entities":[
         
      ],
      "photo":[
         
      ],
      "new_chat_members":[
         
      ],
      "new_chat_photo":[
         
      ],
      "delete_chat_photo":false,
      "group_chat_created":false,
      "supergroup_chat_created":false,
      "channel_chat_created":false,
      "from":{
         "id":id_chat,
         "first_name":"xxx",
         "is_bot":false,
         "username":"xxx",
         "language_code":"it"
      }
   }
}

当我测试它时,我没有从机器人得到任何输出,似乎它忽略了 if/else 条件。 如果我打印update.message.text,我会正确看到发送到机器人的输入。

谢谢大家

编辑

我找到了解决方案,我必须以这种方式更改传递给 MessageHandler 的过滤器

dispatcher.add_handler(MessageHandler(Filters.all, echo))

谢谢你的帮助

【问题讨论】:

  • 我可以知道您为什么要检查 update.message 中的“文本”键吗?
  • 找到了解决方案..用 Filter.all 更改了 Filter.text ..这样每条消息都会传递给 echo 函数

标签: python json python-3.x telegram-bot python-telegram-bot


【解决方案1】:

您的编辑很可能不是实际的解决方案。使用Filters.all 而不是Filters.text & ~Filters.command 只是说MessageHandler 将捕获任何 消息,而不仅仅是包含文本且不以botcommand 开头的消息。

问题在于'text' in update.message 不能工作,因为update.messagetelegram.Message 对象并且不可迭代。因此'text' in update.message 可能会抛出一个错误,因为您既没有启用日志记录,也没有注册错误处理程序(请参阅 PTB 自述文件和 wiki,分别获取有关日志记录和错误处理程序的信息)。

我的猜测是更改为 'text' in update.message.text 应该可以解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多