Skip to content Skip to sidebar Skip to footer

Reading File Attachments (ex; .txt File) - Discord.js

Second time posting on StackOverflow so I apologize for any mistakes. Please bear with me. Same with the title; How do you read contents of a discord attachment let's say a .txt fi

Solution 1:

You can't use the fs module for this as it only deals with local files. When you upload a file to the Discord server, it gets uploaded to a CDN and all you can do is grab the URL of this file from the MessageAttachment using the url property.

If you need to get a file from the web, you can fetch it from a URL using the built-in https module, or you can install one from npm, like the one I used below, node-fetch.

To install node-fetch, run npm i node-fetch in your root folder.

Check out the working code below, it works fine with text files:

const { Client } = require('discord.js');
const fetch = require('node-fetch');

const client = newClient();

client.on('message', async (message) => {
  if (message.author.bot) return;

  // get the file's URLconst file = message.attachments.first()?.url;
  if (!file) returnconsole.log('No attached file found');

  try {
    message.channel.send('Reading the file! Fetching data...');

    // fetch the file from the external URLconst response = awaitfetch(file);

    // if there was an error send a message with the statusif (!response.ok)
      return message.channel.send(
        'There was an error with fetching the file:',
        response.statusText,
      );

    // take the response stream and read it to completionconst text = await response.text();

    if (text) {
      message.channel.send(`\`\`\`${text}\`\`\``);
    }
  } catch (error) {
    console.log(error);
  }
});

enter image description here

Post a Comment for "Reading File Attachments (ex; .txt File) - Discord.js"