pythonpy-telegram-bot-api

How to print user's message in telegram bot?


I'm making a telegram bot that supposed to ask users for ID and print it out in terminal

import telebot
from time import sleep

bot = telebot.TeleBot('BOT TOKEN')

from telebot import types

user_message = ''


@bot.message_handler(commands=['start'])
def start(message):

    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    btn1 = types.KeyboardButton("Send ID")
    markup.add(btn1)
    bot.send_message(message.from_user.id, "Ok, let's start!", reply_markup=markup)


@bot.message_handler(content_types=['text'])
def get_text_messages(message):

    if message.text == 'Send ID':
        bot.send_message(message.from_user.id, 'Ok, send it please!')
        global user_message
        user_message = message.text


print(user_message)
bot.polling(none_stop=True, interval=0)

I tried waiting for five seconds after user presses 'Send ID' button and print the message. But it prints 'Send ID'.


Solution

  • In this function message is something fixed throughout the function execution, message does not change within. And the function is doing something only when message.text == 'Send ID', so there's no reason for anything else to be printed.

    @bot.message_handler(content_types=['text'])
    def get_text_messages(message):
    
        if message.text == 'Send ID':
            bot.send_message(message.from_user.id, 'Ok, send it please!')
            global user_message
            user_message = message.text
    print(user_message)
    bot.polling(none_stop=True, interval=0)
    

    One way to deal with it - to add another if, which will process all other texts:

    @bot.message_handler(content_types=['text'])
    def get_text_messages(message):
    
        if message.text == 'Send ID':
            bot.send_message(message.from_user.id, 'Ok, send it please!')
            global user_message
            user_message = message.text
        else:
            user_message = message.text
    

    That way the dialog will look like this:

    - Bot: "Ok, let's start!"
    - You: "Send ID"
    - Bot: "Ok, send it please!"
    - You: "1234"
    

    And user_message is going to become "1234" in the end.


    Downside of this approach is that if you have more complicated logic with more different responses expected from the user, this if/elif/else method won't be able to differentiate them.

    You can look into telebot states in their official repo which help the bot understand what scenario the user is currently in.

    I also have a github repository with a template for dialog bot where telebot states are used, which may be of help.