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

如何用Python创建Telegram群组话题?原代码失效求解决方案

如何用Python创建Telegram群组话题?

可以通过Python实现Telegram群组话题创建,你之前的代码失效是因为python-telegram-bot库的API调用逻辑已更新,以下是基于最新版本的可行方案:

前置准备

  • 确保安装python-telegram-bot v20.x及以上版本,若版本过低可执行更新:
    pip install python-telegram-bot --upgrade
    
  • 目标群组必须是开启话题功能的超级群(普通群组不支持话题)
  • 机器人需拥有该群组的管理员权限,且开启「管理话题」权限

可行代码示例

import telegram
import asyncio

async def create_topic():
    bot_token = "你的机器人Token"
    chat_id = -你的超级群ID  # 注意是负数格式
    topic_name = "My New Topic"

    bot = telegram.Bot(token=bot_token)
    try:
        # 调用Telegram Bot API的createForumTopic接口
        result = await bot.create_forum_topic(
            chat_id=chat_id,
            name=topic_name
            # 可选参数:设置话题图标颜色或自定义表情
            # icon_color=7322096,  # 绿色,可选值:0(蓝色), 7322096(绿), 16766590(红), 13338331(黄)
            # icon_custom_emoji_id="自定义表情ID"
        )
        print(f"话题创建成功!话题ID: {result.message_thread_id}")
    except telegram.error.TelegramError as e:
        print(f"创建失败:{e.message}")

asyncio.run(create_topic())

关键说明

  • 新版库要求所有API调用必须使用异步方式(await关键字)
  • create_forum_topic方法直接对应Telegram官方Bot API的接口,返回结果包含话题的message_thread_id,可用于后续操作该话题
  • 若报错,可根据TelegramError返回的信息排查:比如权限不足、群组类型不支持等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 09:52:10