discordjda保存包含在消息中的文件附件

nbnkbykc  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(441)

代码如下:

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 我试过使用文件流,但可能做错了什么。我该如何抓取邮件附件,假设它有附件,然后保存文件?

gwbalxhn

gwbalxhn1#

您可以使用downloadtofile(名称):

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;
});

相关问题