I want to use message.attachments to get images from that and upload those to my website (not on localhost). How would i do that?
I already have a working upload form on my website, but how would i do it from a discord.js bot?
According to the discord.js docs , each attachment has a URL property. You can use this to get the image and upload it.
Example code:
const URLsToFetch = [];
const attachments = message.attachments.array();
for(let i = 0;i<attachments.length;++i){
URLsToFetch.push(attachments[i].url);
}
This would get all the attachment URLs, which you can use http
, request
, or some other similar module to download it and then write it to wherever you put your uploads:
const http = require("http");
const https = require("https");
const {URL} = require("url");
const fs = require("fs");
for(let url of URLsToFetch){
const uri = new URL(url);
const protocol = uri.protocol;
let proto = http;
if(protocol === "https:"){
proto = https;
}
proto.get(uri,response=>{
const chunks = [];
response.on("data",chunk={
chunks.push(chunk);
});
response.on("end",()=>{
const file = Buffer.concat(chunks);
fs.writeFile("path/to/filename",file,err=>{
if(err){throw err} // error
// successfully wrote file
});
});
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.