discord.js - 如果用户拥有多个权限,我将如何缩短此 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 是一个包含该权限的所有命令和信息的数组。我怎样才能缩短这段代码?或者那不可能?
解决方案
只需使用另一个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);
}
}
推荐阅读
- android - 没有在android中关闭executorService的调用线程就死了
- c++ - Linux 上的 OpenCV + Eclipse - 构建问题
- reactjs - 如何控制传单反应的CircleMarker的z指数?
- c# - 将 FK 约束异常与 EF Core 中的其他数据库异常区分开来?
- twitter-bootstrap - 多项目轮播的响应性问题(已解决)
- javascript - 创建一个支持函数的持久数据钩子
- vbscript - Adobe Illustrator 脚本
- c# - 如何根据其他 2 个属性的值设置 1 个属性的值?
- testing - jest.mock 和 jest.doMock 之间的区别
- scala - 在 uber jar 而不是单个子模块 jar 中构建 sbt 项目