Skip to content

Get started with command handling

Gil Campini edited this page Apr 12, 2021 · 10 revisions

Why?

Let's face it, command handling in Spigot is a pain. It comes with no utility for developers. Input parsing must be done manually, auto tab-completion is hard to get right, and so on...

The goal

We want to create the command /sayhello <player> <amount> which will send "Hello" to the player's chat a certain number (amount) of times. If amount isn't specified, one "Hello" will be sent.
We just described two sub-commands, one with the amount specified, the other without.

We'll use SpiGotUtils' command utilities to handle this command.

Prerequisite

Let's assume the following command (sayhello) is referenced in your plugin.yml:

commands:
  sayhello:
    usage: /sayhello <player> <amount>

Describing our two "sub-commands"

Let's describe our two "sub-commands" with a very important class: the CommandSchema.
This class stores information about the behavior, expectations and execution of your sub-command.

CommandSchema<CommandSender> schemaWithAmount = new CommandSchema<CommandSender>(
        new PlayerArgument("player"),
        new IntegerArgument("amount")
) {
    @Override
    public void execute(CommandSender sender, CommandInputs inputs) {
        Player target = inputs.get("player");
        int amount = inputs.get("amount");
        for (int i = 0; i < amount; i++) {
            target.sendMessage("Hello");
        }
    }
};

CommandSchema<CommandSender> schemaWithoutAmount = new CommandSchema<CommandSender>(
        new PlayerArgument("player")
) {
    @Override
    public void execute(CommandSender sender, CommandInputs inputs) {
        Player target = inputs.get("player");
        target.sendMessage("Hello");
    }
};

The CommandHandler, our savior

A CommandHandler is a class provided by the library that helps you handle all the interactions of one plugin command. It handles command route finding, tab completion, and command execution, and much more...

You can obtain an instance of CommandHandler just like that:

PluginCommand command = yourPluginInstance.getCommand("sayhello");
CommandHandler handler = new CommandHandler(command);

where yourPluginInstance is the instance of your plugin.

Now that you have your handler, you need to tell him to handle the two schemas you just created.

handler.add(schemaWithAmount, schemaWithoutAmount);

Voilà! Now, the handler is taking care of everything from auto completion to execution through permission, input parsing and more!

Going further

There is another way to handle command with SpiGotUtils. It's more straightforward that the one discussed in this page. However, it is a bit more limited. Go learn about that here.

For more information about CommandSchemas and CommandArguments, go check out the corresponding wiki pages.