Skip to content

Context Menus in JDA Chewtils

Olivia edited this page Jan 29, 2022 · 2 revisions

⚠️ This page is UNDER CONSTRUCTION ⚠️


ContextMenus are a new addition to JDA 5 and JDA-Chewtils 2.0. They are fairly interesting so let's take a deep dive.

Keep in mind you can only have 5 of each context menu, 5 user and 5 message, in your bot (unlike Slash Commands, where you get 100).

Because there's 2 different type of Context Menus, we'll break it up.

Context Menu Configuration

Much like a Command or SlashCommand, you must add the menu name, among other details. They are described below!

Config options are fairly limited here, you only get a few options, and a few key differences:

Option Description
this.name The name that appears on the menu itself. Can be 1-32 characters, and can contain spaces and capital letters.
this.botPermissions Ported from Command and is functionality equivalent. Ensures the bot has the specified permissions.
this.userPermissions Ported from Command and is functionality equivalent. Ensures the user has the specified permissions.

User Context Menu

To start off, make a new class that extends UserContextMenu from com.jagrosh.jdautilities.command, just like a slash command. Then add the constructor and add the required abstract method.

public class MyUserContextMenu extends UserContextMenu {
    public MyUserContextMenu() {
    }

    @Override
    protected void execute(UserContextMenuEvent event) {
    }
}

Great! Off to a good start here. Now, we need to name it. As stated above, it can be whatever we want, we aren't limited to lowercase, no spaces, etc. As an example, we'll put "Send A Hug."

public MyUserContextMenu() {
    this.name = "Send A Hug";
}

And as a body, we'll just reply with a hug to this user.

@Override
protected void execute(UserContextMenuEvent event) {
    event.respond("Aww! " + event.getTargetUser().getAsMention() + " got hugged by " + event.getUser().getAsMention());
}

Note: respond is a special method that replies and automatically does the queue() callback, saving a bit of code. To keep the old functionality, simply use reply() as normal.

Full Example Class
public class MyUserContextMenu extends UserContextMenu {
    public MyUserContextMenu() {
        this.name = "Send A Hug";
    }

    @Override
    protected void execute(UserContextMenuEvent event) {
        event.respond("Aww! " + event.getTargetUser().getAsMention() + " got hugged by " + event.getUser().getAsMention());
    }
}

Be sure to add this to the CommandClientBuilder, or it won't show up:

builder.addContextMenu(new MyUserContextMenu());