如何在Java Telegram Bot中获取用户头像?
使用Java telegrambots库获取Telegram用户头像示例
依赖配置
在你的Maven项目中添加以下依赖:
<dependency> <groupId>org.telegram</groupId> <artifactId>telegrambots</artifactId> <version>6.9.7</version> <!-- 建议使用最新稳定版本 --> </dependency>
完整代码示例
下面是补全后的代码,实现收到/start命令时获取并打印用户头像信息:
import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.User; import org.telegram.telegrambots.meta.api.objects.UserProfilePhotos; import org.telegram.telegrambots.meta.api.objects.PhotoSize; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; // 假设这是你的Bot类中的onUpdateReceived方法 @Override public void onUpdateReceived(Update update) { String languageCode; if (update.hasMessage() && update.getMessage().hasText()) { String messageText = update.getMessage().getText(); long chatId = update.getMessage().getChatId(); User user = update.getMessage().getFrom(); languageCode = user.getLanguageCode(); if (messageText.equals("/start")) { try { // 获取用户头像列表,参数:用户ID、偏移量(0表示最新)、获取数量(1表示只拿最新的一组) UserProfilePhotos profilePhotos = getUserProfilePhotos(user.getId(), 0, 1); if (profilePhotos.getTotalCount() > 0) { // 获取最新的一组头像,每组包含不同尺寸的照片,最后一个元素为最大尺寸 PhotoSize largestPhoto = profilePhotos.getPhotos().get(0).get(profilePhotos.getPhotos().get(0).size() - 1); System.out.println("用户头像(最大尺寸)文件ID:" + largestPhoto.getFileId()); System.out.println("用户头像可访问URL:" + getFileUrl(largestPhoto.getFileId())); } else { System.out.println("该用户未设置头像"); } } catch (TelegramApiException e) { e.printStackTrace(); sendMessage(chatId, "获取头像时出错"); } } else { sendMessage(chatId, localization.getLocalizedString(languageCode, "commandWasNotRecognized")); } } }
关键说明
getUserProfilePhotos(user.getId(), 0, 1):调用Telegram API获取用户头像列表,参数依次为用户ID、偏移量(从哪组头像开始取)、获取的组数。PhotoSize对象:每组头像包含多个不同尺寸的照片实例,通常最后一个元素是最大尺寸的头像。getFileUrl(fileId):通过文件ID生成头像的可访问URL,这是telegrambots库Bot类提供的内置方法。- 异常处理:API调用可能因网络或权限问题失败,需捕获
TelegramApiException并做相应处理。
内容的提问来源于stack exchange,提问作者Sergei Lobachev
相关产品推荐
相关产品推荐

