discord.js saving an attachment “undefined”?

六眼飞鱼酱① 提交于 2021-01-28 06:26:17

问题


I've had a problem recently with users trolling and then deleting images before I can see what they are. So I'm creating a log to download everything into a log. (yes I've instantiated fs.js already). For some reason though, when writing the file... the file is only 9 bytes big (and the content is just "undefined"). Please help.

var attachment = (message.attachments).array();
attachment.forEach(function(attachment) {
  console.log(attachment.url);
  tempName = attachment.url.split("/");
  attachName = tempName[tempName.length-1]
  console.log(attachName);
  fs.writeFileSync(dir + "/" + attachName, attachment.file, (err) => {
      // throws an error, you could also catch it here
      if (err) throw err;

      // success case, the file was saved
      console.log('attachment saved!');

  });
  theLog += '<img src="'+ "attachments/" + message.channel.name + "/" + attachName + '"> \n';
  //theLog += '<img src="'+ attachment.url + '"> \n';
})

回答1:


Lets start with answering why it saves it as undefined. If you check the docs for MessageAttachment message.attachments.first().file is undefined. there is fileName and fileSize but no file

To save the file you can do 2 things...

  • Saving the URLS.

    You can save the url in an array in a JSON file like so:

JSON FILE

 {
     "images":[]
 }

JS FILE

    let imgs = require(JSON_FILE)
    imgs.images.push(attachment.url);
    fs.writeFile(JSON_FILE,JSON.stringify(imgs,null,4));

- Saving the IMAGE itself

You can use the request module to pull images from a url

JS FILE

    //Start of code
    let request = require(`request`);
    let fs = require(`fs`);
    //Later
        request.get(attachment.url)
            .on('error', console.error)
            .pipe(fs.createWriteStream(`Img-${Date.now()}`));//The "Img-${Date.now}" Guarantees Unique file names.

EDIT: request is deprecated. It's been replaced by fetch I can't confirm this code work's with fetch but the underlining principle is the same.




回答2:


I ended up solving it with a tiny function. Thanks everyone (especially the guy asking what a variable was... that was super helpful)

function downloadAttachment(url, dest, hash){
  console.log('initiating download of '+ url +'...');

  request(url).pipe(fs.createWriteStream(dest));

}

the "hash" variable is not used right now. I was hungry and craving corned beef hash...



来源:https://stackoverflow.com/questions/51777869/discord-js-saving-an-attachment-undefined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!