1

How can I make my bot receives responses without using force_reply? something like botFather does?

one

Let say I've sent message to user like this:

bot.sendMessage(chatId, 'What is your name?', { parse_mode: 'HTML' });

Now how do I get user response?

mafortis
  • 6,750
  • 23
  • 130
  • 288

1 Answers1

0

Without the help of force_reply, you'll need to write some custom logic. I've implemented this in my custom bots like so:

  1. Send question to user bot.sendMessage() and remember the ID
  2. Wait for a message bot.on('message')
  3. Check if we're waiting for on a reply from this user
  4. Reply accordingly
// Create bot
const TelegramBot = require('node-telegram-bot-api');
const bot = new TelegramBot('XXXXXXXX:AAEibBwftjTEKuYd9d2X0ACeyyzTk4DLe60', {
    polling: true
});

// List of id's we're waiting for
const wait = [];

// Hardcoded chat id
const chatId = 1234567;

// Ask and add to wait list
bot.sendMessage(chatId, 'What is your name?', { parse_mode: 'HTML' });
wait.push(chatId);

// On message
bot.on('message', (msg) => {

    // Check we're waiting on this user
    if (wait.includes(msg.chat.id)) {

        // Send reply
        bot.sendMessage(chatId, 'Your name: ' + msg.text );

        // Remove from wait list
        wait.splice(wait.indexOf(msg.chat.id), 1);
    } else {

        // Normal message; notify user
        bot.sendMessage(chatId, 'Hi! I\'m not expecting a reply from you! How can I help?');
    }
});

Example


Note: This is just an example! The code can be extended to include multiple checks, and possibly states to see what message the user is replying on.

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • Hi, sorry for late reply, your code doesn't work as expected first the issue is your `wait.push(chatId);` is before bot start and wont get any chat id, and if I put it inside `if (text === '/start') {` then it directly prints `Your name: /start` – mafortis May 24 '21 at 01:19
  • PS: by your default code because it doesn't get chat id when user starts the bot it directly shows this error in console `Unhandled rejection Error: ETELEGRAM: 400 Bad Request: chat_id is empty` – mafortis May 24 '21 at 01:19