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

Python Telegram Bot群组无法接收文本,出现KeyError: 'message'

解决Telegram Bot群组内无法接收消息text字段的问题

问题现象

  • 私聊场景下Bot运行正常,可正常获取消息的text字段
  • 群组场景下无法获取消息的text字段,已完成以下配置调整但问题未解决:关闭隐私模式、禁用内联模式、开启群组加入权限
  • 私聊收到的Update为message类型(含text字段),示例:
{'update_id': 144970421, 'message': {'message_id': 114, 'from': {'id': 211279113, 'is_bot': False, 'first_name': 'Rafael', 'last_name': 'Ribeiro', 'username': 'aybararocks', 'language_code': 'en'}, 'chat': {'id': 211279113, 'first_name': 'Rafael', 'last_name': 'Ribeiro', 'username': 'aybararocks', 'type': 'private'}, 'date': 1671754018, 'text': 'rand'}}
  • 群组收到的Update为my_chat_member类型(Bot加入群组的成员变更事件,无text字段),示例:
{'update_id': 144970079, 'my_chat_member': {'chat': {'id': -1001857987984, 'title': 'Trying to suceed', 'type': 'supergroup'}, 'from': {'id': 211279113, 'is_bot': False, 'first_name': 'Rafael', 'last_name': 'Ribeiro', 'username': 'aybararocks', 'language_code': 'pt-br'}, 'date': 1671730720, 'old_chat_member': {'user': {'id': 5902418100, 'is_bot': True, 'first_name': 'Wheel of Time Quotes || Rafa', 'username': 'wot_group_bot'}, 'status': 'left'}, 'new_chat_member': {'user': {'id': 5902418100, 'is_bot': True, 'first_name': 'Wheel of Time Quotes || Rafa', 'username': 'wot_group_bot'}, 'status': 'member'}}}

代码问题分析

当前代码直接硬编码读取message['message']['text'],但Telegram的Update对象包含多种类型:

  • message:普通文本/媒体消息
  • my_chat_member:成员身份变更事件(如Bot加入群组)
  • callback_query:回调按钮事件等
    群组中收到的是Bot加入的成员变更事件,而非普通消息,因此代码会因找不到message键抛出异常,且无法获取text字段。

解决思路与代码修改

1. 新增Update类型判断与字段容错

修改parse_message函数,先判断Update类型,仅处理message类型的更新,同时检查text字段是否存在:

def parse_message(message):
    # 过滤非普通消息类型的更新
    if 'message' not in message:
        return None, None
    msg_data = message['message']
    # 过滤无text字段的消息(如图片、贴纸)
    if 'text' not in msg_data:
        return msg_data['chat']['id'], None
    chat_id = msg_data['chat']['id']
    txt = msg_data['text']
    return chat_id, txt

2. 调整主逻辑,仅处理有效文本消息

修改index函数,仅在获取到有效文本时执行业务逻辑:

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        msg = request.get_json()

        chat_id, txt = parse_message(msg)
        # 仅当存在有效文本且包含指定关键词时触发回复
        if txt and 'rand' in txt.lower():
            tel_send_message(chat_id, f'<i>{quotes[randint(0, len(quotes)-1)]}</i>')

        return Response('ok', status=200)

3. 额外配置检查

  • 确保Bot在群组中拥有读取消息权限:将Bot设为群组管理员,勾选"读取消息"权限(即使关闭隐私模式,无权限仍无法获取消息)
  • 测试时发送纯文本消息:避免发送图片、贴纸等无text字段的内容
  • 确认Webhook配置:若使用Webhook,检查allowed_updates参数是否包含message类型(默认接收所有类型,若手动指定需确保包含)

内容的提问来源于stack exchange,提问作者Rafael Ribeiro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:31:12