Search code examples
darttelegram-bot

How can I wait for users' response in Telegram Bot?


I am using Televerse to build Telegram Bot in Dart. I want to implement the user verification process. I am thinking of a flow like:

Bot: What is your name?
User: John Doe
Bot: Send me your contact
User: [Contact]
Bot: Finally, add your recovery email.
User: [email protected]
Bot: Account verification request is sent.

As you can see I have to go through 3 steps to complete the verification request process. Is there a way I can complete this in one handler? Is there a way I can wait for the user's response?

I tried to implement this with a global Map<int, dynamic> such that user_id against verification process state. But, it seems like over complicated.


Solution

  • Most common solution for this is to use a database and store your verification step states just like you tried with the Map<int, dynamic map.

    But, with Televerse you can simply do it by Conversation API. At first, create a Conversation instance.

    final conv = Conversation(bot); 
    

    Now you can use different waitFor methods inside the conv object to wait for users's response. The return value for each waitFor method is a nullable Context (Context?).

    Here's a example code:

      bot.command('verification', (ctx) async {
        // Ask name
        ctx.reply("What's your name?");
        final nameCtx = await conv.waitForTextMessage(chatId: ctx.id);
        // Save / Validate name
    
        // Ask for contact
        await nameCtx?.reply(
          "Send me your contact.",
          replyMarkup: Keyboard().requestContact("Send Contact").resized(),
        );
        final contactCtx = await conv.waitForContactMessage(chatId: ctx.id);
        // Verify and validate contact
    
        // ...
      });
    

    Hope this helps!