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

如何获取Telegram群组聊天的Topic ID(message_thread_id)

如何在python-telegram-bot中获取群组话题的message_thread_id

方法1:从接收的消息对象直接提取

当你的机器人在启用话题的群组中收到消息时,Update对象里的effective_message属性会包含message_thread_id字段,这就是当前消息所在话题的ID:

def handle_message(update: Update, context: CallbackContext):
    msg = update.effective_message
    topic_id = msg.message_thread_id
    
    if topic_id:
        # 主话题的ID固定为1,自定义话题为其他正整数
        print(f"消息所在话题ID: {topic_id}")
    else:
        print("该群组未启用话题功能,或消息不在话题内")

方法2:主动获取群组所有话题列表

调用bot.get_forum_topics()方法可以获取目标群组的所有话题,返回的每个ForumTopic实例都包含对应的message_thread_id:

def fetch_all_topics(chat_id: int, bot: Bot):
    topics = bot.get_forum_topics(chat_id=chat_id)
    for topic in topics:
        print(f"话题名称:{topic.name},话题ID:{topic.message_thread_id}")

验证话题ID有效性

如果需要主动发送消息到指定话题,可通过send_message的message_thread_id参数指定ID,若发送成功则说明ID有效:

bot.send_message(
    chat_id=目标群组ID,
    text="测试内容",
    message_thread_id=目标话题ID
)

注意事项

  • 仅启用论坛功能的群组才有话题ID,普通群组的message_thread_id始终为None。
  • 群组默认的主话题(通用话题)ID固定为1,自定义话题会被分配唯一的正整数ID。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:35:15