### Command Syntax Example Source: https://docs.commandapi.dev/create-commands/arguments/command-arguments Example command syntax for raw argument demonstration. ```mccmd /mycommand 15.3 @e ``` -------------------------------- ### Basic Command Registration Example Source: https://docs.commandapi.dev/create-commands/registration An example demonstrating how to register a simple broadcast command with arguments, aliases, permissions, and an executor. ```APIDOC ## POST /register/command ### Description Registers a new command with the CommandAPI. ### Method POST ### Endpoint /register/command ### Request Body - **commandName** (String) - Required - The name of the command. - **arguments** (List) - Optional - The arguments for the command. - **aliases** (String...) - Optional - Aliases for the command. - **permission** (CommandPermission | String) - Optional - The permission required to execute the command. - **requirements** (sender -> {}) - Optional - Additional constraints for command execution. - **help** (String, String | HelpTopic) - Optional - Help topic for the command. - **subcommand** (CommandAPICommand) - Optional - A subcommand for the current command. ### Request Example ```java new CommandAPICommand("broadcastmsg") .withArguments(new GreedyStringArgument("message")) .withAliases("broadcast", "broadcastmessage") .withPermission(CommandPermission.OP) .executes((sender, args) -> { String message = (String) args.get("message"); Bukkit.getServer().broadcastMessage(message); }) .register(); ``` ### Response #### Success Response (200) - **status** (String) - Indicates successful registration. #### Response Example ```json { "status": "Command 'broadcastmsg' registered successfully." } ``` ``` -------------------------------- ### Arbitrary Commands - /sudo Example Source: https://docs.commandapi.dev/create-commands/arguments/types/command-arguments Example of creating a /sudo command that allows users to execute any arbitrary command as another player. ```APIDOC ## Arbitrary Commands - /sudo Example ### Description This example demonstrates how to create a `/sudo` command that allows a user to execute any arbitrary command as another online player. It utilizes `CommandArgument` to capture the command and its arguments, and `Command.execute()` to run the command. ### Method POST ### Endpoint `/sudo ` ### Parameters #### Path Parameters - **target** (EntitySelectorArgument.OnePlayer) - Required - The player to execute the command as. - **command** (CommandArgument) - Required - The arbitrary command to execute. ### Request Example ```json { "target": "player_name", "command": "/say hello world" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation that the command was executed. #### Response Example ```json { "message": "Command executed successfully as player_name." } ``` ### Code Example (Java) ```java new CommandAPICommand("sudo") .withArguments(new EntitySelectorArgument.OnePlayer("target")) .withArguments(new CommandArgument("command")) .executes((sender, args) -> { Player target = (Player) args.get("target"); CommandResult command = (CommandResult) args.get("command"); command.execute(target); }) .register(); ``` ``` -------------------------------- ### Arbitrary Commands - Sudo Example Source: https://docs.commandapi.dev/create-commands/arguments/types/command-arguments?from=9.4.2 Example of creating a /sudo command that allows executing any arbitrary command as another player. ```APIDOC ## Arbitrary Commands - Sudo Example ### Description This example demonstrates how to create a `/sudo` command that allows a user to execute any arbitrary command as another online player. It utilizes `CommandArgument` to capture the command and its arguments, and `Command.execute()` to run it. ### Method POST ### Endpoint `/sudo ` ### Parameters #### Path Parameters - **target** (EntitySelectorArgument.OnePlayer) - Required - The player to execute the command as. - **command** (CommandArgument) - Required - The arbitrary command to execute. ### Request Example ```java new CommandAPICommand("sudo") .withArguments(new EntitySelectorArgument.OnePlayer("target")) .withArguments(new CommandArgument("command")) .executes((sender, args) -> { Player target = (Player) args.get("target"); CommandResult command = (CommandResult) args.get("command"); command.execute(target); }) .register(); ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful execution of the sudo command. ``` -------------------------------- ### Example Command Usage Strings Source: https://docs.commandapi.dev/create-commands/help?from=8.8.0 Examples of raw command usage strings and their resulting formatted output. ```mccmd /command /command ``` ```yaml Usage: - /command - /command - /command - /command - /command - /command - /command ``` -------------------------------- ### Add new method and example for converting specific commands internally Source: https://docs.commandapi.dev/9.6.1?from=11.2.0 Demonstrates adding a new method and example for converting specific commands internally. ```java CommandAPI.register("convert_internal", new LiteralArgument("convert")) .executes((sender, args) -> { CommandAPI.convertCommand("old_cmd", "new_cmd", "/new_cmd argument"); }); ``` -------------------------------- ### Example: Implementing a Command with Safe Argument Instances Source: https://docs.commandapi.dev/create-commands/arguments/command-arguments This example showcases initializing various argument types (String, Integer, Player, GreedyString) and then accessing their values safely using `getByArgument` and `getByArgumentOrDefault` within a player execution context. ```java StringArgument nameArgument = new StringArgument("name"); IntegerArgument amountArgument = new IntegerArgument("amount"); EntitySelectorArgument.OnePlayer playerArgument = new EntitySelectorArgument.OnePlayer("player"); EntitySelectorArgument.OnePlayer targetArgument = new EntitySelectorArgument.OnePlayer("target"); GreedyStringArgument messageArgument = new GreedyStringArgument("message"); new CommandAPICommand("mycommand") .withArguments(nameArgument) .withArguments(amountArgument) .withOptionalArguments(playerArgument) .withOptionalArguments(targetArgument) .withOptionalArguments(messageArgument) .executesPlayer((player, args) -> { String name = args.getByArgument(nameArgument); int amount = args.getByArgument(amountArgument); Player p = args.getByArgumentOrDefault(playerArgument, player); Player target = args.getByArgumentOrDefault(targetArgument, player); String message = args.getOptionalByArgument(messageArgument).orElse("Hello!"); // Do whatever with these values }) .register(); ``` -------------------------------- ### Command Registration Example Source: https://docs.commandapi.dev/create-commands/registration?from=9.4.2 An example demonstrating the registration of a simple broadcast command using the CommandAPICommand builder pattern. ```APIDOC ## POST /register/command ### Description Registers a new command with the CommandAPI using a builder pattern. ### Method POST ### Endpoint /register/command ### Request Body - **commandName** (String) - Required - The name of the command. - **arguments** (List) - Optional - The arguments for the command. - **aliases** (String...) - Optional - Aliases for the command. - **permission** (CommandPermission or String) - Optional - The permission required to execute the command. - **requirements** (sender -> {}) - Optional - Additional constraints for command execution. - **shortDescription** (String) - Optional - A short description for the command's help topic. - **fullDescription** (String) - Optional - A full description for the command's help topic. - **subcommand** (CommandAPICommand) - Optional - A subcommand associated with this command. ### Request Example ```java new CommandAPICommand("broadcastmsg") .withArguments(new GreedyStringArgument("message")) .withAliases("broadcast", "broadcastmessage") .withPermission(CommandPermission.OP) .executes((sender, args) -> { String message = (String) args.get("message"); Bukkit.getServer().broadcastMessage(message); }) .register(); ``` ### Response #### Success Response (200) - **status** (String) - Indicates successful registration. #### Response Example ```json { "status": "Command 'broadcastmsg' registered successfully." } ``` ``` -------------------------------- ### Arbitrary Commands - Sudo Example Source: https://docs.commandapi.dev/create-commands/arguments/types/command-arguments?from=8.8.0 Example demonstrating how to create a '/sudo' command using CommandArgument to execute arbitrary commands as another player. ```APIDOC ## Arbitrary Commands - Sudo Example ### Description This example shows how to implement a `/sudo` command that allows a user to execute any arbitrary command as another online player. It utilizes `CommandArgument` to capture the command and its arguments, and `CommandResult.execute()` to run it. ### Method POST ### Endpoint `/sudo ` ### Parameters #### Path Parameters - **target** (EntitySelectorArgument.OnePlayer) - Required - The player to execute the command as. - **command** (CommandArgument) - Required - The arbitrary command to execute. ### Request Example ```java new CommandAPICommand("sudo") .withArguments(new EntitySelectorArgument.OnePlayer("target")) .withArguments(new CommandArgument("command")) .executes((sender, args) -> { Player target = (Player) args.get("target"); CommandResult command = (CommandResult) args.get("command"); command.execute(target); }) .register(); ``` ### Response #### Success Response (200) - **message** (string) - Confirmation that the command was executed. #### Response Example ```json { "message": "Command executed successfully as target player." } ``` ``` -------------------------------- ### Usage Example for /sendmessage Source: https://docs.commandapi.dev/create-commands/arguments/types/map-arguments?from=9.4.2 Example command execution showing how to provide key-value pairs with default delimiters and separators. ```mccmd /sendmessage Player1:"Hello, Player1!" Player2:"Hello, Player2!" ``` -------------------------------- ### Add method and example for converting specific commands internally Source: https://docs.commandapi.dev/9.6.1?from=11.2.0 Provides an example of how to convert specific commands internally within the CommandAPI. ```java CommandAPI.register("mycommand", new LiteralArgument("convert").executes((sender, args) -> { // Convert command internally CommandAPI.convertCommand("oldcommand", "newcommand", "/newcommand argument"); })); ``` -------------------------------- ### Multiple Command Executors Example Source: https://docs.commandapi.dev/9.3.0?from=11.2.0 Example demonstrating the feature of having multiple command executors with the same implementation. This allows for more flexible command routing. ```java CommandAPI.register("mycommand", new Argument[]{...}, (sender, args) -> { ... } ).register("mycommand.alias", new Argument[]{...}, (sender, args) -> { ... } ); ``` -------------------------------- ### Example Command Syntax with Random Chance Predicate Source: https://docs.commandapi.dev/internal/brigadier-plus-commandapi This example demonstrates the desired syntax for a command that includes a custom predicate for random chances. ```minecraft /execute if randomchance 1 4 run say Hello! ``` -------------------------------- ### Command Format Example Source: https://docs.commandapi.dev/user-setup/command-conversion/entity-selectors This shows the typical format of the EssentialsX /ext command. ```mccmd /ext /ext ``` -------------------------------- ### Example - Searching chests for certain items Source: https://docs.commandapi.dev/create-commands/arguments/types/ranged-arguments An example demonstrating how to use `IntegerRangeArgument` and `ItemStackArgument` to search for chests within a specified distance from the player containing a particular item. ```APIDOC ## POST /searchchests ### Description Searches loaded chests within a specified distance from the player for a given item. ### Method POST ### Endpoint `/searchchests` ### Parameters #### Query Parameters - **range** (IntegerRangeArgument) - Required - The range of distances to search within. - **item** (ItemStackArgument) - Required - The type of item to search for in the chests. ### Request Example ```json { "range": "5..10", "item": "minecraft:diamond" } ``` ### Response #### Success Response (200) - **locations** (List) - A list of locations of the chests found. - **message** (string) - A message indicating the number of chests found or if none were found. #### Response Example ```json { "message": "Found 3 chests:" } ``` ```java new CommandAPICommand("searchchests") .withArguments(new IntegerRangeArgument("range")) // Range argument .withArguments(new ItemStackArgument("item")) // The item to search for .executesPlayer((player, args) -> { // Retrieve the range from the arguments IntegerRange range = (IntegerRange) args.get("range"); ItemStack itemStack = (ItemStack) args.get("item"); // Store the locations of chests with certain items List locations = new ArrayList<>(); // Iterate through all chunks, and then all tile entities within each chunk for (Chunk chunk : player.getWorld().getLoadedChunks()) { for (BlockState blockState : chunk.getTileEntities()) { // The distance between the block and the player int distance = (int) blockState.getLocation().distance(player.getLocation()); // Check if the distance is within the specified range if (range.isInRange(distance)) { // Check if the tile entity is a chest if (blockState instanceof Chest chest) { // Check if the chest contains the item specified by the player if (chest.getInventory().contains(itemStack.getType())) { locations.add(chest.getLocation()); } } } } } // Output the locations of the chests, or whether no chests were found if (locations.isEmpty()) { player.sendMessage("No chests were found"); } else { player.sendMessage("Found " + locations.size() + " chests:"); locations.forEach(location -> { player.sendMessage(" Found at: " + location.getX() + ", " + location.getY() + ", " + location.getZ()); }); } }) .register(); ``` ``` -------------------------------- ### FunctionArgument Example: Implementing /function command Source: https://docs.commandapi.dev/create-commands/functions-and-tags/function-arguments?from=8.8.0 This example demonstrates how to implement Minecraft's native /function command using the FunctionArgument class. It shows how to handle both single functions and tags. ```APIDOC ## POST /runfunction ### Description Executes a specified Minecraft function or tag. ### Method POST ### Endpoint /runfunction ### Parameters #### Request Body - **function** (FunctionArgument) - Required - Represents the function or tag to execute. ### Request Example ```json { "function": "my_namespace:my_function" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates successful execution. #### Response Example ```json { "status": "Function executed successfully" } ``` ``` -------------------------------- ### Command Implementation Source: https://docs.commandapi.dev/create-commands/arguments/types/misc/sound-arguments?from=9.6.1 Examples of registering a command that utilizes the SoundArgument to play sounds. ```APIDOC ## Command Implementation ### Description Registers a command that accepts a sound argument and plays it at the player's location. ### Command Syntax /sound ### Implementation Examples #### Using SoundArgument ```java new CommandAPICommand("sound") .withArguments(new SoundArgument("sound")) .executesPlayer((player, args) -> { player.getWorld().playSound(player.getLocation(), (Sound) args.get("sound"), 100.0f, 1.0f); }) .register(); ``` #### Using SoundArgument.NamespacedKey ```java new CommandAPICommand("sound") .withArguments(new SoundArgument.NamespacedKey("sound")) .executesPlayer((player, args) -> { player.getWorld().playSound(player.getLocation(), ((NamespacedKey) args.get("sound")).asString(), 100.0f, 1.0f); }) .register(); ``` ``` -------------------------------- ### Reference plugin.yml structure Source: https://docs.commandapi.dev/user-setup/command-conversion/single-command?from=8.8.0 Example of a plugin.yml file showing declared commands that can be converted. ```yaml name: Essentials main: com.earth2me.essentials.Essentials version: 2.18.0.0 website: http://tiny.cc/EssentialsCommands description: Provides an essential, core set of commands for Bukkit. softdepend: [ Vault, LuckPerms ] authors: [ Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo, ceulemans, Xeology, KHobbits, md_5, Iaccidentally, drtshock, vemacs, SupaHam, md678685 ] api-version: "1.13" commands: afk: description: Marks you as away-from-keyboard. usage: / [player/message...] aliases: [ eafk,away,eaway ] # (other config options omitted) hat: description: Get some cool new headgear. usage: / [remove] aliases: [ ehat,head,ehead ] # (other config options omitted) ``` -------------------------------- ### Example Command Usage Display Source: https://docs.commandapi.dev/create-commands/help Illustrates how command usage is displayed by default and after applying custom usage strings. ```mccmd /command /command ``` ```yaml Usage: - /command - /command - /command - /command - /command - /command - /command ``` ```yaml Usage: - /command
- /command ``` -------------------------------- ### Update Upgrading Guide for 8.4.0 Changes Source: https://docs.commandapi.dev/9.3.0?from=11.2.0 The Upgrading guide has been updated to reflect changes introduced in version 8.4.0. Consult this guide for smooth transitions between versions. ```text See Upgrading guide for more info. ``` -------------------------------- ### Example Command Usage (Default Displayed) Source: https://docs.commandapi.dev/create-commands/help?from=9.6.1 Shows how the default command usage is displayed to the user. ```yaml Usage: - /command - /command - /command - /command - /command - /command - /command ``` -------------------------------- ### Double Player Level Example Source: https://docs.commandapi.dev/create-commands/arguments/types/misc/mathoperation-arguments?from=9.6.1 Example command to double a player's current level. ```minecraft /changelevel Notch *= 2 ``` -------------------------------- ### Usage examples for changelevel Source: https://docs.commandapi.dev/create-commands/arguments/types/misc/mathoperation-arguments?from=8.8.0 Example inputs for the changelevel command demonstrating different math operations. ```mccmd /changelevel Notch = 10 ``` ```mccmd /changelevel Notch *= 2 ``` ```mccmd /changelevel Notch > 20 ``` -------------------------------- ### Example Command Usage (Default) Source: https://docs.commandapi.dev/create-commands/help?from=9.3.0 Illustrates the default command usage format before customization. ```mccmd /command /command ``` -------------------------------- ### Set Player Level Example Source: https://docs.commandapi.dev/create-commands/arguments/types/misc/mathoperation-arguments?from=9.6.1 Example command to set a player's level to a specific value. ```minecraft /changelevel Notch = 10 ``` -------------------------------- ### Minecraft command syntax examples Source: https://docs.commandapi.dev/create-commands/arguments/types/entities-arguments?from=9.6.1 Examples of command syntax for removing entities using target selectors. ```mccmd /remove /remove /remove ``` ```mccmd /remove @e[type=cow] ``` ```mccmd /remove @e[type=pig,limit=10,sort=furthest] ``` -------------------------------- ### Validate command input examples Source: https://docs.commandapi.dev/create-commands/arguments/types/command-arguments?from=9.4.2 Examples of valid and invalid command inputs based on the defined suggestion branch. ```mccmd /give diamond /give minecraft:diamond ``` ```mccmd /give /give diamond 10 ``` -------------------------------- ### Example Command Usage (Custom Displayed) Source: https://docs.commandapi.dev/create-commands/help?from=9.6.1 Shows how the custom command usage is displayed after using `withUsage()`. ```yaml Usage: - /command
- /command ``` -------------------------------- ### Register Command with Combined Help Method Source: https://docs.commandapi.dev/create-commands/help The `withHelp()` method is a convenient way to set both the short and full descriptions for a command simultaneously. This is the recommended approach for setting command help. ```java new CommandAPICommand("mycmd") .withHelp("Says hi", "Broadcasts hi to everyone on the server") .executes((sender, args) -> { Bukkit.broadcastMessage("Hi!"); }) .register(); ``` -------------------------------- ### Raw JSON Chat Component Examples Source: https://docs.commandapi.dev/create-commands/arguments/types/chat/spigot-chat-arguments?from=9.4.2 Examples of raw JSON chat component structures for book content. ```json ["", { "text": "Once upon a time, there was a guy call " }, { "text": "Skepter", "color": "light_purple", "hoverEvent": { "action": "show_entity", "value": "Skepter" } }, { "text": " and he created the " }, { "text": "CommandAPI", "underlined": true, "clickEvent": { "action": "open_url", "value": "https://github.com/JorelAli/CommandAPI" } }] ``` ```json ["[\"\",{\"text\":\"Once upon a time, there was a guy call \"},{\"text\":\"Skepter\",\"color\":\"light_purple\",\"hoverEvent\":{\"action\":\"show_entity\",\"value\":\"Skepter\"}},{\"text\":\" and he created the \"},{\"text\":\"CommandAPI\",\"underlined\":true,\"clickEvent\":{\"action\":\"open_url\",\"value\":\"https://github.com/JorelAli/CommandAPI\"}}]"] ``` -------------------------------- ### Register Command with Short and Full Description Source: https://docs.commandapi.dev/create-commands/help Use `withShortDescription()` and `withFullDescription()` to set distinct help messages for commands. The short description appears in help lists, and the full description provides more detail. ```java new CommandAPICommand("mycmd") .withShortDescription("Says hi") .withFullDescription("Broadcasts hi to everyone on the server") .executes((sender, args) -> { Bukkit.broadcastMessage("Hi!"); }) .register(); ``` -------------------------------- ### Particle Examples with Data Source: https://docs.commandapi.dev/create-commands/arguments/types/misc/particle-arguments?from=9.4.2 Examples of commands that spawn particles with specific data, such as dust color transitions and block markers. ```mccmd /showparticle minecraft:dust_color_transition 0 0 0 20 1 0 0 ``` ```mccmd /showparticle minecraft:block_marker diamond_block ``` ```mccmd /showparticle minecraft:dust_color_transition{from_color:[0.0,0.0,0.0],scale:20.0,to_color:[1.0,0.0,0.0]} ``` ```mccmd /showparticle minecraft:block_marker{block_state:{Name:"diamond_block"}} ``` -------------------------------- ### Implement Asynchronous Config Suggestions Source: https://docs.commandapi.dev/create-commands/arguments/suggestions/async-suggestions?from=8.8.0 Example of using stringsAsync to fetch configuration keys asynchronously. ```java new CommandAPICommand("setconfig") .withArguments(new StringArgument("key") .replaceSuggestions(ArgumentSuggestions.stringsAsync(info -> CompletableFuture.supplyAsync(() -> plugin.getConfig().getKeys(false).toArray(new String[0]) ) )) ) .withArguments(new TextArgument("value")) .executes((sender, args) -> { String key = (String) args.get("key"); String value = (String) args.get("value"); plugin.getConfig().set(key, value); }) .register(); ``` -------------------------------- ### Example coordinate inputs and outputs Source: https://docs.commandapi.dev/create-commands/arguments/types/position/location-arguments?from=9.6.1 Demonstrates how integer and non-integer coordinate inputs are processed based on centering configuration. ```text 10 20 30 ``` ```text 10.5 20 30.5 ``` ```text 10.2 20.2 30.2 ``` ```text 10.2 20.2 30.2 ``` ```text 10 20 30 ``` ```text 10 20 30 ``` -------------------------------- ### Example: Accessing Command Arguments by Node Name and Index Source: https://docs.commandapi.dev/create-commands/arguments/command-arguments?from=9.4.2 Demonstrates how to access command arguments using both node names and indices, including default values and optional arguments. ```java new CommandAPICommand("mycommand") .withArguments(new StringArgument("name")) .withArguments(new IntegerArgument("amount")) .withOptionalArguments(new EntitySelectorArgument.OnePlayer("player")) .withOptionalArguments(new EntitySelectorArgument.OnePlayer("target")) .withOptionalArguments(new GreedyStringArgument("message")) .executesPlayer((player, args) -> { String name = (String) args.get(0); // Access arguments by index int amount = (int) args.get("amount"); // Access arguments by node name Player p = (Player) args.getOrDefault("player", player); // Access arguments using the getOrDefault(String, Object) method Player target = (Player) args.getOrDefault("target", () -> player); // Access arguments using the getOrDefault(String, Supplier) method String message = (String) args.getOptional("message").orElse("Hello!"); // Access arguments using the getOptional(String) method // Do whatever with these values }) .register(); ``` -------------------------------- ### Example Command Usage (Customized) Source: https://docs.commandapi.dev/create-commands/help?from=9.3.0 Shows the generated command usage after applying `withUsage()`. ```yaml Usage: - /command - /command - /command - /command - /command - /command - /command ``` ```yaml Usage: - /command
- /command ``` -------------------------------- ### Setting up CommandAPI in a plugin Source: https://docs.commandapi.dev/dev-setup/shading?from=9.4.2 Initializes the CommandAPI using platform-specific configurations. Requires placement within the plugin's lifecycle methods. ```java class MyPlugin extends JavaPlugin { @Override public void onLoad() { CommandAPI.onLoad(new CommandAPIPaperConfig(this).verboseOutput(true)); // Load with verbose output new CommandAPICommand("ping") .executes((sender, args) -> { sender.sendMessage("pong!"); }) .register(); } @Override public void onEnable() { CommandAPI.onEnable(); // Register commands, listeners etc. } @Override public void onDisable() { CommandAPI.onDisable(); } } ``` ```java class MyPlugin extends JavaPlugin { @Override public void onLoad() { CommandAPI.onLoad(new CommandAPISpigotConfig(this).verboseOutput(true)); // Load with verbose output new CommandAPICommand("ping") .executes((sender, args) -> { sender.sendMessage("pong!"); }) .register(); } @Override public void onEnable() { CommandAPI.onEnable(); // Register commands, listeners etc. } @Override public void onDisable() { CommandAPI.onDisable(); } } ``` -------------------------------- ### NBTCompoundArgument Usage Example Source: https://docs.commandapi.dev/create-commands/arguments/types/nbt-arguments?from=9.3.0 Example demonstrating how to use the `NBTCompoundArgument` after hooking into an NBT API. The type of the NBT compound implementation must be declared. ```APIDOC ## NBTCompoundArgument Usage Example ### Description Example demonstrating how to use the `NBTCompoundArgument` after hooking into an NBT API. The type of the NBT compound implementation must be declared in angle brackets. ### Method `new CommandAPICommand("award")` ### Endpoint Not applicable (this is a command registration example) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java new CommandAPICommand("award") .withArguments(new NBTCompoundArgument("nbt")) .executes((sender, args) -> { NBTContainer nbt = (NBTContainer) args.get("nbt"); // Do something with "nbt" here... }) .register(); ``` ### Response #### Success Response (200) None (this is a command execution example) #### Response Example None ``` -------------------------------- ### Example: Accessing Arguments Source: https://docs.commandapi.dev/create-commands/arguments/command-arguments?from=9.3.0 Demonstrates how to access command arguments using both node names and indices in a practical scenario. ```APIDOC ## Example - Access Arguments by Node Name and Index Consider a command `/mycommand` with the following structure: ```mccmd /mycommand /mycommand /mycommand /mycommand ``` Implementation example: ```java new CommandAPICommand("mycommand") .withArguments(new StringArgument("name")) .withArguments(new IntegerArgument("amount")) .withOptionalArguments(new EntitySelectorArgument.OnePlayer("player")) .withOptionalArguments(new EntitySelectorArgument.OnePlayer("target")) .withOptionalArguments(new GreedyStringArgument("message")) .executesPlayer((player, args) -> { String name = (String) args.get(0); // Access by index int amount = (int) args.get("amount"); // Access by node name Player p = (Player) args.getOrDefault("player", player); // Access using getOrDefault(String, Object) Player target = (Player) args.getOrDefault("target", () -> player); // Access using getOrDefault(String, Supplier) String message = (String) args.getOptional("message").orElse("Hello!"); // Access using getOptional(String) // Command logic here }) .register(); ``` ``` -------------------------------- ### Change Player Level Command Example Source: https://docs.commandapi.dev/create-commands/arguments/types/misc/mathoperation-arguments?from=9.3.0 An example of how to use the MathOperationArgument to create a command that modifies a player's level using various arithmetic operations. ```APIDOC ## POST /changelevel ### Description Allows modification of a player's level using specified arithmetic operations. ### Method POST ### Endpoint `/changelevel` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Command Structure `mccmd`/changelevel `` `` `` ### Arguments - **player** (EntitySelectorArgument.OnePlayer) - Required - The player whose level will be changed. - **operation** (MathOperationArgument) - Required - The arithmetic operation to perform. - **value** (IntegerArgument) - Required - The value to be used in the operation. ### Request Example (Java) ```java new CommandAPICommand("changelevel") .withArguments(new EntitySelectorArgument.OnePlayer("player")) .withArguments(new MathOperationArgument("operation")) .withArguments(new IntegerArgument("value")) .executes((sender, args) -> { Player target = (Player) args.get("player"); MathOperation op = (MathOperation) args.get("operation"); int value = (int) args.get("value"); target.setLevel(op.apply(target.getLevel(), value)); }) .register(); ``` ### Usage Examples - Set player 'Notch' to level 10: `mccmd`/changelevel Notch = 10 - Double player 'Notch's' level: `mccmd`/changelevel Notch *= 2 - Set player 'Notch's' level to 20, or keep current level if higher: `mccmd`/changelevel Notch > 20 ``` -------------------------------- ### Set Player Level to Max Example Source: https://docs.commandapi.dev/create-commands/arguments/types/misc/mathoperation-arguments?from=9.6.1 Example command to set a player's level to a specific value, or keep their current level if it's higher. ```minecraft /changelevel Notch > 20 ``` -------------------------------- ### Set Full Description for Command Help Source: https://docs.commandapi.dev/create-commands/help Use the `withFullDescription()` method to set the detailed explanation of a command, displayed when a user requests help for that specific command. ```java CommandAPICommand withFullDescription(String description); ``` -------------------------------- ### Brigadier SuggestionsBuilder Example Source: https://docs.commandapi.dev/9.3.0?from=11.2.0 An example demonstrating the use of Brigadier's `SuggestionsBuilder` for providing argument suggestions within the CommandAPI. This allows for dynamic suggestion lists. ```java builder.suggest("option1").suggest("option2"); ``` -------------------------------- ### Add help documentation with @Help Source: https://docs.commandapi.dev/annotations/annotations Provide descriptions for commands, supporting both simple strings and detailed objects. ```java @Command("teleport") @Help("Teleports yourself to another location") public class TeleportCommand { ``` ```java @Command("teleport") @Help(value = "Teleports yourself to another location", shortDescription = "TP to a location") public class TeleportCommand { ``` -------------------------------- ### Example: Load Test CommandAPI with Paper Settings Source: https://docs.commandapi.dev/test/load-mock-commandapi To change, for example, the missing-executor-implementation message while running tests, you can use the method CommandAPIPaperConfig#missingExecutorImplementationMessage when the configureSettings callback is run. ```java @BeforeEach public void setUp() { // Set up MockBukkit server ServerMock server = MockBukkit.mock(); // Load the CommandAPI plugin MockCommandAPIPlugin.load(config -> config .missingExecutorImplementationMessage("This command cannot be run by %S") ); // Load our plugin MockBukkit.load(Main.class); } @org.junit.jupiter.api.AfterEach public void tearDown() { // Reset for a clean slate next test MockBukkit.unmock(); } ``` -------------------------------- ### POST /runfunction Source: https://docs.commandapi.dev/create-commands/functions-and-tags/function-arguments?from=9.3.0 This example demonstrates how to implement Minecraft's /function command using CommandAPI. It allows executing a specified function or a tag containing multiple functions. ```APIDOC ## POST /runfunction ### Description Executes a Minecraft function or a tag. If a function is provided, it runs that single function. If a tag is provided, it executes all functions declared within that tag. ### Method POST ### Endpoint /runfunction ### Parameters #### Request Body - **function** (FunctionArgument) - Required - Represents the function or tag to be executed. ### Request Example ```json { "function": "my_namespace:my_function" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates successful execution. #### Response Example ```json { "status": "success" } ``` ### Java Implementation Example ```java new CommandAPICommand("runfunction") .withArguments(new FunctionArgument("function")) .executes((sender, args) -> { FunctionWrapper[] functions = (FunctionWrapper[]) args.get("function"); // Run all functions in our FunctionWrapper[] for (FunctionWrapper function : functions) { function.run(); } }) .register(); ``` ``` -------------------------------- ### Basic config.yml for command conversion Source: https://docs.commandapi.dev/user-setup/command-conversion/entity-selectors?from=9.6.1 Initial configuration to enable conversion for the Essentials /ext command. ```yaml verbose-outputs: false create-dispatcher-json: false plugins-to-convert: - Essentials: - ext ``` -------------------------------- ### Example: Failing Command for Invalid Input Source: https://docs.commandapi.dev/create-commands/executors/handle-failures?from=8.8.0 This example demonstrates how to fail a command if the player's input for a fruit is not in the predefined list. It uses `StringArgument` and `CommandAPI.failWithString()` for error handling. ```java // Array of fruit String[] fruit = new String[]{"banana", "apple", "orange"}; // Register the command new CommandAPICommand("getfruit") .withArguments(new StringArgument("item").replaceSuggestions(ArgumentSuggestions.strings(fruit))) .executes((sender, args) -> { String inputFruit = (String) args.get("item"); if (Arrays.asList(fruit).contains(inputFruit)) { // Do something with inputFruit } else { // The sender's input is not in the list of fruit throw CommandAPI.failWithString("That fruit doesn't exist!"); } }) .register(); ``` -------------------------------- ### Define Command Help Methods Source: https://docs.commandapi.dev/create-commands/help?from=9.6.1 Methods for setting short and full descriptions for command help topics. ```java CommandAPICommand withShortDescription(String description); ``` ```java CommandAPICommand withFullDescription(String description); ``` ```java CommandAPICommand withHelp(String shortDescription, String fullDescription); ``` -------------------------------- ### Boolean Argument Example Source: https://docs.commandapi.dev/create-commands/arguments/types/primitive-arguments Example demonstrating the use of BooleanArgument to edit a configuration file. It shows how to register a command that accepts a string key and a boolean value, then updates the config accordingly. ```APIDOC ## /editconfig ### Description Allows editing of a configuration file using commands. Accepts a configuration key and a boolean value. ### Method POST (or equivalent command registration) ### Endpoint /editconfig ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config-key** (String) - Required - The key in the configuration file to modify. - **value** (Boolean) - Required - The new boolean value to set for the specified key. ### Request Example ```json { "config-key": "featureEnabled", "value": true } ``` ### Response #### Success Response (200) - **message** (String) - Confirmation that the configuration was updated. #### Response Example ```json { "message": "Configuration 'featureEnabled' updated to true." } ``` ### Code Example (Java) ```java // Load keys from a config file String[] configKeys = getConfig().getKeys(true).toArray(new String[0]); // Register our command new CommandAPICommand("editconfig") .withArguments(new TextArgument("config-key").replaceSuggestions(ArgumentSuggestions.strings(info -> configKeys))) .withArguments(new BooleanArgument("value")) .executes((sender, args) -> { // Update the config with the boolean argument getConfig().set((String) args.get("config-key"), (boolean) args.get("value")); }) .register(); ``` ``` -------------------------------- ### Edit Configuration with Boolean Argument Source: https://docs.commandapi.dev/create-commands/arguments/types/primitive-arguments?from=9.3.0 This example demonstrates how to create a command to edit configuration files, using a TextArgument for the key and a BooleanArgument for the value. It shows how to retrieve config keys and cast the boolean argument. ```java // Load keys from a config file String[] configKeys = getConfig().getKeys(true).toArray(new String[0]); // Register our command new CommandAPICommand("editconfig") .withArguments(new TextArgument("config-key").replaceSuggestions(ArgumentSuggestions.strings(info -> configKeys))) .withArguments(new BooleanArgument("value")) .executes((sender, args) -> { // Update the config with the boolean argument getConfig().set((String) args.get("config-key"), (boolean) args.get("value")); }) .register(); ``` -------------------------------- ### Spawn Pigs Command Example (Ambiguous) Source: https://docs.commandapi.dev/create-commands/registration?from=9.4.2 An example of a command that might cause a Java compilation error due to ambiguous method calls. This occurs when the compiler cannot infer the type of the lambda expression. ```java new CommandAPICommand("spawnpigs") .executesPlayer((player, args) -> { for(int i = 0; i < 10; i++) { player.getWorld().spawnEntity(player.getLocation(), (EntityType) args.get(0)); } }) .register(); ``` -------------------------------- ### Valid Command Examples Source: https://docs.commandapi.dev/create-commands/arguments/types/command-arguments Demonstrates valid command inputs resulting from the empty suggestion configuration. ```mccmd /give diamond /give minecraft:diamond ``` -------------------------------- ### Define a command syntax Source: https://docs.commandapi.dev/create-commands/requirements The command syntax for the repair example. ```mccmd /repair ```