首页 > 解决方案 > 如果用户拥有多个权限,我将如何缩短此 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 是一个包含该权限的所有命令和信息的数组。我怎样才能缩短这段代码?或者那不可能?

标签: discord.js

解决方案


只需使用另一个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);
  }
}

推荐阅读