Search code examples
typescripttelegram-botdenogrammy

How to create a telegram poll with feedback using grammY


I am using Deno and GrammY to create a simple bot that will send a poll to the user on the /q command, and then when the user attempts the poll, would reply to the user on the basis of the choice that he took.

The code of the the bot.ts as of now looks like:

import { Bot } from "https://deno.land/x/grammy@v1.11.2/mod.ts";

const bot = new Bot(MY_REDACTED_BOT_TOKEN);

bot.command("q", async (ctx) => {
  ctx.api.sendPoll(
    ctx.msg.chat.id,
    `What is 1+1?`,
    ["0", "1", "2", "3"],
    {
      is_anonymous: false,
      type: "quiz",
      correct_option_id: 2,
    }
  );
});

bot.start();

How can I add the functionality to wait for the user to attempt the quiz and then proceed on the basis of it (something equivalent to PollAnswerHandler in python-telegram-bot)?


Solution

  • You can listen for poll_answer like shown below. You will find all relevant information in the context object ctx, specifically under ctx.pollAnswer, e.g the user and the chosen option_ids (i.e selected answer(s)) as demonstrated in this code example:

    const correctAnswerId = 2;
    
    bot.command("q", async (ctx) => {
        const message = await ctx.api.sendPoll(
          ctx.msg.chat.id,
          `What is 1+1?`,
          ["0", "1", "2", "3"],
          {
            is_anonymous: false,
            type: "quiz",
            correct_option_id: correctAnswerId,
          }
        );
        console.log("sent poll #" + message.poll.id + " to user " + ctx.from?.id);
      });
    
    bot.on('poll_answer', async (ctx) => {
        console.log(ctx.pollAnswer.user.first_name + " answered to poll " + ctx.pollAnswer.poll_id + " with option " + ctx.pollAnswer.option_ids) 
    
        if (ctx.pollAnswer.option_ids.indexOf(correctAnswerId) > -1 )  {
            await bot.api.sendMessage(ctx.pollAnswer.user.id, "You're a genius!");
        }
        else {
            await bot.api.sendMessage(ctx.pollAnswer.user.id, "Almost correct!");
        }
      });
    

    In the code to send the poll I also added const message = to save the return value, which contains message.poll.id. This can be used to keep track of which poll was sent to which user so that you can easily find out to which poll a poll response refers. Note: the poll Id changes every time you send the poll.

    The console would show for example:

    sent poll #5418284016237281795 to user 1234567890 jps answered to poll 5418284016237281795 with option 2