如何用Python创建Telegram群组话题?原代码失效求解决方案
如何用Python创建Telegram群组话题?
可以通过Python实现Telegram群组话题创建,你之前的代码失效是因为python-telegram-bot库的API调用逻辑已更新,以下是基于最新版本的可行方案:
前置准备
- 确保安装
python-telegram-botv20.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
相关产品推荐
相关产品推荐

