如何使用discord bot node js从discord中保存图像 [英] how to save an image from discord using discord bot node js

查看:42
本文介绍了如何使用discord bot node js从discord中保存图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So far I've only been able to get text and links from what other people on my discord channel type, but I want to be able to save posted images/gifs. is there any way I can do this through the bot or is it impossible? I'm using discord.js.

推荐答案

Discord.js 中的图像以 MessageAttachments 通过 Message#attachments.通过遍历附件的数量,我们可以通过 MessageAttachment#attachment 和文件类型使用 MessageAttachment#name.然后,我们使用 node 的 FileSystem 将文件写入系统.这是一个简单的例子.此示例假设您已经拥有 message 事件和 message 变量.

Images in Discord.js come in the form of 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 to write the file onto the system. Here's a quick example. This example assumes you already have the message event and the message variable.

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

请注意,在实际场景中,您应该在同步函数周围加上 try/catch 语句,以防出错.

Please note that in a real world scenario you should surround the synchronous function with a try/catch statement, for errors.

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

Also note that, according to the docs, the attachment can be a stream. I have yet to have this happen in the real world, but if it does it might be worth checking if a is typeof Stream, and then using fs.createWriteStream and piping the file into it.

这篇关于如何使用discord bot node js从discord中保存图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆