Telegram Bot API - Capturing User Response After Bot Query

I’m struggling with implementing a conversation flow in my Telegram bot where I need to capture the user’s response specifically after the bot asks a question.

What I want to achieve is something like this:

Bot: What’s your favorite color?
User: Blue
Bot: Great choice! Blue is awesome.

The challenge is that I only want to process the user’s input when it comes as a direct answer to my bot’s question, not from random messages they might send.

I’m working with a modular setup using require statements and module.exports which makes this more complicated for me.

SAMPLE CODE

const helpers = require('./bot_helpers');

bot.onText(/\/start/, async (message) => {
    try {
        helpers.logger.saveUser(message);
        await helpers.commands.welcome(bot, message);
    } catch (error) {
        helpers.logger.logError(error.message)
    }
});

How can I set up a proper conversation state where the bot waits for and processes the next user message as a response to its question?

I’ve had good luck with message queues for this. Store the bot’s last action per user, then match incoming messages against it. Send “what’s your favorite color” and save that action with the user ID. Any non-command message from that user becomes the answer. Just remember to clear the stored action after processing - otherwise every message turns into a color response lol

I’ve dealt with this exact issue before. A simple flag-based approach works great for straightforward conversation flows. Add conversation context to your user tracking system. When the bot asks a question, set a flag like awaitingColorResponse: true for that user. Then create a general message handler that checks this flag before processing input. If it’s set, handle their message as the answer and clear the flag. For complex scenarios, you might want a finite state machine pattern, but for basic question-answer pairs this method’s way simpler to implement and debug. Just handle edge cases like users sending commands while in conversation mode.

You need a conversation state management system. Create a user state object that tracks which question each user is answering. When your bot sends a question, store the user’s ID and expected response type in memory or a database. In your main message handler, check if the user has a pending question before processing their input. I create a separate middleware function that intercepts all incoming messages and routes them to either the conversation handler or regular command processing based on the user’s current state. This lets you chain multiple questions together and keep proper conversation flow without mixing responses with random commands.