You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Deno+GrammY中实现Telegram测验投票的用户反馈功能

实现GrammY中测验投票的答案处理功能

在GrammY中,对应python-telegram-bot的PollAnswerHandler功能,可通过监听poll_answer事件实现,以下是具体修改方案:

1. 添加投票答案事件处理器

在现有代码中新增poll_answer事件的处理逻辑,捕获用户提交的投票答案并针对性回复:

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.on("poll_answer", async (ctx) => {
  // 测验为单选,取用户选择的第一个选项ID
  const selectedOptionId = ctx.pollAnswer.option_ids[0];
  const userId = ctx.pollAnswer.user.id;
  const userName = ctx.pollAnswer.user.first_name;

  // 根据答案正确性发送回复
  if (selectedOptionId === 2) {
    await ctx.api.sendMessage(userId, `恭喜${userName},回答正确!`);
  } else {
    await ctx.api.sendMessage(userId, `抱歉${userName},回答错误,正确答案是2哦~`);
  }
});

bot.start();

关键说明

  • ctx.pollAnswer包含投票答案的核心信息:
    • option_ids:用户选择的选项ID数组(测验为单选,数组长度固定为1)
    • user:提交答案的用户对象,包含ID、昵称等信息(需提前设置is_anonymous: false才能获取)
  • 示例中通过用户ID发送私信回复,若需在原聊天群内回复,可额外存储投票ID与聊天ID的映射关系,再调用对应聊天的消息接口。

内容的提问来源于stack exchange,提问作者Eshaan Aggarwal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 01:20:20