Écouter plusieurs commandes dans un cas

Oct 13 2020

J'essaie de l'obtenir de sorte que lorsqu'un utilisateur dit une commande comme '! Help' ou '! Commands', il renvoie le message d'aide, afin d'économiser de l'espace dans mon code et de ne pas utiliser 2 cas, comment puis-je faire cela en 1?

client.on('message', message => {
    let args = message.content.substring(prefix.length).split(" ");

    switch (args[0]) {

        case ('help' || 'commands'):

Je ne sais pas trop quoi faire, il répond à "help" mais pas aux commandes. Des idées?

Réponses

2 Lioness100 Oct 13 2020 at 01:47

L' switchinstruction a une fonctionnalité où vous pouvez créer un fichier vide case. Si le caseretourne true, il exécutera simplement l' caseinstruction suivante avec du code.

switch ('someString') {
  case 'someString':
  case 'someOtherString': {
      console.log('This will still execute');
      break;
    };
};

2 WorthyAlpaca Oct 13 2020 at 01:52

Ce que vous ne devriez pas faire, c'est utiliser a switchpour gérer vos commandes en premier lieu.

Ce que vous devez faire est d'utiliser un gestionnaire de commandes. De cette façon, vous pouvez exporter toutes vos commandes dans des fichiers séparés et utiliser quelque chose appelé aliases.

Commencez par créer un commandsdossier dans le même répertoire que votre index.js. Chaque fichier doit être un .jsfichier avec le contenu suivant.

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
    }
}

Ensuite, vous devez ajouter des éléments à votre index.jsfichier. Nécessite le module de système de fichiers fset Discord. Créez deux nouvelles collections.

const fs = require('fs');
const Discord = require('discord.js');
client.commands = new Discord.Collection();
client.aliases = new Discord.Collection();

Ensuite, vous devez ajouter tous les noms et alias à vos deux nouvelles collections.

// 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));
};

Maintenant que nous avons ajouté toutes nos commandes à la collection, nous devons créer notre gestionnaire de commandes 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);
});

Ceci est un guide sans la clé d'alias.