James Deen
James Deen

Reputation: 53

TelegramBot, how to handle the message next to a command

I'm using pyTelegramBotAPI and I had this idea of creating 2 commands for a bot: username and password (don't mind for what) so that as soon as a bot user clicks on "/username" the next message he sends is gonna be his username, and the same for his password:

@bot.message_handler(commands=['username'])
def send_welcome(message):
    bot.send_message(message.chat.id, "Type your username: ")

But then, I don't know how to proceed, I've tried with:

@bot.message_handler(commands=['username'])
def send_welcome(message):
    bot.send_message(message.chat.id, "Type your username: ")
    @bot.message_handler(func=lambda message: True)
    def echo_message(message):
        bot.send_message(message.chat.id, "So, I'm answering to his username at this point: ")

However, since then, the function is never left, and all the following messages are: "So, I'm answering to his username at this point: "...

Any help?

Upvotes: 2

Views: 1547

Answers (1)

barbax7
barbax7

Reputation: 188

You need to use bot.register_next_step_handler() method.

So, change the handler of start command in:

@bot.message_handler(commands=['username'])
def send_welcome(message):
    msg = bot.send_message(message.chat.id, "Type your username: ")
    bot.register_next_step_handler(msg, function)

Instead of function you have to put the name of the function thate elaborate the new message. So:

def function(message):
    bot.send_message(message.chat.id, "So, I'm answering to his username at this point: {}".format(message.text))

Happy coding!

Upvotes: 2

Related Questions