Search in sources :

Example 26 with CommandResult

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

the class ListPowertoolCommand method executeCommand.

@Override
public CommandResult executeCommand(Player src, CommandContext args) throws Exception {
    PowertoolUserDataModule inu = Nucleus.getNucleus().getUserDataManager().getUnchecked(src).get(PowertoolUserDataModule.class);
    boolean toggle = inu.isPowertoolToggled();
    Map<String, List<String>> powertools = inu.getPowertools();
    if (powertools.isEmpty()) {
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.powertool.list.none"));
        return CommandResult.success();
    }
    // Generate powertools.
    List<Text> mesl = powertools.entrySet().stream().sorted((a, b) -> a.getKey().compareToIgnoreCase(b.getKey())).map(k -> from(inu, src, k.getKey(), k.getValue())).collect(Collectors.toList());
    // Paginate the tools.
    Util.getPaginationBuilder(src).title(plugin.getMessageProvider().getTextMessageWithFormat("command.powertool.list.header", toggle ? "&aenabled" : "&cdisabled")).padding(Text.of(TextColors.YELLOW, "-")).contents(mesl).sendTo(src);
    return CommandResult.success();
}
Also used : NoModifiers(io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers) CommandResult(org.spongepowered.api.command.CommandResult) ClickAction(org.spongepowered.api.text.action.ClickAction) TextActions(org.spongepowered.api.text.action.TextActions) Nucleus(io.github.nucleuspowered.nucleus.Nucleus) RegisterCommand(io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand) Sponge(org.spongepowered.api.Sponge) NonnullByDefault(org.spongepowered.api.util.annotation.NonnullByDefault) PowertoolUserDataModule(io.github.nucleuspowered.nucleus.modules.powertool.datamodules.PowertoolUserDataModule) Collectors(java.util.stream.Collectors) RunAsync(io.github.nucleuspowered.nucleus.internal.annotations.RunAsync) 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) TextColor(org.spongepowered.api.text.format.TextColor) Map(java.util.Map) Optional(java.util.Optional) Util(io.github.nucleuspowered.nucleus.Util) Player(org.spongepowered.api.entity.living.player.Player) Permissions(io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions) ItemType(org.spongepowered.api.item.ItemType) TextColors(org.spongepowered.api.text.format.TextColors) List(java.util.List) Text(org.spongepowered.api.text.Text) PowertoolUserDataModule(io.github.nucleuspowered.nucleus.modules.powertool.datamodules.PowertoolUserDataModule)

Example 27 with CommandResult

use of org.spongepowered.api.command.CommandResult in project SpongeCommon by SpongePowered.

the class SpongeCommandManager method process.

public CommandResult process(final CommandCause cause, final String arguments) throws CommandException, CommandSyntaxException {
    final String[] splitArg = arguments.split(" ", 2);
    final String originalCommand = splitArg[0];
    final String originalArgs = splitArg.length == 2 ? splitArg[1] : "";
    final String command;
    final String args;
    final ExecuteCommandEvent.Pre preEvent = SpongeEventFactory.createExecuteCommandEventPre(cause.cause(), originalArgs, originalArgs, originalCommand, originalCommand, cause, Optional.empty(), false);
    if (this.game.eventManager().post(preEvent)) {
        return preEvent.result().orElse(SpongeCommandManager.UNKNOWN_ERROR);
    }
    command = preEvent.command();
    args = preEvent.arguments();
    final SpongeCommandMapping mapping = this.commandMappings.get(command.toLowerCase());
    if (mapping == null) {
        throw new CommandException(Component.text("Unknown command. Type /help for a list of commands."));
    }
    final Object source = cause.cause().root();
    final CommandResult result;
    try (final CommandPhaseContext context = GeneralPhase.State.COMMAND.createPhaseContext(PhaseTracker.getInstance()).source(source).command(args).commandMapping(mapping)) {
        if (source instanceof ServerPlayer) {
            final ServerPlayer serverPlayer = (ServerPlayer) source;
            context.creator(serverPlayer.uniqueId());
            context.notifier(serverPlayer.uniqueId());
        }
        context.buildAndSwitch();
        try {
            result = this.processCommand(cause, mapping, arguments, command, args);
        } catch (final CommandException exception) {
            final CommandResult errorResult = CommandResult.builder().result(0).error(exception.componentMessage()).build();
            this.postExecuteCommandPostEvent(cause, originalArgs, args, originalCommand, command, errorResult);
            if (SpongeCommandManager.ALWAYS_PRINT_STACKTRACES) {
                this.prettyPrintThrowableError(exception, command, args, cause);
            }
            throw exception;
        } catch (final CommandSyntaxException cse) {
            final CommandResult errorResult = CommandResult.builder().result(0).error(SpongeAdventure.asAdventure(cse.getRawMessage())).build();
            this.postExecuteCommandPostEvent(cause, originalArgs, args, originalCommand, command, errorResult);
            if (SpongeCommandManager.ALWAYS_PRINT_STACKTRACES) {
                this.prettyPrintThrowableError(cse, command, args, cause);
            }
            throw cse;
        } catch (final net.minecraft.commands.CommandRuntimeException ex) {
            final CommandResult errorResult = CommandResult.builder().result(0).error(SpongeAdventure.asAdventure(ex.getComponent())).build();
            this.postExecuteCommandPostEvent(cause, originalArgs, args, originalCommand, command, errorResult);
            if (SpongeCommandManager.ALWAYS_PRINT_STACKTRACES) {
                this.prettyPrintThrowableError(ex, command, args, cause);
            }
            throw ex;
        } catch (final Throwable thr) {
            this.prettyPrintThrowableError(thr, command, args, cause);
            Component excBuilder;
            if (thr instanceof ComponentMessageThrowable) {
                final Component text = ((ComponentMessageThrowable) thr).componentMessage();
                excBuilder = text == null ? Component.text("null") : text;
            } else {
                excBuilder = Component.text(String.valueOf(thr.getMessage()));
            }
            if (cause.hasPermission(Constants.Permissions.DEBUG_HOVER_STACKTRACE)) {
                final StringWriter writer = new StringWriter();
                thr.printStackTrace(new PrintWriter(writer));
                excBuilder = excBuilder.hoverEvent(HoverEvent.showText(Component.text(writer.toString().replace("\t", "    ").replace("\r\n", "\n").replace("\r", // I mean I guess somebody could be running this on like OS 9?
                "\n"))));
            }
            final Component error = Component.text().content("Unexpected error occurred while executing command: ").append(excBuilder).build();
            this.postExecuteCommandPostEvent(cause, originalArgs, args, originalCommand, command, CommandResult.error(error));
            throw new CommandException(error, thr);
        }
        this.postExecuteCommandPostEvent(cause, originalArgs, args, originalCommand, command, result);
        if (!result.isSuccess()) {
            cause.sendMessage(Identity.nil(), result.errorMessage().map(x -> x.colorIfAbsent(NamedTextColor.RED)).orElseGet(() -> Component.text().content(String.format("An empty error result was returned while executing the command \"%s\"", arguments)).color(NamedTextColor.RED).build()));
        }
        return result;
    }
}
Also used : ExecuteCommandEvent(org.spongepowered.api.event.command.ExecuteCommandEvent) CommandException(org.spongepowered.api.command.exception.CommandException) SpongeCommandResult(org.spongepowered.common.command.result.SpongeCommandResult) CommandResult(org.spongepowered.api.command.CommandResult) ComponentMessageThrowable(net.kyori.adventure.util.ComponentMessageThrowable) StringWriter(java.io.StringWriter) CommandPhaseContext(org.spongepowered.common.event.tracking.phase.general.CommandPhaseContext) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) ComponentMessageThrowable(net.kyori.adventure.util.ComponentMessageThrowable) Component(net.kyori.adventure.text.Component) SpongeCommandSyntaxException(org.spongepowered.common.command.exception.SpongeCommandSyntaxException) CommandSyntaxException(com.mojang.brigadier.exceptions.CommandSyntaxException) PrintWriter(java.io.PrintWriter)

Example 28 with CommandResult

use of org.spongepowered.api.command.CommandResult in project Skree by Skelril.

the class MarketListCommand method execute.

@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    Optional<MarketService> optService = Sponge.getServiceManager().provide(MarketService.class);
    if (!optService.isPresent()) {
        src.sendMessage(Text.of(TextColors.DARK_RED, "The market service is not currently running."));
        return CommandResult.empty();
    }
    MarketService service = optService.get();
    PaginationService pagination = Sponge.getServiceManager().provideUnchecked(PaginationService.class);
    Optional<String> optFilter = args.getOne("name");
    String filter = optFilter.isPresent() ? optFilter.get() : "";
    if (!filter.matches(MarketService.VALID_ALIAS_REGEX)) {
        src.sendMessage(Text.of(TextColors.RED, "Invalid filter supplied."));
        return CommandResult.empty();
    }
    List<ItemDescriptor> prices = filter.isEmpty() ? service.getPrices() : service.getPrices(filter + "%");
    if (prices.isEmpty()) {
        src.sendMessage(Text.of(TextColors.YELLOW, "No items matched."));
        return CommandResult.success();
    }
    List<Text> result = prices.stream().filter(a -> filter.isEmpty() || a.getName().startsWith(filter)).sorted(Comparator.comparing(ItemDescriptor::getCurrentValue)).map(a -> createLine(a, service)).collect(Collectors.toList());
    pagination.builder().contents(result).title(Text.of(TextColors.GOLD, "Item List")).padding(Text.of(" ")).sendTo(src);
    return CommandResult.success();
}
Also used : CommandResult(org.spongepowered.api.command.CommandResult) TextActions(org.spongepowered.api.text.action.TextActions) CommandSource(org.spongepowered.api.command.CommandSource) GenericArguments.optional(org.spongepowered.api.command.args.GenericArguments.optional) Sponge(org.spongepowered.api.Sponge) MarketImplUtil.format(com.skelril.skree.content.market.MarketImplUtil.format) GenericArguments.remainingJoinedStrings(org.spongepowered.api.command.args.GenericArguments.remainingJoinedStrings) MarketService(com.skelril.skree.service.MarketService) PaginationService(org.spongepowered.api.service.pagination.PaginationService) ItemDescriptor(com.skelril.skree.service.internal.market.ItemDescriptor) Collectors(java.util.stream.Collectors) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) CommandException(org.spongepowered.api.command.CommandException) BigDecimal(java.math.BigDecimal) List(java.util.List) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) CommandExecutor(org.spongepowered.api.command.spec.CommandExecutor) Optional(java.util.Optional) Comparator(java.util.Comparator) TextColors(org.spongepowered.api.text.format.TextColors) ItemDescriptor(com.skelril.skree.service.internal.market.ItemDescriptor) Text(org.spongepowered.api.text.Text) PaginationService(org.spongepowered.api.service.pagination.PaginationService) MarketService(com.skelril.skree.service.MarketService)

Example 29 with CommandResult

use of org.spongepowered.api.command.CommandResult in project Skree by Skelril.

the class RegionAddMemberCommand method execute.

@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    if (!(src instanceof Player)) {
        src.sendMessage(Text.of("You must be a player to use this command (for now ;) )!"));
        return CommandResult.empty();
    }
    Optional<RegionService> optService = Sponge.getServiceManager().provide(RegionService.class);
    if (!optService.isPresent()) {
        src.sendMessage(Text.of(TextColors.DARK_RED, "The region service is not currently running."));
        return CommandResult.empty();
    }
    RegionService service = optService.get();
    Player player = (Player) src;
    Optional<Region> optRef = service.getSelectedRegion(player);
    if (!optRef.isPresent()) {
        player.sendMessage(Text.of(TextColors.RED, "You do not currently have a region selected."));
        return CommandResult.empty();
    }
    Region ref = optRef.get();
    if (!ref.getMembers().contains(player.getUniqueId())) {
        player.sendMessage(Text.of(TextColors.RED, "You must be a member of the region to modify it!"));
        return CommandResult.empty();
    }
    List<UUID> newMembers = args.<User>getAll("player").stream().map(Identifiable::getUniqueId).filter(a -> !ref.getMembers().contains(a)).collect(Collectors.toList());
    ref.addMember(newMembers);
    player.sendMessage(Text.of(TextColors.YELLOW, "Added ", newMembers.size(), " players to the region."));
    return CommandResult.success();
}
Also used : CommandResult(org.spongepowered.api.command.CommandResult) GenericArguments.allOf(org.spongepowered.api.command.args.GenericArguments.allOf) User(org.spongepowered.api.entity.living.player.User) CommandSource(org.spongepowered.api.command.CommandSource) Sponge(org.spongepowered.api.Sponge) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) RegionService(com.skelril.skree.service.RegionService) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) CommandException(org.spongepowered.api.command.CommandException) List(java.util.List) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) CommandExecutor(org.spongepowered.api.command.spec.CommandExecutor) Region(com.skelril.skree.service.internal.region.Region) Optional(java.util.Optional) GenericArguments.user(org.spongepowered.api.command.args.GenericArguments.user) Player(org.spongepowered.api.entity.living.player.Player) TextColors(org.spongepowered.api.text.format.TextColors) Identifiable(org.spongepowered.api.util.Identifiable) Player(org.spongepowered.api.entity.living.player.Player) User(org.spongepowered.api.entity.living.player.User) Region(com.skelril.skree.service.internal.region.Region) RegionService(com.skelril.skree.service.RegionService) UUID(java.util.UUID) Identifiable(org.spongepowered.api.util.Identifiable)

Example 30 with CommandResult

use of org.spongepowered.api.command.CommandResult in project Skree by Skelril.

the class RegionListMarkersCommand method execute.

@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    if (!(src instanceof Player)) {
        src.sendMessage(Text.of("You must be a player to use this command (for now ;) )!"));
        return CommandResult.empty();
    }
    Optional<RegionService> optService = Sponge.getServiceManager().provide(RegionService.class);
    if (!optService.isPresent()) {
        src.sendMessage(Text.of(TextColors.DARK_RED, "The region service is not currently running."));
        return CommandResult.empty();
    }
    RegionService service = optService.get();
    Player player = (Player) src;
    Optional<Region> optRef = service.getSelectedRegion(player);
    if (!optRef.isPresent()) {
        player.sendMessage(Text.of(TextColors.RED, "You do not currently have a region selected."));
        return CommandResult.empty();
    }
    Region ref = optRef.get();
    PaginationService pagination = Sponge.getServiceManager().provideUnchecked(PaginationService.class);
    List<RegionPoint> points = ref.getPoints();
    List<Text> result = ref.getFullPoints().stream().map(a -> Text.of((points.contains(a) ? TextColors.GREEN : TextColors.RED), a.getFloorX(), ", ", a.getFloorY(), ", ", a.getFloorZ())).collect(Collectors.toList());
    pagination.builder().contents(result).title(Text.of(TextColors.GOLD, "Region Markers")).padding(Text.of(" ")).sendTo(src);
    return CommandResult.success();
}
Also used : RegionPoint(com.skelril.skree.service.internal.region.RegionPoint) CommandResult(org.spongepowered.api.command.CommandResult) CommandSource(org.spongepowered.api.command.CommandSource) Sponge(org.spongepowered.api.Sponge) PaginationService(org.spongepowered.api.service.pagination.PaginationService) Collectors(java.util.stream.Collectors) RegionService(com.skelril.skree.service.RegionService) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) CommandException(org.spongepowered.api.command.CommandException) List(java.util.List) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) CommandExecutor(org.spongepowered.api.command.spec.CommandExecutor) Region(com.skelril.skree.service.internal.region.Region) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) TextColors(org.spongepowered.api.text.format.TextColors) Player(org.spongepowered.api.entity.living.player.Player) Region(com.skelril.skree.service.internal.region.Region) RegionService(com.skelril.skree.service.RegionService) Text(org.spongepowered.api.text.Text) PaginationService(org.spongepowered.api.service.pagination.PaginationService) RegionPoint(com.skelril.skree.service.internal.region.RegionPoint)

Aggregations

CommandResult (org.spongepowered.api.command.CommandResult)62 Text (org.spongepowered.api.text.Text)46 CommandContext (org.spongepowered.api.command.args.CommandContext)40 List (java.util.List)39 CommandSource (org.spongepowered.api.command.CommandSource)37 Player (org.spongepowered.api.entity.living.player.Player)36 Sponge (org.spongepowered.api.Sponge)34 Optional (java.util.Optional)33 Collectors (java.util.stream.Collectors)33 Permissions (io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions)26 RegisterCommand (io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand)26 AbstractCommand (io.github.nucleuspowered.nucleus.internal.command.AbstractCommand)26 NonnullByDefault (org.spongepowered.api.util.annotation.NonnullByDefault)26 TextColors (org.spongepowered.api.text.format.TextColors)25 CommandElement (org.spongepowered.api.command.args.CommandElement)21 Util (io.github.nucleuspowered.nucleus.Util)20 GenericArguments (org.spongepowered.api.command.args.GenericArguments)20 NoModifiers (io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers)18 SuggestedLevel (io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel)18 CommandException (org.spongepowered.api.command.CommandException)18