[英]Uploading image from discord.js bot to my website
我想使用 message.attachments 從中獲取圖像並將其上傳到我的網站(不在本地主機上)。 我該怎么做?
我的網站上已經有一個有效的上傳表單,但是我將如何從 discord.js 機器人執行此操作?
根據discord.js 文檔,每個附件都有一個 URL 屬性。 您可以使用它來獲取圖像並上傳。
示例代碼:
const URLsToFetch = [];
const attachments = message.attachments.array();
for(let i = 0;i<attachments.length;++i){
URLsToFetch.push(attachments[i].url);
}
這將獲取所有附件 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.