本文介绍使用 telegrambots 库在 java 中调用 telegram bot api 获取用户头像(userprofilephotos)的完整方法,包含代码示例、关键参数说明及常见注意事项。
本文介绍使用 telegrambots 库在 java 中调用 telegram bot api 获取用户头像(userprofilephotos)的完整方法,包含代码示例、关键参数说明及常见注意事项。
在 Telegram Bot 开发中,用户头像并非直接随 Update 对象返回,而是需通过独立 API 方法 getUserProfilePhotos 主动查询。该方法返回最多 100 张历史头像(按上传时间倒序),每组头像包含多个尺寸(如小、中、大),实际使用时通常取最新一组(索引为 0)中的最大尺寸照片。
以下是在 /start 命令处理逻辑中安全获取并打印用户头像信息的完整示例:
if (update.hasMessage() && update.getMessage().hasText()) {
String messageText = update.getMessage().getText();
long chatId = update.getMessage().getChatId();
User user = update.getMessage().getFrom();
String languageCode = user.getLanguageCode();
if ("/start".equals(messageText)) {
// ✅ 注意:此处应传 user.getId(),而非 chatId!
GetUserProfilePhotos getUserProfilePhotos = new GetUserProfilePhotos();
getUserProfilePhotos.setUserId(user.getId()); // 关键:传用户唯一 ID,不是聊天 ID
try {
UserProfilePhotos result = execute(getUserProfilePhotos);
if (result.getPhotos().isEmpty()) {
System.out.println("User has no profile photos.");
} else {
// 获取最新一组头像(通常为当前头像)
List<PhotoSize> latestPhotos = result.getPhotos().get(0);
// 推荐取尺寸最大的一张(Telegram 通常按 size 递增排序)
PhotoSize largestPhoto = latestPhotos.get(latestPhotos.size() - 1);
System.out.println("Avatar file_id: " + largestPhoto.getFileId());
System.out.println("Avatar width: " + largestPhoto.getWidth());
System.out.println("Avatar height: " + largestPhoto.getHeight());
// 可进一步调用 getFile() 获取下载链接(需 bot token 鉴权)
}
} catch (TelegramApiException e) {
System.err.println("Failed to fetch profile photos: " + e.getMessage());
throw new RuntimeException(e);
}
} else {
sendMessage(chatId, localization.getLocalizedString(languageCode, "commandWasNotRecognized"));
}
}⚠️ 重要注意事项:
分析 Java Spring Boot 后端 Controller 代码,自动生成 Markdown 格式的接口文档。当用户说“生成 Java 接口文档”、“生成 API 文档”、“从 Spring 代码生成文档”时触发。
- setUserId() 必须传入 user.getId()(即发送消息用户的唯一整数 ID),不可误用 chatId(群聊/频道 ID 与用户 ID 不同,且头像属于用户而非聊天);
- getUserProfilePhotos 默认返回最多 1 组(limit=1),如需更多历史头像,可调用 setLimit(n);
- 返回的 PhotoSize 列表按分辨率从小到大排列,建议取最后一项作为高质量头像;
- 头像 file_id 仅用于后续调用 getFile 接口下载;实际文件 URL 需拼接 https://api.telegram.org/file/bot
/ ,且有效期有限; - 用户若从未设置头像,result.getPhotos() 将为空列表,务必判空处理。
综上,获取头像是典型的两步操作:先查 getUserProfilePhotos 得到 file_id,再用 getFile 获取可下载路径。本方案已通过 telegrambots v6.9+ 验证,适用于私聊与群聊中的用户头像拉取场景。
立即学习“Java免费学习笔记(深入)”;

















