如何使用Telethon向Telegram群组指定主题发送文件?
向Telegram群组指定主题发送文件(Telethon v1.26+)
要实现向指定主题发送文件,核心是利用Telethon新增的主题支持,通过reply_to参数指定目标主题的起始消息ID(或主题内任意消息ID),具体实现如下:
实现步骤
- 获取群组实体与主题列表:先获取目标群组的实体,再拉取该群组下的所有主题。
- 定位目标主题:通过主题名称筛选出你要发送的目标主题。
- 发送文件到指定主题:调用
send_file时添加reply_to参数,值为目标主题的起始消息ID(top_message字段)。
修改后的代码示例
from telethon.sync import TelegramClient api_id = '你的API ID' api_hash = '你的API Hash' group_id = '你的群组ID(可以是用户名、整数ID)' topic_name = '目标主题名称' with TelegramClient('anon', api_id, api_hash) as client: # 获取群组实体 group_entity = client.get_entity(group_id) # 获取群组内所有主题 all_topics = client.get_discussion_topics(group_entity) # 查找指定名称的主题(如果名称重复,可根据需求调整筛选逻辑) try: target_topic = next(topic for topic in all_topics if topic.title == topic_name) except StopIteration: print(f"未找到名称为{topic_name}的主题") exit() # 发送文件到指定主题 client.send_file( group_id, 'test.jpg', reply_to=target_topic.top_message # 指定主题的起始消息ID )
补充说明
- 如果已经知道目标主题内某条消息的ID,也可以直接将
reply_to设为该消息ID,效果相同。 - 只有超级群(Supergroup)支持主题功能,普通群组无法使用该特性。
- 确保Telethon版本为v1.26及以上,可通过
pip show telethon查看当前版本。
内容的提问来源于stack exchange,提问作者Garobi
相关产品推荐
相关产品推荐

