我的类别帮助命令运行不正常

时间:2021-01-20 17:27:28

标签: javascript node.js discord discord.js

我正在尝试在我的不和谐机器人中创建类别,我也在尝试创建类别帮助命令,但效果不佳,所以我需要一些帮助。它不是错误,我的控制台中没有显示 DiscordAPIErrors、Syntax Errors 或任何错误。它应该在嵌入消息中显示所选类别和命令,但事实并非如此。它只显示特定的命令帮助,例如,当我输入 (prefix)help kick 时,它会显示 kick 命令帮助,但是当我输入 (prefix)help 实用程序时,它只说提供的命令无效。所以它只对命令而不是类别做出反应。这是我的代码:

代码

const Discord = require('discord.js')
const fs = require('fs')
const { prefix, owner_id } = require('../../configs.json')

module.exports.run = async (message, args, client) => {
    const data = [];
    const allCategories = ['general','currency','premium','settings'];
    const categoryName = {
        "general": 'General Commands',
        "currency": 'Currency Commands',
        "settings": 'Settings Commands'
    }
    
    const user = await client.users.fetch('685079477629485093');
    const colors = [
        'WHITE','#add8e6','#e0ffff','#d3d3d3',
        '#20b2aa','#5d8aa8','#f0f8ff','#f2f3f4',
        '#b2beb5','#007fff','#f0ffff','#89cff0',
        '#a1caf1','#21abcd','#848482','#bcd4e6',
        '#f5f5dc','#318ce7','#ace5ee','#a2a2d0',
        '#6699cc','#0d98ba','#0095b6','#e3dac9',
        '#0070ff','#1dacd6','#08e8de','#e7feff'
    ]
    const randomColor = colors[Math.round(Math.random()*colors.length)];

    if (!args[0]) {
        let firstHelp = new Discord.MessageEmbed()
        .setColor(randomColor)
        .setDescription(`
        Commands Usage: \`${prefix}(command)\`\nYou're asking for help, 
**${message.author.username}**? I'm here to help!
        `, { split: true })
        .addFields(
            { name: `⚙️ General`, value: `${(client.generalCommands.map(command => 
`\`${command.help.name}\``).join(', ')) || '\`coming soon...\`'}`, inline: true },
            { name: `? Currency`, value: `${(client.currencyCommands.map(command => 
`\`${command.help.name}\``).join(', ')) || '\`coming soon...\`'}`, inline: true },
        )
        .setFooter(`For more information about a specific command, ${prefix}help <command>`)
        .setThumbnail(`${message.guild.iconURL({ dynamic: true })}`)
        .setTitle(`E-Mod Command List`);

        if (!message.guild.iconURL()) {
            firstHelp.setThumbnail(`${client.user.displayAvatarURL({ dynamic: true })}`)
        }
        return message.channel.send(firstHelp)
    }

    const name = args[0].toLowerCase();
    const command = client.generalCommands.get(name)
        || client.generalCommands.find(cmd => cmd.help.aliases && cmd.help.aliases.includes(name))
        || client.currencyCommands.get(name)
        || client.currencyCommands.find(cmd => cmd.help.aliases && cmd.help.aliases.includes(name))
        || client.premiumCommands.get(name)
        || client.premiumCommands.find(cmd => cmd.help.aliases && cmd.help.aliases.includes(name))

    if (!command) {
        const categorySelected = allCategories.map(category => category.startsWith(name));
        if (name == categorySelected) {
            let { categoryCommands } = message.client.get(name + 'Commands')
            let categoryHelp = new Discord.MessageEmbed()
            .setColor(randomColor)
            .addFields(
                { name: `${categoryName.map(category => category.startsWith(name))}`, value: 
`${(categoryCommands.map(command => `\`${command.help.name}\``).join(', ')) || '\`coming 
soon...\`'}`, inline: false },
            )
            .setFooter(`Premium commands can be used by specific users!`);
    
            return message.channel.send(categoryHelp);
        } else {
            return message.reply(`it seems you\'ve supplied an invalid command.\nPlease use 
\`${prefix}help\` to check out what commands do I support.`)
        }
    }

    let commandHelp = new Discord.MessageEmbed()
    .setColor(randomColor)
    .addFields(
        { name: 'Description:', value: `${command.help.description}`, inline: false },
        { name: 'Triggers:', value: `${((command.help.aliases).join(', ')) || 'No triggers found'}`, 
inline: true },
        { name: 'Usage:', value: `\`${command.help.usage}\``, inline: true },
    )
    .setFooter(`Premium commands can be used by specific users!`)
    .setTitle(`Help | ${command.help.name}`);

    return message.channel.send(commandHelp);
}

module.exports.help = {
    name: 'help',
    description: 'Get a list of all commands or info about a specific command.',
    usage: `${prefix}help <command>`,
    aliases: ['commands', 'cmds'],
    cooldown: 3,
}

1 个答案:

答案 0 :(得分:0)

您可以尝试制作一个数组并制作一个可以推送的对象。如果您使用命令处理程序,它会更容易使用。这是带有命令处理程序的示例:

const roleColor =
      message.guild.me.displayHexColor === "#000000" ?
      "#ffffff" :
      message.guild.me.displayHexColor;

    if (!args[0]) {
      let categories = [];
//Use below for each category emoji, may pop up as Undefined
      const dirEmojis = {
        Category: '?‍♂️'
      }
      const ignoredCategories = [`moderation`, `Other`, `suggest`, `Warn`, `Mute`, `ReactionRoles`, `Economy`, `Ticket`, `Welcome_Message`, `Welcome-Message`]
      fs.readdirSync("./commands/").forEach((dir) => {
        if (ignoredCategories.includes(dir)) return;

        const editedName = `${dirEmojis[dir]} ${dir.toUpperCase()}`;
        const commands = fs.readdirSync(`./commands/${dir}/`).filter((file) =>
          file.endsWith(".js")
        );

// 如果您的处理程序不使用类别文件夹,则删除目录,目录就是类别名称

        const cmds = commands.filter((command) => {
          let file = require(`../../commands/${dir}/${command}`);
          return !file.hidden;
        }).map((command) => {
          let file = require(`../../commands/${dir}/${command}`);

          if (!file.name) return "No command name.";

          let name = file.name.replace(".js", "");

          return `\`${name}\``;
        });

        let data = new Object();

        data = {
          name: editedName,
          value: cmds.length === 0 ? "In progress." : cmds.join(" "),
        };

        categories.push(data);
      });

      const embed = new Discord.MessageEmbed()
        .setTitle("Here Are My Commands:")
        .addFields(categories)
        .setDescription(
          `Use \`${prefix}help\` followed by a command name to get more additional information on a command. For example: \`${prefix}help ban\`.`
        )
        .setFooter(
          `Requested by ${message.author.tag}`,
          message.author.displayAvatarURL({
            dynamic: true
          })
        )
        .setTimestamp()
        .setColor(roleColor);
      return message.channel.send(embed);
    } else {
      const command =
        client.commands.get(args[0].toLowerCase()) ||
        client.commands.find(
          (c) => c.aliases && c.aliases.includes(args[0].toLowerCase())
        );

      if (!command) {
        const embed = new Discord.MessageEmbed()
          .setTitle(`Invalid command! Use \`${prefix}help\` for all of my commands!`)
          .setColor("FF0000");
        return message.channel.send(embed);
      }

//This will show command info here

      const embed = new Discord.MessageEmbed()
        .setTitle("Command Details:")
        .addField("PREFIX:", `\`${prefix}\``)
        .addField(
          "COMMAND:",
          command.name ? `\`${command.name}\`` : "No name for this command."
        )
        .addField(
          "ALIASES:",
          command.aliases ?
          `\`${command.aliases.join("` `")}\`` :
          "No aliases for this command."
        )
        .addField(
          "USAGE:",
          command.usage ?
          `\`${prefix}${command.name} ${command.usage}\`` :
          `\`${prefix}${command.name}\``
        )
        .addField(
          "DESCRIPTION:",
          command.description ?
          command.description :
          "No description for this command."
        )
        .setFooter(
          `Requested by ${message.author.tag}`,
          message.author.displayAvatarURL({
            dynamic: true
          })
        )
        .setTimestamp()
        .setColor(roleColor);
      return message.channel.send(embed);
    }
  }
}

这是受 reconlx 的启发,但经过修改。 github.com/reconlx

如果您决定不使用处理程序方法,请执行以下操作:

let category = []

let data = new Object()

data = {
name: category name/ category array
value: commands in the category
}
category.push(data)

let embed = new Discord.MessageEmbed()
.setTitle('Help')
.addFields(category)

下面的基本命令处理程序(复制并粘贴到主文件中)

fs.readdirSync('./commands').forEach(dirs => {
        const commands = fs.readdirSync(`./commands/${dirs}`).filter(files => files.endsWith('.js'));

        for (const file of commands) {
            const command = require(`./commands/${dirs}/${file}`);
            console.log(`Loading command ${file}`);
            if (command.name) {
                client.commands.set(command.name.toLowerCase(), command);
            } else {
                continue;
            }
        }
    });