-
Notifications
You must be signed in to change notification settings - Fork 0
Get started with command handling
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...
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.
Let's assume the following command (sayhello) is referenced in your plugin.yml
:
commands:
sayhello:
usage: /sayhello <player> <amount>
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");
}
};
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!
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 CommandSchema
s and CommandArgument
s, go check out the corresponding wiki pages.