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

如何使用pyTelegramBotAPI的poll_answer_handler获取投票答复

pyTelegramBotAPI 投票答复获取实现方案

直接给出完整可运行的示例代码:

import telebot
from telebot.types import PollAnswer

# 替换为你自己的机器人Token
BOT_TOKEN = "你的机器人TOKEN"
bot = telebot.TeleBot(BOT_TOKEN)

# 可用于存储投票ID与对应业务信息的映射,生产环境建议使用数据库
poll_info_map = {}

@bot.message_handler(commands=['start'])
def send_vote(message):
    # 发送非匿名投票,is_anonymous设为False才能获取答题用户信息
    sent_poll = bot.send_poll(
        chat_id=message.chat.id,
        question="choose one",
        options=["a", "b", "c"],
        is_anonymous=False
    )
    # 存储投票ID和对应选项、发起聊天等信息,方便后续匹配答复
    poll_info_map[sent_poll.poll.id] = {
        "options": ["a", "b", "c"],
        "from_chat_id": message.chat.id
    }

@bot.poll_answer_handler()
def handle_poll_reply(poll_answer: PollAnswer):
    # 提取投票答复核心信息
    target_poll_id = poll_answer.poll_id
    answer_user = poll_answer.user
    selected_indexes = poll_answer.option_ids

    # 匹配之前存储的投票信息
    if target_poll_id not in poll_info_map:
        return
    current_poll = poll_info_map[target_poll_id]
    selected_options = [current_poll["options"][idx] for idx in selected_indexes]

    # 自定义业务逻辑,示例为给答题用户发反馈
    reply_text = f"你已选择:{','.join(selected_options)}"
    bot.send_message(chat_id=answer_user.id, text=reply_text)

if __name__ == "__main__":
    bot.infinity_polling()

核心说明

  • @bot.poll_answer_handler() 装饰器不需要额外传参,装饰的回调函数会自动接收一个PollAnswer类型的参数,该参数包含以下常用属性:

    • poll_id:用户作答的投票唯一ID,与send_poll返回的投票对象ID一致,可用于匹配预先存储的投票业务信息
    • user:作答用户的对象,包含用户ID、用户名、昵称等信息,仅当投票设置为非匿名(is_anonymous=False)时该字段有值
    • option_ids:用户选中的选项索引列表,索引从0开始计数。单选投票该列表长度为1,多选投票长度等于用户选中的选项数量
  • 如果业务不需要匹配投票的原始信息,也可以不存储poll_id映射,直接处理返回的答复内容即可。

内容的提问来源于stack exchange,提问作者M.Mawlawi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:45:03