提问者:小点点

discord.js重新加载comomand的一个问题


在更改命令后,我的reload命令出现了问题。我以前把命令存储在。/commands文件夹中,reload命令工作得很好,但我对此做了一些更改,希望更好地组织我的命令,并为每个命令类别创建了子文件夹,它们现在存储为这样的/commands/fun/commandname.js,并将我的主bot文件的代码更改为

const isDirectory = source => fs.lstatSync(source).isDirectory();
const getDirectories = source => fs.readdirSync(source).map(name => path.join(source, name)).filter(isDirectory);


getDirectories(__dirname + '/commands').forEach(category => {
  const commandFiles = fs.readdirSync(category).filter(file => file.endsWith('.js'));

  for(const file of commandFiles) {
    const command = require(`${category}/${file}`);
    client.commands.set(command.name, command);
  }
});

reload命令的代码

  
module.exports = {
    name: 'reload',
    description: 'Reloads a command',
    args: true,
    usage: '<command name>',
    execute(message, args) {
        const config = require('../config.json');
        if(message.author.id !== config.ownerID) return;
        const commandName = args[0].toLowerCase();
        const command = message.client.commands.get(commandName)
            || message.client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));

        if (!command) {
            return message.channel.send(`There is no command with name or alias \`${commandName}\`, ${message.author}!`);
        }

        delete require.cache[require.resolve(`./${command.name}.js`)];

        try {
            const newCommand = require(`./${command.name}.js`);
            message.client.commands.set(newCommand.name, newCommand);
            message.channel.send(`Reloaded command \`${command.name}\`.`);
        } catch (error) {
            console.error(error);
            message.channel.send(`There was an error while reloading a command \`${command.name}\`:\n\`${error.message}\``);
        }
    },
};

当使用该命令时,它会抛出错误“错误:无法找到模块'./commandname.js'”。我试图将更改为,但似乎无法工作


共1个答案

匿名用户

尝试更改

        delete require.cache[require.resolve(`./${command.name}.js`)];
to 
            delete require.cache[require.resolve(`../../${command.name}.js`)];

在生成新命令时执行相同操作