0

I'm making a map loader that relies on attachments and .txt files. I could do it with normal text, but since Discord has a character limit for each message, it doesn't work.

That's why I want to download message attachments on my local machine to process them further.

How can I download attachments from Discord messages using fs?

Aci
  • 546
  • 5
  • 22
DcraftBg
  • 27
  • 5

1 Answers1

1

I think you can just use a simple get request to the image's url (you can get this through attachment.url) using node-fetch then pipe the response to a .png file using fs

(If you get errors while installing node-fetch or while using the code below, try installing node-fetch v2 instead of the latest release via npm install node-fetch@2)

const fs = require('fs')
const fetch = require('node-fetch')

const imageUrl = 'https://cdn.discordapp.com/attachments/GLD_ID/MSG_ID/IMAGE.png'

fetch(imageUrl)
    .then(res =>
        res.body.pipe(fs.createWriteStream('./path/to/image.png'))
    )

You can also read this post which goes into more detail

  • Yea i tried doing that. I also found another one about txt files but in both cases i get an error probably because i haven't installed node-fetch :|. Thank you. Also is there a way i could get a text file as an attachment because thats what im going after. Thank you either way! – DcraftBg Mar 07 '22 at 06:09
  • It should be a similar process to download a text file, and putting it as an attachment is similar to how you would attach a image to the bot's message. To download the contents of a text file, the code will be different. Read [this post](https://stackoverflow.com/a/57997902/14688730) to get the text file, then use [fs to write it to a file](https://nodejs.org/api/fs.html#filehandlewritefiledata-options) – smallketchup82 Mar 07 '22 at 06:26
  • Tysm smallketchup82! – DcraftBg Mar 07 '22 at 06:41
  • I got the URL t least but it seems as though you can't use : ```js const smth = fetch(message.attachments.first().url); const atht = smth.text(); – DcraftBg Mar 07 '22 at 07:22
  • Does .text() only work with assync functions??/ – DcraftBg Mar 07 '22 at 08:37
  • Sorry for not responding sooner but you should be using await. Use the [module's documentation](https://www.npmjs.com/package/node-fetch#plain-text-or-html) for an example on how to do that – smallketchup82 Mar 16 '22 at 23:30