Java Code Examples for com.sk89q.minecraft.util.commands.CommandContext#getString()

The following examples show how to use com.sk89q.minecraft.util.commands.CommandContext#getString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ModelCommands.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Command(
    aliases = "all",
    usage = "<model>",
    desc = "List all stored instances of a model",
    min = 1,
    max = 1
)
public List<String> all(CommandContext args, CommandSender sender) throws CommandException {
    final String modelName = args.getString(0, "");

    if(args.getSuggestionContext() != null) {
        return completeModel(modelName);
    }
    for(Model doc : parseModel(modelName).store().get().set()) {
        sender.sendMessage(new Component(doc._id() + " " + doc.toShortString()));
    }
    return null;
}
 
Example 2
Source File: ModelCommands.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Command(
    aliases = "refresh",
    usage = "<model>",
    desc = "Refresh a model store from the API",
    min = 1,
    max = 1
)
public List<String> refresh(CommandContext args, CommandSender sender) throws CommandException {
    final String modelName = args.getString(0, "");

    if(args.getSuggestionContext() != null) {
        return completeModel(modelName);
    }

    final ModelMeta<?, ?> model = parseModel(modelName);
    sender.sendMessage("Refreshing model " + model.name() + "...");
    syncExecutor.callback(
        model.store().get().refreshAll(),
        response -> sender.sendMessage("Refreshed " + response.documents().size() + " " + model.name() + " document(s)")
    );
    return null;
}
 
Example 3
Source File: PermissionCommands.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Command(
    aliases = {"test"},
    desc = "Test for a specific permission",
    usage = "<permission> [player]",
    min = 1,
    max = 2
)
public void test(CommandContext args, CommandSender sender) throws CommandException {
    CommandSender player = CommandUtils.getCommandSenderOrSelf(args, sender, 1);
    String perm = args.getString(0);
    if(player.hasPermission(perm)) {
        sender.sendMessage(ChatColor.GREEN + player.getName() + " has permission " + perm);
    } else {
        sender.sendMessage(ChatColor.RED + player.getName() + " does NOT have permission " + perm);
    }
}
 
Example 4
Source File: MojangSessionServiceCommands.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Command(
        aliases = {"session"},
        desc = "Session status control",
        usage = "[on|off|clear]",
        max = 1
)
@CommandPermissions("bungeecord.command.session")
public void session(final CommandContext args, CommandSender sender) throws CommandException {
    if (args.argsLength() == 1) {
        String arg = args.getString(0);
        SessionState newState = parseSessionStateCommand(arg);
        if (newState == null) throw new CommandException("Unknown session state command: " + arg);

        sender.sendMessage(new ComponentBuilder("Old Force Status: " + monitor.getForceState()).color(ChatColor.LIGHT_PURPLE).create());

        monitor.setForceState(newState);
    }

    sender.sendMessage(new ComponentBuilder("Current Force Status: " + monitor.getForceState()).color(ChatColor.GOLD).create());
    sender.sendMessage(new ComponentBuilder("Current Session Status: " + monitor.getDiscoveredState()).color(ChatColor.GOLD).create());
}
 
Example 5
Source File: TeamCommands.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Command(
    aliases = {"force"},
    desc = "Force a player onto a team",
    usage = "<player> [team]",
    min = 1,
    max = 2
)
@CommandPermissions("pgm.team.force")
public void force(CommandContext args, CommandSender sender) throws CommandException, SuggestException {
    MatchPlayer player = CommandUtils.findSingleMatchPlayer(args, sender, 0);

    if(args.argsLength() >= 2) {
        String name = args.getString(1);
        if(name.trim().toLowerCase().startsWith("obs")) {
            player.getMatch().setPlayerParty(player, player.getMatch().getDefaultParty());
        } else {
            Team team = utils.teamArgument(args, 1);
            utils.module().forceJoin(player, team);
        }
    } else {
        utils.module().forceJoin(player, null);
    }
}
 
Example 6
Source File: WhitelistCommands.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Command(
    aliases = {"remove"},
    desc = "Remove a player from the whitelist",
    usage = "<username>",
    min = 1,
    max = 1
)
public void remove(CommandContext args, final CommandSender sender) throws CommandException {
    final String username = args.getString(0);
    for(Iterator<PlayerId> iter = whitelist.iterator(); iter.hasNext();) {
        PlayerId playerId = iter.next();
        if(username.equalsIgnoreCase(playerId.username())) {
            iter.remove();
            audiences.get(sender).sendMessage(
                new TranslatableComponent(
                    "whitelist.remove",
                    new PlayerComponent(identities.currentIdentity(playerId), NameStyle.FANCY)
                )
            );
            return;
        }
    }
    throw new TranslatableCommandException("whitelist.notFound", username);
}
 
Example 7
Source File: ServerCommands.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Command(
        aliases = {"gserver"},
        desc = "Global server teleport",
        usage = "<server>",
        min = 1,
        max = 1
)
@CommandPermissions("bungeecord.command.server")
public void gserver(final CommandContext args, CommandSender sender) {
    if(sender instanceof ProxiedPlayer) {
        String name = args.getString(0);
        ServerInfo info = proxy.getServerInfo(name);
        if(info != null) {
            ((ProxiedPlayer) sender).connect(info);
            sender.sendMessage(new ComponentBuilder("Teleporting you to: ").color(ChatColor.GREEN).append(name).color(ChatColor.GOLD).create());
        } else {
            sender.sendMessage(new ComponentBuilder("Invalid server: ").color(ChatColor.RED).append(name).color(ChatColor.GOLD).create());
        }
    } else {
        sender.sendMessage(new ComponentBuilder("Only players may use this command").color(ChatColor.RED).create());
    }
}
 
Example 8
Source File: PermissionCommands.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Command(
    aliases = {"list"},
    desc = "List all permissions",
    usage = "[player] [prefix]",
    min = 0,
    max = 2
)
public void list(CommandContext args, CommandSender sender) throws CommandException {
    CommandSender player = CommandUtils.getCommandSenderOrSelf(args, sender, 0);
    String prefix = args.getString(1, "");

    sender.sendMessage(ChatColor.WHITE + "Permissions for " + player.getName() + ":");

    List<PermissionAttachmentInfo> perms = new ArrayList<>(player.getEffectivePermissions());
    Collections.sort(perms, new Comparator<PermissionAttachmentInfo>() {
        @Override
        public int compare(PermissionAttachmentInfo a, PermissionAttachmentInfo b) {
            return a.getPermission().compareTo(b.getPermission());
        }
    });

    for(PermissionAttachmentInfo perm : perms) {
        if(perm.getPermission().startsWith(prefix)) {
            sender.sendMessage((perm.getValue() ? ChatColor.GREEN : ChatColor.RED) +
                               "  " + perm.getPermission() +
                               (perm.getAttachment() == null ? "" : " (" + perm.getAttachment().getPlugin().getName() + ")"));
        }
    }
}
 
Example 9
Source File: NavigationCommands.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Command(
        aliases = {"jumpto", "j"},
        usage = "[world,x,y,z]",
        desc = "Teleport to a location" +
        		"Flags:\n" + 
        		"  -f forces the specified position to be used",
        flags = "f",
        min = 0,
        max = 1
)
@CommandPermissions("worldedit.navigation.jumpto.command")
public void jumpTo(Player player, LocalSession session, CommandContext args) throws WorldEditException {
    WorldVector pos;
    if (args.argsLength() == 1) {
        String arg = args.getString(0);
        String[] split = arg.split(",");
        World world = FaweAPI.getWorld(split[0]);
        if (world != null && split.length == 4 && MathMan.isInteger(split[1]) && MathMan.isInteger(split[2]) && MathMan.isInteger(split[3])) {
            pos = new WorldVector((LocalWorld) world, Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3]));
        } else {
            BBC.SELECTOR_INVALID_COORDINATES.send(player, args.getString(0));
            return;
        }
    } else {
        pos = player.getSolidBlockTrace(300);
    }
    if (pos != null) {
        if(args.hasFlag('f')) player.setPosition(pos); else player.findFreePosition(pos);
        BBC.POOF.send(player);
    } else {
        BBC.NO_BLOCK.send(player);
    }
}
 
Example 10
Source File: OptionsCommands.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Command(
        aliases = {"/fast"},
        usage = "[on|off]",
        desc = "Toggles FAWE undo",
        min = 0,
        max = 1
)
@CommandPermissions("worldedit.fast")
public void fast(Player player, LocalSession session, CommandContext args) throws WorldEditException {

    String newState = args.getString(0, null);
    if (session.hasFastMode()) {
        if ("on".equals(newState)) {
            BBC.FAST_ENABLED.send(player);
            return;
        }

        session.setFastMode(false);
        BBC.FAST_DISABLED.send(player);
    } else {
        if ("off".equals(newState)) {
            BBC.FAST_DISABLED.send(player);
            return;
        }

        session.setFastMode(true);
        BBC.FAST_ENABLED.send(player);
    }
}
 
Example 11
Source File: ScriptingCommands.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Command(aliases = {"cs"}, usage = "<filename> [args...]", desc = "Execute a CraftScript", min = 1, max = -1)
@CommandPermissions("worldedit.scripting.execute")
@Logging(ALL)
public void execute(final Player player, final LocalSession session, final CommandContext args) throws WorldEditException {
    final String[] scriptArgs = args.getSlice(1);
    final String name = args.getString(0);

    if (!player.hasPermission("worldedit.scripting.execute." + name)) {
        player.printError("You don't have permission to use that script.");
        return;
    }

    session.setLastScript(name);

    final File dir = this.worldEdit.getWorkingDirectoryFile(this.worldEdit.getConfiguration().scriptsDir);
    final File f = this.worldEdit.getSafeOpenFile(player, dir, name, "js", "js");
    try {
        new RhinoCraftScriptEngine();
    } catch (NoClassDefFoundError e) {
        player.printError("Failed to find an installed script engine.");
        player.printError("Download: https://github.com/downloads/mozilla/rhino/rhino1_7R4.zip");
        player.printError("Extract: `js.jar` to `plugins` or `mods` directory`");
        player.printError("More info: https://github.com/boy0001/CraftScripts/");
        return;
    }
    this.worldEdit.runScript(LocationMaskedPlayerWrapper.unwrap(player), f, scriptArgs);
}
 
Example 12
Source File: BrushOptionsCommands.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Command(
        aliases = {"/", ","},
        usage = "[on|off]",
        desc = "Toggle the super pickaxe function",
        min = 0,
        max = 1
)
@CommandPermissions("worldedit.superpickaxe")
public void togglePickaxe(Player player, LocalSession session, CommandContext args) throws WorldEditException {
    String newState = args.getString(0, null);
    if (session.hasSuperPickAxe()) {
        if ("on".equals(newState)) {
            BBC.SUPERPICKAXE_ENABLED.send(player);
            return;
        }

        session.disableSuperPickAxe();
        BBC.SUPERPICKAXE_DISABLED.send(player);
    } else {
        if ("off".equals(newState)) {

            BBC.SUPERPICKAXE_DISABLED.send(player);
            return;
        }
        session.enableSuperPickAxe();
        BBC.SUPERPICKAXE_ENABLED.send(player);
    }
}
 
Example 13
Source File: CommandUtils.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Get an online {@link Player} by partial name.
 * @throws CommandException if the name does not match any player, or matches multiple players
 */
public static Player findOnlinePlayer(CommandContext args, CommandSender sender, int index) throws CommandException {
    if(args.argsLength() > index) {
        String name = args.getString(index);
        List<Player> players = sender.getServer().matchPlayer(name, sender);
        switch(players.size()) {
            case 0: throw new CommandException(Translations.get().t("command.playerNotFound", sender));
            case 1: return players.get(0);
            default: throw new CommandException(Translations.get().t("command.multiplePlayersFound", sender));
        }
    } else {
        throw new CommandException(Translations.get().t("command.specifyPlayer", sender));
    }
}
 
Example 14
Source File: QueueCommands.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Command(
    aliases = {"ping"},
    desc = "Send a Ping message to the direct exchange, -r to wait for a reply",
    usage = "<routing key> [-s | -f | -e]",
    flags = "sfe",
    min = 1,
    max = 1
)
public void ping(CommandContext args, CommandSender sender) throws CommandException {
    final String routingKey = args.getString(0);
    final Audience audience = audiences.get(sender);

    audience.sendMessage("ping " + routingKey);

    final Ping.ReplyWith replyWith;
    if(args.hasFlag('s')) {
        replyWith = Ping.ReplyWith.success;
    } else if(args.hasFlag('f')) {
        replyWith = Ping.ReplyWith.failure;
    } else if(args.hasFlag('e')) {
        replyWith = Ping.ReplyWith.exception;
    } else {
        replyWith = null;
    }

    if(replyWith == null) {
        exchange.publishAsync(new Ping(), routingKey);
    } else {
        final Transaction<Reply> transaction = transactions.request(new Ping(replyWith), routingKey);
        syncExecutor.callback(
            transaction,
            CommandFutureCallback.onSuccess(sender, args, reply -> {
                audience.sendMessage(reply.getClass().getSimpleName() + String.format(" (%.3fms)", transaction.elapsedTimeMillis()));
            })
        );
    }
}
 
Example 15
Source File: MutationCommands.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public void set(CommandContext args, final CommandSender sender, final boolean value) throws CommandException {
    final MutationMatchModule module = verify(sender);
    final Match match = module.getMatch();
    String action = args.getString(0);
    // Mutations that *will* be added or removed
    final Collection<Mutation> mutations = new HashSet<>();
    // Mutations that *are allowed* to be added or removed
    final Collection<Mutation> availableMutations = Sets.newHashSet(Mutation.values());

    final Collection<Mutation> queue = mutationQueue.mutations();
    if(value) availableMutations.removeAll(queue); else availableMutations.retainAll(queue);
    // Check if all mutations have been enabled/disabled
    if((queue.size() == Mutation.values().length && value) || (queue.isEmpty() && !value)) {
        throw newCommandException(sender, new TranslatableComponent(value ? "command.mutation.error.enabled" : "command.mutation.error.disabled"));
    }
    // Get which action the user wants to preform
    switch (action) {
        case "*": mutations.addAll(availableMutations); break;
        case "?": mutations.add(Iterables.get(availableMutations, RandomUtils.safeNextInt(match.getRandom(), availableMutations.size()))); break;
        default:
            Mutation query = StringUtils.bestFuzzyMatch(action, Sets.newHashSet(Mutation.values()), 0.9);
            if (query == null) {
                throw newCommandException(sender, new TranslatableComponent("command.mutation.error.find", action));
            } else {
                mutations.add(query);
            }
    }

    // Send the queued changes off to the api
    syncExecutor.callback(
        value ? mutationQueue.mergeAll(mutations)
              : mutationQueue.removeAll(mutations),
        result -> {
            audiences.get(sender).sendMessage(new Component(new TranslatableComponent(
                message(false, value, mutations.size() == 1),
                new ListComponent(Collections2.transform(mutations, Mutation.toComponent(ChatColor.AQUA)))
            ), ChatColor.WHITE));
        }
    );
}
 
Example 16
Source File: MapDevelopmentCommands.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Command(
    aliases = {"environment", "env"},
    desc = "Get/set map environment variables"
)
@CommandPermissions(Permissions.MAPDEV)
public void environment(CommandContext args, final CommandSender sender) throws CommandException {
    final Audience audience = audiences.get(sender);

    boolean reset = false;
    Map<String, Boolean> vars = new HashMap<>();
    Pattern pattern = Pattern.compile("([A-Za-z0-9_]+)=(true|false)");

    for(int i = 0; i < args.argsLength(); i++) {
        String arg = args.getString(i);
        if("reset".equals(arg)) {
            reset = true;
        } else {
            Matcher matcher = pattern.matcher(arg);
            if(!matcher.matches()) {
                throw new CommandException("Can't understand variable assignment '" + arg + "'");
            }
            vars.put(matcher.group(1).toLowerCase(), "true".equals(matcher.group(2)));
        }
    }

    if(reset) mapEnvironment.clear();
    mapEnvironment.putAll(vars);

    for(Map.Entry<String, Boolean> entry : mapEnvironment.entrySet()) {
        audience.sendMessage(
            new Component(ChatColor.GRAY)
                .extra(new Component(entry.getKey(), ChatColor.WHITE))
                .extra("=")
                .extra(new Component(String.valueOf(entry.getValue()), ChatColor.BLUE))
        );
    }
}
 
Example 17
Source File: SchematicCommands.java    From FastAsyncWorldedit with GNU General Public License v3.0 4 votes vote down vote up
@Command(aliases = {"move", "m"}, usage = "<directory>", desc = "Move your loaded schematic", help = "Move your currently loaded schematics", min = 1, max = 1)
@CommandPermissions({"worldedit.schematic.move", "worldedit.schematic.move.other"})
public void move(final Player player, final LocalSession session, final CommandContext args) throws WorldEditException, IOException {
    final LocalConfiguration config = this.worldEdit.getConfiguration();
    final File working = this.worldEdit.getWorkingDirectoryFile(config.saveDir);
    final File dir = Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS ? new File(working, player.getUniqueId().toString()) : working;
    File destDir = new File(dir, args.getString(0));
    if (!MainUtil.isInSubDirectory(working, destDir)) {
        player.printError("Directory " + destDir + " does not exist!");
        return;
    }
    if (Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS && !MainUtil.isInSubDirectory(dir, destDir) && !player.hasPermission("worldedit.schematic.move.other")) {
        BBC.NO_PERM.send(player, "worldedit.schematic.move.other");
        return;
    }
    ClipboardHolder clipboard = session.getClipboard();
    List<File> sources = getFiles(clipboard);
    if (sources.isEmpty()) {
        BBC.SCHEMATIC_NONE.send(player);
        return;
    }
    if (!destDir.exists() && !destDir.mkdirs()) {
        player.printError("Creation of " + destDir + " failed! (check file permissions)");
        return;
    }
    for (File source : sources) {
        File destFile = new File(destDir, source.getName());
        if (destFile.exists()) {
            BBC.SCHEMATIC_MOVE_EXISTS.send(player, destFile);
            continue;
        }
        if (Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS && (!MainUtil.isInSubDirectory(dir, destFile) || !MainUtil.isInSubDirectory(dir, source)) && !player.hasPermission("worldedit.schematic.delete.other")) {
            BBC.SCHEMATIC_MOVE_FAILED.send(player, destFile, BBC.NO_PERM.f("worldedit.schematic.move.other"));
            continue;
        }
        try {
            File cached = new File(source.getParentFile(), "." + source.getName() + ".cached");
            Files.move(source.toPath(), destFile.toPath());
            if (cached.exists()) Files.move(cached.toPath(), destFile.toPath());
            BBC.SCHEMATIC_MOVE_SUCCESS.send(player, source, destFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 18
Source File: SnapshotCommands.java    From FastAsyncWorldedit with GNU General Public License v3.0 4 votes vote down vote up
@Command(
        aliases = {"use"},
        usage = "<snapshot>",
        desc = "Choose a snapshot to use",
        min = 1,
        max = 1
)
@CommandPermissions("worldedit.snapshots.restore")
public void use(Player player, LocalSession session, CommandContext args) throws WorldEditException {

    LocalConfiguration config = we.getConfiguration();

    if (config.snapshotRepo == null) {
        player.printError("Snapshot/backup restore is not configured.");
        return;
    }

    String name = args.getString(0);

    // Want the latest snapshot?
    if (name.equalsIgnoreCase("latest")) {
        try {
            Snapshot snapshot = config.snapshotRepo.getDefaultSnapshot(player.getWorld().getName());

            if (snapshot != null) {
                session.setSnapshot(null);
                BBC.SNAPSHOT_NEWEST.send(player);
            } else {
                player.printError("No snapshots were found.");
            }
        } catch (MissingWorldException ex) {
            player.printError("No snapshots were found for this world.");
        }
    } else {
        try {
            session.setSnapshot(config.snapshotRepo.getSnapshot(name));
            BBC.SNAPSHOT_SET.send(player, name);
        } catch (InvalidSnapshotException e) {
            player.printError("That snapshot does not exist or is not available.");
        }
    }
}
 
Example 19
Source File: NicknameCommands.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
@Command(aliases = {"nick" },
         usage = "list | show [player] | set <nickname> [player] | clear [player] | <nickname> [player]",
         desc = "Show, set, or clear a nickname for yourself or another player. " +
                "Changes will take effect the next time the player " +
                "connects to the server. The -i option makes the change " +
                "visible immediately.",
         flags = "i",
         min = 0,
         max = 3)
@CommandPermissions(PERMISSION)
public void nick(final CommandContext args, final CommandSender sender) throws CommandException {
    if(!config.enabled()) {
        throw new CommandException(Translations.get().t("command.nick.notEnabled", sender));
    }

    final boolean immediate = args.hasFlag('i');

    if(args.argsLength() == 0) {
        show(sender, null);
    } else {
        final String arg = args.getString(0);
        switch(arg) {
            case "list":
                list(sender);
                break;

            case "show":
                show(sender, args.getString(1, null));
                break;

            case "set":
                if(args.argsLength() < 2) CommandUtils.notEnoughArguments(sender);
                set(sender, args.getString(1), args.getString(2, null), immediate);
                break;

            case "clear":
                set(sender, null, args.getString(1, null), immediate);
                break;

            default:
                set(sender, arg, args.getString(1, null), immediate);
                break;
        }
    }
}