Search code examples
node.jstelegram-bottelegraftelegraf.js

Waiting for response from Telegraf.js user


Waiting for user response. For example, the bot asks the user for his age, he enters it and the bot must catch his answer and send the next question. How can i do this?


Solution

  • You can simply take a look at Telegraf.js documentation to know how.

    To wait for a text message and reply, you can do this:

    const { Telegraf } = require("telegraf");
    
    const bot = new Telegraf(process.env.BOT_TOKEN); // Your bot api token
    
    // waiting for messages and replying
    bot.on("text", (ctx) => {
         ctx.reply("Hello World");
    });
    
    bot.start();
    

    To answer to a specific question (Eg: what is your name) you can do something like this:

    const { Telegraf } = require("telegraf");
    
    const bot = new Telegraf(process.env.BOT_TOKEN); // Your bot api token
    
    let ask = false;
    let name;
    
    bot.on("text", (ctx) => {
         if(ask) {
              name = ctx.message.text;
         } else {
              ask = true;
              ctx.reply("What is your name?");
         }
    });
    
    bot.start();