download file to local computer sent attatched to message discord

后端 未结 2 557
闹比i
闹比i 2021-01-27 03:37

after looking on the Discord.js docs i can find an answer for the question, does someone know how to do it? theres already a question the page but has no answers or comments.

2条回答
  •  迷失自我
    2021-01-27 04:15

    For starters... You'd need the code to access the attachment.

    client.on(`message`,function(msg){
        if(msg.attachments.first()){//checks if an attachment is sent
            if(msg.attachments.first().filename === `png`){//Download only png (customize this)
                download(msg.attachments.first().url);//Function I will show later
            }
        }
    });
    

    Note: I limited attachments to png only so we download verified images. Otherwise we might download some bad scripts and possibly viruses. Be careful when downloading stuff.

    Now the code I just gave you calls download and passes in the url.
    Now you will need the request module AND the fs module.

    Why? Glad you asked... The request module accesses the url and pulls it the data from the web.
    The fs module create/reads/writes files on your local/external machine...

    Using the two modules, we will pull it and then save it.

    Now lets assume url is this meme.png (discord png attachment)

    let request = require(`request`);
    let fs = require(`fs`);
    function download(url){
        request.get(url)
            .on('error', console.error)
            .pipe(fs.createWriteStream('meme.png'));
    }
    

    and Voila! We now have a meme.png image about Doritos XD

提交回复
热议问题