Skip to content

Command API: Class based

Lorenzo Rutayisire edited this page Jun 13, 2020 · 7 revisions

Let's say we want to create the /quake create <arena> command using the class-based command-api approach.

First, we make the class for create <arena>:

public class CreateArenaCommand extends Command {
    public CreateArenaCommand() {
        super("create");

        // Sets the description that will be displayed in the help command.
        setDescription("Creates a new arena with the given name."); 

        // Sets the senders that can execute this command.
        setSenderType(SenderType.PLAYER); 

        // Sets an alias for the command.
        addAliases("c");
    }

    @Override
    public String getUsage(CommandSender sender, boolean colored) {
        return "<arena>"; // The parameters required to use this command.
    }

    @Override
    protected boolean onCall(CommandSender sender, Queue<String> args) {
        // Here we're already sure the sender is a player.
        if (args.isEmpty()) {
            sender.sendMessage(RED + "Specify the arena."); // Wrong command usage!
            return false;
        }
        // (...) Does some stuff to actually create the arena...
        sender.sendMessage(GREEN + "Arena created successfully.");
        return true;
    }
}

Then, we create the node-command for quake:

public class QuakeCommand extends NodeCommand {
    public QuakeCommand() {
        super("quake");

        setDescription("The main Quake command.");
        //setSenderType(SenderType.ALL); This is the default sender-type.
        addAliases("q");

        append(new CreateArenaCommand()); // Adds "create <arena>" as a sub-command of quake.
    }
}

Finally, we have to register quake as a root Bukkit's command:

CommandRegistry.register(new QuakeCommand());

HelpCommand

Along with /quake create you'll probably notice another command has been generated. The help command. It is automatically added within every node command and its features can be defined in the uppercore.yml config.