读取文件附件(例如;.txt 文件)-Discord.JS

sys*_*ene 2 javascript fs node.js discord discord.js

第二次在 StackOverflow 上发帖,对于任何错误我深表歉意。请多多包涵。

与标题相同;如何读取不和谐附件的内容(假设是一个.txt文件)并打印内容?

我尝试过fs,但不幸的是失败了,我也搜索了文档,但也失败了。

在此输入图像描述

有想法吗?

Zso*_*ros 5

您不能fs为此使用该模块,因为它只处理本地文件。当您将文件上传到 Discord 服务器时,它会上传到 CDN,您所能做的就是使用该MessageAttachment属性获取该文件的 URL url

如果您需要从网络获取文件,您可以使用内置https模块从 URL 获取它,或者您可以从 npm 安装一个文件,就像我下面使用的那样node-fetch

要安装node-fetch,请npm i node-fetch在根文件夹中运行。

查看下面的工作代码,它可以很好地处理文本文件:

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

const client = new Client();

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

  // get the file's URL
  const file = message.attachments.first()?.url;
  if (!file) return console.log('No attached file found');

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

    // fetch the file from the external URL
    const response = await fetch(file);

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

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

    if (text) {
      message.channel.send(`\`\`\`${text}\`\`\``);
    }
  } catch (error) {
    console.log(error);
  }
});
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述