0

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:\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'

  • `update.effective_chat.id` doesn't exist. Please take a look at the examples: – 0stone0 Mar 25 '21 at 14:31
  • Does this answer your question? [how to get chat\_id and message\_id in telebot(pytelegramBotAPI) to update last sent message in telegram bot(Python)](https://stackoverflow.com/questions/51611532/how-to-get-chat-id-and-message-id-in-telebotpytelegrambotapi-to-update-last-se) – 0stone0 Mar 25 '21 at 16:57

2 Answers2

0

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...'
Beppe C
  • 11,256
  • 2
  • 19
  • 41
0

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.

Rafael Colombo
  • 339
  • 1
  • 2
  • 8