【问题标题】:Discord bot: Command Handler alias for command nameDiscord bot:命令名称的命令处理程序别名
【发布时间】:2020-11-18 05:26:39
【问题描述】:

我正在开发一个 Discord 机器人,并试图改进我已经运行的命令处理程序。 我有一个文件夹,每个文件都是一个额外的命令。我想扩展系统,所以我有相同命令的别名,例如我希望我的 clearchat 命令与 /clearchat 或 /cc 一起运行,但我不想只创建另一个文件并复制代码。这就是我所拥有的:

// I left out the other imports etc.
client.commands = new Discord.Collection();

// Reading commands-folder
const commandFiles = fs.readdirSync("./commands/").filter(file => file.endsWith(".js"));
for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    client.commands.set(command.name, command); 
}

client.on("message", msg => {

    if (msg.content.startsWith(config.prefix) && !msg.author.bot && msg.guild) {
        const args = msg.content.slice(config.prefix.length).split(" ");
        const command = args.shift().toLowerCase();
        
        if (client.commands.find(f => f.name === command)) {
            client.commands.get(command).execute(client, msg, args);    
        }
    }
});

然后是命令文件夹中的命令文件:

module.exports = {
    name: "clearchat",
    execute(client, msg, args) {
        if (msg.member.hasPermission("ADMINISTRATOR")) {
              msg.channel.messages.fetch({limit: 99}).then(messages => {
                  msg.channel.bulkDelete(messages);
              });
        }
    }
}

(我知道它最多只能删除 100 条消息,我很好)

我在我的 client.on("message) 函数中更改了几行,并且只需要在 clearchat.js 文件中写入像 name: ["clearchat", "cc", ...] 这样的行,我可以在其中编写尽可能多的别名.

提前致谢!

【问题讨论】:

  • 我认为我们必须假设,每个别名/名称只使用一次

标签: javascript node.js discord.js


【解决方案1】:

首先,您必须在命令中使用别名创建一个数组。

module.exports = {
    name: "clearchat",
    aliases: ["cc"],
    execute(client, msg, args) {
        
    }
}

然后,与您对命令所做的一样,为别名创建一个集合。

client.aliases = new Discord.Collection()

最后,将别名绑定到命令:

if (command.aliases) {
    command.aliases.forEach(alias => {
        client.aliases.set(alias, command)
    })
}

现在,当你想执行一个命令时,你必须检查它是否有别名。

const commandName = "testcommand" // This should be the user's input.
const command = client.commands.get(commandName) || client.aliases.get(commandName); // This will return the command and you can proceed by running the execute method.

fs.readdir(`./commands/`, (error, files) => {
    if (error) {return console.log("Error while trying to get the commmands.");};
    files.forEach(file => {
        const command = require(`./commands/${file}`);
        const commandName = file.split(".")[0];

        client.commands.set(commandName, command);

        if (command.aliases) {
            command.aliases.forEach(alias => {
                client.aliases.set(alias, command);
            });
        };
    });
});

【讨论】:

  • 你应该把它粘贴到你初始化命令的地方,但在最后。所以是的,在你的 for 循环中。我已经用一个例子更新了我的答案。
猜你喜欢
  • 2021-11-10
  • 2019-11-12
  • 2021-11-04
  • 1970-01-01
  • 2018-08-15
  • 2022-07-12
  • 2018-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多