User Tools

Site Tools


tutorial:command_redirects

This is an old revision of the document!


Command Redirects

Redirects are Brigadier's form of aliases and subcommands.

Aliases

Below is how Minecraft makes /msg have an alias of /tell and /w.

  1. public static void register(CommandDispatcher<ServerCommandSource> dispatcher) {
  2. LiteralCommandNode node = dispatcher
  3. .register(literal("msg")
  4. .then(argument("targets", EntityArgumentType.players())
  5. .then(argument("message", MessageArgumentType.message())
  6. .executes(context -> {... /* code ommited */ }))));
  7.  
  8. dispatcher.register(literal("tell")
  9. .redirect(node)); // Alias 1, redirect to main command
  10. dispatcher.register(literal("w")
  11. .redirect(node)); // Alias 2, redirect to main command
  12. }

The redirect tells brigadier to continue parsing the command at another command node.

Chainable Commands

Commands such as /execute as @e[type=player] in the_end run tp ~ ~ ~ are also possible because of redirects. Below is an example of a chainable command:

  1. LiteralCommandNode<ServerCommandSource> rootNode = dispatcher.register(literal("fabric_test"));
  2. LiteralCommandNode<ServerCommandSource> root1 = dispatcher.register(literal("fabric_test")
  3. // 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.
  4. .then(literal("extra")
  5. .then(literal("long")
  6. .redirect(rootNode, this::lengthen)) // Return to root for chaining
  7. .then(literal("short")
  8. .redirect(rootNode, this::shorten))) // Return to root for chaining
  9. .then(literal("command")
  10. .executes(ctx -> {
  11. ctx.getSource().sendFeedback(Text.literal("Chainable Command"), false);
  12. return Command.SINGLE_SUCCESS;
  13. })));

The redirect can also modify the CommandSource by use of a “redirect modifier”, which is used as a lambda.

  1. .redirect(rootNode, context -> {
  2. // When redirecting, modify the looking direction of the command source.
  3. return ((ServerCommandSource) context.getSource()).withLookingAt(Vec3ArgumentType.getVec3(context, "pos"));
  4. })
tutorial/command_redirects.1659925157.txt.gz · Last modified: 2022/08/08 02:19 by solidblock