在JDA中向所提到的用户添加角色

时间:2019-01-03 01:54:47

标签: java api bots discord discord-jda

我希望能够运行一个以!suspend开头的命令,提到一个用户,然后确定一个时间长度,并在指定的时间长度内为所提到的用户添加一个名为“ Suspended”的角色。

    Message message = event.getMessage(); //Sets the message equal to the variable type 'Message' so it can be modified within the program.
    String content = message.getContentRaw(); //Gets the raw content of the message and sets it equal to a string (best way to convert types Message to String).
    MessageChannel channel = event.getChannel(); //Gets the channel the message was sent in (useful for sending error messages).
    Guild guild = event.getGuild();
    //Role group = content.matches("((Suspended))") ? guild.getRolesByName("Suspended", true).get(0) : null;

    if(content.startsWith("!suspend"))//Pretty self explanatory. Enters the loop if the message begins with !suspend.
    {
        String[] spliced = content.split("\\s+"); //Splits the message into an array based on the spaces in the message.
        TextChannel textChannel = event.getGuild().getTextChannelsByName("ranked-ms_punishments",true).get(0); //If there is a channel called ranked-ms_punishments which there should be set the value of it equal to the variable.

        int length = spliced.length;//Sets 'length' equal to the number of items in the array.

        if(length == 3)//If the number of items in the array is 3 then...
        {
            if(spliced[1].startsWith("<"))
            {
                list.add(spliced[1]);
                String tempuser = spliced[1];
                textChannel.sendMessage(tempuser + " you have been suspended for " + spliced[2] + " days.").queue();//Sends the message in the quotations.
                //add role to the member
            }
        }else {
            channel.sendMessage("Please use the following format for suspending a user: '!suspend' <@user> (length)").queue(); //If length doesn't equal 3 then it sends the message in quotations.
        }
    }

不确定如何执行此操作,因为我对JDA不太熟悉,无法使其正常工作。除了实际添加的名为“ Suspended”的角色外,其他所有工作都可以进行。

2 个答案:

答案 0 :(得分:0)

可以在消息中为上述成员添加角色,如下所示:

Role role = event.getGuild().getRolesByName("Suspended", false).get(0);
List<Member> mentionedMembers = message.getMentionedMembers();
for (Member mentionedMember : mentionedMembers) {
    event.getGuild().getController().addRolesToMember(mentionedMember, role).queue();
}

请注意,您的漫游器需要获得MANAGE_ROLES权限才能添加角色。

答案 1 :(得分:0)

您可以这样做:?

event.getGuild().addRoleToMember(memberId, jda.getRoleById(yourRole));