Search code examples
javadiscorddiscord-jda

Mention any member via Java DIscord Bot


So i am making a bot where the purpose of it would be to tag the user who has been reported by typing .inappropriate @discordUser.

Here is the sample:

if(message.getMessageContent().equalsIgnoreCase(main.prefix + "inappropriate"))
{
            message.getChannel().sendMessage("username of <@!USER_ID> is inappropriate.");
}

However, the problem is that it is not a specified user. In other words, it won't always be the same user.

So this is how it should look on Discord:

Me: .inappropriate @discordUser

Bot: username of @discordUser is inappropriate.

So, i wanted to know, how i can make this possible?


Solution

  • You didn't tell which discord wrapper you are using, but from getMessageContent(), it seems to be Javacord. And if it not, note that everything that I will say are the same/have equivalent in other wrappers.

    • First you need to get the id or the member mentioned.
    • Second you have to make a mention from it.

    To get the mentioned member, you can use the method Message#getMentionedUsers() which returns a List of the users mentioned in the message. This means that you can even get several users. To get the id, either you use User#getId() or User#getIdAsString() or you can try to parse the Message#getMessageContent() by for example splitting it and then using a regex (remember that a mention is <@!id>)

    How do you get a mention from user or id ? From the user, you can simply use the method User#getMentionTag​() or User#getNicknameMentionTag​​(). From the id, you can append "<@!" + id + ">".

    So in short, you can either do :
    message → member (method) → mention (method)
    message → id (manual parsing) → mention (manual appending)
    message → member (method) → id (getter method) → mention (method)
    The last one may seem useless, but in the case where you store ids (you can't store entities), it can be useful. And also, you can retrieve member from id, but it's useless here compared to the other on top of needing intents, actually you can simply do the first solution, it's just two method calls.

    I gave you several ways to do it, some of them are manual, other use existing methods. You should prefer using those method unless it's not convenient for you (ie you want your own command parser so you can't use getMentionedUsers()).

    Also, you can look up at the method of each classes, you may find gold, the doc is available in your ide or online here with a search bar. I knew the wrapper JDA but I have no idea about Javacord until I answer your question. It's my first answer, I hope I didn't mess up something.