如何通过Telegram Bot API验证用户提供的话题链接有效性?
用Telegram Bot API验证话题链接有效性
核心步骤
- 解析链接提取关键信息
Telegram话题链接的标准格式为https://t.me/<chat_username>/<topic_id>或t.me/<chat_username>/<topic_id>,需要从中分离出<chat_username>(可带@或不带)和<topic_id>(纯数字)。 - 验证聊天对象合法性
调用Bot API的getChat接口,传入chat_id为@<chat_username>(或直接用用户名)。若返回正常数据,说明该聊天对象(超级群/支持话题的频道)存在;若返回400或404错误,则聊天对象无效。 - 验证话题是否存在
调用getForumTopicInfo接口,参数为chat_id(同上)和message_thread_id(即话题ID)。若返回包含话题标题、创建时间的有效数据,说明话题合法;若返回400错误(如Topic not found),则话题无效。
代码示例(Python)
import requests BOT_TOKEN = "你的机器人Token" BASE_API_URL = f"https://api.telegram.org/bot{BOT_TOKEN}/" def check_topic_validity(link): # 统一链接格式 if not link.startswith(('http://', 'https://')): link = f"https://{link}" # 解析链接内容 try: path_segment = link.split('t.me/')[1] chat_username, topic_id = path_segment.split('/') topic_id = int(topic_id) except (IndexError, ValueError): return False, "链接格式不符合Telegram话题规范" # 验证聊天对象 chat_check_res = requests.get(f"{BASE_API_URL}getChat?chat_id=@{chat_username}") chat_data = chat_check_res.json() if not chat_data.get('ok'): return False, f"聊天对象无效: {chat_data.get('description')}" # 验证话题存在性 topic_check_res = requests.get(f"{BASE_API_URL}getForumTopicInfo?chat_id=@{chat_username}&message_thread_id={topic_id}") topic_data = topic_check_res.json() if not topic_data.get('ok'): return False, f"话题无效: {topic_data.get('description')}" return True, f"话题有效,标题: {topic_data['result']['name']}" # 测试调用示例 test_link = "https://t.me/test_supergroup/123" is_valid, result_msg = check_topic_validity(test_link) print(is_valid, result_msg)
注意事项
- 机器人必须被添加到目标超级群/频道,且至少拥有「查看消息」权限,否则会返回
403 Forbidden错误。 - 私有超级群/频道的链接无法被未加入的机器人验证,因为机器人无访问权限。
- 若链接包含额外参数(如跟踪参数),需要先清理掉无关内容再解析。
内容的提问来源于stack exchange,提问作者Ashutosh
相关产品推荐
相关产品推荐

