如何使用Discord机器人节点JS从Discord保存图像

编程入门 行业动态 更新时间:2024-10-10 11:29:28
本文介绍了如何使用Discord机器人节点JS从Discord保存图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

到目前为止,我只能从不和谐频道类型上的其他人那里获取文本和链接,但我希望能够保存发布的图像/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保存图像

本文发布于:2023-11-23 13:12:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621566.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:节点   如何使用   机器人   图像   Discord

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!