PsychopathNextdoor
PsychopathNextdoor

Reputation: 31

Discord JDA Save a file attachment that was included in a message

The code is as follows:

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


    }
}

My goal is to do the following:

I've tried using a Filestream, but I might be doing something wrong. How would I manage so grab the messages attachment, assuming it has an attachment, then save the file?

Upvotes: 2

Views: 2435

Answers (1)

Minn
Minn

Reputation: 6134

You can use 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;
});

Upvotes: 2

Related Questions