如何用Python(Telethon)获取Telegram超级群组话题名称
如何用Telethon获取Telegram超级群(Forum)的话题列表
问题分析
你原代码的核心问题是错误依赖消息回复关系推断话题,这完全不符合Telegram API对话题(Forum)的设计逻辑。Telegram的话题是作为Forum的独立实体存在的,有专门的接口用于获取,靠回复消息识别的方法不仅不可靠,还会因为没有调用正确接口导致报错。
解决方案
要获取超级群的话题,必须使用Telethon针对Forum类型实体的专用接口,以下是具体实现步骤:
1. 前置确认
确保你的超级群已经开启了话题功能,此时群实体的类型会变为Forum(而非普通超级群的Channel)。
2. 修正后的代码实现
import asyncio from telethon import TelegramClient from telethon.tl.types import Channel api_id = 99999999 api_hash = 'b5b09783707618xxxxxxxxxxxxxxxxxx' phone_number = '+39xxxxxxxxxx' group_id = -100xxxxxxxxxx client = TelegramClient('session_name', api_id, api_hash) async def get_forum_topics(): try: await client.start(phone_number) entity = await client.get_entity(group_id) # 校验群组是否开启话题功能 if not isinstance(entity, Channel) or not entity.forum: print("该群组未开启话题功能") return None # 获取话题创建消息集合(topic=0为话题列表入口) topic_messages = await client.get_messages(entity, limit=100, topic=0) # 提取话题名称与ID topics = [] for msg in topic_messages: if hasattr(msg, 'forum_topic_created'): topics.append({ "名称": msg.forum_topic_created.title, "话题ID": msg.id }) return topics except Exception as e: print(f"错误: {e}") return None async def main(): topics = await get_forum_topics() if topics: print("超级群话题列表:") for idx, topic in enumerate(topics, 1): print(f"{idx}. {topic['名称']} (ID: {topic['话题ID']})") else: print("未找到有效话题信息") if __name__ == "__main__": asyncio.run(main())
关键代码说明
entity.forum:用于判断群组是否开启了话题功能,只有开启后才能获取话题列表client.get_messages(entity, limit=100, topic=0):当topic参数传0时,会返回Forum下所有话题的创建消息,这类消息包含forum_topic_created属性,存储了话题的名称、图标等核心信息- 从
forum_topic_created.title直接提取话题名称,话题ID对应创建消息的ID
额外注意事项
- 确保Telethon版本为最新:执行
pip install --upgrade telethon升级,旧版本对Forum API支持不完善 - 你的账号必须是该超级群的成员(普通成员权限即可查看公开话题)
- 如果话题数量超过100,需调整
limit参数或实现分页逻辑获取更多话题
内容的提问来源于stack exchange,提问作者Peter Long
相关产品推荐
相关产品推荐

