简体   繁体   中英

Is it possible to get an image from a message and add it to a folder in Discord.js?

Like is it possible to do something like !image add [image file] and then add the attachment to a folder? I think i can do that with fs, but i'm not sure how

You can use the fs function fs.writeFile() or fs.writeFileSync() . This function accepts the absolute path to a file to write to, and the data to write. In your case, it should be a buffer or stream.

// const fs = require('fs');
fs.writeFileSync('./some_dir/some_file_name.extension', data);

To get the data in question, you should access Message#attachments() , a collection of all attachments on the message. Assuming you only want the first, you can use Collection#first() to narrow down the results.

const attachment = message.attachments.first();
if (!attachment) {
  // maybe place in some error handling
}

Unfortunately, the MessageAttachment class doesn't actually hold a buffer/stream representing the attachment, only the URL leading to it. This means you'll need a third-party library such as axios or node-fetch .

// const fetch = require('node-fetch');
fetch(attachment.url)
  .then(res => res.buffer())
  .then(buffer => {
    fs.writeFileSync(`./images/${attachment.name}`, buffer);
  });

Make sure to validate that URL to make sure it's an image!

if(!/\.(png|jpe?g|svg)$/.test(attachment.url)) {
  // this attachment isn't an image!
  // we don't want to be downloading .exe files now, do we?
}

Finally, you should also be weary that if two files are named the same, such as image.png , trying to write the second one will overwrite the first. One way to overcome that issue is to add numerical suffixes to duplicates, such as image.png , image-1.png , image-2.png , etc. That could work out a little like this:

fetch(attachment.url)
  .then(res => res.buffer())
  .then(buffer => {
    let path = `./images/${attachment.name}`;
    // increment the suffix every iteration until a file
    // by the same name cannot be found
    for (let count = 1; fs.existsSync(path); count++) {
      path = `./images/${attachment.name}-${count}`;
    }
    fs.writeFileSync(path, buffer);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM