Ghazal Shirzad
Ghazal Shirzad

Reputation: 11

Find chat_id in python-telegram-bot

I tried to create a bot in telegram with python, bot I can't find chat_id. What should I do?

My code:

from telegram.ext import Updater, CommandHandler
from telegram import ReplyKeyboardMarkup

updater = Updater(Token)
def start(update, _) :
    update.message.reply_text('Hello {}'.format(update.message.chat.first_name))

def service_keyboards(bot,update) :
    chat_id = update.message.chat_id
    keyboard = [['Send Video'], ['Send Music']]
    bot.sendMessage(chat_id, 'Plese choose an item.', reply_markup = ReplyKeyboardMarkup(keyboard))

start_command = CommandHandler('start' , start)
service_command = CommandHandler('service' , service_keyboards)
updater.dispatcher.add_handler(start_command)
updater.dispatcher.add_handler(service_command)
updater.start_polling()
updater.idle()

Eror:

No error handlers are registered, logging exception. Traceback (most recent call last): File "c:\users\Ghazal\appdata\local\programs\python\python38\lib\site-packages\telegram\ext\dispatcher.py", line 442, in process_update handler.handle_update(update, self, check, context) File "c:\users\Ghazal\appdata\local\programs\python\python38\lib\site-packages\telegram\ext\handler.py", line 160, in handle_update return self.callback(update, context) File "", line 9, in start chat_id = update.message.chat_id AttributeError: 'CallbackContext' object has no attribute 'message'

Upvotes: 1

Views: 4488

Answers (1)

Muslimbek Abduganiev
Muslimbek Abduganiev

Reputation: 941

Command handler functions (in your case start function) accepts two arguments, first is Update, the second is CallbackContext.

You have misplaced your update argument in the function. It should come first:

def echo(update: Update, _: CallbackContext) -> None:
    """Echo the user message."""
    update.message.reply_text(str(update.message.chat_id) + ": " + 
update.message.text)

Your error message is clearly indicating that you are trying to access CollbackContex's message attribute. And CallbackContext does not have that.

Please refer to these examples to learn more about telegram-bot library in python.

Upvotes: 1

Related Questions