使用telebot开发Telegram quiz机器人如何在用户作答后展示正确答案
实现方案
核心依赖Telegram Bot API推送的用户答题更新事件实现,步骤如下:
- 使用
@bot.poll_answer_handler()装饰器注册答题事件处理函数 - 提前存储发送的测验ID与对应正确答案、所属会话的映射关系,收到答题事件后匹配映射发送提示
完整修改后代码
import telebot bot = telebot.TeleBot("替换为你自己的API KEY") # 存储测验映射:key为poll_id,value存储对应正确答案、会话id、正确选项id poll_data = {} print("Bot starting...") @bot.message_handler(commands=['quiz']) def quiz(message): q = 'What is the capital of Italy?' answers = ['Rome', 'London', 'Amsterdam'] correct_option = 0 # 发送测验并拿到返回的poll对象 sent_poll = bot.send_poll( message.chat.id, question=q, options=answers, correct_option_id=correct_option, open_period=5 ) # 存入映射表 poll_data[sent_poll.poll.id] = { "correct_answer": answers[correct_option], "chat_id": message.chat.id, "correct_option_id": correct_option } @bot.poll_answer_handler() def handle_quiz_answer(answer): poll_id = answer.poll_id # 匹配当前回答对应的测验 if poll_id not in poll_data: return quiz_info = poll_data[poll_id] user_selected = answer.option_ids[0] # 生成提示文案 if user_selected == quiz_info["correct_option_id"]: tip = "🎉 回答正确!" else: tip = "❌ 回答错误" # 发送正确答案提示 bot.send_message( quiz_info["chat_id"], f"{tip}\n正确答案是 *{quiz_info['correct_answer']}*", parse_mode="Markdown" ) # 可选:私聊场景下单次回答后移除映射,避免重复推送 # del poll_data[poll_id] bot.polling()
注意事项
- 上述代码默认适配私聊场景,如果需要在群组中使用,可扩展
poll_data的存储结构,支持多用户同一测验的答题统计 - 建议定期清理
poll_data中已超过open_period时长的过期测验数据,避免内存占用过高
内容的提问来源于stack exchange,提问作者Phasma Dragon
相关产品推荐
相关产品推荐

