如何在创建Telegram话题后获取message_thread_id并实现自动发消息
Telegram Bot 话题管理与消息发送解决方案
一、创建话题后立即获取message_thread_id
调用Telegram Bot API的createForumTopic接口创建话题时,接口返回结果中会直接包含message_thread_id字段,这就是你需要的话题ID。
以Python为例,用requests库调用API的示例:
import requests BOT_TOKEN = "你的机器人令牌" CHAT_ID = "目标超级群组ID(带-前缀的负数,如-1001234567890)" TOPIC_NAME = "测试话题" # 创建话题 create_topic_url = f"https://api.telegram.org/bot{BOT_TOKEN}/createForumTopic" payload = { "chat_id": CHAT_ID, "name": TOPIC_NAME } response = requests.post(create_topic_url, json=payload) result = response.json() if result["ok"]: message_thread_id = result["result"]["message_thread_id"] print(f"创建的话题ID:{message_thread_id}") else: print(f"创建话题失败:{result['description']}")
二、实现“检查话题存在→发送/创建→发送”的自动流程
核心逻辑是先调用getForumTopics接口获取群组内所有话题,遍历匹配名称;找到对应话题则直接发消息,未找到则创建新话题后再发送。
完整Python示例:
import requests BOT_TOKEN = "你的机器人令牌" CHAT_ID = "目标超级群组ID" TARGET_TOPIC_NAME = "目标话题名称" MESSAGE_CONTENT = "要发送的消息内容" def get_topic_id_by_name(chat_id, topic_name): """根据话题名称获取对应的message_thread_id,不存在则返回None""" get_topics_url = f"https://api.telegram.org/bot{BOT_TOKEN}/getForumTopics" payload = {"chat_id": chat_id} response = requests.post(get_topics_url, json=payload) result = response.json() if not result["ok"]: return None for topic in result["result"]["topics"]: if topic["name"] == topic_name: return topic["message_thread_id"] return None def send_message_to_topic(chat_id, message_thread_id, text): """向指定话题发送消息""" send_msg_url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage" payload = { "chat_id": chat_id, "message_thread_id": message_thread_id, "text": text } response = requests.post(send_msg_url, json=payload) return response.json() # 执行流程 topic_id = get_topic_id_by_name(CHAT_ID, TARGET_TOPIC_NAME) if topic_id: print(f"找到现有话题,ID:{topic_id}") send_result = send_message_to_topic(CHAT_ID, topic_id, MESSAGE_CONTENT) else: print("未找到话题,创建新话题...") # 创建新话题 create_topic_url = f"https://api.telegram.org/bot{BOT_TOKEN}/createForumTopic" create_payload = {"chat_id": CHAT_ID, "name": TARGET_TOPIC_NAME} create_response = requests.post(create_topic_url, json=create_payload) create_result = create_response.json() if create_result["ok"]: topic_id = create_result["result"]["message_thread_id"] print(f"新话题创建成功,ID:{topic_id}") send_result = send_message_to_topic(CHAT_ID, topic_id, MESSAGE_CONTENT) else: print(f"创建话题失败:{create_result['description']}") if 'send_result' in locals() and send_result["ok"]: print("消息发送成功") else: print("消息发送失败")
关键注意事项
- 机器人必须拥有目标超级群组的管理员权限,且开启
manage_topics权限,否则无法创建或查询话题。 - 只有超级群组支持话题功能,普通群组无法使用该API。
CHAT_ID必须使用带负号的数值ID,不能用群组用户名。
内容的提问来源于stack exchange,提问作者Андрей Белый
相关产品推荐
相关产品推荐

