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

如何使用Telethon向Telegram话题(子群组)发送消息?

如何用Telethon向Telegram论坛话题发送消息

你已经能获取论坛群组的话题列表,要实现向指定话题发送消息,只需要在调用send_message时指定reply_to参数为目标话题的id即可——Telegram的论坛话题本质是特殊的消息线程,通过话题ID就能定位到对应的讨论串。

修改你的代码,在遍历话题的循环中添加发送逻辑:

from datetime import datetime

from telethon import TelegramClient
from telethon.tl.custom import Dialog
from telethon.tl.functions.channels import GetForumTopicsRequest
from telethon.tl.types import PeerChannel, ForumTopic, InputPeerChannel
from telethon.tl.types.messages import ForumTopics


async def main(client: TelegramClient):
    async for dialog in client.iter_dialogs():  # type: Dialog
        if not dialog.is_group:
            continue

        print(f"\n{dialog.id=} {dialog.name=}")
        if dialog.is_channel and dialog.entity.forum:
            input_peer_channel: InputPeerChannel = await client.get_input_entity(PeerChannel(dialog.entity.id))
            topics_request = GetForumTopicsRequest(
                channel=input_peer_channel, offset_date=datetime.now(), offset_id=-1, offset_topic=-1, limit=50
            )
            forum_topics: ForumTopics = await client(topics_request)
            for topic in forum_topics.topics:  # type: ForumTopic
                print(f"\t{topic.id=} {topic.title=}")
                # 向该话题发送消息
                await client.send_message(
                    entity=input_peer_channel,
                    message=f"测试消息:发送到话题「{topic.title}」",
                    reply_to=topic.id
                )

if __name__ == '__main__':
    api_id = 123
    api_hash = '123...456'
    telegram_client = TelegramClient('user', api_id, api_hash)

    with telegram_client:
        telegram_client.loop.run_until_complete(main(telegram_client))

关键说明

  • entity参数传入论坛频道的InputPeerChannel,确保消息发送到正确的群组
  • reply_to参数指定话题的id,这是将消息定向到对应话题的核心,Telegram会自动识别该ID对应的话题线程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:05:11