问题描述
代码如下:
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();
}
}
我的目标是做到以下几点:
我尝试过使用文件流,但我可能做错了什么。 假设它有附件,我将如何管理如此抓取消息附件,然后保存文件?
解决方法
您可以使用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;
});