所以我有一個 discord.js 機器人。我希望版主能夠運行斜杠命令并將影像上傳到機器人的目錄(我的 Raspberry Pi 上的檔案夾,我的機器人所在的位置)。于是我下了命令,
const fs = require("fs");
const path = require("path");
const Discord = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("addimg")
.setDescription("Allows Moderators to add needed images.")
.addAttachmentOption((option) =>
option
.setName('image')
.setDescription('The image you want to add.')
.setRequired(true)
),
async execute(interaction, client) {
var image = interaction.options.getAttachment("image");
console.log(image)
if(path.parse(image.name).ext == ".png" || path.parse(image.name).ext == ".jpg"){
await fs.writeFileSync(`../../../imgs/${image.name}`, /*Data*/)
const embed = new Discord.EmbedBuilder()
.setTitle(`Image Added!`)
.setColor("000000")
.setDescription(`Check it out by using the /img command and choosing ${image}`)
interaction.reply({ embeds: [embed] });
}
else{
return interaction.reply({ embeds: [new Discord.EmbedBuilder()
.setTitle(`Failed to Add Image.`)
.setColor("000000")
.setDescription(`This format of image is not allowed. Try again with a .png or .jpg image.`)] })
}
}
}
但我不知道如何/從哪里開始將 Discord 附件轉換為二進制(原始影像資料)。而且我知道 Discord 附件有一個可能應該使用的 .url?但我仍然不知道我會怎么做。
uj5u.com熱心網友回復:
我對該主題進行了一些研究,希望這能奏效。
我認為使用這樣的東西可能會起作用:
const imageUrl = image.url
var request = require('request').defaults({ encoding: null });
request.get(imageUrl, function (error, response, body) {
if (!error && response.statusCode == 200) {
data = "data:" response.headers["content-type"] ";base64," Buffer.from(body).toString('base64');
console.log(data);
}
});
資料來源:
- 來源 1
- 來源 2
uj5u.com熱心網友回復:
于是我找到了答案。這里是。
var request = require("request").dafaults({ })
await request(image.url).pipe(fs.createWriteStream(`./imgs/${image.name}`))
您將替換./imgs/${image.name}為您要寫入的任何路徑。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/520183.html
下一篇:如何將影像拆分為4個三角形
