java - Discord JDA 保存邮件中包含的文件附件
问题描述
代码如下:
package volmbot.commands;
import lombok.SneakyThrows;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class SandBox extends ListenerAdapter {
@SneakyThrows
public void onGuildMessageReceived(GuildMessageReceivedEvent e) {
String[] args = e.getMessage().getContentRaw().split(" ");
e.getMessage().getAttachments();
String authId = e.getMessage().getAuthor().getId();
//Grab file and save it as the user's ID
FileOutputStream saveFile = new FileOutputStream(authId + ".txt");
ObjectOutputStream save = new ObjectOutputStream(saveFile);
save.writeObject(e.getMessage().getAttachments());
save.close();
}
}
我的目标是做到以下几点:
- 保存用户在邮件中发送的文件(如果邮件有附件)
- 如果消息不包含消息,则忽略它
- 将用户 ID 保存到文件中
id.txt
我试过使用 Filestream,但我可能做错了什么。假设它有附件,我将如何管理如此抓取消息附件,然后保存文件?
解决方案
您可以使用downloadToFile(name):
List<Message.Attachment> attachments = event.getMessage().getAttachments();
if (attachments.isEmpty()) return; // no attachments on the message!
CompletableFuture<File> future = attachments.get(0).downloadToFile(authId + ".txt");
future.exceptionally(error -> { // handle possible errors
error.printStackTrace();
return null;
});
推荐阅读
- android - 如何使用 HILT android 在服务中调用 api
- ios - 如何在 iOS 14 的内联样式日期选择器顶部设置时间选择器?
- java - 仅使用 Mockito 模拟新对象
- javascript - 根据其他 div 的可见性和不可见性调整 div 的大小(仅在 javascript 中)
- c - 如何从共享对象(.so)执行功能
- sqlite - 如何修复 SQlite?
- python - 面临错误:“TypeError:'int'对象不可调用”
- amazon-web-services - 如何将亚马逊机器学习服务与 Ionic-5 Angular 应用程序集成?
- keras - 使用 LSTM 根据不同的年度目标数据预测每周结果
- ios - Xamarin iOS WebView 为空白