javascript - 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 个字符(不和谐消息的最大限制)。
有人可以帮忙吗?
提前致谢。
杰克
解决方案
我建议使用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);
});
推荐阅读
- vba - 如何在word中通过vba根据单选按钮组启用文本框
- extjs - ExtJS 存储同步发送空字符串而不是 null
- ruby-on-rails - 如何在 ruby on rails 的 mongoid 聚合中将字符串转换为 double
- android - Flutter ListView 项目根据 TextField 中添加的数字进行更改
- javascript - React - 无法访问传递的函数
- android - 滚动视图内的约束布局,总是参考线高度变化
- python - Python3并行处理opencv视频帧
- java - 在 Spring Boot Eclipse 中使用多个外部 JAR
- java - 无法从 JOINed 表中获取正确的信息
- qt - 当头文件存在时,Qt/MinGW 给出“没有这样的文件或目录”