Skip to content

Building commands based on annotations

Daniel edited this page May 3, 2024 · 2 revisions

To create commands, Jyraf uses the coud command framework based on annotations, so familiarize yourself with the examples in their documentation. The only thing Jyraf does differently is providing a more convenient wrapper, including for parameter parsers. Here's an example from a real plugin.

import dev.ckateptb.minecraft.jcommands.JCommands;
import dev.ckateptb.minecraft.jcommands.config.JCommandsConfig;
import dev.ckateptb.minecraft.jyraf.command.Command;
import dev.ckateptb.minecraft.jyraf.component.Text;
import dev.ckateptb.minecraft.jyraf.container.annotation.Component;
import dev.ckateptb.minecraft.jyraf.internal.commands.annotations.Argument;
import dev.ckateptb.minecraft.jyraf.internal.commands.annotations.CommandMethod;
import dev.ckateptb.minecraft.jyraf.internal.commands.annotations.CommandPermission;
import lombok.RequiredArgsConstructor;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

@Component
@RequiredArgsConstructor
public class SudoCommand implements Command {
    private final JCommands plugin;
    private final JCommandsConfig config;

    @CommandMethod("sudo <target> <command>")
    @CommandPermission("jcommands.sudo")
    public void sudo(CommandSender sender, @Argument("target") Player target, @Argument("command") String[] command) {
        sender.sendMessage(Text.of(this.config.getSudo(), "%player_name%", target.getName()));
        this.plugin.syncScheduler().schedule(() -> Bukkit.dispatchCommand(target, String.join(" ", command)));
    }

    @CommandMethod("sudo <target> c: <command>")
    @CommandPermission("jcommands.sudo")
    public void sudoChat(CommandSender sender, @Argument("target") Player target, @Argument("command") String[] command) {
        sender.sendMessage(Text.of(this.config.getSudoChat(), "%player_name%", target.getName()));
        this.plugin.syncScheduler().schedule(() -> target.chat(String.join(" ", command)));
    }
}

As you can see, all we need to do is add the implementation of the Command interface.

It's important to know that commands are processed asynchronously. If you want to synchronize with the main thread, you can use the SyncScheduler, which we will discuss later.

By default, commands have a preset error handling format. However, if you want to replace it with your own, use CommandInjection#setExceptionHandler before calling scan for your plugin.

Clone this wiki locally