1

So far I've only been able to get text and links from what other people on my discord channel type, but I want to be able to save posted images/gifs. is there any way I can do this through the bot or is it impossible? I'm using discord.js.

Kyle
  • 28
  • 1
  • 3
  • 2
    Where are you wanting to save the images / gifs? You mean on your person computer, or on the server hosting your bot, or some other database like firebase? – Blundering Philosopher Mar 02 '18 at 09:15

1 Answers1

3

Images in Discord.js come in the form of MessageAttachments via Message#attachments. By looping through the amount of attachments, we can retrieve the raw file via MessageAttachment#attachment and the file type using MessageAttachment#name. Then, we use node's FileSystem to write the file onto the system. Here's a quick example. This example assumes you already have the message event and the message variable.

const fs = require('fs');
msg.attachments.forEach(a => {
    fs.writeFileSync(`./${a.name}`, a.file); // Write the file to the system synchronously.
});

Please note that in a real world scenario you should surround the synchronous function with a try/catch statement, for errors.

Also note that, according to the docs, the attachment can be a stream. I have yet to have this happen in the real world, but if it does it might be worth checking if a is typeof Stream, and then using fs.createWriteStream and piping the file into it.

FireController1847
  • 1,458
  • 1
  • 11
  • 26