Search in sources :

Example 31 with CommandContext

use of org.spongepowered.api.command.args.CommandContext in project AtherysCore by Atherys-Horizons.

the class PartyInviteCommand method execute.

@Nonnull
@Override
public CommandResult execute(@Nonnull User user, @Nonnull CommandContext args) throws CommandException {
    Optional<Player> invitee = args.getOne("invitedPlayer");
    if (!invitee.isPresent())
        return CommandResult.empty();
    // if invitee is already in another party, don't invite
    if (PartyManager.getInstance().hasPlayerParty(invitee.get())) {
        PartyMsg.error(user, "That player is already in another party.");
        return CommandResult.success();
    }
    Optional<Party> playerParty = PartyManager.getInstance().getPlayerParty(user);
    if (playerParty.isPresent() && playerParty.get().isLeader(user)) {
        // If player has party and is leader of that party, invitee will be invited to player's party
        Party party = playerParty.get();
        Question q = Question.of(Text.of(user.getName(), " has invited you to their party. Would you like to join?")).addAnswer(Question.Answer.of(Text.of(TextStyles.BOLD, TextColors.DARK_GREEN, "Yes"), (respondent) -> {
            party.addPlayer(respondent);
            PartyMsg.info(party, respondent.getName(), " has joined your party!");
        })).addAnswer(Question.Answer.of(Text.of(TextStyles.BOLD, TextColors.DARK_RED, "No"), (respondent) -> PartyMsg.error(user, respondent.getName(), " has refused to join your party."))).build();
        q.pollChat(invitee.get());
    } else {
        // If player does not have a party, and neither does invitee, then the party will be created when invitee accepts party invite
        Question q = Question.of(Text.of(user.getName(), " has invited you to their party. Would you like to join?")).addAnswer(Question.Answer.of(Text.of(TextStyles.BOLD, TextColors.DARK_GREEN, "Yes"), (respondent) -> {
            if (!user.isOnline()) {
                // If when party invite is accepted, player is offline, party will not be created.
                PartyMsg.error(respondent, user.getName(), " has gone offline since sending you that invite. Party could not be created. Sorry!");
                return;
            }
            Party party = Party.of(user, invitee.get());
            PartyMsg.info(party, "Your party has been created! Do ", TextColors.GREEN, TextStyles.BOLD, "/party", TextColors.DARK_AQUA, TextStyles.RESET, " for a list of members.");
        })).addAnswer(Question.Answer.of(Text.of(TextStyles.BOLD, TextColors.DARK_RED, "No"), (respondent) -> PartyMsg.error(user, respondent.getName(), " has refused to join your party."))).build();
        q.pollChat(invitee.get());
    }
    return CommandResult.success();
}
Also used : Party(com.atherys.core.party.Party) CommandResult(org.spongepowered.api.command.CommandResult) User(org.spongepowered.api.entity.living.player.User) TextStyles(org.spongepowered.api.text.format.TextStyles) Question(com.atherys.core.utils.Question) GenericArguments(org.spongepowered.api.command.args.GenericArguments) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) CommandException(org.spongepowered.api.command.CommandException) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) PartyManager(com.atherys.core.party.PartyManager) UserCommand(com.atherys.core.commands.UserCommand) Optional(java.util.Optional) PartyMsg(com.atherys.core.party.PartyMsg) Player(org.spongepowered.api.entity.living.player.Player) TextColors(org.spongepowered.api.text.format.TextColors) Nonnull(javax.annotation.Nonnull) Player(org.spongepowered.api.entity.living.player.Player) Party(com.atherys.core.party.Party) Question(com.atherys.core.utils.Question) Nonnull(javax.annotation.Nonnull)

Example 32 with CommandContext

use of org.spongepowered.api.command.args.CommandContext in project LanternServer by LanternPowered.

the class CommandSetData method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    final ThreadLocal<Key<?>> currentKey = new ThreadLocal<>();
    specBuilder.arguments(GenericArguments.playerOrSource(Text.of("player")), new PatternMatchingCommandElement(Text.of("key")) {

        @Override
        protected Iterable<String> getChoices(CommandSource source) {
            return Sponge.getGame().getRegistry().getAllOf(Key.class).stream().map(Key::getId).collect(Collectors.toList());
        }

        @Override
        protected Object getValue(String choice) throws IllegalArgumentException {
            final Optional<Key> ret = Sponge.getGame().getRegistry().getType(Key.class, choice);
            if (!ret.isPresent()) {
                throw new IllegalArgumentException("Invalid input " + choice + " was found");
            }
            currentKey.set(ret.get());
            return ret.get();
        }
    }, new CommandElement(Text.of("data")) {

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            args.next();
            final String content = args.getRaw().substring(args.getRawPosition()).trim();
            while (args.hasNext()) {
                args.next();
            }
            final Object data;
            try {
                // Don't be too strict
                data = JsonDataFormat.read(content, true).orElse(null);
            } catch (IOException e) {
                throw args.createError(t("Invalid json data: %s\nError: %s", content, e.getMessage()));
            }
            final Key key = currentKey.get();
            final TypeToken<?> typeToken = key.getElementToken();
            if (content.isEmpty()) {
                return null;
            }
            final DataTypeSerializer dataTypeSerializer = Lantern.getGame().getDataManager().getTypeSerializer(typeToken).orElse(null);
            if (dataTypeSerializer == null) {
                throw args.createError(Text.of("Unable to deserialize the data key value: {}, " + "no supported deserializer exists.", key.getId()));
            } else {
                final DataTypeSerializerContext context = Lantern.getGame().getDataManager().getTypeSerializerContext();
                try {
                    // Put it in a holder object, the command element separates iterable objects
                    return new ValueHolder(dataTypeSerializer.deserialize(typeToken, context, data));
                } catch (InvalidDataException e) {
                    throw args.createError(t("Invalid data: %s", e.getMessage()));
                }
            }
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            return new ArrayList<>();
        }
    }).executor((src, args) -> {
        final Player target = args.<Player>getOne("player").get();
        final Key key = args.<Key>getOne("key").get();
        final Object data = args.<ValueHolder>getOne("data").get().data;
        target.offer(key, data);
        src.sendMessage(t("Successfully offered the data for the key %s to the player %s", key.getId(), target.getName()));
        return CommandResult.success();
    });
}
Also used : CommandArgs(org.spongepowered.api.command.args.CommandArgs) Player(org.spongepowered.api.entity.living.player.Player) CommandContext(org.spongepowered.api.command.args.CommandContext) DataTypeSerializerContext(org.lanternpowered.server.data.persistence.DataTypeSerializerContext) ArrayList(java.util.ArrayList) IOException(java.io.IOException) CommandSource(org.spongepowered.api.command.CommandSource) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) InvalidDataException(org.spongepowered.api.data.persistence.InvalidDataException) CommandElement(org.spongepowered.api.command.args.CommandElement) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) Key(org.spongepowered.api.data.key.Key)

Example 33 with CommandContext

use of org.spongepowered.api.command.args.CommandContext in project LanternServer by LanternPowered.

the class CommandOp method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    specBuilder.arguments(new CommandElement(Text.of("player")) {

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            return args.next();
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            final String prefix = args.nextIfPresent().orElse("");
            final UserConfig<OpsEntry> config = Lantern.getGame().getOpsConfig();
            return Lantern.getGame().getGameProfileManager().getCache().getProfiles().stream().filter(p -> p.getName().isPresent() && !config.getEntryByUUID(p.getUniqueId()).isPresent()).map(p -> p.getName().get()).filter(new StartsWithPredicate(prefix)).collect(ImmutableList.toImmutableList());
        }
    }, GenericArguments.optional(GenericArguments.integer(Text.of("level")))).executor((src, args) -> {
        String playerName = args.<String>getOne("player").get();
        UserConfig<OpsEntry> config = Lantern.getGame().getOpsConfig();
        if (!(src instanceof ConsoleSource) && args.hasAny("level")) {
            throw new CommandException(Text.of("Only the console may specify the op level."));
        }
        int opLevel = args.<Integer>getOne("level").orElse(Lantern.getGame().getGlobalConfig().getDefaultOpPermissionLevel());
        Lantern.getGame().getGameProfileManager().get(playerName).whenComplete((profile, error) -> {
            if (error != null) {
                src.sendMessage(t("commands.op.failed", playerName));
            } else {
                src.sendMessage(t("commands.op.success", playerName));
                config.addEntry(new OpsEntry(((LanternGameProfile) profile).withoutProperties(), opLevel));
            }
        });
        return CommandResult.success();
    });
}
Also used : CommandArgs(org.spongepowered.api.command.args.CommandArgs) CommandResult(org.spongepowered.api.command.CommandResult) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) TranslationHelper.t(org.lanternpowered.server.text.translation.TranslationHelper.t) CommandSource(org.spongepowered.api.command.CommandSource) OpsEntry(org.lanternpowered.server.config.user.OpsEntry) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandArgs(org.spongepowered.api.command.args.CommandArgs) CommandElement(org.spongepowered.api.command.args.CommandElement) GenericArguments(org.spongepowered.api.command.args.GenericArguments) LanternGameProfile(org.lanternpowered.server.profile.LanternGameProfile) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) CommandException(org.spongepowered.api.command.CommandException) UserConfig(org.lanternpowered.server.config.user.UserConfig) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) Lantern(org.lanternpowered.server.game.Lantern) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) PluginContainer(org.spongepowered.api.plugin.PluginContainer) Nullable(javax.annotation.Nullable) CommandContext(org.spongepowered.api.command.args.CommandContext) LanternGameProfile(org.lanternpowered.server.profile.LanternGameProfile) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) CommandException(org.spongepowered.api.command.CommandException) CommandSource(org.spongepowered.api.command.CommandSource) OpsEntry(org.lanternpowered.server.config.user.OpsEntry) CommandElement(org.spongepowered.api.command.args.CommandElement) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource)

Example 34 with CommandContext

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

the class PrintPermsCommand method executeCommand.

@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
    Map<String, PermissionInformation> l = plugin.getPermissionRegistry().getPermissions();
    List<String> notsuggested = l.entrySet().stream().filter(x -> x.getValue().level == SuggestedLevel.NONE).map(Map.Entry::getKey).collect(Collectors.toList());
    List<String> owner = l.entrySet().stream().filter(x -> x.getValue().level == SuggestedLevel.NONE).map(Map.Entry::getKey).collect(Collectors.toList());
    List<String> admin = l.entrySet().stream().filter(x -> x.getValue().level == SuggestedLevel.ADMIN).map(Map.Entry::getKey).collect(Collectors.toList());
    List<String> mod = l.entrySet().stream().filter(x -> x.getValue().level == SuggestedLevel.MOD).map(Map.Entry::getKey).collect(Collectors.toList());
    List<String> user = l.entrySet().stream().filter(x -> x.getValue().level == SuggestedLevel.USER).map(Map.Entry::getKey).collect(Collectors.toList());
    String file = "plugin-perms.txt";
    BufferedWriter f = new BufferedWriter(new FileWriter(file));
    Consumer<String> permWriter = x -> {
        try {
            f.write(x);
            f.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    };
    f.write("Not Suggested");
    f.write("-----");
    f.newLine();
    notsuggested.stream().sorted().forEach(permWriter);
    f.newLine();
    f.write("Owner");
    f.write("-----");
    f.newLine();
    owner.stream().sorted().forEach(permWriter);
    f.newLine();
    f.write("Admin");
    f.write("-----");
    f.newLine();
    admin.stream().sorted().forEach(permWriter);
    f.newLine();
    f.write("Mod");
    f.write("-----");
    f.newLine();
    mod.stream().sorted().forEach(permWriter);
    f.newLine();
    f.write("User");
    f.write("-----");
    f.newLine();
    user.stream().sorted().forEach(permWriter);
    f.flush();
    f.close();
    src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.printperms", file));
    return CommandResult.success();
}
Also used : NoModifiers(io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers) CommandResult(org.spongepowered.api.command.CommandResult) RegisterCommand(io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand) CommandSource(org.spongepowered.api.command.CommandSource) BufferedWriter(java.io.BufferedWriter) PermissionInformation(io.github.nucleuspowered.nucleus.internal.permissions.PermissionInformation) FileWriter(java.io.FileWriter) NonnullByDefault(org.spongepowered.api.util.annotation.NonnullByDefault) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) RunAsync(io.github.nucleuspowered.nucleus.internal.annotations.RunAsync) Consumer(java.util.function.Consumer) List(java.util.List) AbstractCommand(io.github.nucleuspowered.nucleus.internal.command.AbstractCommand) CommandContext(org.spongepowered.api.command.args.CommandContext) Map(java.util.Map) SuggestedLevel(io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel) Permissions(io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions) FileWriter(java.io.FileWriter) IOException(java.io.IOException) Map(java.util.Map) PermissionInformation(io.github.nucleuspowered.nucleus.internal.permissions.PermissionInformation) BufferedWriter(java.io.BufferedWriter)

Example 35 with CommandContext

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

the class KitListCommand method executeCommand.

@Override
public CommandResult executeCommand(final CommandSource src, CommandContext args) throws Exception {
    Set<String> kits = KIT_HANDLER.getKitNames();
    if (kits.isEmpty()) {
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.kit.list.empty"));
        return CommandResult.empty();
    }
    PaginationService paginationService = Sponge.getServiceManager().provideUnchecked(PaginationService.class);
    ArrayList<Text> kitText = Lists.newArrayList();
    final KitUserDataModule user = src instanceof Player ? Nucleus.getNucleus().getUserDataManager().getUnchecked(((Player) src).getUniqueId()).get(KitUserDataModule.class) : null;
    final boolean showHidden = kitPermissionHandler.testSuffix(src, "showhidden");
    Stream<String> kitStream = KIT_HANDLER.getKitNames(showHidden).stream();
    if (this.isSeparatePermissions) {
        kitStream = kitStream.filter(kit -> src.hasPermission(KitHandler.getPermissionForKit(kit.toLowerCase())));
    }
    kitStream.forEach(kit -> kitText.add(createKit(src, user, kit, KIT_HANDLER.getKit(kit).get())));
    PaginationList.Builder paginationBuilder = paginationService.builder().contents(kitText).title(plugin.getMessageProvider().getTextMessageWithFormat("command.kit.list.kits")).padding(Text.of(TextColors.GREEN, "-"));
    paginationBuilder.sendTo(src);
    return CommandResult.success();
}
Also used : KitUserDataModule(io.github.nucleuspowered.nucleus.modules.kit.datamodules.KitUserDataModule) RegisterCommand(io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand) Kit(io.github.nucleuspowered.nucleus.api.nucleusdata.Kit) NonnullByDefault(org.spongepowered.api.util.annotation.NonnullByDefault) KitFallbackBase(io.github.nucleuspowered.nucleus.modules.kit.commands.KitFallbackBase) RunAsync(io.github.nucleuspowered.nucleus.internal.annotations.RunAsync) ArrayList(java.util.ArrayList) PaginationList(org.spongepowered.api.service.pagination.PaginationList) Lists(com.google.common.collect.Lists) KitUserDataModule(io.github.nucleuspowered.nucleus.modules.kit.datamodules.KitUserDataModule) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) Duration(java.time.Duration) SuggestedLevel(io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel) Util(io.github.nucleuspowered.nucleus.Util) Permissions(io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions) TextColors(org.spongepowered.api.text.format.TextColors) Nullable(javax.annotation.Nullable) NoModifiers(io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers) CommandPermissionHandler(io.github.nucleuspowered.nucleus.internal.CommandPermissionHandler) CommandResult(org.spongepowered.api.command.CommandResult) KitHandler(io.github.nucleuspowered.nucleus.modules.kit.handlers.KitHandler) TextActions(org.spongepowered.api.text.action.TextActions) Nucleus(io.github.nucleuspowered.nucleus.Nucleus) CommandSource(org.spongepowered.api.command.CommandSource) TextStyles(org.spongepowered.api.text.format.TextStyles) Sponge(org.spongepowered.api.Sponge) Set(java.util.Set) PaginationService(org.spongepowered.api.service.pagination.PaginationService) Instant(java.time.Instant) Reloadable(io.github.nucleuspowered.nucleus.internal.interfaces.Reloadable) Stream(java.util.stream.Stream) Player(org.spongepowered.api.entity.living.player.Player) KitConfigAdapter(io.github.nucleuspowered.nucleus.modules.kit.config.KitConfigAdapter) Player(org.spongepowered.api.entity.living.player.Player) PaginationList(org.spongepowered.api.service.pagination.PaginationList) Text(org.spongepowered.api.text.Text) PaginationService(org.spongepowered.api.service.pagination.PaginationService)

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