Java Telegram Bot升级后如何将file_id转为InputFile发送照片?
问题解答
1. 将数据库中的file_id字符串转换为InputFile参数(适配6.4.0版本)
从telegrambots 5.0.0版本开始,setPhoto方法不再接受String类型的file_id,必须传入InputFile对象。你可以直接通过InputFile的构造函数,将数据库读取到的file_id字符串转换为所需参数,具体实现如下:
单张照片发送示例
// 从MySQL数据库读取的file_id String photoFileId = "xxx"; // 用file_id直接实例化InputFile InputFile inputPhoto = new InputFile(photoFileId); // 构造发送请求 SendPhoto sendPhoto = new SendPhoto(); sendPhoto.setChatId(groupChatId); sendPhoto.setPhoto(inputPhoto); // 添加地点信息(根据你的业务需求设置) sendPhoto.setLocation(new Location(39.9042, 116.4074)); sendPhoto.setCaption("地点名称:北京天安门"); // 发送消息 Message sentMessage = execute(sendPhoto); // 置顶消息 PinChatMessage pinMsg = new PinChatMessage(); pinMsg.setChatId(groupChatId); pinMsg.setMessageId(sentMessage.getMessageId()); pinMsg.setDisableNotification(true); // 可选:是否静默置顶 execute(pinMsg);
多张照片(关联同一地点)发送示例
如果需要给单个地点发送最多2张照片,可使用SendMediaGroup批量发送,再置顶消息组:
List<String> photoFileIds = Arrays.asList("file_id_1", "file_id_2"); // 从数据库读取的file_id列表 List<InputMedia> mediaList = new ArrayList<>(); for (String fileId : photoFileIds) { InputMediaPhoto mediaPhoto = new InputMediaPhoto(new InputFile(fileId)); mediaPhoto.setCaption("地点:XX景区"); // 统一或单独设置描述 mediaList.add(mediaPhoto); } SendMediaGroup sendMediaGroup = new SendMediaGroup(); sendMediaGroup.setChatId(groupChatId); sendMediaGroup.setMedias(mediaList); // 发送媒体组 List<Message> sentMessages = execute(sendMediaGroup); // 置顶媒体组的第一条消息(Telegram会自动置顶整个组) PinChatMessage pinMsg = new PinChatMessage(); pinMsg.setChatId(groupChatId); pinMsg.setMessageId(sentMessages.get(0).getMessageId()); execute(pinMsg);
2. 关于4.9.2版本是否修复用户ID溢出问题
telegrambots 3.6.1版本因用户ID使用int类型存储(最大值为2147483647),导致超过该值的用户ID触发溢出崩溃。从4.x版本开始,库已将用户ID的类型替换为long(支持更大数值范围),因此4.9.2版本已完全解决用户ID溢出问题。
内容的提问来源于stack exchange,提问作者Fabio
相关产品推荐
相关产品推荐

