如果用户拥有,我将如何缩短此discord.js代码以检查多个权限?

时间:2019-10-14 17:10:00

标签: discord.js

if(message.member.hasPermission("SEND_MESSAGES")){
      for(i=0;i<config.commands.SEND_MESSAGES.length;i++){
        helpArray.push(config.commands.SEND_MESSAGES[i]);
      };
    };
    if(message.member.hasPermission("MANAGE_MESSAGES")){
      for(i=0;i<config.commands.MANAGE_MESSAGES.length;i++){
        helpArray.push(config.commands.MANAGE_MESSAGES[i]);
      };
    };
    if(message.member.hasPermission("MANAGE_CHANNELS")){
      for(i=0;i<config.commands.MANAGE_CHANNELS.length;i++){
        helpArray.push(config.commands.MANAGE_CHANNELS[i]);
      };
    };
    if(message.member.hasPermission("KICK_MEMBERS")){
      for(i=0;i<config.commands.KICK_MEMBERS.length;i++){
        helpArray.push(config.commands.KICK_MEMBERS[i]);
      };
    };
    if(message.member.hasPermission("BAN_MEMBERS")){
      for(i=0;i<config.commands.BAN_MEMBERS.length;i++){
        helpArray.push(config.commands.BAN_MEMBERS[i]);
      };
    };
    if(config.whitelist.botowners.includes(message.author.id)){
      for(i=0;i<config.commands.whitelist.botowners.length;i++){
        helpArray.push(config.commands.whitelist.botowners[i]);
      };
    };
    var help_embed = new discord.RichEmbed()
    .setTitle(config.embed.title)
    .setColor(config.embed.color)
    .setFooter(config.embed.footer, client.user.displayAvatarURL)
    .setDescription(helpArray.join('\n'));
    message.channel.send(help_embed);
  }

基本上config.commands.permission是一个数组,其中包含该权限的所有命令和信息。我如何缩短此代码?还是不可能?

1 个答案:

答案 0 :(得分:0)

只需使用另一个for循环(请参阅:for...of来遍历每个权限,就可以缩短和清理代码。

for (let perm of config.commands) {
  // Handle the outlier permission...
  if (perm === 'whitelist' && config.whitelist.botowners.includes(message.author.id)) {
    for (let cmd of config.commands.whitelist.botowners) helpArray.push(cmd);
    continue;
  }

  if (message.member.hasPermission(perm)) {
    for (let cmd of config.commands[perm]) helpArray.push(cmd);
  }
}