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

如何让Telegram Bot将消息发送至指定论坛主题而非普通聊天

Telegram Bot 发送消息到论坛主题的正确方法

你当前的问题是把频道ID和主题ID拼在一起当成chat_id传递,但这不符合Telegram API的要求。要发送消息到论坛主题,需要分开传递频道ID和主题ID:

  • 频道ID:就是你原来topic_id里的-1002124######部分,不带后面的_33903
  • 主题ID:就是单独的数字33903,需要通过message_thread_id参数指定

修改后的代码示例

方法1:直接在send_message方法中添加主题ID参数

import os
import asyncio
from typing import Optional
from telegram import Bot, Message

class AsyncBotClient:
    def __init__(self, bot_token: str):
        self.bot = Bot(token=bot_token)

    async def send_message(
        self,
        chat_id: str,
        text: str,
        *,
        parse_mode: Optional[str] = None,
        disable_web_page_preview: Optional[bool] = None,
        disable_notification: Optional[bool] = None,
        reply_to_message_id: Optional[int] = None,
        message_thread_id: Optional[int] = None,  # 新增主题ID参数
        api_kwargs: Optional[dict] = None,
    ) -> Message:
        return await self.bot.send_message(
            chat_id=chat_id,
            text=text,
            parse_mode=parse_mode,
            disable_web_page_preview=disable_web_page_preview,
            disable_notification=disable_notification,
            reply_to_message_id=reply_to_message_id,
            message_thread_id=message_thread_id,  # 传递主题ID
            api_kwargs=api_kwargs,
        )

async def main():
    bot_token = "你的bot令牌"
    async_bot_client = AsyncBotClient(bot_token)
    channel_id = "-1002124######"  # 纯频道ID
    topic_id = 33903  # 单独的主题ID
    message_text = "test"
    await async_bot_client.send_message(
        chat_id=channel_id,
        text=message_text,
        message_thread_id=topic_id
    )

if __name__ == "__main__":
    asyncio.run(main())

方法2:通过api_kwargs传递主题ID(无需修改原有方法)

如果不想改动AsyncBotClient的方法,可以直接在调用时通过api_kwargs传参:

async def main():
    bot_token = "你的bot令牌"
    async_bot_client = AsyncBotClient(bot_token)
    channel_id = "-1002124######"
    topic_id = 33903
    message_text = "test"
    await async_bot_client.send_message(
        chat_id=channel_id,
        text=message_text,
        api_kwargs={"message_thread_id": topic_id}
    )

关键说明

Telegram的论坛主题属于频道内的子线程,发送消息时必须:

  1. 用频道的原始ID作为chat_id
  2. 用message_thread_id指定目标主题的ID(这个ID可以通过获取论坛主题列表或者查看主题消息的message_thread_id字段得到)

内容的提问来源于stack exchange,提问作者Xsenix Prod.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 19:17:03