1

As an experiment, I was trying to find whether I could read files that were entered as attachments into chat eg: image files, txt, etc.

I've been looking around for a long while and I have still found no information on it.

So it possible to do this using Discord.js? If so, how would I go about doing it?

Kookie
  • 328
  • 4
  • 14

1 Answers1

3

This can be done using the attachments property of a Message to find the attachment and consequently its URL. You can then download the URL using the http and fs modules. It would look something like this:

dClient.on('message', msg => {
    if (msg.attachments) {
        for (var key in msg.attachments) {
            let attachment = msg.attachments[key];
            download(attachment.url);
        }
    }
});
bluecereal
  • 453
  • 4
  • 6
  • I guess I wasn't really 100% specific with my question, but when the download() function is called, does the file get saved somewhere on my computer? – Kookie May 23 '18 at 13:40
  • Yes, the file will be saved to the directory your program is running in. You would have to read the file back into your program after downloading it. I'm sure there is a way to avoid saving the attachment to your hard drive, but I do not know it. – bluecereal May 25 '18 at 21:04
  • @Paydayzcool [Streams](https://nodejs.org/api/stream.html) can be used to do this. You could use the [request module](https://github.com/request/request) to create a stream from the attachment URL and then write the data from the stream into chat. – bluecereal Jun 05 '18 at 04:38
  • Got it. Thanks! – Kookie Sep 26 '18 at 07:04