【问题标题】:Discord bot can't load data from attachmentDiscord 机器人无法从附件加载数据
【发布时间】:2018-12-15 17:08:16
【问题描述】:

我想从消息中加载数据。 我上网查了一下,发现:

if (message.attachments) {

       let attachment = message.attachments.first;
                    download(attachment.url);
                                
                    var myData = fs.readFileSync(attachment.filename);
                    data = JSON.parse(myData);

        }

但是 download() 不存在。 我没有找到其他方法。

我该怎么办?

【问题讨论】:

    标签: javascript json discord.js


    【解决方案1】:

    我不知道你在哪里找到那段代码,但它可能有点过时了。

    您可以将MessageAttachment.attachmentfs.readFile()fs.readFileSync() 结合使用

    你可以试试这样写:

    if (message.attachments) {
      let file = message.attachments.first(); //this is the attchment you choose to use
      let data = fs.readFileSync(file.attachment); //this reads the attachment & returns the data
      //then you can parse it or use it however you want
    }
    

    如果有问题或您有任何其他问题,请告诉我

    【讨论】:

    • UnhandledPromiseRejectionWarning: TypeError: path must be a string or Buffer at Object.fs.openSync (fs.js:646:18) at Object.fs.readFileSync (fs.js:551:33) at Client.bot.on.message (/app/main.js:180:9) 上的 loadDataFromMessage (/app/main.js:2314:29) 感谢您的快速帮助,但它不起作用:/
    【解决方案2】:

    我猜可能是这样,它会下载例如 url https://example.com/image.pngimage.png

    const path = require("path");
    const https = require("https");
    
    let download = function(url) {
        let filename = path.basename(url);
        let file = fs.createWriteStream(filename);
        let request = https.get(url, function(response) {
            response.pipe(file);
            file.on('finish', function() {
                file.close();
                });
            file.on('error', function(err) {
                fs.unlink(filename);
                console.error(err);
                });
            });
        };
    

    【讨论】:

      猜你喜欢
      • 2021-02-19
      • 1970-01-01
      • 2020-12-27
      • 2018-07-22
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2019-10-31
      相关资源
      最近更新 更多