你不应该做的是,首先使用switch 来处理你的命令。
您应该做的是使用命令处理程序。这样您就可以将所有命令导出到单独的文件中,并使用名为 aliases 的东西。
首先在与您的index.js 相同的目录中创建一个commands 文件夹。每个文件都需要是.js 文件,内容如下。
module.exports = {
name: 'your command name', // needs to be completly lowercase
aliases: ["all", "of", "your", "aliases"],
description: 'Your description',
execute: (message, args) => {
// the rest of your code
}
}
接下来,您需要将一些内容添加到您的 index.js 文件中。
需要文件系统模块fs 和Discord。创建两个新集合。
const fs = require('fs');
const Discord = require('discord.js');
client.commands = new Discord.Collection();
client.aliases = new Discord.Collection();
接下来,您需要将所有名称和别名添加到您的两个新集合中。
// Read all files in the commands folder and that ends in .js
const commands = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
// Loop over the commands, and add all of them to a collection
// If there's no name found, prevent it from returning an error
for (let file of commands) {
const command = require(`./commands/${file}`);
// Check if the command has both a name and a description
if (command.name && command.description) {
client.commands.set(command.name, command);
} else {
console.log("A file is missing something")
}
// check if there is an alias and if that alias is an array
if (command.aliases && Array.isArray(command.aliases))
command.aliases.forEach(alias => client.aliases.set(alias, command.name));
};
现在我们已将所有命令添加到集合中,我们需要在 client.on('message', message {...}) 中构建命令处理程序。
client.on('message', message => {
// check if the message comes through a DM
//console.log(message.guild)
if (message.guild === null) {
return message.reply("Hey there, no reason to DM me anything. I won't answer anyway :wink:");
}
// check if the author is a bot
if (message.author.bot) return;
// set a prefix and check if the message starts with it
const prefix = "!";
if (!message.content.startsWith(prefix)) {
return;
}
// slice off the prefix and convert the rest of the message into an array
const args = message.content.slice(prefix.length).trim().split(/ +/g);
// convert all arguments to lowercase
const cmd = args.shift().toLowerCase();
// check if there is a message after the prefix
if (cmd.length === 0) return;
// look for the specified command in the collection of commands
let command = client.commands.get(cmd);
// If no command is found check the aliases
if (!command) command = client.commands.get(client.aliases.get(cmd));
// if there is no command we return with an error message
if (!command) return message.reply(`\`${prefix + cmd}\` doesn't exist!`);
// finally run the command
command.execute(message, args);
});
This 是没有别名键的指南。