【问题标题】:Reading file attachments (Ex; .txt file) - Discord.JS读取文件附件(例如;.txt 文件)- Discord.JS
【发布时间】:2021-08-11 14:40:11
【问题描述】:

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

与标题相同;你如何阅读不和谐附件的内容,比如.txt 文件并打印内容?

我尝试使用fs,但不幸失败了,我也搜索了文档,但也失败了。

想法?

【问题讨论】:

    标签: javascript node.js discord discord.js fs


    【解决方案1】:

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

    如果您需要从 Web 获取文件,您可以使用内置的 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);
      }
    });
    

    【讨论】:

    • 我想知道这在实践中可以应用到什么地方?
    • 老实说,我不知道。也许@systemGene 可以告诉我们:)
    • 这是个秘密! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多