[英]Uploading image from discord.js bot to my website
I want to use message.attachments to get images from that and upload those to my website (not on localhost).我想使用 message.attachments 从中获取图像并将其上传到我的网站(不在本地主机上)。 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?我的网站上已经有一个有效的上传表单,但是我将如何从 discord.js 机器人执行此操作?
According to the discord.js docs , each attachment has a URL property.根据discord.js 文档,每个附件都有一个 URL 属性。 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:这将获取所有附件 URL,您可以使用
http
、 request
或其他类似模块下载它,然后将其写入您上传的任何位置:
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
});
});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.