docs icon indicating copy to clipboard operation
docs copied to clipboard

[Brigadier] Add `/execute` extension example

Open Strokkur424 opened this issue 11 months ago • 0 comments

[!NOTE] This issue is part of a series of issues regarding the extension of the Paper documentation regarding Paper's Brigadier API.

Bringing together #533 and #532, the concepts explained in both of those pages can be used to provide an example on how to extend the most complicated command vanilla offers: /execute.

This is to serve as a technical example in order for people, who seek to actually use this kind of command modification, to have a reference to go back to, but also serve as a great learning point for people who wish to further deepen their knowledge about Brigadier.

A possible extension to the command could be the addition of /execute permission in order to only execute a command if the executor actually has a permission. If you have a better idea for an extension, be sure to suggest it!

The code for such an extension might look like this:

private void registerExecuteExtension(final @NotNull Commands commands) {
    final CommandDispatcher<CommandSourceStack> dispatcher = commands.getDispatcher();
    if (!(dispatcher.getRoot().getChild("execute") instanceof LiteralCommandNode<CommandSourceStack> executeNode)) {
        return;
    }

    dispatcher.register(executeNode.createBuilder().then(Commands.literal("permission")
        .then(Commands.argument("permission", StringArgumentType.word())
            .fork(executeNode, ctx -> ctx.getSource().getExecutor() instanceof Player player
                && player.hasPermission(StringArgumentType.getString(ctx, "permission"))
                ? List.of(ctx.getSource())
                : List.of()))
    ));
}

And it would result in the following usage:

execute as @a permission minecraft.broadcast run say wassup
[16:39:03 INFO]: [Not Secure] [Strokkur24] wassup

deop Strokkur24
[16:39:10 INFO]: Made Strokkur24 no longer a server operator
execute as @a permission minecraft.broadcast run say wassup

op Strokkur24
[16:39:20 INFO]: Made Strokkur24 a server operator
execute as @a permission minecraft.broadcast run say wassup
[16:39:22 INFO]: [Not Secure] [Strokkur24] wassup

Strokkur424 avatar Jan 22 '25 15:01 Strokkur424