如何在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
相关产品推荐
相关产品推荐

