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

Telethon接收纯媒体消息时from_id为None引发AttributeError求助

解决Telethon处理媒体消息时from_id的AttributeError问题

问题根源

你的代码错误在于直接访问event.from_id.user_id前没有先判断event.from_id是否为None。当接收他人发送的媒体消息时,event.from_id可能为None(比如某些转发场景、频道消息,或是Telethon对特定媒体消息的字段填充逻辑),此时直接访问user_id就会触发AttributeError: 'NoneType' object has no attribute 'user_id'。

另外你尝试用peer_id替代但未解决,是因为peer_id也可能是PeerChat或PeerChannel类型,直接访问user_id同样会出错。

修复方案

方法1:统一处理所有Peer类型

修改plugins.py第25行的代码,用Telethon内置工具函数安全获取ID:

from telethon.utils import get_peer_id

# 替换原来的author赋值行
author_id = get_peer_id(event.from_id) if event.from_id else get_peer_id(event.peer_id)
'author': author_id,

方法2:针对私聊场景的精细判断

如果你的业务以私聊为主,可以针对性筛选用户类型:

from telethon.tl.types import PeerUser

author_id = None
# 优先从from_id取用户ID
if event.from_id and isinstance(event.from_id, PeerUser):
    author_id = event.from_id.user_id
# from_id无效时,取私聊对象的用户ID
elif isinstance(event.peer_id, PeerUser):
    author_id = event.peer_id.user_id
# 群聊/频道场景按需补充处理
else:
    author_id = get_peer_id(event.peer_id)

'author': author_id,

关键注意点

  • 永远不要直接访问event.from_id.user_id或event.peer_id.user_id,必须先判断对象是否为None,以及是否是PeerUser类型。
  • get_peer_id工具函数可以统一处理PeerUser/PeerChat/PeerChannel三种类型,返回对应的ID值,避免类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:10:34