首页 > 解决方案 > 如何使用 discord.js 创建动态帮助嵌入,以便按类别组织命令

问题描述

在制作 Discord 机器人时,手动将每个命令、描述和类别硬编码到帮助嵌入中显然效率低下(并且可能不准确),因此我决定使用以下代码使其自动化:

    const commands = loadCommands()
    let embed = new Discord.MessageEmbed()
    embed.setTitle('Commands List')
    embed.setColor(`${embedColor}`)
    embed.setDescription('Prefix: `' + `${prefix}`+ '` \n\n')
    let list = ' '
    for (const command of commands) {
   
      const mainCommand =
        typeof command.commands === 'string'
          ? command.commands
          : command.commands[0]
      const args = command.expectedArgs ? ` ${command.expectedArgs}` : ''
      const { description } = command

      list += ' `'+`${mainCommand}`+'` '
    }
    
    embed.addFields(
        {name: 'general commands', value: list, inline: true
        })
    message.channel.send(embed)
  },
}

它需要我所有的命令并将它们放入嵌入中。

问题是我不知道如何按类别排序。我已经列出了所有命令的类别(例如,“帮助”和“ping”等命令在实用程序中);我希望能够做到这一点,以便嵌入对于每个类别都有一个字段,其值是一个类别中的所有命令。

关于这一点,我还想知道如何制作它,以便如果您执行类似的命令<prefix>help [command],机器人会检查 [command] 是否存在,如果存在,机器人会返回一个硬编码描述命令(如果 [command] 不存在,机器人将返回嵌入的通用帮助)。

提前感谢您提供的任何和所有帮助。

标签: discord.js

解决方案


据我了解,您需要类似这种嵌入的东西:

const commandsEmbed = new Discord.MessageEmbed()
    .setColor('#0091ff')
    .setTitle('Commands Help!')
    .setDescription('Below you will see the available commands of our Bot!')
    .addFields(
        { name: 'Utilities', value: '!help, !ping' },
        { name: 'Command Category 2', value: 'Commands' },
        { name: 'Command Category 3', value: 'Some other Commands' },
    )
    .setTimestamp()

对于您的第二个问题,我认为最实用的方法是复制和粘贴并制作一些单独的嵌入(所有颜色、语法等与原始内容相同),并在用户使用命令时发送它们。例如:

if(msg.content === `${prefix}help Utility`){
   msg.user.send(helpEmbed);
}
if (msg.content === `${prefix}help OtherCommands {
.
.
.
};

推荐阅读