Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python-telegram-bot ERROR 'CallbackContext' object has no attribute 'message'

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

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()
like image 723
sdmnt Avatar asked Jul 23 '26 20:07

sdmnt


1 Answers

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

like image 148
sdmnt Avatar answered Jul 26 '26 09:07

sdmnt