3

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()
7
  • Is it supposed to have the callback kwarg? Like so dp.add_handler(CommandHandler('start', callback=greet_user)) Commented Mar 22, 2020 at 20:23
  • I tried it, but it didn 't help Commented Mar 22, 2020 at 21:20
  • what version of telegram-bot you running? Commented Mar 23, 2020 at 0:53
  • version python-telegram-bot = 12.4.2 Commented Mar 23, 2020 at 6:09
  • I ran your code on mine on Python 3.7 and it works fine. I can't seem to figure out what the error is! Maybe install the latest version of the package and python. Commented Mar 23, 2020 at 15:23

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.