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

如何基于TDLib的Python-Telegram直接获取Telegram论坛特定Topic消息?

直接获取Telegram论坛特定Topic消息的方案

当然有更高效的方案,无需拉取整个群组的所有聊天历史。基于TDLib的Python库(比如Telethon)支持直接针对单个Forum Topic拉取消息,核心是使用TDLib原生的getForumTopicMessages方法或其封装接口。

具体步骤:

  1. 获取目标Topic的ID
    通过群组ID获取该论坛的所有Topic列表,根据标题或标识匹配到你需要的Topic ID。
  2. 直接拉取该Topic的消息
    使用指定Topic ID的方法拉取消息,跳过无关Topic的内容,大幅提升效率。

Python代码示例(以Telethon为例):

from telethon import TelegramClient
from telethon.tl.types import InputForumTopic

# 替换为你的API信息和会话文件路径
client = TelegramClient('my_session', api_id=YOUR_API_ID, api_hash='YOUR_API_HASH')

async def get_specific_topic_messages(chat_id, target_topic_title):
    # 获取群组内所有论坛Topic
    topics = await client.get_forum_topics(chat_id)
    # 筛选出目标Topic
    target_topic = next((topic for topic in topics if topic.title == target_topic_title), None)
    if not target_topic:
        print(f"未找到标题为{target_topic_title}的Topic")
        return
    
    # 拉取该Topic的消息,limit控制单次拉取数量,可循环拉取历史
    messages = await client.get_messages(
        chat_id,
        limit=200,
        reply_to=InputForumTopic(target_topic.id)
    )
    
    # 遍历处理消息(示例:打印内容,实际替换为保存到本地的逻辑)
    for msg in messages:
        if msg.text:
            print(f"[{msg.date}] {msg.text}")

# 运行客户端执行任务
with client:
    client.loop.run_until_complete(
        get_specific_topic_messages(-100123456789, "我的个人数据Topic")
    )

关键说明:

  • 若需拉取更早的历史消息,可循环调用get_messages,每次将offset_id设为上一次拉取的最后一条消息ID,直到返回的消息列表为空。
  • 如果使用的是原生TDLib封装的python-tdlib库,直接调用以下接口即可:
    client.execute({
        '@type': 'getForumTopicMessages',
        'chat_id': chat_id,
        'message_thread_id': topic_id,
        'limit': 100
    })
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 18:05:03