python-telegram-bot 错误 'CallbackContext' 对象没有属性 'message' [英] python-telegram-bot ERROR 'CallbackContext' object has no attribute 'message'

查看:142
本文介绍了python-telegram-bot 错误 'CallbackContext' 对象没有属性 'message'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是电报机器人的示例.帮助我理解为什么函数 message_handler 在我的代码中起作用,而 greet_user - 不起作用.

Below is an example of the telegram bot. Help me understand why function message_handler works in my code, and greet_user - not working.

error_log 装饰器出错:'CallbackContext' 对象没有属性 'message'

There is a error from error_log decorator: 'CallbackContext' object has no attribute 'message'

from telegram import Update, Bot
from telegram.ext import Updater, MessageHandler, Filters, CallbackContext, CommandHandler
from telegram.utils.request import Request


def log_error(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as exc:
            print(f'Error: {exc}')
            raise exc

    return wrapper


def message_handler(update: Update, context: CallbackContext):
    update.message.reply_text(text='Example')


@log_error
def greet_user(bot, update):
    update.message.reply_text('hello')

def main():
    req = Request(connect_timeout=0.5)
    t_bot = Bot(
        request=req,
        token='xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
        base_url='https://telegg.ru/orig/bot',
    )
    updater = Updater(bot=t_bot, use_context=True)

    dp = updater.dispatcher
    dp.add_handler(CommandHandler('start', greet_user))
    dp.add_handler(MessageHandler(filters=Filters.all, callback=message_handler))

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

推荐答案

我想出了问题所在.如果我们在 Updater 中使用 use_context=True,我们应该这样传递参数给函数:

I figured out what the problem was . If we use use_context=True in Updater, we should pass arguments to the function this way:

def greet_user(`update: Update, context: CallbackContext`):
    update.message.reply_text('hello')

https://github.com/python-telegram-bot/python-telegram-bot/wiki/Transition-guide-to-Version-12.0

这篇关于python-telegram-bot 错误 'CallbackContext' 对象没有属性 'message'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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