到目前为止,我只能从不和谐频道类型上的其他人那里获取文本和链接,但我希望能够保存发布的图像/gifs.有什么办法可以通过机器人执行此操作,还是不可能?我正在使用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 .然后,我们使用节点的 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机器人节点JS从Discord保存图像
发布评论