如何通过用户名获取用户ID(基于aiogram库)
使用aiogram通过用户名获取Telegram用户ID的方法
要通过用户名获取用户ID,你可以利用Telegram Bot API提供的get_chat方法——在Telegram体系中,用户账号属于private类型的chat,因此通过用户名调用该方法就能获取到包含用户ID的chat对象。
实现步骤与注意事项
- 权限要求:机器人必须与目标用户有过交互(比如用户主动给机器人发过消息,或者机器人在用户所在的群组/频道中),否则因Telegram隐私限制,无法获取用户信息。
- 用户名格式:用户名需以
@开头(如果用户输入时没加,代码中可以自动补上)。
代码实现(结合你的现有项目)
在你的代码中添加一个新的命令处理器,用于处理获取用户ID的请求:
import logging from configparser import ConfigParser from aiogram import Bot, Dispatcher, executor, types logging.basicConfig(level=logging.INFO) config = ConfigParser() config.read('config.ini') TOKEN = config.get('BOT', 'Token') bot = Bot(token=TOKEN) dp = Dispatcher(bot) @dp.message_handler(commands=['start']) async def start(message: types.Message): text = config.get('BOT_TEXT', 'Start') await bot.send_message(message.chat.id, text) @dp.message_handler(commands=['getid']) async def get_user_id(message: types.Message): # 检查是否提供了用户名参数 if len(message.text.split()) < 2: await message.reply("请提供目标用户名,格式:/getid @username") return username = message.text.split()[1] # 确保用户名以@开头 if not username.startswith('@'): username = f'@{username}' try: chat = await bot.get_chat(username) # 判断是否为用户账号 if chat.type == 'private': await message.reply(f"用户 {username} 的ID是:{chat.id}") else: await message.reply("输入的不是用户账号,可能是群组或频道") except Exception as e: # 捕获无法获取信息的异常(如用户不存在、无权限) await message.reply(f"获取失败:{str(e)}") @dp.message_handler() async def forward(message: types.Message): await bot.send_message(message.forward_from.id, 'Kuku') if __name__ == '__main__': executor.start_polling(dp, skip_updates=True)
补充说明
你现有代码中的forward函数是通过转发消息的message.forward_from.id获取发送者ID,这是针对转发场景的ID获取方式,和通过用户名主动查询的逻辑不同。
内容的提问来源于stack exchange,提问作者archdrdr
相关产品推荐
相关产品推荐

