-
Notifications
You must be signed in to change notification settings - Fork 3
Commands
light has a built-in abstraction-based command handler. This allows you to easily create Bukkit commands, using an OOP-based approach, and without having to register them in the plugin.yml. It also supports sub-commands which helps keep code clean, readable and easy to manage.
You can create a command by extending the AbstractCommand class and by calling the super() constructor. This can be achieved as follows:
public class ExampleCommand extends AbstractCommand {
public ExampleCommand() {
super(name: "example");
setPermission("example.permission");
setSubCommands(Collections.singletonList(new ExampleSubCommand()));
}
@Override
public boolean onCommand(CommandSender commandSender, String[] args) {
if (args.length == 0) {
commandSender.sendMessage("Example command working!");
return false;
}
for (SubCommand subCommand : getSubCommands()) {
if (!subCommand.getName().equalsIgnoreCause(args[0])) {
continue;
}
if (!commandSender.hasPermission(subCommand.getPermission())) {
commandSender.sendMessage("You do not have permission to execute that sub-command!");
return false;
}
subCommand.onCommand(commandSender, args);
}
return false;
}
You can also create sub-commands by extending the SubCommand class and calling the super() constructor. This can be achieved as follows:
public class ExampleSubCommand extends SubCommand {
public ExampleSubCommand() {
super(name: "sub", permission: "example.subcommand.permission");
}
@Override
public boolean onCommand(CommandSender commandSender, String[] args) {
commandSender.sendMessage("Example sub-command working!");
}
After we have created our command, we have to register it. This can be achieved by creating an instance of our new command and calling the register() method. This can be achieved as follows:
new ExampleCommand().register();
I would also recommend creating a CommandManager class which contains methods to register commands, this will help keep your code base clean and manageable. You could also automatically register commands by using reflection, which can be achieved by scanning a package for classes extending AbstractCommand and creating a new instance of them.