Skip to content

Creating a command

GabRay edited this page Feb 18, 2023 · 6 revisions

Creating the command

Creating a new command is done either by creating a new class that extends CommandContext, and adding the @Command annotation.

@Command(name = "money", description = "Manage your money", playerOnly = true)
public class MoneyCommand extends CommandContext {
}
Parameter required description
name false Name of the command. If not provided, it is derived from the class name by removing any 'Command' suffix and converting the first letter in lowercase (ex: MoneyCommand --> money)
description false Description shown in help messages
permission false Permission to test before executing the command. Player's who don't have the permission won't see the command in help messages and tab completions, and won't be able to execute it. See the corresponding wiki page for more info.
playerOnly false If true, the command can't be executing from the console. False by default
alias  false List of aliases for this commands. Works only for subcommands.
args false List of arguments
subCommands false List of sub commands

Defining behaviors

@Command(name = "money", description = "Manage your money", playerOnly = true)
public class MoneyCommand extends CommandContext {

    @CommandBody
    void command(CommandEnvironment env) {
        // Do stuff...
        env.getSender().sendMessage("Hello world!");
    }
}

It is possible to add more parameters to the method annotated with @CommandBody, they will be injected automatically. For example, you can add a parameter CommandSender (or Player for player-only commands) instead of getting it from the environment. CommandEnvironment is itself optional. You can also get values stored in the env with the @Env annotation.

@CommandBody
void command(Player player, @Env(key="myVariable") String message)
{
    player.sendMessage(message);
}

Register the command

Now that your command is declared, you need to register it.

class MyPlugin extends JavaPlugin {

    @Override
    public void onEnable() {
        CommandManager manager = new CommandManager()
        manager.register(new MoneyCommand());
    }
}

Clone this wiki locally