tutorial:commands
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revisionNext revisionBoth sides next revision | ||
tutorial:commands [2019/11/16 04:35] – liach | tutorial:commands [2023/11/18 10:59] – [Why does my code not compile] solidblock | ||
---|---|---|---|
Line 1: | Line 1: | ||
+ | Licensing: The code in this article is licensed under the " | ||
+ | |||
====== Creating Commands ====== | ====== Creating Commands ====== | ||
- | Creating commands can allow a mod developer to add functionality that a player | + | Creating commands can allow a mod developer to add functionality that can used through a command. This tutorial will teach you how to register commands, and the general |
- | This tutorial will teach you how to register commands, and the command structure of Brigadier | + | |
- | ===== Registering Commands ===== | + | Note: All code written here was written for 1.19.2. For old versions, some versions and mappings may differ. |
- | If you just want to see how to register commands you've come to the right place here. | + | ===== What is Brigadier? ===== |
- | Registering commands | + | Brigadier |
- | The '' | + | The source code for brigadier can be found here: https:// |
- | The dedicated flag if set to true will tell Fabric to only register the command on a '' | + | ===== The '' |
- | Below are a few examples | + | In Minecraft, '' |
- | <code java [enable_line_numbers=" | + | The single method in '' |
- | CommandRegistry.INSTANCE.register(false, | + | |
- | + | ||
- | CommandRegistry.INSTANCE.register(false, | + | |
- | TutorialCommand.register(dispatcher); | + | |
- | TutorialHelpCommand.register(dispatcher); | + | |
- | }); | + | |
- | + | ||
- | CommandRegistry.INSTANCE.register(true, dispatcher -> { // Or directly registering | + | |
- | dispatcher.register(LiteralArgumentBuilder.literal(" | + | |
- | }); | + | |
- | </ | + | |
- | ==== A very basic command ==== | + | Like other functional interfaces, it is usually used as a lambda or a method reference: |
- | Wait isn't this the exact same command from the Brigadier tutorial? Well yes it is but it is here to help explain the structure of a command. | + | <code java> |
- | + | Command< | |
- | <code java [enable_line_numbers=" | + | return |
- | // The root of the command. This must be a literal argument. | + | }; |
- | dispatcher.register(CommandManager.literal(" | + | |
- | // Then add an argument named bar that is an integer | + | |
- | .then(CommandManager.argument(" | + | |
- | // The command to be executed if the command " | + | |
- | .executes(ctx | + | |
- | System.out.println(" | + | |
- | // Return a result. -1 is failure, 0 is a pass and 1 is success. | + | |
- | return 1; | + | |
- | })) | + | |
- | | + | |
- | .executes(ctx -> { | + | |
- | System.out.println(" | + | |
- | | + | |
- | }) | + | |
- | ); | + | |
</ | </ | ||
- | The main process registers the command " | + | In vanilla Minecraft, they are usually used as method references, such as static methods named '' |
- | Since the root node must be literal, The sender must enter the exact same sequence of letters to execute the command, so " | + | |
- | ===== Brigadier Explained ===== | + | The integer can be considered the result of the command. Typically negative values mean a command has failed and will do nothing. A result of '' |
- | Brigadier starts with the '' | ||
- | The trunk of the tree is the CommandDispatcher. | ||
- | The register(LiteralArgumentBuilder) methods specify the beginning of branches with the following then methods specifying the shape of length of the branches. | ||
- | The executes blocks can be seen at the leaves of the tree where it ends and also supplies the outcome of the system. | ||
- | The execute blocks specify the command to be ran. As Brigadier' | + | ==== What can the ServerCommandSource do? ==== |
- | ==== CommandContexts ==== | + | A '' |
- | + | ||
- | When a command is ran, Brigadier provides a CommandContext to the command that is ran. | + | |
- | The CommandContext contains all arguments and other objects such as the inputted String and the '' | + | |
- | + | ||
- | ==== Arguments ==== | + | |
- | + | ||
- | The arguments in Brigadier both parse and error check any inputted arguments. | + | |
- | Minecraft creates some special arguments for it's own use such as the '' | + | |
- | + | ||
- | You could do the long method of typing '' | + | |
- | This also works for getting arguments, which shortens the already long '' | + | |
- | This also works for Minecraft' | + | |
- | + | ||
- | And your imports would look something like this: | + | |
- | <code java [enable_line_numbers=" | + | |
- | import static com.mojang.brigadier.arguments.StringArgumentType.getString; | + | |
- | import static com.mojang.brigadier.arguments.StringArgumentType.word; | + | |
- | import static net.minecraft.server.command.CommandManager.literal; | + | |
- | import static net.minecraft.server.command.CommandManager.argument; | + | |
- | import static net.minecraft.server.command.CommandManager.*; | + | |
- | </ | + | |
- | + | ||
- | Brigadier' | + | |
- | + | ||
- | Minecraft' | + | |
- | + | ||
- | ==== Suggestions ==== | + | |
- | + | ||
- | Suggestions can be provided to the client to recommend what to input into the command. | + | |
- | < | + | |
- | SUMMONABLE_ENTITIES | + | |
- | AVAILIBLE_SOUNDS | + | |
- | ALL_RECIPES | + | |
- | ASK_SERVER | + | |
- | </ | + | |
- | + | ||
- | Loot tables specify their own SuggestionProvider inside LootCommand for example. | + | |
- | + | ||
- | The example below is a dynamically changing SuggestionProvider that lists several words for a StringArgumentType | + | |
- | <code java [enable_line_numbers=" | + | |
- | public static SuggestionProvider< | + | |
- | return (ctx, builder) -> getSuggestionsBuilder(builder, | + | |
- | } | + | |
- | + | ||
- | private static CompletableFuture< | + | |
- | String remaining = builder.getRemaining().toLowerCase(Locale.ROOT); | + | |
- | + | ||
- | if(list.isEmpty()) { // If the list is empty then return no suggestions | + | |
- | return Suggestions.empty(); | + | |
- | } | + | |
- | + | ||
- | for (String str : list) { // Iterate through the supplied list | + | |
- | if (str.toLowerCase(Locale.ROOT).startsWith(remaining)) { | + | |
- | builder.suggest(str); | + | |
- | } | + | |
- | } | + | |
- | return builder.buildFuture(); | + | |
- | } | + | |
- | </ | + | |
- | + | ||
- | The SuggestionProvider is a FunctionalInterface | + | |
- | + | ||
- | Though remember these are suggestions. The inputted | + | |
- | + | ||
- | To use the suggestion you would append it right after the argument you want to recommend arguments for. This can be any argument and the normal client side exception popups will still work. Note this cannot be applied to literals. | + | |
- | + | ||
- | <code java [enable_line_numbers=" | + | |
- | argument(argumentName, word()) | + | |
- | .suggests(CompletionProviders.suggestedStrings()) | + | |
- | .then(/ | + | |
- | </ | + | |
- | + | ||
- | ==== Requires ==== | + | |
- | + | ||
- | Lets say you have a command you only want operators to be able to execute. This is where the '' | + | |
- | + | ||
- | For example this may look like the following: | + | |
- | + | ||
- | <code java [enable_line_numbers=" | + | |
- | dispatcher.register(literal(" | + | |
- | .requires(source -> source.hasPermissionLevel(4)) | + | |
- | .executes(ctx -> { | + | |
- | ctx.getSource().sendFeedback(new LiteralText(" | + | |
- | return 1; | + | |
- | }); | + | |
- | </ | + | |
- | + | ||
- | This command will only execute if the Source of the command is a level 4 operator at minimum. If the predicate returns false, then the command will not execute. Also this has the side effect of not showing this command | + | |
- | + | ||
- | ==== Exceptions ==== | + | |
- | + | ||
- | Brigadier supports command exceptions which can be used to end a command such as if an argument didn't parse properly | + | |
- | + | ||
- | All the exceptions from Brigadier are based on the CommandSyntaxException. The two main types of exceptions Brigadier provides are Dynamic and Simple exception types, of which you must '' | + | |
- | Below is a coin flip command to show an example of exceptions in use. | + | |
- | + | ||
- | <code java [enable_line_numbers=" | + | |
- | dispatcher.register(CommandManager.literal(" | + | |
- | .executes(ctx -> { | + | |
- | Random random = new Random(); | + | |
- | + | ||
- | if(random.nextBoolean()) { // If heads succeed. | + | |
- | ctx.getSource().sendMessage(new TranslateableText(" | + | |
- | return Command.SINGLE_SUCCESS; | + | |
- | } | + | |
- | throw new SimpleCommandExceptionType(new TranslateableText(" | + | |
- | })); | + | |
- | </ | + | |
- | + | ||
- | Though you are not just limited to a single type of exception as Brigadier also supplies Dynamic exceptions. | + | |
- | + | ||
- | <code java [enable_line_numbers=" | + | |
- | DynamicCommandExceptionType used_name = new DynamicCommandExceptionType(name -> { | + | |
- | return new LiteralText(" | + | |
- | }); | + | |
- | </ | + | |
- | + | ||
- | There are more Dynamic exception types which each take a different amount of arguments into account ('' | + | |
- | You should remember that the Dynamic exceptions takes an object as an argument so you may have to cast the argument for your use. | + | |
- | + | ||
- | ==== Redirects (Aliases) ==== | + | |
- | + | ||
- | Redirects are Brigadier' | + | |
- | + | ||
- | <code java [enable_line_numbers=" | + | |
- | public static void register(CommandDispatcher< | + | |
- | LiteralCommandNode node = registerMain(dispatcher); | + | |
- | dispatcher.register(literal(" | + | |
- | .redirect(node)); | + | |
- | dispatcher.register(literal(" | + | |
- | .redirect(node)); | + | |
- | } | + | |
- | + | ||
- | public static LiteralCommandNode registerMain(CommandDispatcher< | + | |
- | return dispatcher.register(literal(" | + | |
- | .then(argument(" | + | |
- | .then(argument(" | + | |
- | .executes(ctx -> { | + | |
- | return execute(ctx.getSource(), | + | |
- | })))); | + | |
- | } | + | |
- | </ | + | |
- | + | ||
- | The redirect registers a branch into the command tree, where the dispatcher is told when executing a redirected command to instead look on a different branch for more arguments and executes blocks. The literal argument that the redirect is placed on will also rename first literal on the targeted branch in the new command. | + | |
- | + | ||
- | Redirects do not work in shortened aliases such as ''/ | + | |
- | + | ||
- | ==== Redirects (Chainable Commands) ==== | + | |
- | Commands such as ''/ | + | |
- | + | ||
- | <code java [enable_line_numbers=" | + | |
- | LiteralCommandNode< | + | |
- | LiteralCommandNode< | + | |
- | // You can register under the same literal more than once, it will just register new parts of the branch as shown below if you register a duplicate branch an error will popup in console warning of conflicting commands but one will still work. | + | |
- | .then(literal(" | + | |
- | .then(literal(" | + | |
- | .redirect(root)) // Return to root for chaining | + | |
- | .then(literal(" | + | |
- | .redirect(root))) // Return to root for chaining | + | |
- | .then(literal(" | + | |
- | .executes(ctx -> { | + | |
- | ctx.getSource().sendFeedback(new LiteralText(" | + | |
- | return Command.SINGLE_SUCCESS; | + | |
- | }))); | + | |
- | </ | + | |
- | The redirect can also modify the CommandSource. | + | |
- | + | ||
- | <code java [enable_line_numbers=" | + | |
- | .redirect(rootNode, | + | |
- | return ((ServerCommandSource) commandContext_1x.getSource()).withLookingAt(Vec3ArgumentType.getVec3(commandContext_1x, | + | |
- | }) | + | |
- | </ | + | |
- | + | ||
- | ===== ServerCommandSource ===== | + | |
- | + | ||
- | What if you wanted a command that the CommandSource must be an entity to execute? The ServerCommandSource provides this option with a couple of methods | + | |
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
- | ServerCommandSource source = ctx.getSource(); | ||
// Get the source. This will always work. | // Get the source. This will always work. | ||
+ | final ServerCommandSource source = ctx.getSource(); | ||
- | Entity sender = source.getEntity(); | + | // Unchecked, may be null if the sender was the console |
- | // Unchecked, may be null if the sender was the console. | + | final @Nullable Entity sender = source.getEntity(); |
- | Entity sender2 = source.getEntityOrThrow(); | + | // Will throw an exception |
- | // Will end the command | + | |
// The result of this could contain a player. Also will send feedback telling the sender of the command that they must be an entity. | // The result of this could contain a player. Also will send feedback telling the sender of the command that they must be an entity. | ||
// This method will require your methods to throw a CommandSyntaxException. | // This method will require your methods to throw a CommandSyntaxException. | ||
// The entity options in ServerCommandSource could return a CommandBlock entity, any living entity or a player. | // The entity options in ServerCommandSource could return a CommandBlock entity, any living entity or a player. | ||
+ | final @NotNull Entity sender2 = source.getEntityOrThrow(); | ||
- | ServerPlayerEntity player = source.getPlayer(); | + | // null if the executor |
- | // Will end the command | + | final @Nullable ServerPlayerEntity |
- | </ | + | |
- | The ServerCommandSource also provides other information about the sender of the command. | + | // Will throw an exception if the executor of the command was not explicitly a Player. |
+ | // Also will send feedback telling | ||
+ | // This method will require your methods to throw a CommandSyntaxException. | ||
+ | final @NotNull ServerPlayerEntity player = source.getPlayerOrThrow(); | ||
- | <code java [enable_line_numbers=" | + | // Gets the sender' |
- | source.getPosition(); | + | // This could be the location of the entity/ |
- | // Get' | + | final Vec3d position = source.getPosition(); |
- | source.getWorld(); | + | // Gets the world the sender is within. The console' |
- | // Get' | + | final ServerWorld world = source.getWorld(); |
- | source.getRotation(); | + | // Gets the sender' |
- | // Get' | + | final Vec2f rotation = source.getRotation(); |
- | source.getMinecraftServer(); | ||
// Access to the instance of the MinecraftServer this command was ran on. | // Access to the instance of the MinecraftServer this command was ran on. | ||
+ | final MinecraftServer server = source.getServer(); | ||
- | source.getName(); | + | // The name of the command source. This could be the name of the entity, player, |
- | // The name of the command source. This could be the name of the entity, player, the name of a CommandBlock that has been renamed before being placed down or in the case of the Console, " | + | // the name of a CommandBlock that has been renamed before being placed down, or in the case of the Console, " |
+ | final String name = source.getName(); | ||
- | source.hasPermissionLevel(int level); | + | // Returns true if the source of the command has a certain permission level. |
- | // Returns true if the source of the command has a certain permission level. This is based on the operator status of the sender. (On an integrated server, the player must have cheats enabled to execute these commands) | + | // This is based on the operator status of the sender. |
+ | // (On an integrated server, the player must have cheats enabled to execute these commands.) | ||
+ | final boolean b = source.hasPermissionLevel(int level); | ||
</ | </ | ||
- | ===== Some actual examples | + | ===== Register a basic command |
- | Just a few to show: | + | Commands are registered by registering in '' |
- | === Broadcast | + | The event should be registered in your mod's initializer. The callback has three parameters. The '' |
- | <code java [enable_line_numbers=" | + | To simplify the code, it is highly recommended to '' |
- | public | + | <code java> |
- | dispatcher.register(literal(" | + | import |
- | .requires(source -> source.hasPermissionLevel(2)) // Must be a game master to use the command. Command will not show up in tab completion or execute to non op's or any op that is permission level 1. | + | |
- | .then(argument(" | + | |
- | .then(argument(" | + | |
- | .executes(ctx -> broadcast(ctx.getSource(), | + | |
- | } | + | |
- | + | ||
- | public | + | |
- | Text text = new LiteralText(message).formatting(formatting); | + | |
- | + | ||
- | source.getMinecraftServer().getPlayerManager().broadcastChatMessage(text, | + | |
- | return Command.SINGLE_SUCCESS; // Success | + | |
- | } | + | |
</ | </ | ||
- | === / | + | In the mod initializer, |
- | First the basic code where we register | + | <code java [enable_line_numbers="true"]> |
+ | public class ExampleMod implements ModInitializer { | ||
+ | @Override | ||
+ | public void onInitialize() { | ||
+ | CommandRegistrationCallback.EVENT.register((dispatcher, | ||
+ | .executes(context -> { | ||
+ | // For versions below 1.19, replace " | ||
+ | context.getSource().sendFeedback(Text.literal(" | ||
+ | // For versions since 1.20, please use the following, | ||
+ | context.getSource().sendFeedback(() -> Text.literal(" | ||
- | <code java [enable_line_numbers=" | + | |
- | public static LiteralCommandNode register(CommandDispatcher< | + | |
- | | + | } |
- | .executes(ctx -> giveDiamond(ctx))); | + | |
} | } | ||
</ | </ | ||
- | Then since we only want to give to players, we check if the CommandSource | + | **Please ensure you import |
- | <code java [enable_line_numbers=" | + | In the '' |
- | public static int giveDiamond(CommandContext< | + | |
- | ServerCommandSource source = ctx.getSource(); | + | |
- | + | ||
- | PlayerEntity self = source.getPlayer(); | + | |
- | </code> | + | |
- | Then we add to the player's inventory, with a check to see if the inventory is full: | + | If the command fails, instead of calling '' |
- | <code java [enable_line_numbers=" | + | To execute this command, you must type ''/ |
- | if(!player.inventory.insertStack(new ItemStack(Items.DIAMOND))){ | + | |
- | throw new SimpleCommandExceptionType(new TranslateableText(" | + | |
- | } | + | |
- | return 1; | + | |
- | } | + | |
- | </code> | + | |
- | === Antioch | + | ===== Registration environment ===== |
- | ...lobbest thou thy Holy Hand Grenade of Antioch towards thy foe. | + | If desired, you can also make sure a command is only registered under some specific circumstances, |
- | who being naughty in My sight, shall snuff it. | + | |
- | Aside from the joke this command summons a primed TNT to a specified location or the location of the sender' | + | < |
+ | public class ExampleCommandMod implements ModInitializer { | ||
+ | @Override | ||
+ | public void onInitialize() { | ||
+ | CommandRegistrationCallback.EVENT.register((dispatcher, | ||
+ | if (environment.field_25423) { | ||
+ | ...; | ||
+ | } | ||
+ | }); | ||
+ | } | ||
+ | } | ||
+ | </ | ||
- | First create an entry into the CommandDispatcher that takes a literal of antioch with an optional | + | ===== Static Imports ===== |
+ | In the example above, the use of static imports is used for code simplifying. For a literal | ||
+ | Below is an example of some static imports: | ||
<code java [enable_line_numbers=" | <code java [enable_line_numbers=" | ||
- | public static void register(CommandDispatcher< | + | // getString(ctx, "string") |
- | dispatcher.register(literal("antioch") | + | import static com.mojang.brigadier.arguments.StringArgumentType.getString; |
- | .then(required(" | + | // word() |
- | | + | import static com.mojang.brigadier.arguments.StringArgumentType.word; |
- | .executes(ctx -> antioch(ctx.getSource(), null))); | + | // literal("foo") |
- | } | + | import static net.minecraft.server.command.CommandManager.literal; |
+ | // argument(" | ||
+ | import static net.minecraft.server.command.CommandManager.argument; | ||
+ | // Import everything in the CommandManager | ||
+ | import static net.minecraft.server.command.CommandManager.*; | ||
</ | </ | ||
- | Then the creation | + | Note: Please be sure you use the '' |
- | <code java [enable_line_numbers=" | + | Brigadier' |
- | public static int antioch(ServerCommandSource source, BlockPos blockPos) throws CommandSyntaxException { | + | |
- | + | ||
- | if(blockPos==null) { | + | |
- | blockPos = LocationUtil.calculateCursorOrThrow(source, | + | |
- | } | + | |
- | + | ||
- | TntEntity tnt = new TntEntity(source.getWorld(), | + | |
- | + | ||
- | source.getMinecraftServer().getPlayerManager().broadcastChatMessage(new LiteralText(" | + | |
- | source.getMinecraftServer().getPlayerManager().broadcastChatMessage(new LiteralText(" | + | |
- | source.getWorld().spawnEntity(tnt); | + | |
- | return 1; | + | |
- | } | + | |
- | </ | + | |
- | === Finding Biomes via Command === | + | Minecraft' |
- | This example shows examples of redirects, exceptions, suggestions and a tiny bit of text. Note this command when used works but can take a bit of time to work similarly to ''/ | + | ===== Add Requirements |
- | <code java [enable_line_numbers=" | + | |
- | public class CommandLocateBiome { | + | |
- | // First make method to register | + | |
- | public static void register(CommandDispatcher< | + | |
- | LiteralCommandNode< | + | |
- | .then(argument(" | + | |
- | .then(argument(" | + | |
- | .executes(ctx -> execute(ctx.getSource(), | + | |
- | .executes(ctx -> execute(ctx.getSource(), | + | |
- | // Register redirect | + | |
- | dispatcher.register(literal(" | + | |
- | .redirect(basenode)); | + | |
- | } | + | |
- | // Beginning of the method | + | |
- | private static int execute(ServerCommandSource source, Identifier biomeId, int range) throws CommandSyntaxException { | + | |
- | Biome biome = Registry.BIOME.get(biomeId); | + | |
- | + | ||
- | if(biome | + | |
- | throw new SimpleCommandExceptionType(new TranslatableText(" | + | |
- | } | + | |
- | + | ||
- | List< | + | |
- | bio.add(biome); | + | |
- | + | ||
- | ServerWorld world = source.getWorld(); | + | |
- | + | ||
- | BiomeSource bsource | + | |
- | + | ||
- | BlockPos loc = new BlockPos(source.getPosition()); | + | |
- | // Now here is the heaviest part of the method. | + | |
- | BlockPos pos = bsource.locateBiome(loc.getX(), | + | |
- | + | ||
- | // Since this method can return null if it failed to find a biome | + | |
- | if(pos == null) { | + | |
- | throw new SimpleCommandExceptionType(new TranslatableText(" | + | |
- | } | + | |
- | + | ||
- | int distance = MathHelper.floor(getDistance(loc.getX(), | + | |
- | // Popup text that can suggest commands. This is the exact same system that /locate uses. | + | |
- | Text teleportButtonPopup = Texts.bracketed(new TranslatableText(" | + | |
- | style_1x.setColor(Formatting.GREEN).setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, | + | |
- | }); | + | |
- | + | ||
- | source.sendFeedback(new TranslatableText(" | + | |
- | return 1; | + | Let's say you have a command that you only want operators to be able to execute. This is where the '' |
- | } | + | |
- | // Just a normal old 2d distance | + | |
- | private static float getDistance(int int_1, int int_2, int int_3, int int_4) { | + | |
- | int int_5 = int_3 - int_1; | + | |
- | int int_6 = int_4 - int_2; | + | |
- | return MathHelper.sqrt((float) (int_5 * int_5 + int_6 * int_6)); | + | For example this may look like the following: |
- | } | + | |
- | + | ||
- | | + | |
- | public static class BiomeCompletionProvider { | + | <code java [enable_line_numbers=" |
- | // This provides suggestions of what biomes can be selected. Since this uses the registry, mods that add new biomes will work without modification. | + | dispatcher.register(literal("foo") |
- | public static final SuggestionProvider<ServerCommandSource> BIOMES = SuggestionProviders.register(new Identifier("biomes"), (ctx, builder) | + | .requires(source |
- | Registry.BIOME.getIds().stream().forEach(identifier | + | |
- | return | + | ctx.getSource().sendFeedback(() -> Text.literal("You are an operator" |
- | }); | + | return |
- | + | }); | |
- | } | + | |
</ | </ | ||
- | ===== Custom Arguments ===== | + | This command will only execute if the source of the command is a level 2 operator at minimum, // |
- | Brigadier has support for custom argument types and this section goes into showing how to create | + | To create |
- | Warning: Custom arguments require client mod installation to be registered correctly! If you are making a server plugin, consider using existing argument type and a custom suggestions provider instead. | + | ===== Arguments ===== |
- | For this example we will create a UUIDArgumentType. | + | Arguments are used in most of commands. Sometimes they can be optional, which means if you do not provide that argument, the command |
- | First create a class which extends '' | + | In this case, we add one integer argument, and calculate |
<code java> | <code java> | ||
- | public class UUIDArgumentType implements ArgumentType< | + | dispatcher.register(literal(" |
+ | .then(argument(" | ||
+ | .executes(context -> { | ||
+ | final int value = IntegerArgumentType.getInteger(context, | ||
+ | final int result = value * value; | ||
+ | context.getSource().sendFeedback(() -> Text.literal(" | ||
+ | return result; | ||
+ | }))); | ||
</ | </ | ||
- | ArgumentType requires you to implement | + | In this case, after the word '' |
- | <code java> | + | |
- | @Override | + | |
- | public UUID parse(StringReader reader) throws CommandSyntaxException { | + | |
- | </code> | + | |
- | This method is where all of your parsing will occur. Either this method will return the object based on the arguments provided in the command line or throw a CommandSyntaxException | + | Note: for simplicity, '' |
- | + | ||
- | Next you will store the current position of the cursor, this is so you can substring out only the specific argument. This will always | + | |
+ | Then we add an optional second argument: | ||
<code java> | <code java> | ||
- | int argBeginning | + | dispatcher.register(literal(" |
- | if (!reader.canRead()) { | + | .then(argument(" |
- | | + | .executes(context -> { |
- | } | + | final int value = IntegerArgumentType.getInteger(context, " |
+ | final int result = value * value; | ||
+ | context.getSource().sendFeedback(() -> Text.literal(" | ||
+ | | ||
+ | }) | ||
+ | .then(argument(" | ||
+ | .executes(context -> { | ||
+ | final int value = IntegerArgumentType.getInteger(context, " | ||
+ | final int value2 = IntegerArgumentType.getInteger(context, | ||
+ | final int result = value * value2; | ||
+ | context.getSource().sendFeedback(() -> Text.literal(" | ||
+ | return result; | ||
+ | | ||
</ | </ | ||
- | Now we grab the entire argument. Depending on your argument type, you may have a different criteria | + | Now you can type one or two integers. If you give one integer, that integer will be self-multiplied. If you provide two integers, they will be multipled. You may find it unnecessary |
<code java> | <code java> | ||
- | while (reader.canRead() && reader.peek() != ' ') { // peek provides the character at the current cursor position. | + | public class ExampleMod implements ModInitializer { |
- | | + | @Override |
- | } | + | public void onInitialize() { |
- | </code> | + | CommandRegistrationCallback.EVENT.register((dispatcher, |
+ | | ||
+ | .executes(context -> executeMultiply(IntegerArgumentType.getInteger(context, | ||
+ | | ||
+ | | ||
+ | } | ||
- | Then we will ask the StringReader what the current position of the cursor is an substring our argument out of the command line. | + | private static int executeMultiply(int value, int value2, CommandContext<ServerCommandSource> context) |
- | + | | |
- | <code java> | + | |
- | + | return result; | |
- | Now finally we check if our argument is correct and parse the specific argument to our liking, and throwing an exception if the parsing fails. | + | } |
- | + | ||
- | <code java> | + | |
- | try { | + | |
- | | + | |
- | | + | |
- | } catch (Exception ex) { | + | |
- | // UUIDs can throw an exception when made by a string, so we catch the exception and repackage it into a CommandSyntaxException type. | + | |
- | // Create with context tells Brigadier to supply some context to tell the user where the command failed at. | + | |
- | // Though normal create method could be used. | + | |
- | throw new SimpleCommandExceptionType(new LiteralText(ex.getMessage())).createWithContext(reader); | + | |
} | } | ||
</ | </ | ||
+ | ===== A sub command ===== | ||
- | The ArgumentType is done, however your client will refuse the parse the argument and throw an error. To fix this we need to register | + | To add a sub command, you register the first literal node of the command |
- | Within your ModInitializer (Not only client or server) you will add this so the client can recognize the argument when the command | + | |
- | < | + | < |
- | ArgumentTypes.register(" | + | dispatcher.register(literal("foo")) |
- | // The argument should be what will create the ArgumentType. | + | |
</ | </ | ||
- | And here is the whole ArgumentType: | + | In order to have a sub command, one needs to append |
- | <file java UUIDArgumentType.java> | + | <code java [enable_line_numbers=" |
+ | dispatcher.register(literal(" | ||
+ | .then(literal(" | ||
+ | .executes(context -> { | ||
+ | // For versions below 1.19, use '' | ||
+ | // For versions below 1.20, use directly the '' | ||
+ | context.getSource().sendFeedback(() -> Text.literal(" | ||
- | import com.mojang.brigadier.StringReader; | + | return 1; |
- | import com.mojang.brigadier.arguments.ArgumentType; | + | }) |
- | import com.mojang.brigadier.context.CommandContext; | + | ) |
- | import com.mojang.brigadier.exceptions.CommandSyntaxException; | + | ); |
- | import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; | + | </ |
- | import net.minecraft.text.LiteralText; | + | |
- | import net.minecraft.util.SystemUtil; | + | |
- | import java.util.ArrayList; | + | Similar to arguments, sub command nodes can also be set optional. In the following cases, both ''/ |
- | import | + | < |
- | import java.util.UUID; | + | dispatcher.register(literal(" |
+ | .executes(context -> { | ||
+ | context.getSource().sendFeedback(() -> Text.literal(" | ||
+ | | ||
+ | }) | ||
+ | | ||
+ | | ||
+ | context.getSource().sendFeedback(() -> Text.literal(" | ||
+ | return 1; | ||
+ | }) | ||
+ | ) | ||
+ | ); | ||
+ | </ | ||
+ | ====== Advanced concepts ====== | ||
- | /** | + | Below are links to the articles about more complex concepts used in brigadier. |
- | * Represents an ArgumentType that will return a UUID. | + | |
- | */ | + | |
- | public class UUIDArgumentType implements ArgumentType< | + | |
- | // This method exists for convince and you could just initialize | + | |
- | public static UUIDArgumentType uuid() { | + | |
- | return new UUIDArgumentType(); | + | |
- | } | + | |
- | // This is also for convince and you could always just grab the argument from the CommandContext. | + | ^ Page ^ Description |
- | | + | | [[command_exceptions |
- | // Note that you should assume the CommandSource wrapped inside | + | | [[command_suggestions|Suggestions]] |
- | // If you access | + | | [[command_redirects|Redirects]] |
- | | + | | [[command_argument_types|Custom Argument Types]] |
- | } | + | | [[command_examples|Examples]] | Some example commands | |
- | private static final Collection< | + | ====== FAQ ====== |
- | list.add(" | + | |
- | list.add(" | + | |
- | list.add(" | + | |
- | }); | + | |
- | @Override | + | ===== Why does my code not compile ===== |
- | public UUID parse(StringReader reader) throws CommandSyntaxException { | + | |
- | int argBeginning | + | |
- | if (!reader.canRead()) { | + | |
- | reader.skip(); | + | |
- | } | + | |
- | // Now we check the contents of the argument till either we hit the end of the command line (When canRead becomes false) | + | There are several immediate possibilities for why this could occur. |
- | // Otherwise we go till reach reach a space, which signifies the next argument | + | |
- | while (reader.canRead() && reader.peek() != ' ') { // peek provides the character at the current cursor position. | + | |
- | reader.skip(); | + | |
- | } | + | |
- | // Now we substring the specific part we want to see using the starting cursor position | + | * **Catch or throw a CommandSyntaxException: |
- | | + | * **Issues with generics:** You may have an issue with generics once in a while. If you are registering server command |
- | try { | + | * **Check '' |
- | UUID uuid = UUID.fromString(uuidString); // Now our actual logic. | + | * **'' |
- | | + | |
- | } catch (Exception ex) { | + | |
- | // UUIDs can throw an exception when made by a string, so we catch the exception and repackage it into a CommandSyntaxException type. | + | |
- | // Create with context tells Brigadier to supply some context to tell the user where the command failed at. | + | |
- | // Though normal create | + | |
- | throw new SimpleCommandExceptionType(new LiteralText(ex.getMessage())).createWithContext(reader); | + | |
- | } | + | |
- | } | + | |
- | @Override | + | ===== Can I register client side commands? |
- | public Collection< | + | |
- | return EXAMPLES; | + | |
- | } | + | |
- | } | + | |
- | </ | + | |
- | ===== FAQ ===== | + | |
- | === What else can I send feedback to the CommandSource? | + | Fabric has a '' |
- | + | ||
- | You can choose between Brigadier' | + | |
- | + | ||
- | === Why does my IDE complain saying that a method executed by my command needs to catch or throw a CommandSyntaxException === | + | |
- | + | ||
- | The solution to this is just to make the methods throw a CommandSyntaxException down the whole chain as the executes block handles the exceptions. | + | |
- | + | ||
- | === Can I register commands in run time? === | + | |
- | + | ||
- | You can do this but it is not reccomended. You would get the instance of the CommandManager and add anything you wish to the CommandDispatcher within it. | + | |
- | + | ||
- | After that you will need to send the command tree to every player again using '' | + | |
- | + | ||
- | === Can I unregister commands in run time? === | + | |
- | + | ||
- | You can also do this but it is very unstable and could cause unwanted side effects. Lets just say it involves a bunch of Reflection. | + | |
- | + | ||
- | Once again you will need to send the command tree to every player again using '' | + | |
- | + | ||
- | === Can I register client side commands? === | + | |
- | + | ||
- | Well Fabric currently doesn' | + | |
- | https:// | + | |
- | + | ||
- | If you only want the command to only be visible on the integrated server like ''/ | + | |
<code java> | <code java> | ||
- | dispatcher.register(literal(" | + | ClientCommandRegistrationCallback.EVENT.register((dispatcher, |
- | // The permission level 4 on integrated server is the equivalent of having cheats enabled. | + | .executes(context |
- | .requires(source | + | context.getSource().sendFeedback(Text.literal("The command is executed in the client!" |
+ | return 1; | ||
+ | } | ||
+ | | ||
</ | </ | ||
- | === I want to access X from my mod when a command | + | If you need to open a screen in the client |
- | This is going to require a way to statically access your mod with a '' | + | ===== Can I register commands |
- | <code java> | + | You can do this but it is not recommended. You would get the '' |
- | private static Type instance; | + | |
- | static { // Static option on class initalize for seperate API class for example | + | After that you need to send the command tree to every player again using '' |
- | | + | |
- | } | + | |
- | public void onInitalize() { // If within your mod initalizer | + | ===== Can I unregister commands in runtime? ===== |
- | | + | |
- | } | + | You can also do this, however it is much less stable than registering commands and could cause unwanted side effects. To keep things simple, you need to use reflection on brigadier and remove the nodes. After this, you need to send the command tree to every player again using '' |
- | public static Type getInstance() { | ||
- | return instance; | ||
- | } | ||
- | </ |
tutorial/commands.txt · Last modified: 2024/02/23 14:22 by allen1210