Telegram Bot: How to handle custom reply messages along with those from the keyboard?

154 Views Asked by At

I created a Telegram Bot for a flower shop using node-telegram-bot-api.

Some of the questions I ask a user can be replied using a reply keyboard (for example, the time and date of the delivery, or if a card should be added), but some questions require a custom answer (a name, phone, delivery address).

While keyboard answers can be handled using RegExp because I know them ahead :

bot.onText(new RegExp('Add a card'), msg => {
    bot.sendMessage(msg.chat.id, messages.askDeliveryDate,   //here I send the next question of the sequence 
    ,{
        reply_markup: keyboard.dateMenu      // here I send the keyboard to answer the next question
    })
})

I don't understand how to handle custom replies (how to recognise and catch them, validate, proceed to the next question of the sequence)?

Would be grateful if you could help. Thank you.

1

There are 1 best solutions below

0
On

As you are already expecting this, I should say you can write custom RegExp to match the user phrases and hence to work with the logic. That is if you are asking for the phone number, you can create regex something like this:

const phoneExp = /^\+(?:[0-9] ?){6,14}[0-9]$/
bot.onText(phoneExp, msg => {
  // Your logic here
});

Similarly, you can setup multiple listeners for email and all the data you need to collect from the users.

Tip: I'd always prefer using a database and always tracking the users' current state in the bot.

Edit: On the other hand you can also make use of other features like request_contact in the KeyboardButton to request the phone number of the user etc. Read more here: https://core.telegram.org/bots/api#keyboardbutton

Hope this helps :)