Análisis de argumentos

The Command Builder API comes with a powerful argument parser. It converts the string input to java base types (integers, booleans, strings) or game objects (players, worlds, block types, …). The parser supports optional arguments and flags. It also handles TAB completion of arguments.

Los argumentos analizados se almacenan en el objeto: javadoc: “CommandContext”. Si el analizador sintáctico devuelve un solo objeto, obténgalo con :javadoc: “CommandContext#getOne(String)”. Los argumentos opcionales y débiles pueden devolver “” Optional.empty()””.

Muchos de los analizadores pueden devolver más de un objeto (por ejemplo, varios jugadores con el mismo nombre de usuario que coincida). En ese caso, debe utilizar el método :javadoc:”CommandContext#getAll(String)” para obtener la “” colección “” de posibles coincidencias. ** De lo contrario, el objeto de contexto generará una excepción! **

When creating a command, consider whether the argument could return multiple values, for example, whether a player argument could support multiple players when using a selector. If you support multiple values the users need to type only one command and can use an easier command syntax. Example: /tell @a Who took the cookies?

Truco

You can use the GenericArguments#onlyOne(CommandElement) element to restrict the amount of returned values to a single one, so you can safely use args.<T>getOne(String). However the user will still get a message, if they try to select more than one value.

Para crear un nuevo :javadoc:´CommandElement´(argumento), utilice la clase de fábrica :javadoc: ´GenericArguments´. Muchos elementos de comando requieren una tecla de texto breve, la cual se muestra en los mensajes de error y de ayuda.

Apply the CommandElement to the command builder with the CommandSpec.Builder#arguments(CommandElement…) method. It is possible to pass more than one CommandElement to the method, thus chaining multiple arguments (e.g. /msg <player> <msg>). This has the same effect as wrapping the CommandElement objects in a GenericArguments#seq(CommandElement…) element.

Ejemplo: Construir un comando con múltiples argumentos

import org.spongepowered.api.Sponge;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.command.spec.CommandSpec;

PluginContainer plugin = ...;

CommandSpec myCommandSpec = CommandSpec.builder()
        .description(Text.of("Send a message to a player"))
        .permission("myplugin.command.message")

        .arguments(
                GenericArguments.onlyOne(GenericArguments.player(Text.of("player"))),
                GenericArguments.remainingJoinedStrings(Text.of("message")))

        .executor((CommandSource src, CommandContext args) -> {

            Player player = args.<Player>getOne("player").get();
            String message = args.<String>getOne("message").get();

            player.sendMessage(Text.of(message));

            return CommandResult.success();
        })
        .build();

Sponge.getCommandManager().register(plugin, myCommandSpec, "message", "msg", "m");

Descripción general de los elementos del comando `` GenericArguments``

Elemento de comando

Descripción

Tipo de valor y monto

«ninguno»

No espere argumentos. Este es el comportamiento predeterminado de un `` CommandSpec``.

** Tipos de base de Java **

«cadena»

Requiere un argumento para ser una cadena.

una «cadena»

cadenasunidasrestantes

Concatena todos los argumentos restantes separados por espacios (muy útil para los comandos de mensaje).

una «cadena»

«booleano»

Requiere un argumento para ser un booleano.

un «Booleano»

«entero»

Requiere un argumento para ser un entero.

un «entero»

«doblenúmero»

Requiere un argumento para ser un doble.

un «Doble»

Objetos de juego

«jugador»

Espere un argumento para representar a un jugador en línea. ** ¡Puede devolver varios jugadores! **

instancias de múltiples «jugadores»

«jugadorofuente»

Como «jugador», pero devuelve el remitente del comando si no encuentra ningún jugador coincidente.

instancias de múltiples «jugadores»

«usuarioofuente»

Como «jugadorofuente», pero devuelve un usuario en lugar de un jugador.

instancias de múltiples «usuarios»

«mundo»

Espere un argumento para representar un mundo (también incluye mundos descargados).

múltiples «MundosPropiedad»

«dimensión»

Espere un argumento para representar una dimensión («FIN», «INFERIOR», «SUPRAMUNDO»).

instancias de múltiples «Tiposdedimensión»

«ubicación»

Espere un argumento para representar una «ubicación».

una «ubicación»

“” vector3d””

Espere un argumento para representar un “” Vector3d””.

un “” Vector3d””

«ElementoCatalogado»

Espere un argumento que sea un miembro de la :javadoc: especificado “CatalogType”.

múltiples elementos coincidentes del tipo de catálogo especificado

Jugadores

«selección»

Devuelve un argumento que permite seleccionar de un conjunto limitado de valores.

un valor específico

«literal»

Espere una secuencia literal de argumentos (por ejemplo, `` «i», «luv», «u» : `` / cmd i luv u). Lanza un error si los argumentos no coinciden.

un valor específico

enumValue

Requiere que el argumento sea una clave bajo la enumeración proporcionada.

múltiples elementos coincidentes de la enumeración especificada

Utilidades

Se puede envolver alrededor de elementos de comando. El tipo de valor se hereda del elemento envuelto.

seq

Construye una secuencia de elementos de mando (por ejemplo: “” / cmd <arg1><arg2><arg3>””).

heredado

«repetido»

Requiere un comando dado para ser provisto un cierto número de veces.

hereditario múltiple

«Todo»

Requiere que todos los argumentos restantes coincidan con el elemento de comando provisto.

hereditario múltiple

«opcional»

Hace que el elemento de comando provisto sea opcional. Lanza un error si el argumento es de formato no válido y no hay más argumentos.

heredado

«DebilidadOpcional»

Hace que el elemento de comando provisto sea opcional. No arroja un error si el argumento es de formato no válido y no hay más argumentos.

heredado

«primerAnálisis»

Devuelve un elemento de comando que coincide con el primero de los elementos proporcionados que analiza (útil para la sobrecarga de comandos, por ejemplo `` / settime <day | night | <number> ``).

heredado

«soloUno»

Restringe el elemento de comando dado para insertar solo un valor en el contexto en la clave proporcionada.

heredado

«comandos»

Devuelve un constructor para indicadores de comando (por ejemplo, `` / cmd [-a] [-b <value>] ``).

Ver :doc:»comandos»

Bandera Corta: un Boolean

Bandera Larga: un String

Comando valor: heredado

«requierePermiso»

Requiere que el remitente de comando tenga el permiso especificado para usar el argumento de comando dado

heredado

requiringPermissionWeak

Requires the command sender to have the specified permission in order to use the given command argument. Does not throw an error if the user does not have the permission.

heredado

Truco

Vea los Javadocs para: javadoc: GenericArguments para más información.

Advertencia

Don’t expect that a CommandElements will only ever return a single value, a lot of them support multiple return values; some might even support regular expressions or use a command selector. This is intentional as it makes commands easier to use. Example: /tell @a BanditPlayer has the cookies!. If you want to make sure to only get a single value use GenericArguments#onlyOne(CommandElement).

Elementos de comando personalizados

Es posible crear elementos de comando personalizados (por ejemplo, un analizador de URL o un elemento `` Vector2i``) extendiendo la clase abstracta `` CommandElement``.

El método: javadoc: CommandElement # parseValue (CommandSource, CommandArgs) debe buscar una cadena de argumento sin procesar con: javadoc: CommandArgs # next () y convertirlo en un objeto. El método debería arrojar un: javadoc: ArgumentParseException si el análisis falla.

El método CommandElement # complete (CommandSource, CommandArgs, CommandContext) debe usar :javadoc: CommandArgs # peek () para leer el siguiente argumento sin formato. Devuelve una lista de sugerencias para completar el TAB.

Ejemplo: definición de elemento de comando `` Vector2i``

El analizador en este ejemplo lee dos argumentos de entrada y los convierte a un vector.

import com.flowpowered.math.vector.Vector2i;
import org.spongepowered.api.command.args.ArgumentParseException;
import org.spongepowered.api.command.args.CommandArgs;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.command.args.CommandElement;

import java.util.Collections;
import java.util.List;

public class Vector2iCommandElement extends CommandElement {

    protected Vector2iCommandElement(Text key) {
        super(key);
    }

    @Override
    protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {

        String xInput = args.next();
        int x = parseInt(xInput, args);

        String yInput = args.next();
        int y = parseInt(yInput, args);

        return new Vector2i(x, y);
    }

    private int parseInt(String input, CommandArgs args) throws ArgumentParseException {
        try {
            return Integer.parseInt(input);
        } catch(NumberFormatException e) {
            throw args.createError(Text.of("'" + input + "' is not a valid number!"));
        }
    }

    @Override
    public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
        return Collections.emptyList();
    }

    @Override
    public Text getUsage(CommandSource src) {
        return Text.of("<x> <y>");
    }
}

Ejemplo: uso del elemento de comando `` Vector2i``

// /plottp <x> <y>
CommandSpec myCommandSpec = CommandSpec.builder()
        .description(Text.of("Teleport to a plot"))
        .permission("myplugin.command.plot.tp")

        .arguments(new Vector2iCommandElement(Text.of("coordinates")))

        .executor(new MyCommandExecutor())
        .build();

Truco

Revise el código fuente <https://github.com/SpongePowered/SpongeAPI/blob/stable-7/src/main/java/org/spongepowered/api/command/args/GenericArguments.java> _ de la clase ` GenericArguments` para más ejemplos.

Using Selectors in Custom Command Elements

Sponge provides support for parsing selectors, meaning that you can make use of them in your custom elements. There are two steps in using selectors, parsing (getting a Selector from the string) and resolving (getting a set of Entity objects selected by the selector).

To parse a selector string, use the Selector#parse(String) method, passing the entire selector, including the @ symbol. This will turn the string into a Selector object that can be queried or resolved. Note that if the string is not a valid selector, an IllegalArgumentException will be thrown.

To resolve this selector, use Selector#resolve(CommandSource). This will return a set of Entity objects selected by the selector.

The following parseValue method from the CommandElement class attempts to parse a selector and return a set of entities based on the location of the CommandSource. If the passed string does not start with @, an exception will be thrown indicating that the passed argument is not a selector.

@Override
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
    String nextArg = args.next();
    if (nextArg.startsWith("@")) {
        Set<Entity> selectedEntities;
        try {
            selectedEntities = Selector.parse(nextArg).resolve(source);
        } catch (IllegalArgumentException e) {
            throw args.createError(Text.of("Could not parse selector."));
        }

        if (selectedEntities.isEmpty()) {
            throw args.createError(Text.of("No entities selected."));
        }

        return selectedEntities;
    }

    throw args.createError(Text.of("Not a selector."));
}

Truco

Look at the SelectorCommandElement source code for an example of how selector parsing is performed in the standard Sponge CommandElements.