如何使用discord bot node js从discord中保存图像

how to save an image from discord using discord bot node js

到目前为止,我只能从我的不和谐频道类型中的其他人那里获取文本和链接,但我希望能够保存发布的 images/gifs。有什么办法可以通过机器人做到这一点还是不可能?我正在使用 discord.js.

Discord.js中的图像以MessageAttachments via Message#attachments. By looping through the amount of attachments, we can retrieve the raw file via MessageAttachment#attachment and the file type using MessageAttachment#name. Then, we use node's FileSystem的形式出现,将文件写入系统。这是一个简单的例子。此示例假定您已经拥有消息事件和消息变量。

const fs = require('fs');
msg.attachments.forEach(a => {
    fs.writeFileSync(`./${a.name}`, a.file); // Write the file to the system synchronously.
});

请注意,在现实世界中,您应该用 try/catch 语句包围同步函数,以防出错。

另请注意,根据文档,附件可以是流。我还没有在现实世界中发生过这种情况,但如果确实如此,可能值得检查 a 是否为 typeof Stream,然后使用 fs.createWriteStream 并将文件传输到其中。