I’m working on a Discord bot using discord.js and I need some help with image handling. Right now my bot can read messages and extract text content plus URLs that users post in channels. However, I’m stuck trying to figure out how to download and save image files that people upload to the server.
Is it possible to capture uploaded images and GIFs through a bot? I’ve been searching for solutions but haven’t found a clear way to handle file attachments. Can anyone point me in the right direction or let me know if this is even achievable with the discord.js library?
Any code examples or guidance would be really helpful. Thanks in advance!
attachments.forEach() is perfect for this. Just pull the .url from each attachment and use node-fetch or axios to download. Make sure you handle errors - Discord URLs can expire and files get deleted. You can also check attachment.contentType if you only want images.
I’ve built something similar and hit a few gotchas you should know about. Those attachment URLs expire pretty quickly, so download them right when the message event fires. Discord also rate limits their CDN - if you’re processing lots of images, you’ll need throttling. I set up separate folders for different file types and added timestamps to filenames to avoid conflicts. Pro tip: check the attachment size first before downloading. Regular users can upload 8MB max, Nitro users get 50MB, so plan your storage accordingly.
Yes, it’s indeed possible to download images and files using discord.js. When you’re handling a message event, you should look at the message.attachments property. Each attachment object there contains a URL that you can fetch with the fetch API. I implemented a similar feature where I used fs.writeFile to save the files locally. Just ensure you manage different file types correctly and make sure your paths are valid. It’s also crucial to validate the file sizes beforehand to prevent memory issues. Since your bot can already read messages, you won’t need additional authentication for accessing the attachment URLs.