如何用Java Spring Boot的LongPollingBot高质量保存Telegram用户照片到本地
解决方案
核心问题分析
你之前的代码错误在于直接将photoSize.getFileId()的字节写入文件,这只是保存了Telegram对文件的唯一标识字符串,而非实际的图片内容。同时旧版的getInputStream()方法已被废弃,需要使用官方推荐的新API来下载文件。
正确实现步骤
- 优先选择最高质量的图片:Telegram返回的
PhotoSize列表是按尺寸从小到大排序的,最后一个元素是分辨率最高的图片,所以应该取msg.getPhoto().get(msg.getPhoto().size() - 1)而非第一个元素。 - 通过
FileId获取文件路径:调用GetFileRequest接口获取图片在Telegram服务器上的文件路径。 - 下载图片字节流:使用Bot实例的
downloadFile方法获取图片的字节数组。 - 写入本地文件:确保目标文件夹存在,再通过
FileOutputStream将字节数组写入文件。
完整代码示例
import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.PhotoSize; import org.telegram.telegrambots.meta.api.methods.GetFile; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; // 在处理消息的方法中添加如下逻辑 public void handlePhotoMessage(Message msg) { // 获取最高质量的图片 PhotoSize highestQualityPhoto = msg.getPhoto().get(msg.getPhoto().size() - 1); String fileId = highestQualityPhoto.getFileId(); // 创建保存图片的文件夹,不存在则创建 File photoDir = new File("./photos"); if (!photoDir.exists()) { photoDir.mkdirs(); } File outputFile = new File(photoDir, fileId + ".jpg"); try { // 1. 获取文件信息(包含Telegram服务器上的文件路径) GetFile getFileRequest = new GetFile(); getFileRequest.setFileId(fileId); org.telegram.telegrambots.meta.api.objects.File file = execute(getFileRequest); // 2. 下载图片字节数组 byte[] photoBytes = downloadFile(file.getFilePath()); // 3. 写入本地文件 try (FileOutputStream outputStream = new FileOutputStream(outputFile)) { outputStream.write(photoBytes); } System.out.println("图片已成功保存至:" + outputFile.getAbsolutePath()); } catch (TelegramApiException | IOException e) { e.printStackTrace(); } }
关键说明
execute(getFileRequest):继承LongPollingBot后可直接调用该方法发送请求,获取Telegram服务器上的文件路径信息。downloadFile(file.getFilePath()):这是官方替代旧getInputStream()的新方法,直接返回文件字节数组,无需手动处理流关闭。- 文件夹创建:提前创建
./photos文件夹,避免写入时抛出FileNotFoundException。
内容的提问来源于stack exchange,提问作者Павлюченко Антон
相关产品推荐
相关产品推荐

