使用Python的Telethon获取Telegram频道消息评论遇Replies属性为空问题
Telegram频道评论获取问题:replies属性为空的原因与解决办法
原因
- 用DiscussBot启用的评论区,本质是和频道关联的私有群组,并非频道内置的回复系统。Telethon返回的频道消息
replies属性,只针对频道原生的消息回复功能,所以会显示为None。 - 评论内容实际存储在DiscussBot创建的关联群组中,而非频道本身,直接遍历频道消息自然拿不到评论。
解决方法
1. 获取关联的评论群组实体
DiscussBot创建评论区时会自动生成一个关联群组,你可以通过频道实体的linked_chat属性获取这个群组的信息,之后遍历群组消息就能拿到所有评论:
with TelegramClient("anon", api_id, api_hash) as client: channel_entity = client.get_entity("testchannel") # 检查频道是否关联了评论群组 if channel_entity.linked_chat: chat_entity = client.get_entity(channel_entity.linked_chat) # 遍历评论群组的消息 for comment in client.iter_messages(chat_entity): # 评论的reply_to_msg_id对应频道原始消息的ID print(f"评论内容:{comment.text},对应频道消息ID:{comment.reply_to_msg_id}") else: print("当前频道未启用评论功能或未关联评论群组")
2. 关联频道消息与评论
评论群组内的每条评论,reply_to_msg_id字段会指向频道中对应的原始消息ID。可以先收集频道消息,再通过这个ID匹配对应评论:
with TelegramClient("anon", api_id, api_hash) as client: channel_entity = client.get_entity("testchannel") # 收集频道消息,以消息ID为键存储 channel_msg_map = {} for msg in client.iter_messages(channel_entity, offset_date=till_date): channel_msg_map[msg.id] = msg print(f"频道消息[{msg.id}]:{msg.text}") # 获取评论群组并匹配评论 if channel_entity.linked_chat: chat_entity = client.get_entity(channel_entity.linked_chat) for comment in client.iter_messages(chat_entity): original_msg_id = comment.reply_to_msg_id if original_msg_id in channel_msg_map: original_msg = channel_msg_map[original_msg_id] print(f"消息[{original_msg.id}]的评论:{comment.text}")
内容的提问来源于stack exchange,提问作者mav_nob
相关产品推荐
相关产品推荐

