【问题标题】:discord.js saving an attachment "undefined"?discord.js 保存附件“未定义”?
【发布时间】:2019-01-17 13:25:40
【问题描述】:

我最近遇到了一个问题,即用户在查看图片内容之前先拖钓然后删除图片。所以我正在创建一个日志以将所有内容下载到日志中。 (是的,我已经实例化了 fs.js)。但是由于某种原因,在写入文件时......文件只有 9 个字节大(并且内容只是“未定义”)。请帮忙。

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';
})

【问题讨论】:

  • theLog 到底是什么?您指的是它,但从不显示它的创建位置或写入文件的位置。请提供minimal reproducible example

标签: discord.js


【解决方案1】:

让我们从回答为什么将其保存为 undefined 开始。 如果您检查 MessageAttachment 的文档,message.attachments.first().file 未定义。有fileNamefileSize 但没有file

要保存文件,您可以做两件事...

  • 保存 URL。

    您可以将 URL 保存在 JSON 文件中的数组中,如下所示:

JSON 文件

 {
     "images":[]
 }

JS 文件

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

- 保存图像本身

您可以使用request 模块从网址拉取图片

JS 文件

    //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.

编辑: request 已弃用。它已被fetch 替换我无法确认此代码是否与fetch 一起工作,但下划线原理是相同的。

【讨论】:

  • 谢谢。我今天会试试这个。
  • 请求已弃用
  • @FourCinnamon0 使用 fetch 它应该几乎与 request 一样工作
【解决方案2】:

我最终用一个小函数解决了这个问题。谢谢大家(尤其是那个问变量是什么的人......这非常有帮助)

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

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

}

“哈希”变量现在不使用。我饿了,想吃咸牛肉杂烩……

【讨论】:

    猜你喜欢
    • 2021-10-16
    • 2020-08-07
    • 2021-06-20
    • 2021-06-28
    • 2020-12-14
    • 2022-08-21
    • 1970-01-01
    • 2021-05-06
    • 2021-07-10
    相关资源
    最近更新 更多