检查成员是否具有特定角色

Checking if a member has a certain role

我试图只允许特定角色查看帮助命令的一部分。 我试过以下方法,但它似乎不起作用,它只显示默认的帮助嵌入:

List<Role> staff = event.getGuild().getRolesByName("Staff", true);

                if (event.getGuild().getSelfMember().getRoles().contains(staff)) {

                    final EmbedBuilder ahelp = new EmbedBuilder();

                    ahelp.setTitle("Commands List", null);
                    ahelp.setColor(Color.CYAN);
                    ahelp.addField("Member:", "*help: Returns with this message." +
                            "\n*bugreport <Bug>: Creates a new bug report." +
                            "\n*suggest <Suggestion>: Creates a new suggestion."
                            , false);
                    ahelp.addField("Staff:", "*ban <Member> [Reason]: Bans a member." +
                            "\n*mute <Member> [Reason]: Mutes a member." +
                            "\n*kick <Member> [Reason]: Kicks a member." +
                            "\n*unmute <Member>: Unmutes a member."
                            , false);
                    ahelp.setFooter("Bot • " + dtf.format(now));

                    event.getChannel().sendTyping().queue();
                    event.getChannel().sendMessage(ahelp.build()).queue();
                    return;

                } else {

                    final EmbedBuilder help = new EmbedBuilder();

                    help.setTitle("Commands List", null);
                    help.setColor(Color.CYAN);
                    help.addField("Member:", "*help: Returns with this message." +
                            "\n*bugreport <Bug>: Creates a new bug report." +
                            "\n*suggest <Suggestion>: Creates a new suggestion."
                            , false);
                    help.setFooter("Bot • " + dtf.format(now));

                    event.getChannel().sendTyping().queue();
                    event.getChannel().sendMessage(help.build()).queue();
                    return;

                }

如果有更好的方法,或者您知道如何回答我的问题,请告诉我。 谢谢

您正在尝试检查 List<Role> 是否包含另一个 List<Role>。这不是 contains 的工作方式。正确的用法是使用 Role 对象而不是 List<Role> 对象。

因为我假设您只是在寻找成员具有名为 "Staff" 的角色这一事实,您可以使用 Stream API:

public boolean hasRole(Member member, String name) {
    return member.getRoles().stream().map(Role::getName).anyMatch(name::equalsIgnoreCase);
}

if (hasRole(event.getGuild().getSelfMember(), "Staff")) {
   // ... your code here ...
}

您也只检查 "self member",这意味着您只检查机器人本身的角色,而不是用户的角色。我想您可能想改用 event.getMember()