Search in sources :

Example 16 with CommandContext

use of org.spongepowered.api.command.args.CommandContext in project Nucleus by NucleusPowered.

the class AvailableBaseCommand method executeCommand.

@Override
protected CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
    MessageProvider mp = Nucleus.getNucleus().getMessageProvider();
    List<Text> types = Sponge.getRegistry().getAllOf(this.catalogType).stream().map(x -> mp.getTextMessageWithFormat("command.world.presets.item", x.getId(), x.getName())).collect(Collectors.toList());
    Util.getPaginationBuilder(src).title(mp.getTextMessageWithTextFormat(this.titleKey)).contents(types).sendTo(src);
    return CommandResult.success();
}
Also used : CommandResult(org.spongepowered.api.command.CommandResult) Nucleus(io.github.nucleuspowered.nucleus.Nucleus) CommandSource(org.spongepowered.api.command.CommandSource) CatalogType(org.spongepowered.api.CatalogType) Sponge(org.spongepowered.api.Sponge) NonnullByDefault(org.spongepowered.api.util.annotation.NonnullByDefault) Collectors(java.util.stream.Collectors) List(java.util.List) AbstractCommand(io.github.nucleuspowered.nucleus.internal.command.AbstractCommand) MessageProvider(io.github.nucleuspowered.nucleus.internal.messages.MessageProvider) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) Util(io.github.nucleuspowered.nucleus.Util) MessageProvider(io.github.nucleuspowered.nucleus.internal.messages.MessageProvider) Text(org.spongepowered.api.text.Text)

Example 17 with CommandContext

use of org.spongepowered.api.command.args.CommandContext in project Nucleus by NucleusPowered.

the class AFKCommandInterceptor method onPostCommand.

@Override
public void onPostCommand(Class<? extends AbstractCommand<?>> commandClass, CommandSource source, CommandContext context, CommandResult result) {
    if (this.send && result.getSuccessCount().orElse(0) > 0 && commandClass.isAnnotationPresent(NotifyIfAFK.class)) {
        NotifyIfAFK annotation = commandClass.getAnnotation(NotifyIfAFK.class);
        Cause cause = CauseStackHelper.createCause(source);
        for (String key : annotation.value()) {
            context.getAll(key).stream().filter(x -> x instanceof User).map(x -> ((User) x).getPlayer().orElse(null)).filter(Objects::nonNull).filter(this.handler::isAFK).forEach(x -> {
                Text messageToSend = this.message == null ? null : message.getForCommandSource(x);
                AFKEvents.Notify event = new AFKEvents.Notify(x, messageToSend, cause);
                Sponge.getEventManager().post(event);
                event.getMessage().ifPresent(source::sendMessage);
            });
        }
    }
}
Also used : NotifyIfAFK(io.github.nucleuspowered.nucleus.internal.annotations.command.NotifyIfAFK) AFKConfig(io.github.nucleuspowered.nucleus.modules.afk.config.AFKConfig) CommandResult(org.spongepowered.api.command.CommandResult) Nucleus(io.github.nucleuspowered.nucleus.Nucleus) User(org.spongepowered.api.entity.living.player.User) CommandSource(org.spongepowered.api.command.CommandSource) CauseStackHelper(io.github.nucleuspowered.nucleus.util.CauseStackHelper) Sponge(org.spongepowered.api.Sponge) Reloadable(io.github.nucleuspowered.nucleus.internal.interfaces.Reloadable) Objects(java.util.Objects) Cause(org.spongepowered.api.event.cause.Cause) AbstractCommand(io.github.nucleuspowered.nucleus.internal.command.AbstractCommand) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) NucleusTextTemplate(io.github.nucleuspowered.nucleus.api.text.NucleusTextTemplate) ICommandInterceptor(io.github.nucleuspowered.nucleus.internal.command.ICommandInterceptor) AFKHandler(io.github.nucleuspowered.nucleus.modules.afk.handlers.AFKHandler) AFKEvents(io.github.nucleuspowered.nucleus.modules.afk.events.AFKEvents) AFKConfigAdapter(io.github.nucleuspowered.nucleus.modules.afk.config.AFKConfigAdapter) Nullable(javax.annotation.Nullable) User(org.spongepowered.api.entity.living.player.User) Cause(org.spongepowered.api.event.cause.Cause) Objects(java.util.Objects) Text(org.spongepowered.api.text.Text) AFKEvents(io.github.nucleuspowered.nucleus.modules.afk.events.AFKEvents) NotifyIfAFK(io.github.nucleuspowered.nucleus.internal.annotations.command.NotifyIfAFK)

Example 18 with CommandContext

use of org.spongepowered.api.command.args.CommandContext in project Nucleus by NucleusPowered.

the class AbstractCommand method process.

private CommandResult process(CommandSource source, String command, String arguments, CommandArgs args) throws CommandException {
    // Phase one: child command processing. Keep track of all thrown arguments.
    List<Tuple<String, CommandException>> thrown = Lists.newArrayList();
    final CommandContext context = new CommandContext();
    T castedSource;
    try {
        // If we have a child command to execute, then we execute it.
        if (args.hasNext() && this.dispatcher.containsAlias(args.peek())) {
            Object state = args.getState();
            String next = args.next();
            try {
                // If this works, then we're A-OK.
                CommandCallable callable = this.dispatcher.get(next.toLowerCase()).get().getCallable();
                if (callable instanceof AbstractCommand) {
                    return ((AbstractCommand) callable).process(source, command + " " + next, arguments, args);
                }
                return callable.process(source, arguments);
            } catch (NucleusCommandException e) {
                // Didn't work out. Let's move on.
                thrown.addAll(e.getExceptions());
                if (!e.isAllowFallback()) {
                    throw e;
                }
            } catch (CommandException e) {
                // If the Exception is _not_ of right type, wrap it and add it. This shouldn't happen though.
                thrown.add(Tuple.of(command + " " + next, e));
            } finally {
                args.setState(state);
            }
        }
        // Phase one: test for what is required
        if (requiresEconomy && !plugin.getEconHelper().economyServiceExists()) {
            source.sendMessage(NucleusPlugin.getNucleus().getMessageProvider().getTextMessageWithFormat("command.economyrequired"));
            return CommandResult.empty();
        }
        // Phase two: source type - test to see if the person in question can execute this command.
        castedSource = checkSourceType(source);
        // Phase three - test the permission.
        if (!testPermissionOnSubject(castedSource)) {
            throw new CommandPermissionException();
        }
        if (!this.hasExecutor) {
            if (thrown.isEmpty()) {
                // OK, we just process the usage command instead.
                return this.usageCommand.process(source, "", args.nextIfPresent().map(String::toLowerCase).orElse(null));
            } else {
                throw new NucleusCommandException(thrown);
            }
        }
        // Phase four - create the context and parse the arguments.
        this.argumentParser.parse(source, args, context);
        if (args.hasNext()) {
            thrown.add(Tuple.of(command, new NucleusArgumentParseException(Text.of(TextColors.RED, "Too many arguments"), args.getRaw(), args.getRawPosition(), Text.of(getSimpleUsage(source)), getChildrenUsage(source).orElse(null), true)));
            throw new NucleusCommandException(thrown, allowFallback(source, args, context));
        }
    } catch (NucleusCommandException nce) {
        throw nce;
    } catch (ArgumentParseException ape) {
        // get the command to get the usage/subs from.
        thrown.add(Tuple.of(command, NucleusArgumentParseException.from(ape, Text.of(getSimpleUsage(source)), getChildrenUsage(source).orElse(null))));
        throw new NucleusCommandException(thrown, allowFallback(source, args, context));
    } catch (CommandException ex) {
        // Errors at this point are expected, so we'll run with it - no need for debug mode checks.
        thrown.add(Tuple.of(command, ex));
        throw new NucleusCommandException(thrown, allowFallback(source, args, context));
    } catch (Throwable throwable) {
        String m;
        if (throwable.getMessage() == null) {
            m = "null";
        } else {
            m = throwable.getMessage();
        }
        thrown.add(Tuple.of(command, new CommandException(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.exception.unexpected", m), throwable)));
        // this is on demand, so we should throw it.
        throwable.printStackTrace();
        throw new NucleusCommandException(thrown, allowFallback(source, args, context));
    }
    try {
        commandTimings.startTimingIfSync();
        ContinueMode mode = preProcessChecks(castedSource, context);
        if (!mode.cont) {
            return mode.returnType;
        }
        if (castedSource instanceof Player) {
            @SuppressWarnings("unchecked") ContinueMode cm = runChecks((Player) castedSource, context);
            if (!cm.cont) {
                return cm.returnType;
            }
        }
        // If we're running async...
        if (isAsync) {
            // Create an executor that runs the command async.
            plugin.getLogger().debug("Running " + this.getClass().getName() + " in async mode.");
            Sponge.getScheduler().createAsyncExecutor(plugin).execute(() -> onExecute(castedSource, context));
            // Tell Sponge we're done.
            return CommandResult.success();
        }
        return onExecute(castedSource, context);
    } finally {
        commandTimings.stopTimingIfSync();
    }
}
Also used : CommandPermissionException(org.spongepowered.api.command.CommandPermissionException) Player(org.spongepowered.api.entity.living.player.Player) CommandContext(org.spongepowered.api.command.args.CommandContext) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandException(org.spongepowered.api.command.CommandException) CommandCallable(org.spongepowered.api.command.CommandCallable) Tuple(org.spongepowered.api.util.Tuple)

Example 19 with CommandContext

use of org.spongepowered.api.command.args.CommandContext in project Nucleus by NucleusPowered.

the class BroadcastCommand method executeCommand.

@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
    String m = args.<String>getOne(message).get();
    NucleusTextTemplate textTemplate = NucleusTextTemplateFactory.createFromAmpersandString(m);
    Text p = bc.getPrefix().getForCommandSource(src);
    Text s = bc.getSuffix().getForCommandSource(src);
    new NucleusTextTemplateMessageSender(textTemplate, src, t -> TextParsingUtils.joinTextsWithColoursFlowing(p, t, s)).send();
    return CommandResult.success();
}
Also used : NoModifiers(io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers) NucleusTextTemplateFactory(io.github.nucleuspowered.nucleus.internal.text.NucleusTextTemplateFactory) CommandResult(org.spongepowered.api.command.CommandResult) RegisterCommand(io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand) RemainingStringsArgument(io.github.nucleuspowered.nucleus.argumentparsers.RemainingStringsArgument) AdminConfig(io.github.nucleuspowered.nucleus.modules.admin.config.AdminConfig) CommandSource(org.spongepowered.api.command.CommandSource) AdminConfigAdapter(io.github.nucleuspowered.nucleus.modules.admin.config.AdminConfigAdapter) TextParsingUtils(io.github.nucleuspowered.nucleus.internal.text.TextParsingUtils) NonnullByDefault(org.spongepowered.api.util.annotation.NonnullByDefault) AdminModule(io.github.nucleuspowered.nucleus.modules.admin.AdminModule) CommandElement(org.spongepowered.api.command.args.CommandElement) GenericArguments(org.spongepowered.api.command.args.GenericArguments) RunAsync(io.github.nucleuspowered.nucleus.internal.annotations.RunAsync) Reloadable(io.github.nucleuspowered.nucleus.internal.interfaces.Reloadable) AbstractCommand(io.github.nucleuspowered.nucleus.internal.command.AbstractCommand) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) NucleusTextTemplate(io.github.nucleuspowered.nucleus.api.text.NucleusTextTemplate) NucleusTextTemplateMessageSender(io.github.nucleuspowered.nucleus.internal.text.NucleusTextTemplateMessageSender) BroadcastConfig(io.github.nucleuspowered.nucleus.modules.admin.config.BroadcastConfig) EssentialsEquivalent(io.github.nucleuspowered.nucleus.internal.docgen.annotations.EssentialsEquivalent) Permissions(io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions) NucleusTextTemplateMessageSender(io.github.nucleuspowered.nucleus.internal.text.NucleusTextTemplateMessageSender) NucleusTextTemplate(io.github.nucleuspowered.nucleus.api.text.NucleusTextTemplate) Text(org.spongepowered.api.text.Text)

Example 20 with CommandContext

use of org.spongepowered.api.command.args.CommandContext in project Nucleus by NucleusPowered.

the class EnchantCommand method executeCommand.

@Override
public CommandResult executeCommand(Player src, CommandContext args) throws Exception {
    // Check for item in hand
    if (!src.getItemInHand(HandTypes.MAIN_HAND).isPresent()) {
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.noitem"));
        return CommandResult.empty();
    }
    // Get the arguments
    ItemStack itemInHand = src.getItemInHand(HandTypes.MAIN_HAND).get();
    EnchantmentType enchantment = args.<EnchantmentType>getOne(enchantmentKey).get();
    int level = args.<Integer>getOne(levelKey).get();
    boolean allowUnsafe = args.hasAny("u");
    boolean allowOverwrite = args.hasAny("o");
    // Can we apply the enchantment?
    if (!allowUnsafe) {
        if (!enchantment.canBeAppliedToStack(itemInHand)) {
            src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.nounsafe.enchant", itemInHand.getTranslation().get()));
            return CommandResult.empty();
        }
        if (level > enchantment.getMaximumLevel()) {
            src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.nounsafe.level", itemInHand.getTranslation().get()));
            return CommandResult.empty();
        }
    }
    // We know this should exist.
    EnchantmentData ed = itemInHand.getOrCreate(EnchantmentData.class).get();
    // Get all the enchantments.
    List<Enchantment> currentEnchants = ed.getListValue().get();
    List<Enchantment> enchantmentsToRemove = currentEnchants.stream().filter(x -> !x.getType().isCompatibleWith(enchantment) || x.getType().equals(enchantment)).collect(Collectors.toList());
    if (!allowOverwrite && !enchantmentsToRemove.isEmpty()) {
        // Build the list of the enchantment names, and send it.
        final StringBuilder sb = new StringBuilder();
        enchantmentsToRemove.forEach(x -> {
            if (sb.length() > 0) {
                sb.append(", ");
            }
            sb.append(Util.getTranslatableIfPresent(x.getType()));
        });
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.overwrite", sb.toString()));
        return CommandResult.empty();
    }
    // Remove all enchants that cannot co-exist.
    currentEnchants.removeIf(enchantmentsToRemove::contains);
    // Create the enchantment
    currentEnchants.add(Enchantment.of(enchantment, level));
    ed.setElements(currentEnchants);
    // Offer it to the item.
    DataTransactionResult dtr = itemInHand.offer(ed);
    if (dtr.isSuccessful()) {
        // If successful, we need to put the item in the player's hand for it to actually take effect.
        src.setItemInHand(HandTypes.MAIN_HAND, itemInHand);
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.success", Util.getTranslatableIfPresent(enchantment), String.valueOf(level)));
        return CommandResult.success();
    }
    src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.enchant.error", Util.getTranslatableIfPresent(enchantment), String.valueOf(level)));
    return CommandResult.empty();
}
Also used : RegisterCommand(io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand) EnchantmentType(org.spongepowered.api.item.enchantment.EnchantmentType) PermissionInformation(io.github.nucleuspowered.nucleus.internal.permissions.PermissionInformation) NonnullByDefault(org.spongepowered.api.util.annotation.NonnullByDefault) GenericArguments(org.spongepowered.api.command.args.GenericArguments) DataTransactionResult(org.spongepowered.api.data.DataTransactionResult) Enchantment(org.spongepowered.api.item.enchantment.Enchantment) ItemStack(org.spongepowered.api.item.inventory.ItemStack) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) Map(java.util.Map) SuggestedLevel(io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel) Util(io.github.nucleuspowered.nucleus.Util) Permissions(io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions) ImprovedCatalogTypeArgument(io.github.nucleuspowered.nucleus.argumentparsers.ImprovedCatalogTypeArgument) BoundedIntegerArgument(io.github.nucleuspowered.nucleus.argumentparsers.BoundedIntegerArgument) CommandResult(org.spongepowered.api.command.CommandResult) Maps(com.google.common.collect.Maps) CommandElement(org.spongepowered.api.command.args.CommandElement) Collectors(java.util.stream.Collectors) EnchantmentData(org.spongepowered.api.data.manipulator.mutable.item.EnchantmentData) List(java.util.List) AbstractCommand(io.github.nucleuspowered.nucleus.internal.command.AbstractCommand) HandTypes(org.spongepowered.api.data.type.HandTypes) EssentialsEquivalent(io.github.nucleuspowered.nucleus.internal.docgen.annotations.EssentialsEquivalent) Player(org.spongepowered.api.entity.living.player.Player) EnchantmentType(org.spongepowered.api.item.enchantment.EnchantmentType) DataTransactionResult(org.spongepowered.api.data.DataTransactionResult) ItemStack(org.spongepowered.api.item.inventory.ItemStack) EnchantmentData(org.spongepowered.api.data.manipulator.mutable.item.EnchantmentData) Enchantment(org.spongepowered.api.item.enchantment.Enchantment)

Aggregations

CommandContext (org.spongepowered.api.command.args.CommandContext)55 CommandResult (org.spongepowered.api.command.CommandResult)46 Text (org.spongepowered.api.text.Text)45 CommandSource (org.spongepowered.api.command.CommandSource)40 List (java.util.List)36 Collectors (java.util.stream.Collectors)30 CommandElement (org.spongepowered.api.command.args.CommandElement)30 Player (org.spongepowered.api.entity.living.player.Player)29 Optional (java.util.Optional)28 Sponge (org.spongepowered.api.Sponge)28 Permissions (io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions)27 RegisterCommand (io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand)27 AbstractCommand (io.github.nucleuspowered.nucleus.internal.command.AbstractCommand)27 NonnullByDefault (org.spongepowered.api.util.annotation.NonnullByDefault)27 GenericArguments (org.spongepowered.api.command.args.GenericArguments)26 TextColors (org.spongepowered.api.text.format.TextColors)24 Util (io.github.nucleuspowered.nucleus.Util)19 SuggestedLevel (io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel)19 NoModifiers (io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers)18 CommandException (org.spongepowered.api.command.CommandException)18