【问题标题】:Ask for file, read and send content to the channel using discord.js/javascript?使用 discord.js/javascript 请求文件、读取内容并将内容发送到频道?
【发布时间】:2021-09-16 15:47:33
【问题描述】:

我想请求一个 .txt 文件,读取文件并使用 discord bot 将文件内容发送到频道。

预期行为描述:

  • 用户写入命令:!readfile
  • Bot 响应消息,要求用户在 聊天
  • Bot 等待文件
  • Bot 读取文件内容
  • 通过消息将内容发送回频道

这是我最近创建此命令的尝试:

if (message.content === '!readfile') {

message.channel.send("Send your file please...");

 message.channel.awaitMessages(filter, {max: 1}).then(msg => {
   const filter = m => m.author.id === message.author.id;
   let file = msg.attachments.first().file;
   fs.readFile(file, (err, data) => {
     msg.channel.send("Read the file! Fetching data...");
     msg.channel.send(data);
   });
 });
}

【问题讨论】:

  • 您遇到了什么问题/错误?如果你不告诉我们它到底是如何不工作的,这很难提供帮助。
  • @MrMythical 这不是错误,他/她想获取“.txt”或消息中发送的任何文件。
  • 还有@noobami 我觉得除了链接和文本或文本格式之外,没有任何方法可以从消息中获取文件
  • 100% 确定,没有用户会滥用它。向机器人发送文件并阅读这些文件是使用不和谐机器人可以做的最危险的事情之一。您的机器人可能会崩溃,或者在最坏的情况下,您的机器人可能会被黑客入侵。作为安全预防措施,可能会将功能限制为仅具有特定角色的用户。
  • 嘿@noobami 我试图帮助你回答下面的问题。你有机会去看看吗?有意义吗?如果回答有用,请点击其左侧的点赞按钮(▲)。如果它回答了您的问题,请单击复选标记 (✓) 接受它。谢谢:)

标签: javascript node.js discord.js


【解决方案1】:

正如我在previous post 中提到的,您不能使用fs 模块来读取附件的内容,因为它只处理本地文件。

当您通过 Discord 上传文件时,它会被上传到 CDN。您无法抓取文件本身(MessageAttachment 上也没有 file 属性),您所能做的就是使用 url 属性抓取上传文件的 URL。

当您想从 Web 获取文件时,您需要通过 URL 获取它。您可以使用内置的https 模块,也可以从npm 安装一个,例如axiosnode-fetch 等。

我在示例中使用了node-fetch,并确保首先通过在根文件夹中运行npm i node-fetch 来安装它。

查看下面的工作代码,它适用于文本文件:

// on the top
const fetch = require('node-fetch');

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

  const args = message.content.slice(prefix.length).split(/ +/);
  const command = args.shift().toLowerCase();

  if (command === 'readfile') {
    message.channel.send('Send your file please...');

    const filter = (m) => m.author.id === message.author.id;

    try {
      const collected = await message.channel.awaitMessages(filter, { max: 1 });

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

      // await the message, so we can later delete it
      const sent = await 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) {
        sent.delete();
        return message.channel.send(
          'There was an error fetching your file:',
          response.statusText,
        );
      }

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

      if (text) {
        sent.delete();
        return message.channel.send(`\`\`\`${text}\`\`\``);
      }
    } catch (err) {
      console.log(err);
      return message.channel
        .send(`Oops, that's lame. There was an error...`)
        .then((sent) => setTimeout(() => sent.delete(), 2000));
    }
  }
});

此外,即使max 选项设置为 1,请不要忘记 awaitMessages() 返回消息集合,因此您需要获取 first() 一个。

【讨论】:

    猜你喜欢
    • 2013-01-26
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    相关资源
    最近更新 更多