Search code examples
pythontelegramchatbottelegram-botpython-telegram-bot

Telegram Conversation bot in python


I am trying to make a conversation telegram bot in python. I am trying to get the reply of the user and want my bot to reply him. but the bot is not reading the new message except it keep send the previous text which is the bot command.

This is the function I am using:

def start(bot, update):
    username = update['message']['chat']['first_name']
    chat_id = get_chat_id(update)

    message = f"Hi {username} my name is Xeniour_Bot...\nHow are you?"

    message_id = update['message']['message_id']
    bot.send_message(chat_id, message, reply_to_message_id=update.message.message_id)
    time.sleep(5)
    reply = update.message.text
    bot.send_message(chat_id, reply, reply_to_message_id=update.message.message_id)

This is my main function:

def main():
    updater = Updater(botToken)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('start', start))
    updater.start_polling()
    updater.idle()


if __name__ == '__main__':
    main()

This is the Output I am getting:

This is the output


Solution

  • The implementation of the CommandHandler needs to be corrected. The default MessageHandler implementation is also missing (unless you didnt copy in the question)

    def start(update, context):
       username = update['message']['chat']['first_name']
       chat_id = get_chat_id(update)
       ...
    
    def main_handler(update, context):
      logging.info(f'update : {update}')
      msg = update.message.text
      update.message.reply_text('Just received: ' + update.message.text)
    
    
    # message handler
    dp.add_handler(CommandHandler('start', start))    
    dp.add_handler(MessageHandler(Filters.text, main_handler)) 
    

    A good reference is the Telegram Python echo example