### Party System Example - Initial Setup Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/requirements.md Initializes the party system by setting up the `partyMembers` map. This is a prerequisite for the subsequent command implementations. ```java Map partyMembers = new HashMap<>(); ``` ```kotlin val partyMembers = mutableMapOf() ``` -------------------------------- ### Command Examples (Pre-1.20.4) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/misc/particle-arguments.md Examples of commands to spawn particles with data, compatible with versions prior to 1.20.4. ```mccmd /showparticle minecraft:dust_color_transition 0 0 0 20 1 0 0 ``` ```mccmd /showparticle minecraft:block_marker diamond_block ``` -------------------------------- ### Example other-commands-to-convert Configuration Source: https://github.com/commandapi/docs/blob/master/docs/en/user-setup/config.md Provides an example of how to configure `other-commands-to-convert` to include commands like /set and mycommand for conversion. ```yaml other-commands-to-convert: - /set - mycommand ``` -------------------------------- ### Async Suggestions Example (Java) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/suggestions/async-suggestions.md An example of implementing asynchronous suggestions in Java by reading keys from a plugin's configuration file. ```java package createcommands.arguments.suggestions; import com.mojang.brigadier.arguments.StringArgumentType; import dev.jorel.commandapi.CommandAPI; import dev.jorel.commandapi.arguments.Argument; import dev.jorel.commandapi.arguments.ArgumentSuggestions; import dev.jorel.commandapi.arguments.LiteralArgument; import dev.jorel.commandapi.arguments.StringArgument; import dev.jorel.commandapi.executors.CommandArguments; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; public { public static void asyncSuggestionsExample(JavaPlugin plugin) { LiteralArgument setConfigCommand = CommandAPI.literal("setconfig") .then(CommandAPI.argument("key", new StringArgument()) .executes((sender, args) -> { String key = (String) args.get("key"); String value = (String) args.get("value"); plugin.getConfig().set(key, value); plugin.saveConfig(); sender.sendMessage("Set config key " + key + " to " + value); }) .then(CommandAPI.argument("value", new StringArgument()) .replaceSuggestions(ArgumentSuggestions.stringsAsync(info -> { File configFile = new File(plugin.getDataFolder(), "config.yml"); if (!configFile.exists()) { return CompletableFuture.completedFuture(new String[0]); } try { List keys = Files.readAllLines(configFile.toPath()).stream() .filter(line -> !line.trim().startsWith("#") && line.contains(":")) .map(line -> line.split(":")[0].trim()) .collect(Collectors.toList()); return CompletableFuture.completedFuture(keys.toArray(new String[0])); } catch (IOException e) { e.printStackTrace(); return CompletableFuture.completedFuture(new String[0]); } })) )); CommandAPI.register(setConfigCommand, plugin); } } ``` -------------------------------- ### Command Examples (Post-1.20.4) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/misc/particle-arguments.md Examples of commands to spawn particles with data, compatible with versions 1.20.4 and later, using the new data format. ```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"}} ``` -------------------------------- ### Async Suggestions Example (Kotlin) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/suggestions/async-suggestions.md An example of implementing asynchronous suggestions in Kotlin by reading keys from a plugin's configuration file. ```kotlin package createcommands.arguments.suggestions import dev.jorel.commandapi.CommandAPI import dev.jorel.commandapi.arguments.LiteralArgument import dev.jorel.commandapi.arguments.StringArgument import dev.jorel.commandapi.arguments.ArgumentSuggestions import dev.jorel.commandapi.executors.CommandArguments import org.bukkit.plugin.java.JavaPlugin import java.io.File import java.io.IOException import java.nio.file.Files import java.util.concurrent.CompletableFuture object AsyncSuggestions { fun asyncSuggestionsExample(plugin: JavaPlugin) { val setConfigCommand: LiteralArgument = CommandAPI.literal("setconfig") .then(CommandAPI.argument("key", StringArgument()) .executes { sender, args -> val key = args.get("key") as String val value = args.get("value") as String plugin.config.set(key, value) plugin.saveConfig() sender.sendMessage("Set config key $key to $value") } .then(CommandAPI.argument("value", StringArgument()) .replaceSuggestions(ArgumentSuggestions.stringsAsync { info -> val configFile = File(plugin.dataFolder, "config.yml") if (!configFile.exists()) { return@stringsAsync CompletableFuture.completedFuture(arrayOf()) } try { val keys = Files.readAllLines(configFile.toPath()) .filter { line -> !line.trim().startsWith("#") && line.contains(":") } .map { line -> line.split(":")[0].trim() } .toTypedArray() return@stringsAsync CompletableFuture.completedFuture(keys) } catch (e: IOException) { e.printStackTrace() return@stringsAsync CompletableFuture.completedFuture(arrayOf()) } })) )) CommandAPI.register(setConfigCommand, plugin) } } ``` -------------------------------- ### Shaded CommandAPI Setup (Paper) Source: https://context7.com/commandapi/docs/llms.txt Manual setup for CommandAPI when shading the library directly into your plugin jar. Call onLoad() and onEnable() in your main plugin class. ```java // Shaded setup – Paper: call in onLoad() and onEnable() public class MyPlugin extends JavaPlugin { @Override public void onLoad() { CommandAPI.onLoad(new CommandAPIPaperConfig(this, this) .verboseOutput(false) .silentLogs(false)); } @Override public void onEnable() { CommandAPI.onEnable(); // register commands here } @Override public void onDisable() { CommandAPI.onDisable(); } } ``` -------------------------------- ### Async Suggestions Example (Kotlin DSL) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/suggestions/async-suggestions.md An example of implementing asynchronous suggestions using Kotlin DSL, reading keys from a plugin's configuration file. ```kotlin package createcommands.arguments.suggestions import dev.jorel.commandapi.CommandAPI import dev.jorel.commandapi.arguments.LiteralArgument import dev.jorel.commandapi.arguments.StringArgument import dev.jorel.commandapi.arguments.ArgumentSuggestions import dev.jorel.commandapi.executors.CommandArguments import org.bukkit.plugin.java.JavaPlugin import java.io.File import java.io.IOException import java.nio.file.Files import java.util.concurrent.CompletableFuture object AsyncSuggestions { fun asyncSuggestionsExampleDSL(plugin: JavaPlugin) { CommandAPI.register("setconfig") { literal("setconfig") .then(argument("key", StringArgument()) .executes { sender, args -> val key = args.get("key") as String val value = args.get("value") as String plugin.config.set(key, value) plugin.saveConfig() sender.sendMessage("Set config key $key to $value") } .then(argument("value", StringArgument()) .replaceSuggestions(ArgumentSuggestions.stringsAsync { info -> val configFile = File(plugin.dataFolder, "config.yml") if (!configFile.exists()) { return@stringsAsync CompletableFuture.completedFuture(arrayOf()) } try { val keys = Files.readAllLines(configFile.toPath()) .filter { line -> !line.trim().startsWith("#") && line.contains(":") } .map { line -> line.split(":")[0].trim() } .toTypedArray() return@stringsAsync CompletableFuture.completedFuture(keys) } catch (e: IOException) { e.printStackTrace() return@stringsAsync CompletableFuture.completedFuture(arrayOf()) } })) ) } } } ``` -------------------------------- ### Example skip-sender-proxy Configuration Source: https://github.com/commandapi/docs/blob/master/docs/en/user-setup/config.md Provides an example of how to configure `skip-sender-proxy` to skip specific plugin senders like SkinsRestorer and MyPlugin. ```yaml skip-sender-proxy: - SkinsRestorer - MyPlugin ``` -------------------------------- ### Give Player ItemStack Example Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/misc/itemstack-arguments.md This example demonstrates how to create a command that gives a player an itemstack. The ItemStack returned by the argument will always have a size of 1. ```java package commands.arguments.types.misc; import dev.jorel.commandapi.CommandAPI; import dev.jorel.commandapi.arguments.ItemStackArgument; import dev.jorel.commandapi.bukkit.arguments.PlayerArgument; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; public class ItemStackArguments { // Example – Giving a player an itemstack public static void itemStackArgumentsExample() { CommandAPI.register("item", new ItemStackArgument("itemstack") .replaceSuggestions( (sender, input) -> CommandAPI.convertListToArray(new String[]{"minecraft:apple", "minecraft:banana"}) ), (sender, args) -> { ItemStack item = (ItemStack) args[0]; sender.sendMessage("You received " + item.getType().name() + " x" + item.getAmount()); }); } // Example – Giving a player an itemstack (using the PlayerArgument) public static void itemStackArgumentsExampleWithPlayer() { CommandAPI.register("giveitem", new PlayerArgument("player"), new ItemStackArgument("itemstack") .replaceSuggestions( (sender, input) -> CommandAPI.convertListToArray(new String[]{"minecraft:apple", "minecraft:banana"}) ), (sender, args) -> { Player player = (Player) args[0]; ItemStack item = (ItemStack) args[1]; player.getInventory().addItem(item); sender.sendMessage("Gave " + player.getName() + " " + item.getType().name() + " x" + item.getAmount()); }); } // Example – Giving a player an itemstack (using the PlayerArgument and Item ID) public static void itemStackArgumentsExampleWithPlayerAndItemID() { CommandAPI.register("giveitemid", new PlayerArgument("player"), new ItemStackArgument("itemstack") .withPrimitiveType(Material.class), (sender, args) -> { Player player = (Player) args[0]; ItemStack item = (ItemStack) args[1]; player.getInventory().addItem(item); sender.sendMessage("Gave " + player.getName() + " " + item.getType().name() + " x" + item.getAmount()); }); } } ``` -------------------------------- ### Set Block Data Example Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/misc/blockstate-arguments.md This example demonstrates how to set the block data for the block a player is looking at using a command. ```java public class BlockStateArguments { @Example public static void blockStateArgumentsExample(@CommandArg(BlockStateArgument.class) BlockState blockState) { // This is an example of how to use the BlockState argument. // You can get the block state from the argument and use it. // For example, you can set the block data of the block you are looking at: // blockState.setBlockData(Bukkit.createBlockData(Material.DISPENSER)); } } ``` ```kotlin class BlockStateArguments { @Example fun blockStateArgumentsExample(@CommandArg(BlockStateArgument::class) blockState: BlockState) { // This is an example of how to use the BlockState argument. // You can get the block state from the argument and use it. // For example, you can set the block data of the block you are looking at: // blockState.setBlockData(Bukkit.createBlockData(Material.DISPENSER)) } } ``` ```kotlin block("set") { // This is an example of how to use the BlockState argument. // You can get the block state from the argument and use it. // For example, you can set the block data of the block you are looking at: // blockState.setBlockData(Bukkit.createBlockData(Material.DISPENSER)) literal("block") { blockState("blockState") runs { context -> val blockState = context.get("blockState") as BlockState // ... } } } ``` -------------------------------- ### Install Dependencies Source: https://github.com/commandapi/docs/blob/master/README.md Installs project dependencies using Yarn. Run this before building or developing the documentation. ```bash yarn install ``` -------------------------------- ### Give Player ItemStack Example (Kotlin) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/misc/itemstack-arguments.md This Kotlin example demonstrates how to create a command that gives a player an itemstack. The ItemStack returned by the argument will always have a size of 1. ```kotlin package commands.arguments.types.misc import dev.jorel.commandapi.CommandAPI import dev.jorel.commandapi.arguments.ItemStackArgument import dev.jorel.commandapi.bukkit.arguments.PlayerArgument import org.bukkit.Material import org.bukkit.inventory.ItemStack object ItemStackArguments { // Example – Giving a player an itemstack @JvmStatic fun itemStackArgumentsExample() { CommandAPI.register("item", ItemStackArgument("itemstack") .replaceSuggestions { _, _ -> CommandAPI.convertListToArray(arrayOf("minecraft:apple", "minecraft:banana")) }, { sender, args -> val item = args[0] as ItemStack sender.sendMessage("You received ${item.type.name} x${item.amount}") }) } // Example – Giving a player an itemstack (using the PlayerArgument) @JvmStatic fun itemStackArgumentsExampleWithPlayer() { CommandAPI.register("giveitem", PlayerArgument("player"), ItemStackArgument("itemstack") .replaceSuggestions { _, _ -> CommandAPI.convertListToArray(arrayOf("minecraft:apple", "minecraft:banana")) }, { sender, args -> val player = args[0] as Player val item = args[1] as ItemStack player.inventory.addItem(item) sender.sendMessage("Gave ${player.name} ${item.type.name} x${item.amount}") }) } // Example – Giving a player an itemstack (using the PlayerArgument and Item ID) @JvmStatic fun itemStackArgumentsExampleWithPlayerAndItemID() { CommandAPI.register("giveitemid", PlayerArgument("player"), ItemStackArgument("itemstack") .withPrimitiveType(Material::class.java), { sender, args -> val player = args[0] as Player val item = args[1] as ItemStack player.inventory.addItem(item) sender.sendMessage("Gave ${player.name} ${item.type.name} x${item.amount}") }) } } ``` -------------------------------- ### Example /economy Command with Argument Permissions Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/permissions.md This example outlines the structure of an `/economy` command with associated permissions for different subcommands and arguments. It shows how to map command variations to specific permission nodes. ```mccmd /economy - shows your own balance | economy.self /economy - shows you another players balance | economy.other /economy give - gives the target a set amount of money | economy.admin.give /economy reset - resets the targets balance | economy.admin.reset ``` -------------------------------- ### Example: /rate Command Registration Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/optional-arguments.md This example demonstrates registering a `/rate` command with multiple optional and required arguments using `combineWith`. It shows how to implement different command syntaxes, including rating a topic, providing a rating and target, and sending an information message. ```java package createcommands.arguments; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.arguments.IntegerArgumentType; import dev.jorel.commandapi.CommandAPI; import dev.jorel.commandapi.CommandAPICommand; import dev.jorel.commandapi.arguments.EntitySelectorArgument; import dev.jorel.commandapi.arguments.OptionalArg; import dev.jorel.commandapi.arguments.StringArgument; import dev.jorel.commandapi.arguments.IntegerArgument; public class OptionalArguments { public static void argumentsAfterOptionalArgumentsExample() { // /rate CommandAPICommand rateCommand = new CommandAPICommand("rate") .executes((sender, args) -> { sender.sendMessage("This is a command to rate topics!"); }); // /rate // /rate rateCommand.withOptionalArguments( new StringArgument("topic").combineWith( new IntegerArgument("rating") ) ); rateCommand.register(); } } ``` ```kotlin package createcommands.arguments import dev.jorel.commandapi.CommandAPI import dev.jorel.commandapi.CommandAPICommand import dev.jorel.commandapi.arguments.EntitySelectorArgument import dev.jorel.commandapi.arguments.OptionalArg import dev.jorel.commandapi.arguments.StringArgument import dev.jorel.commandapi.arguments.IntegerArgument object OptionalArguments { fun argumentsAfterOptionalArgumentsExample() { // /rate val rateCommand = CommandAPICommand("rate") .executes { it.sender.sendMessage("This is a command to rate topics!") } // /rate // /rate rateCommand.withOptionalArguments( StringArgument("topic").combineWith( IntegerArgument("rating") ) ) rateCommand.register() } } ``` ```kotlin package createcommands.arguments import dev.jorel.commandapi.CommandAPI import dev.jorel.commandapi.CommandAPICommand import dev.jorel.commandapi.arguments.EntitySelectorArgument import dev.jorel.commandapi.arguments.OptionalArg import dev.jorel.commandapi.arguments.StringArgument import dev.jorel.commandapi.arguments.IntegerArgument object OptionalArguments { fun argumentsAfterOptionalArgumentsExampleDSL() { // /rate CommandAPICommand("rate") .executes { it.sender.sendMessage("This is a command to rate topics!") } .withOptionalArguments( StringArgument("topic").combineWith( IntegerArgument("rating") ) ) .register() } } ``` -------------------------------- ### Setup CommandAPI with Shading (Paper - Java) Source: https://github.com/commandapi/docs/blob/master/docs/en/dev-setup/shading.md Initialize the CommandAPI in your plugin's onEnable method. This setup is for the Paper platform using Java. ```java package devsetup; import com.}(commandapi.CommandAPI; import com.}(commandapi.CommandAPIConfig; import org.bukkit.plugin.java.JavaPlugin; public class Shading extends JavaPlugin { @Override public void onEnable() { // The CommandAPI is not loaded by default. You need to load it. CommandAPI.load(new CommandAPIConfig().silentLogs(true)); getLogger().info("CommandAPI loaded!"); } @Override public void onDisable() { // Unregister all commands when the plugin is disabled CommandAPI.unregister(true); getLogger().info("CommandAPI unloaded!"); } } ``` -------------------------------- ### Example Commands for /speed Source: https://github.com/commandapi/docs/blob/master/docs/en/user-setup/command-conversion/single-command-with-args.md These are examples of how the /speed command can be run with different arguments. ```mccmd /speed 5 ``` ```mccmd /speed 2 Notch ``` ```mccmd /speed fly 6 ``` ```mccmd /speed walk 3 Notch ``` -------------------------------- ### Setup CommandAPI with Shading (Paper - Kotlin) Source: https://github.com/commandapi/docs/blob/master/docs/en/dev-setup/shading.md Initialize the CommandAPI in your plugin's onEnable method. This setup is for the Paper platform using Kotlin. ```kotlin package devsetup import com.}(commandapi.CommandAPI import com.}(commandapi.CommandAPIConfig import org.bukkit.plugin.java.JavaPlugin class Shading : JavaPlugin() { override fun onEnable() { // The CommandAPI is not loaded by default. You need to load it. CommandAPI.load(CommandAPIConfig().silentLogs(true)) logger.info("CommandAPI loaded!") } override fun onDisable() { // Unregister all commands when the plugin is disabled CommandAPI.unregister(true) logger.info("CommandAPI unloaded!") } } ``` -------------------------------- ### Example: Registering a Warp Command Source: https://github.com/commandapi/docs/blob/master/docs/en/annotations/registration.md This example demonstrates how to register a `/warp` command defined using annotations. The registration should be done in your plugin's onLoad() method. ```java package com.example.commands; import dev.jorel.commandapi.CommandAPI; import org.bukkit.plugin.java.JavaPlugin; public final class Registration extends JavaPlugin { @Override public void onLoad() { CommandAPI.registerCommand(WarpCommand.class); } @Override public void onEnable() { // Plugin startup logic } @Override public void onDisable() { // Plugin shutdown logic } } ``` -------------------------------- ### Give Player ItemStack Example (Kotlin DSL) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/misc/itemstack-arguments.md This Kotlin DSL example demonstrates how to create a command that gives a player an itemstack. The ItemStack returned by the argument will always have a size of 1. ```kotlin package commands.arguments.types.misc import dev.jorel.commandapi.CommandAPI import dev.jorel.commandapi.arguments.ItemStackArgument import dev.jorel.commandapi.bukkit.arguments.PlayerArgument import org.bukkit.Material import org.bukkit.inventory.ItemStack fun itemStackArgumentsExampleDSL() { CommandAPI.register("itemdsl", ItemStackArgument("itemstack") .replaceSuggestions { _, _ -> CommandAPI.convertListToArray(arrayOf("minecraft:apple", "minecraft:banana")) }, { sender, args -> val item = args[0] as ItemStack sender.sendMessage("You received ${item.type.name} x${item.amount}") }) } // Example – Giving a player an itemstack (using the PlayerArgument) fun itemStackArgumentsExampleWithPlayerDSL() { CommandAPI.register("giveitemdsl", PlayerArgument("player"), ItemStackArgument("itemstack") .replaceSuggestions { _, _ -> CommandAPI.convertListToArray(arrayOf("minecraft:apple", "minecraft:banana")) }, { sender, args -> val player = args[0] as Player val item = args[1] as ItemStack player.inventory.addItem(item) sender.sendMessage("Gave ${player.name} ${item.type.name} x${item.amount}") }) } // Example – Giving a player an itemstack (using the PlayerArgument and Item ID) fun itemStackArgumentsExampleWithPlayerAndItemIDDSL() { CommandAPI.register("giveitemiddsl", PlayerArgument("player"), ItemStackArgument("itemstack") .withPrimitiveType(Material::class.java), { sender, args -> val player = args[0] as Player val item = args[1] as ItemStack player.inventory.addItem(item) sender.sendMessage("Gave ${player.name} ${item.type.name} x${item.amount}") }) } ``` -------------------------------- ### Constructing NativeProxyCommandSender Example Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/executors/native-sender.md This example shows how to manually construct a NativeProxyCommandSender object using the static 'from' method, useful for creating custom command execution logic similar to Minecraft's /execute command. ```java CommandAPI.register("customexecute", new LiteralArgumentBuilder() .withArguments(new StringArgument("command").greedy()) .executes((context, args) -> { NativeProxyCommandSender nativeSender = NativeProxyCommandSender.from( context.getSource(), // Caller context.getSource(), // Callee ((Player) context.getSource()).getLocation(), ((Player) context.getSource()).getWorld() ); CommandAPI.performCommand(nativeSender, (String) args[0]); return Command.SINGLE_SUCCESS; }) ).setUnregisterWhenFinished(false); ``` ```kotlin CommandAPI.register("customexecute", LiteralArgumentBuilder() .withArguments(StringArgument("command").greedy()) .executes { context, args -> val nativeSender = NativeProxyCommandSender.from( context.source, // Caller context.source, // Callee (context.sender as Player).location, (context.sender as Player).world ) CommandAPI.performCommand(nativeSender, args[0] as String) Command.SINGLE_SUCCESS } ).setUnregisterWhenFinished(false); ``` ```kotlin CommandAPI.register("customexecute") .withArguments(StringArgument("command").greedy()) .executes { context, args -> val nativeSender = NativeProxyCommandSender.from( context.source, // Caller context.source, // Callee (context.sender as Player).location, (context.sender as Player).world ) CommandAPI.performCommand(nativeSender, args[0] as String) Command.SINGLE_SUCCESS } .setUnregisterWhenFinished(false) ``` -------------------------------- ### Example: Editing config.yml with BooleanArgument Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/primitive-arguments.md This example demonstrates how to create a command that allows editing a config file, specifically using a BooleanArgument. It shows how to retrieve keys, register the command, and cast the BooleanArgument to a boolean value. ```Java public class PrimitiveArguments { @RegisterSender public static void register(CommandAPICommand command) { CommandAPICommand editConfig = new CommandAPICommand("editconfig") .withArguments(new TextArgument("config-key").replaceSuggestions(ArgumentSuggestions.strings(info -> { // Retrieve keys from config.yml return new String[0]; // Placeholder for actual key retrieval }))) .withArguments(new BooleanArgument("value")) .executes((sender, args) -> { String key = (String) args[0]; boolean value = (boolean) args[1]; // Cast to boolean // Update config.yml with the new value sender.sendMessage("Config key " + key + " updated to " + value); }); editConfig.register(); } } ``` -------------------------------- ### Kotlin DSL ChatComponent Argument Example for Book Creation Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/chat/spigot-chat-arguments.md Example demonstrating how to use ChatComponentArgument to create a book with custom pages using raw JSON text. This requires a Spigot server. ```kotlin literal("makebook") { player { chat { executes { val player = it.source as Player val rawJson = chat().getJsonString(it, "contents") val meta = (ItemStack(Material.WRITTEN_BOOK).itemMeta as? BookMeta) ?: return@executes meta.spigot().pages = chat().parse(it, "contents") meta.author = player.name val book = ItemStack(Material.WRITTEN_BOOK) book.itemMeta = meta player.inventory.addItem(book) player.sendMessage("Book created!") } } } }.register() ``` -------------------------------- ### Kotlin ChatComponent Argument Example for Book Creation Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/chat/spigot-chat-arguments.md Example demonstrating how to use ChatComponentArgument to create a book with custom pages using raw JSON text. This requires a Spigot server. ```kotlin literal("makebook") .then(player().then(chat().executes { val player = it.source as Player val rawJson = chat().getJsonString(it, "contents") val meta = (ItemStack(Material.WRITTEN_BOOK).itemMeta as? BookMeta) ?: return@executes meta.spigot().pages = chat().parse(it, "contents") meta.author = player.name val book = ItemStack(Material.WRITTEN_BOOK) book.itemMeta = meta player.inventory.addItem(book) player.sendMessage("Book created!") })) .register() ``` -------------------------------- ### Java ChatComponent Argument Example for Book Creation Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/chat/spigot-chat-arguments.md Example demonstrating how to use ChatComponentArgument to create a book with custom pages using raw JSON text. This requires a Spigot server. ```java new LiteralArgumentBuilder("makebook") .then(ArgumentType.player().then(ArgumentType.chat().executes(c -> { Player player = (Player) c.getSource(); String rawJson = ArgumentType.chat().getJsonString(c, "contents"); BookMeta meta = new ItemStack(Material.WRITTEN_BOOK).getItemMeta() instanceof BookMeta ? (BookMeta) new ItemStack(Material.WRITTEN_BOOK).getItemMeta() : null; meta.spigot().setPages(ArgumentType.chat().parse(c, "contents")); meta.setAuthor(player.getName()); ItemStack book = new ItemStack(Material.WRITTEN_BOOK); book.setItemMeta(meta); player.getInventory().addItem(book); player.sendMessage("Book created!"); }))) .register(); ``` -------------------------------- ### Command-Level Permissions Source: https://context7.com/commandapi/docs/llms.txt This example demonstrates how to apply a permission to an entire command. Only players with the 'command.god' permission can execute the /god command. ```APIDOC ## /god command with permission ### Description This command grants god mode to the player, making them invulnerable. It requires the 'command.god' permission. ### Method CommandAPICommand ### Endpoint /god ### Parameters None ### Request Example ```java new CommandAPICommand("god") .withPermission("command.god") .executesPlayer((player, args) -> { player.setInvulnerable(true); player.sendMessage("God mode enabled!"); }) .register(); ``` ### Response None ``` -------------------------------- ### Example: Editing config.yml with BooleanArgument (Kotlin) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/primitive-arguments.md This Kotlin example demonstrates how to create a command that allows editing a config file, specifically using a BooleanArgument. It shows how to retrieve keys, register the command, and cast the BooleanArgument to a boolean value. ```Kotlin class PrimitiveArguments { @RegisterSender fun register(command: CommandAPICommand) { val editConfig = CommandAPICommand("editconfig") .withArguments(TextArgument("config-key").replaceSuggestions(ArgumentSuggestions.strings { info -> // Retrieve keys from config.yml arrayOf() // Placeholder for actual key retrieval })) .withArguments(BooleanArgument("value")) .executes { val key = it.args[0] as String val value = it.args[1] as Boolean // Cast to boolean // Update config.yml with the new value it.sender.sendMessage("Config key $key updated to $value") } editConfig.register() } } ``` -------------------------------- ### Example: Gamemode Command with Multi Literals (Kotlin) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/literal/multiliteral-arguments.md This Kotlin example shows the implementation of the /gamemode command using multi literal arguments. The CommandAPI ensures that only the specified literals are valid inputs. ```kotlin literal("gamemode") .then(multiLiteralArgument("gamemode", "survival", "creative", "adventure", "spectator") .executes { sender, args -> // Code to execute when /gamemode is used 1 }) ``` -------------------------------- ### Example: Access Raw Arguments by Node Name and Index Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/command-arguments.md Demonstrates how to access raw command arguments using both node names and indices in Java and Kotlin. This example helps determine the entity selector used during command execution. ```java String getRawExample() { String entitySelector = args.getRaw("entities"); return "Entity selector used: " + entitySelector; } ``` ```kotlin fun getRawExample(): String { val entitySelector = args.getRaw("entities") return "Entity selector used: $entitySelector" } ``` -------------------------------- ### Assert Command Suggestions Starting At Index (List) Source: https://github.com/commandapi/docs/blob/master/docs/en/test/utils.md Verify command suggestions, optionally specifying a starting index in the command string where the suggestions are expected to apply. Suggestions are provided as a List. ```java void assertCommandSuggests(CommandSender sender, String command, int startingAt, List expectedSuggestions) ``` -------------------------------- ### Example: Editing config.yml with BooleanArgument (Kotlin DSL) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/primitive-arguments.md This Kotlin DSL example demonstrates how to create a command that allows editing a config file, specifically using a BooleanArgument. It shows how to retrieve keys, register the command, and cast the BooleanArgument to a boolean value. ```Kotlin command("editconfig") { val configKey = TextArgument("config-key").replaceSuggestions(ArgumentSuggestions.strings { info -> // Retrieve keys from config.yml arrayOf() // Placeholder for actual key retrieval }) val value = BooleanArgument("value") withArguments(configKey, value) executes { val key = it.args[0] as String val booleanValue = it.args[1] as Boolean // Cast to boolean // Update config.yml with the new value it.sender.sendMessage("Config key $key updated to $booleanValue") } }.register() ``` -------------------------------- ### Multi-give Command Example Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/list-arguments.md This example demonstrates a multi-give command using an IntegerArgument for amount and a ListArgument for materials. It shows how to configure the ListArgumentBuilder to accept a list of Material objects and map their names to lowercase strings, using a space as the default delimiter. ```java ListArgument materials = ListArgument.builder( Material.class, Material::name ).transform(Material::toLowerCase).build(); CommandAPI.register( "multigive", new IntegerArgument("amount", 1, 64), materials ).executes((sender, args) -> { int amount = (int) args[0]; List givenMaterials = (List) args[1]; for (Material material : givenMaterials) { // Give items to sender } sender.sendMessage(ChatColor.GREEN + "Gave " + amount + " of " + givenMaterials.size() + " materials!"); }); ``` ```kotlin val materials = ListArgument.builder( Material::class.java, Material::name ).transform { it.toLowerCase() }.build() CommandAPI.register( "multigive", IntegerArgument("amount", 1, 64), materials ) { sender, args -> val amount = args[0] as Int val givenMaterials = args[1] as List for (material in givenMaterials) { // Give items to sender } sender.sendMessage(ChatColor.GREEN.toString() + "Gave " + amount + " of " + givenMaterials.size + " materials!") } ``` ```kotlin commandAPI("multigive") { withArguments( integer("amount", 1, 64), list("materials") { // Example of providing a list of materials directly // This is not used in the example above, but shows the DSL capability // For the example above, the ListArgument is created separately and passed in } ) executes { val amount = it.args.getInt("amount") // Accessing the list argument would be similar to the Java/Kotlin examples // val givenMaterials = it.args.getList("materials") // ... rest of the logic } } ``` -------------------------------- ### Load CommandAPI on Spigot (Java) Source: https://github.com/commandapi/docs/blob/master/docs/en/dev-setup/shading.md Example of loading the CommandAPI on a Spigot server with all logging disabled. Requires a `JavaPlugin` instance. ```java CommandAPISpigotConfig.builder(this) .silentLogs(true) .build() .load(); ``` -------------------------------- ### View Documentation Locally Source: https://github.com/commandapi/docs/blob/master/README.md Starts a local development server to view documentation changes in real-time. Use this during development to preview your edits. ```bash yarn docs:dev ``` -------------------------------- ### MapArgumentBuilder Example Initialization Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/map-arguments.md Example of initializing a MapArgumentBuilder for a map with String keys and Integer values. ```java new MapArgumentBuilder ``` -------------------------------- ### Argument Casting Example (Kotlin) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/arguments.md Demonstrates how to cast arguments to their respective types in Kotlin. ```kotlin CommandAPICommand("test") .withArguments(StringArgument("string"), IntegerArgument("integer")) .executes { val stringArg: String = it.args[0] as String val integerArg: Int = it.args[1] as Int } .register() ``` -------------------------------- ### Load CommandAPI on Paper (Kotlin) Source: https://github.com/commandapi/docs/blob/master/docs/en/dev-setup/shading.md Example of loading the CommandAPI on a Paper server with all logging disabled. Requires a `LifecycleEventOwner`. ```kotlin CommandAPIPaperConfig.builder(this) .silentLogs(true) .build() .load() ``` -------------------------------- ### Load CommandAPI on Spigot (Kotlin) Source: https://github.com/commandapi/docs/blob/master/docs/en/dev-setup/shading.md Example of loading the CommandAPI on a Spigot server with all logging disabled. Requires a `JavaPlugin` instance. ```kotlin CommandAPISpigotConfig.builder(this) .silentLogs(true) .build() .load() ``` -------------------------------- ### Register Command with Short and Full Description (Java) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/help.md Use withShortDescription() and withFullDescription() to set the short and full descriptions for a command's help topic. The short description appears in help lists, and the full description is shown when viewing the command's help individually. ```java CommandAPICommand("mycmd") .withShortDescription("Says hi") .withFullDescription("Broadcasts hi to everyone on the server") .register(); ``` -------------------------------- ### Legacy Warp Command Example Source: https://github.com/commandapi/docs/blob/master/docs/en/annotations/intro.md Demonstrates creating a warp command using the regular CommandAPI registration system with StringArguments, suggestions, and subcommands. ```java // Legacy command registration example // The command: // /warp - Shows help // /warp - Teleports a player to // /warp create - Creates a new warp at the player's location new CommandAPICommand("warp") .withArguments(new GreedyStringArgument("warp").replaceSuggestions(ArgumentSuggestions.suggest(info -> { // Deferred suggestions return WarpManager.getWarps().toArray(new String[0]); }))) .executes((sender, args) -> { // Teleport player to warp WarpManager.teleportToWarp(sender, (String) args[0]); }) .withSubcommand(new CommandAPICommand("create") .withArguments(new StringArgument("name")) .executes((sender, args, context) -> { // Create new warp WarpManager.createWarp(sender, (String) args[0]); })) .register(); ``` -------------------------------- ### Map Argument Example (Kotlin DSL) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/map-arguments.md This Kotlin DSL example provides a concise way to define a Map Argument for commands. It uses a similar structure to the standard Kotlin example, specifying Player as the key type and String as the value type, along with custom delimiter and separator characters. ```kotlin mapArgument(PlayerArgument("player"), StringArgument("message")) .withDelimiter(':') .withSeparator(' ') ``` -------------------------------- ### Time Argument Example - Kotlin Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/misc/time-arguments.md This Kotlin example demonstrates how to use the TimeArgument to create a command that displays a title message to all players for a specified duration. ```kotlin package commands.arguments.types.misc import dev.jorel.commandapi.CommandAPI import dev.jorel.commandapi.arguments.IntegerArgument import dev.jorel.commandapi.arguments.LiteralArgument import dev.jorel.commandapi.arguments.TimeArgument import dev.jorel.commandapi.arguments.TextArgument import org.bukkit.entity.Player object TimeArguments { init { CommandAPI.register( LiteralArgument("bigmsg") .then(TimeArgument("duration") .then(TextArgument("message") .executes { sender, args -> val duration = args.get("duration") as Long val message = args.get("message") as String for (player in sender.server.onlinePlayers) { player.sendTitle(message, "", duration.toInt(), 20 * 5, duration.toInt()) } } ) ) ) } } ``` -------------------------------- ### Time Argument Example - Java Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/misc/time-arguments.md This Java example demonstrates how to use the TimeArgument to create a command that displays a title message to all players for a specified duration. ```java package commands.arguments.types.misc; import dev.jorel.commandapi.CommandAPI; import dev.jorel.commandapi.arguments.IntegerArgument; import dev.jorel.commandapi.arguments.LiteralArgument; import dev.jorel.commandapi.arguments.TimeArgument; import dev.jorel.commandapi.arguments.TextArgument; import org.bukkit.entity.Player; public class TimeArguments { static { CommandAPI.register( new LiteralArgument("bigmsg") .then(new TimeArgument("duration") .then(new TextArgument("message") .executes((sender, args) -> { long duration = (long) args.get("duration"); String message = (String) args.get("message"); for (Player player : sender.getServer().getOnlinePlayers()) { player.sendTitle(message, "", (int) duration, 20 * 5, (int) duration); } }) ) ) ); } } ``` -------------------------------- ### Example: Access Arguments by Node Name and Index (Java) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/command-arguments.md Demonstrates accessing command arguments by both node name and index in Java. ```java new CommandAPICommand("mycommand") .withArguments(new StringArgument("name"), new IntegerArgument("amount"), new EntitySelectorArgument("player"), new EntitySelectorArgument("target", EntitySelectorArgument.EntitySelector.MANY_ENTITIES), new GreedyStringArgument("message")) .executes((sender, args) -> { // Access by node name String name = (String) args.get("name"); int amount = (int) args.get("amount"); Collection players = (Collection) args.get("player"); Collection targets = (Collection) args.get("target"); String message = (String) args.get("message"); // Access by index String nameByIndex = (String) args.get(0); int amountByIndex = (int) args.get(1); Collection playersByIndex = (Collection) args.get(2); Collection targetsByIndex = (Collection) args.get(3); String messageByIndex = (String) args.get(4); // Access with default values String nameOrDefault = (String) args.getOrDefault("name", "DefaultName"); int amountOrDefault = (int) args.getOrDefault("amount", 0); // Access with optional Optional optionalName = args.getOptional("name"); Optional optionalNonExistent = args.getOptional("nonExistent"); }) .register(); ``` -------------------------------- ### Register Command with Combined Help (Kotlin) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/help.md Use the withHelp() method as a shorthand to set both the short and full descriptions for a command's help topic simultaneously. This is the recommended approach for setting command help. ```kotlin CommandAPICommand("mycmd") .withHelp("Says hi", "Broadcasts hi to everyone on the server") .register() ``` -------------------------------- ### Register Command with Combined Help (Java) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/help.md Use the withHelp() method as a shorthand to set both the short and full descriptions for a command's help topic simultaneously. This is the recommended approach for setting command help. ```java CommandAPICommand("mycmd") .withHelp("Says hi", "Broadcasts hi to everyone on the server") .register(); ``` -------------------------------- ### Kotlin ChatColor Argument Example Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/chat/spigot-chat-arguments.md Example demonstrating the usage of ChatColorArgument in Kotlin to change a player's name color. This requires a Spigot server. ```kotlin literal("namecolor") .then(chatColor().executes { val player = it.source as Player val color = ChatColor.valueOf(chatColor().getName()) player.setDisplayName(color.toString() + player.name) player.sendMessage("Your name color has been changed!") }) .register() ``` -------------------------------- ### Java ChatColor Argument Example Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/arguments/types/chat/spigot-chat-arguments.md Example demonstrating the usage of ChatColorArgument in Java to change a player's name color. This requires a Spigot server. ```java new LiteralArgumentBuilder("namecolor") .then(ArgumentType.chatColor().executes(c -> { Player player = (Player) c.getSource(); ChatColor color = ChatColor.valueOf(ArgumentType.chatColor().getName()); player.setDisplayName(color + player.getName()); player.sendMessage("Your name color has been changed!"); })) .register(); ``` -------------------------------- ### CommandAPICommand Builder Example Source: https://context7.com/commandapi/docs/llms.txt Demonstrates chaining multiple builder methods to configure a command, including arguments, aliases, permissions, requirements, help text, subcommands, various executor types, and registration. ```java new CommandAPICommand("spawnpigs") // Add arguments (chained or varargs) .withArguments(new EntitySelectorArgument.OnePlayer("target")) .withArguments(new IntegerArgument("count", 1, 100)) // Aliases .withAliases("spawnpig", "pigs") // Permission: OP, NONE, or a permission string .withPermission("myplugin.spawnpigs") // same as CommandPermission.fromString(...) .withPermission(CommandPermission.OP) // only OPs .withPermission(CommandPermission.NONE) // anyone // Dynamic requirement (predicate on the sender) .withRequirement(sender -> sender instanceof Player p && p.getLevel() >= 5) // Help text .withShortDescription("Spawns pigs near a player") .withFullDescription("Spawns the given number of pigs at the target player's location.") // OR combined: .withHelp("Spawns pigs near a player", "Spawns the given number of pigs at target location.") .withUsage("/spawnpigs ") // Subcommands (nested CommandAPICommand) .withSubcommand(new CommandAPICommand("clear") .executes((sender, args) -> { /* clear pigs */ })) // Executor variants (all accept (sender, args) -> {} OR info -> {}) .executes((sender, args) -> { /* any CommandSender */ }) .executesPlayer((player, args) -> { Player target = (Player) args.get("target"); int count = (int) args.get("count"); for (int i = 0; i < count; target.getWorld().spawnEntity(target.getLocation(), EntityType.PIG); }) .executesEntity((entity, args) -> { /* entity only */ }) .executesConsole((console, args) -> { /* console only */ }) .executesCommandBlock((block, args) -> { /* command block only */ }) .executesProxy((proxy, args) -> { /* proxied sender */ }) .executesNative((native_, args) -> { /* NativeProxyCommandSender */ }) // Registration variants .register() // default namespace ("commandapi" or plugin name if shaded) .register("myplugin") // explicit namespace // .register(this) // namespace = plugin.getName() ; ``` -------------------------------- ### Register Command with Combined Help (Kotlin DSL) Source: https://github.com/commandapi/docs/blob/master/docs/en/create-commands/help.md Use the withHelp() method as a shorthand to set both the short and full descriptions for a command's help topic simultaneously. This is the recommended approach for setting command help. ```kotlin commandAPICommand("mycmd") { withHelp("Says hi", "Broadcasts hi to everyone on the server") } ```