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

如何用Python解析Telegram的MessageMediaPoll数据并格式化输出?数据类型是JSON吗?

解析Telegram MessageMediaPoll数据并格式化输出(Python实现)

一、数据类型确认

Telegram的MessageMediaPoll数据通常以JSON格式存在,或是可序列化为JSON的Python字典/类对象(比如通过Telethon、Pyrogram等库获取的封装对象)。你可以直接解析JSON字符串,或从对象中提取对应属性。

二、Python实现方案

1. 基础JSON/字典解析

如果拿到的是JSON字符串或原生字典,直接提取字段并格式化即可:

import json

def format_poll(poll_data):
    # 处理JSON字符串转字典
    if isinstance(poll_data, str):
        poll_data = json.loads(poll_data)
    
    # 提取问题
    question = poll_data.get('question', {}).get('text', '无问题内容')
    print(f"📝 投票问题:{question}\n")
    
    # 提取选项与正确答案
    options = poll_data.get('options', [])
    correct_ids = poll_data.get('correct_answers', {}).get('option_ids', [])
    
    print("🗳️ 选项列表:")
    for idx, opt in enumerate(options):
        opt_text = opt.get('text', '无选项内容')
        status = "✅ 正确选项" if idx in correct_ids else "❌ 错误选项"
        print(f"- {opt_text} {status}")

# 测试用示例数据
sample_poll = '''
{
    "question": {"text": "Python中哪个是可变数据类型?"},
    "options": [
        {"text": "列表(list)"},
        {"text": "元组(tuple)"},
        {"text": "字符串(str)"}
    ],
    "correct_answers": {"option_ids": [0]}
}
'''

format_poll(sample_poll)

输出效果:

📝 投票问题:Python中哪个是可变数据类型?

🗳️ 选项列表:
- 列表(list) ✅ 正确选项
- 元组(tuple) ❌ 错误选项
- 字符串(str) ❌ 错误选项

2. 适配Telethon/Pyrogram库

如果是通过Telethon获取的MessageMediaPoll对象,直接访问对象属性即可:

from telethon.tl.types import MessageMediaPoll

def format_telethon_poll(poll_obj: MessageMediaPoll):
    print(f"📝 投票问题:{poll_obj.poll.question}\n")
    print("🗳️ 选项列表:")
    for idx, opt in enumerate(poll_obj.poll.options):
        # 仅测验型投票有correct_answers字段
        is_correct = idx in poll_obj.poll.correct_answers.option_ids if hasattr(poll_obj.poll, 'correct_answers') else False
        status = "✅ 正确选项" if is_correct else "❌ 错误选项"
        print(f"- {opt.text} {status}")

三、注意事项

  • 普通投票(非测验型)没有correct_answers字段,可去掉对错状态判断逻辑;
  • 不同场景下的Poll数据结构可能略有差异,需根据实际返回字段调整提取逻辑。

内容的提问来源于stack exchange,提问作者3rdx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:20:49