如何通过@bot.poll_answer_handler()获取Telegram机器人投票结果?
如何用telebot获取投票结果
要获取用户对投票的选择结果,只需给你的代码添加@bot.poll_answer_handler()装饰器对应的处理函数即可,具体修改如下:
修改后的完整代码
import telebot from telebot import types, util API_TOKEN = 'token' bot = telebot.TeleBot(API_TOKEN) @bot.message_handler(regexp="work") def send_poll(message: types.Message): bot.send_poll( message.chat.id, question='When do you prefer to work?', options=['Morning', 'Night'], allows_multiple_answers=False # 明确设置为单选,可选但建议添加以避免歧义 ) @bot.poll_answer_handler() def handle_poll_answer(poll_answer: types.PollAnswer): # 提取投票相关信息 user_id = poll_answer.user.id # 单选场景下,answers列表仅含一个选中项的索引 selected_option_index = poll_answer.answers[0].option_id # 对应到投票预设的选项文本 options = ['Morning', 'Night'] selected_option = options[selected_option_index] # 执行你需要的后续逻辑,比如给用户反馈结果 bot.send_message( user_id, f"你选择了{selected_option},已记录你的偏好~" ) bot.infinity_polling()
关键说明
poll_answer对象包含投票核心数据:poll_answer.user:参与投票的用户信息poll_answer.poll_id:投票的唯一标识,可用来区分不同投票poll_answer.answers:用户选中的选项索引列表,单选时长度为1,多选时包含多个索引
- 因为我们的投票是单选模式,直接取
answers[0].option_id就能拿到选中选项的位置,再对应到预先定义的选项文本即可。
内容的提问来源于stack exchange,提问作者mina Zarief
相关产品推荐
相关产品推荐

