问题
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.
imagine that someone on the chat sentí an image, is there a way of the bot downloading the image or get the url of the image?
thanks!
回答1:
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
回答2:
Besides the link I posted in the comments section, from looking at the Discord documentation, it appears the url
is in the attachment
object.
来源:https://stackoverflow.com/questions/51550993/download-file-to-local-computer-sent-attatched-to-message-discord