skip to Main Content

I want to make a keyboard in telegram-bot, but I can’t find chat_id. How can fix it?

Code:

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

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

def service_keyboards(bot,update) :
    chat_id = update.effective_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()

I get these Eror:

No error handlers are registered, logging exception. Traceback (most
recent call last): File
"c:usersGhazalappdatalocalprogramspythonpython38libsite-packagestelegramextdispatcher.py",
line 442, in process_update handler.handle_update(update, self, check,
context) File
"c:usersGhazalappdatalocalprogramspythonpython38libsite-packagestelegramexthandler.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’

2

Answers


  1. You can get the chat_id from the JSON payload of the incoming message

    def get_chat_id(update, context):
      chat_id = -1
    
      if update.message is not None:
        # from a text message
        chat_id = update.message.chat.id
      elif update.callback_query is not None:
        # from a callback message
        chat_id = update.callback_query.message.chat.id
    
    return chat_id
    
    chat_id = get_chat_id(update, context)
    bot.sendMessage(chat_id, 'etc...'
    
    Login or Signup to reply.
  2. That’s how I code my bots:

    def start (update, context):
        user = update.message.from_user
        chat_id = user['id']
        ##foo
     
    def service_keyboards (update, context):
        user = update.message.from_user
        chat_id = user['id']
        ##foo
    

    Try this and let me know if it works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search