无法从文件夹中获取随机类型的随机文件



我为我的discord bot编写了这个命令,但我尝试修复了很多次,我已经花了2个小时尝试编码,但我得到的只是控制台中的一个无法发送空消息

const fs = require('fs');
module.exports = {
name: 'name',
description: 'description',
aliases: ['aliase1','aliase2'],
usage: '[command]',
guildOnly: true,
execute(message) {
const fileType = ['png','jpg','gif','mp4','mov'];
const Rfile2 = fs.readdirSync(`./commands/Database`).filter(file => file.endsWith(fileType));
for (const file of Rfile2) {
const Rfile = require(`.commands/Database/${file}`)
const randomFile = Rfile(Math.floor(Math.random()*5) * Rfile.length);
}
try {
message.channel.send(randomFile);
} catch (error) {
message.channel.send(error);
}
}
}

String.prototype.endsWith函数需要一个字符串或只有一个项的数组。所以你要传递一个总是返回false的完整数组,因此过滤掉一个空数组。

您可以通过周期.的所有出现split字符串,然后pop最后一个字符元素,然后检查extension是否包含在fileType数组中

const Rfile2 = fs.readdirSync('./commands/Database').filter(file => fileType.includes(file.split('.').pop())));

考虑学习Typescript,这样即使在运行代码之前也可以捕捉并防止简单的错误。

最新更新