Skip to content

Command Hooks

Redempt edited this page Nov 16, 2021 · 5 revisions

Command Hooks are the methods in your code which are called when your command is run and all of its conditions are satisfied. The basic concept is very simple: You annotate a method with @CommandHook("hooknamehere"), and when the command is run, that method will be called. In general, hook methods should look like this:

@CommandHook("hooknamehere")
public void someCommand(CommandSender sender) {
	//Do stuff
}

You must always take a CommandSender as the first argument. In cases where the command is usable by players only, it is also fine to take a Player as the first argument.

But before this will work, we need to actually register the command file. In the previous wiki page, you learned about the command file, and hooks were mentioned. You need to specify that, but you also need to parse the command file. Doing this is fairly straightforward. If you're exporting directly, your command file should be in the root directory of the project. If you're using a build system like Gradle or Maven, it should be in the respective resources folder. This will ensure it's included in the plugin jar.

To register the command file, you need to fetch it from within the jar. Thankfully, Spigot provides a method to do just that: JavaPlugin#getResource(String). It's standard to name the command file command.rdcml. If you've done this, and it's in the root directory of your jar, all you have to do is this in your plugin's onEnable:

@Override
public void onEnable() {
	new CommandParser(this.getResource("command.rdcml")).parse().register("prefix", this);
}

That will load all of the commands from the command file, then register them to the method hooks within the plugin. Calling parse() parses the command file and returns a CommandCollection. Calling register() on the CommandCollection registers the commands. The first argument to register() is the prefix, also known as the fallback prefix. For all Minecraft commands, the fallback prefix is minecraft. An example is /minecraft:kill. The second argument is a vararg of listener objects - objects containing the method hooks. If you pass this, and include the method hooks in your plugin's main class, they will be called when the commands specified by your command file are run. You can also create other listener objects and register them instead of or alongside your plugin's main class.

So now, you've learned how to write and register basic command hooks so you can run your commands in-game and have them work. However, commands get much more complicated than this, and one of their most common ingredients is arguments. To learn how to use command arguments, read on to the Command Arguments page.

Clone this wiki locally