首页 > 解决方案 > JavaScript 命令处理程序没有运行其他命令?

问题描述

我的不和谐机器人有一个命令处理程序。它可以很好地加载命令模块(并且控制台日志也显示了很多),但是我无法让它执行第一个命令模块之外的命令。这是代码:

const Discord = require("discord.js");
const client = new Discord.Client();
client.commands = new Discord.Collection();

const prefix = "f$";

const fs = require("fs");
try {
    const files = fs.readdirSync("./commands/");
    let jsFiles = files.filter(filename => filename.split(".").pop() === "js");
    for (const filename of jsFiles) {
        let command = require(`./commands/${filename}`);
        if (!command) return console.error(`Command file '${filename}' doesn't export an object.`);
        client.commands.set(command.name, command);
        console.log(`Loaded command: ${command.name}`);
    }
} catch (err) {
    console.error(`Error loading command: '${err}'`);
}
console.log("Finished loading\n");


client.on("ready", () => {
    console.log("Client ready!");
});

client.on("message", async message => {
    if (message.author.bot) return;
    if (!message.content.startsWith(prefix)) return;
    let args = message.content.slice(prefix.length).trim().split(/ +/g);
    //console.log(args);
    let cmdName = args.shift().toLowerCase();
    for (const command of client.commands.values()) {
        console.log(command.name);
        console.log(cmdName);
        console.log(command === cmdName);
        if (command.name !== cmdName /*&& !command.aliases.includes(cmdName)*/) return;
        try {
            await command.executor(message, args, client);
        } catch (err) {
            console.error(`Error executing command ${command.name}: '$```{err.message}'`);
        }
    }

});

client.login(TOKEN).catch(err => console.log(`Failed to log in: ${err}`));

在每个命令模块中你都有这个位:

module.exports = {
    name: "command",
    description: "description of command",
    aliases: [],
    executor: async function (message, args, client) {

(我还没有为此做别名,所以别名行要么是空的,要么被删除。)

标签: javascriptnode.jsdiscord.jsbots

解决方案


您在模板文字中错误地引用了您的变量,这意味着您的很多代码被忽略了,这可能是问题的全部,它应该如下所示:

console.error(`Error executing command ${command.name}: ${err.message}`);

有关模板文字的指导,请使用https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals。如果您想使用 ``` 但忽略它们,请使用以下代码:

console.error(`Error executing command ${command.name}: \`\`\` ${err.message} \`\`\`  `);

此外,在您的执行功能上,您没有右大括号,因此应该是:

module.exports = {
    name: "command",
    description: "description of command",
    aliases: [],
    executor: async function (message, args, client) {
// code to be executed
}

推荐阅读