基于aiogram框架:如何通过Telegram聊天链接获取聊天ID?
基于aiogram从Telegram聊天URL提取聊天ID
核心思路
Telegram聊天URL主要分两类:含用户名的(私聊/公开群组/频道)、含邀请链接的(私有群组/频道)。aiogram的Bot.get_chat()方法支持直接传入用户名或邀请链接字符串,返回的Chat对象中id字段即为目标聊天ID。
实现步骤
1. 解析用户发送的URL,提取关键标识
从用户输入的URL中剥离前缀,提取核心部分:
- 对
https://t.me/xxx或t.me/xxx格式,提取xxx(用户名/公开群组名) - 对
https://t.me/joinchat/xxxxxx格式,提取joinchat/xxxxxx完整邀请路径
简单字符串处理示例:
def extract_chat_identifier(url: str) -> str: if url.startswith(("https://t.me/", "t.me/")): return url.split("t.me/")[-1] # 兼容用户直接发送用户名或邀请链接的情况 return url
2. 调用aiogram接口获取聊天ID
在消息处理函数中调用bot.get_chat(),传入解析后的标识,同时处理异常场景(如链接无效、bot无权限访问等)。
完整代码示例:
from aiogram import Bot, Dispatcher, types from aiogram.types import Message from aiogram.utils.exceptions import ChatNotFound, Unauthorized # 初始化Bot和Dispatcher API_TOKEN = "你的Bot Token" bot = Bot(token=API_TOKEN) dp = Dispatcher(bot) def extract_chat_identifier(url: str) -> str: if url.startswith(("https://t.me/", "t.me/")): return url.split("t.me/")[-1] return url @dp.message_handler(content_types=types.ContentTypes.TEXT) async def get_chat_id(message: Message): user_input = message.text.strip() chat_identifier = extract_chat_identifier(user_input) try: chat = await bot.get_chat(chat_identifier) await message.reply(f"对应的聊天ID是:{chat.id}") except ChatNotFound: await message.reply("无法找到该聊天,请检查链接是否正确,或确认我已加入目标群组/频道") except Unauthorized: await message.reply("我没有权限访问该聊天,请先将我添加到群组/频道中") except Exception as e: await message.reply(f"出现错误:{str(e)}") if __name__ == "__main__": from aiogram import executor executor.start_polling(dp, skip_updates=True)
注意事项
- 私有群组/频道需先将bot加入,否则会抛出权限相关异常
- 私聊场景下,目标用户需已与bot有过对话(或bot主动发起过对话),否则无法通过用户名获取ID
- 确保bot在群组中至少拥有普通成员权限
内容的提问来源于stack exchange,提问作者san1rope
相关产品推荐
相关产品推荐

