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

Posted

技术标签:

【中文标题】在 JDA 中向提及的用户添加角色【英文标题】:Adding roles to a mentioned user in JDA 【发布时间】:2019-05-29 15:17:50 【问题描述】:

我希望能够运行以 !suspend 开头的命令,提及用户,然后确定时间长度并将名为“暂停”的角色添加到提及的用户指定的时间长度。

    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 太不熟悉,无法使其工作。除了实际添加名为“已暂停”的角色外,我一切正常。

【问题讨论】:

【参考方案1】:
event.getGuild().addRoleToMember(member, event.getGuild().getRoleById(yourRole)).queue();

【讨论】:

您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。【参考方案2】:

你可以这样做:?

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

【讨论】:

【参考方案3】:

向消息中提到的成员添加角色可以如下完成:

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 权限才能添加角色。

【讨论】:

以上是关于在 JDA 中向提及的用户添加角色的主要内容,如果未能解决你的问题,请参考以下文章

JDA 事件获取器返回 null 并让所有成员在一个角色中只返回机器人本身

给立即加入 JDA 的用户 jda 一个角色最好的方法是啥

如何在 Javascript 中向 btn.innerHTML 添加函数?

如何在 Plone 4.1.4 中向 intranet_workflow 添加更多自定义状态

如何从提及 discord.js 添加角色

当某个用户提到某人时,我将如何编写用于提及角色的代码? [关闭]