-
Notifications
You must be signed in to change notification settings - Fork 2
Requirements for Commands
This guide explains how to use the Requirement interface in CommandsAPI to enforce contextual conditions before a command is executed.
A Requirement is a lightweight interface that allows you to define external conditions that must be met by the CommandSender before the command runs. If the requirement fails, an error message is shown and the command will be canceled.
This gives you the ability to define location-, role-, or context-specific access to commands in a clean, reusable way.
package fr.traqueur.commands.api.requirements;
public interface Requirement {
boolean check(CommandSender sender);
String errorMessage();
}The check method returns whether the sender satisfies the requirement. The errorMessage() defines what message should be sent when they don't.
🗨 If
errorMessage()returnsnullor empty, a generic fallback message from theMessageHandleris used.
The following implementations are bundled with the API:
Requirement OVERWORLD_REQUIREMENT = new WorldRequirement(Bukkit.getWorld("world"));
Requirement NETHER_REQUIREMENT = new WorldRequirement(Bukkit.getWorld("world_nether"));
Requirement END_REQUIREMENT = new WorldRequirement(Bukkit.getWorld("world_the_end"));These check if the sender (must be a Player) is in a specific Minecraft world.
If supported in your plugin, you can use or extend ZoneRequirement to restrict command usage to custom-defined zones.
CommandsAPI allows you to register one or more requirements per command:
addRequirements(Requirement... requirements);Example:
public class TeleportCommand extends Command<MyPlugin> {
public TeleportCommand(MyPlugin plugin) {
super(plugin, "teleport");
addRequirements(Requirement.OVERWORLD_REQUIREMENT);
}
@Override
public void execute(CommandSender sender, Arguments args) {
sender.sendMessage("Teleporting...");
}
}If the player is not in the Overworld, the command will be blocked with the appropriate error message.
You can define your own conditions easily:
public class PermissionRequirement implements Requirement {
private final String permission;
public PermissionRequirement(String permission) {
this.permission = permission;
}
@Override
public boolean check(CommandSender sender) {
return sender.hasPermission(permission);
}
@Override
public String errorMessage() {
return "§cYou lack permission: " + permission;
}
}Then use it like this:
addRequirements(new PermissionRequirement("myplugin.use"));- Requirements are additive. All must pass for the command to run.
- Requirements are checked before
execute()is called. - You can combine built-in and custom requirements as needed.
By using requirements, you make your command logic more maintainable and user-aware, avoiding unnecessary checks in execute() and improving error feedback.
Start gating your commands smartly with Requirement!