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

微笑、不失礼 提交于 2021-02-10 14:41:55

问题


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.


回答1:


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.
});

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

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.



来源:https://stackoverflow.com/questions/49063287/how-to-save-an-image-from-discord-using-discord-bot-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!