首页 > 解决方案 > Discord.JS - 将目录中的所有文件作为一条消息列出

问题描述

我遇到了一个似乎找不到解决方案的问题。

我从 Discord.JS 编写了一个 Discord 机器人,它需要从一个目录发送一个文件名列表作为一条消息。到目前为止,我已经尝试将 fs.readddir 与 path.join 和 fs.readfilesync() 一起使用。下面是一个例子。

        const server = message.guild.id;
        const serverpath = `./sounds/${server}`;
        const fs = require('fs');
        const path = require('path');

        const directoryPath = path.join('/home/pi/Pablo', serverpath);

        fs.readdir(directoryPath, function(err, files) {
            if (err) {
                return console.log('Unable to scan directory: ' + err);
            }
            files.forEach(function(file) {
                message.channel.send(file);
            });
        });

虽然这确实会发送目录中每个文件的消息,但它会将每个文件作为单独的消息发送。由于 Discord API 速率限制,这会导致它需要一段时间。我希望它们都在同一条消息中,用换行符分隔,最多 2000 个字符(不和谐消息的最大限制)。

有人可以帮忙吗?

提前致谢。

杰克

标签: javascriptdiscord.js

解决方案


我建议使用fs.readdirSync(),它将返回给定目录中的文件名数组。使用Array#filter()将文件过滤为 JavaScript 文件(以“.js”结尾的扩展名)。要从文件名中删除“.js”,请使用Array#map()将每个替换".js"""(有效地完全删除它)并使用Array#join()将它们加入字符串并发送。

const server = message.guild.id;
const serverpath = `./sounds/${server}`;
const { readdirSync } = require('fs');
const path = require('path');

const directoryPath = path.join('/home/pi/Pablo', serverpath);

const files = readdirSync(directoryPath)
   .filter(fileName => fileName.endsWith('.js'))
   .map(fileName => fileName.replace('.js', ''));
   .join('\n');
message.channel.send(files);

关于处理超过 2000 个字符的消息的发送:您可以使用 Discord.JS 中的Util.splitMessage ()方法并提供maxLength. 2000只要需要发送的块数不超过几个,API ratelimits 就可以了

const { Util } = require('discord.js');

// Defining "files"

const textChunks = Util.splitMessage(files, {
   maxLength: 2000
});

textChunks.forEach(async chunk => {
   await message.channel.send(chunk);
});

推荐阅读