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

Pyrogram开发Telegram Bot:如何获取群组话题并提取指定消息?

Pyrogram机器人提取特定群组话题消息的方案

为什么调用GetForumTopics等接口报错?

你之前调用的是Telegram客户端API的方法,机器人账号无法直接使用这类接口,必须使用Pyrogram封装的Bot API对应方法。

具体实现步骤

1. 获取群组内的话题列表

使用Pyrogram为机器人提供的get_forum_topics方法,前提是机器人在目标群组拥有manage_topics权限:

from pyrogram import Client

app = Client("your_bot_session", bot_token="YOUR_BOT_TOKEN")

async def fetch_topics(chat_id):
    # 获取指定群组的所有话题
    topics = await app.get_forum_topics(chat_id)
    # 遍历输出话题ID和标题,方便找到目标话题ID
    for topic in topics:
        print(f"话题ID: {topic.id} | 标题: {topic.title}")

# 替换为你的目标群组ID(负数格式,比如-100XXXXXXX)
app.run(fetch_topics(-1001234567890))

2. 过滤并提取特定话题的消息

在消息处理逻辑中,通过message.topic.id判断消息所属话题,仅处理目标话题的内容:

from pyrogram import Client, filters

# 替换为你要提取的目标话题ID
TARGET_TOPIC_ID = 123
# 替换为目标群组ID
TARGET_CHAT_ID = -1001234567890

app = Client("your_bot_session", bot_token="YOUR_BOT_TOKEN")

@app.on_message(filters.group & filters.chat(TARGET_CHAT_ID))
async def process_topic_messages(client, message):
    # 跳过无话题的消息(如果需要)
    if not message.topic:
        return
    # 仅处理目标话题的消息
    if message.topic.id == TARGET_TOPIC_ID:
        # 这里编写你的消息收集逻辑
        print(f"收集到目标话题消息: {message.text or message.caption}")
        
        # 如需将响应发送到指定话题,添加message_thread_id参数
        await client.send_message(
            chat_id=TARGET_CHAT_ID,
            text="已成功收集该消息",
            message_thread_id=TARGET_TOPIC_ID
        )

app.run()

3. 必要权限说明

  • 机器人必须被添加到目标超级群组,且群组已开启论坛(话题)模式;
  • 机器人需拥有read_messages权限以读取消息,manage_topics权限以获取话题列表;
  • 如果仅需读取特定话题消息,read_messages权限足够,无需manage_topics。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 13:33:30