コード例 #1
0
  @Command(
      aliases = {"/paste"},
      usage = "",
      flags = "ao",
      desc = "Вставляет содержимое буфера обмена",
      help =
          "Вставить содержимое буфера обмена.\n"
              + "Флаги:\n"
              + "  -a пропускает блоки воздуха\n"
              + "  -o вставляет на позициях, которые были скопированы/вырезаны",
      min = 0,
      max = 0)
  @CommandPermissions("worldedit.clipboard.paste")
  @Logging(PLACEMENT)
  public void paste(
      CommandContext args, LocalSession session, LocalPlayer player, EditSession editSession)
      throws WorldEditException {

    boolean atOrigin = args.hasFlag('o');
    boolean pasteNoAir = args.hasFlag('a');

    if (atOrigin) {
      Vector pos = session.getClipboard().getOrigin();
      session.getClipboard().place(editSession, pos, pasteNoAir);
      session.getClipboard().pasteEntities(pos);
      player.findFreePosition();
      player.print("Вставлено. Для отмены напишите //undo");
    } else {
      Vector pos = session.getPlacementPosition(player);
      session.getClipboard().paste(editSession, pos, pasteNoAir, true);
      player.findFreePosition();
      player.print("Вставлено. Для отмены напишите //undo");
    }
  }
コード例 #2
0
  @Command(
      aliases = {"delete"},
      desc = "Lists the areas of the given namespace or lists all areas.",
      usage = "[-n namespace] [area]",
      flags = "an:")
  public void delete(CommandContext context, CommandSender sender) throws CommandException {

    if (!(sender instanceof Player)) return;
    LocalPlayer player = plugin.wrapPlayer((Player) sender);

    String namespace = "~" + player.getName();
    String areaId = null;

    // Get the namespace
    if (context.hasFlag('n')
        && player.hasPermission("craftbook.mech.area.delete." + context.getFlag('n'))) {
      namespace = context.getFlag('n');
    } else if (!player.hasPermission("craftbook.mech.area.delete.self"))
      throw new CommandPermissionsException();

    if (plugin.getConfiguration().areaShortenNames && namespace.length() > 14)
      namespace = namespace.substring(0, 14);

    boolean deleteAll = false;
    if (context.argsLength() > 0 && !context.hasFlag('a')) {
      areaId = context.getString(0);
    } else if (context.hasFlag('a')
        && player.hasPermission("craftbook.mech.area.delete." + namespace + ".all")) {
      deleteAll = true;
    } else throw new CommandException("You need to define an area or -a to delete all areas.");

    // add the area suffix
    areaId = areaId + (config.areaUseSchematics ? ".schematic" : ".cbcopy");

    File areas = null;
    try {
      areas = new File(plugin.getDataFolder(), "areas/" + namespace);
    } catch (Exception ignored) {
    }

    if (areas == null || !areas.exists())
      throw new CommandException("The namespace " + namespace + " does not exist.");

    if (deleteAll) {
      if (deleteDir(areas)) {
        player.print("All areas in the namespace " + namespace + " have been deleted.");
      }
    } else {
      File file = new File(areas, areaId);
      if (file.delete()) {
        player.print(
            "The area '" + areaId + " in the namespace '" + namespace + "' has been deleted.");
      }
    }
  }
コード例 #3
0
  @Command(
      aliases = "toggle",
      desc = "Toggle an area sign at the given location.",
      usage = "[-w world] <x,y,z>",
      flags = "sw:",
      min = 1)
  @CommandPermissions("craftbook.mech.area.command.toggle")
  public void toggle(CommandContext context, CommandSender sender) throws CommandException {

    World world = null;
    boolean hasWorldFlag = context.hasFlag('w');

    if (hasWorldFlag) {
      world = Bukkit.getWorld(context.getFlag('w'));
    } else if (sender instanceof Player) {
      world = ((Player) sender).getWorld();
    }

    if (world == null) {
      throw new CommandException(
          "You must be a player or specify a valid world to use this command.");
    }

    int[] xyz = new int[3];
    String[] loc = context.getString(0).split(",");

    if (loc.length != 3) {
      throw new CommandException("Invalid location specified.");
    }

    try {
      for (int i = 0; i < xyz.length; i++) {
        xyz[i] = Integer.parseInt(loc[i]);
      }
    } catch (NumberFormatException ex) {
      throw new CommandException("Invalid location specified.");
    }

    Block block = world.getBlockAt(xyz[0], xyz[1], xyz[2]);
    if (!SignUtil.isSign(block))
      throw new CommandException("No sign found at the specified location.");

    if (!Area.toggleCold(BukkitUtil.toChangedSign(block))) {
      throw new CommandException("Failed to toggle an area at the specified location.");
    }
    // TODO Make a sender wrap for this
    if (!context.hasFlag('s')) sender.sendMessage(ChatColor.YELLOW + "Area toggled!");
  }
コード例 #4
0
  @Command(
      aliases = {"/smooth"},
      usage = "[iterations]",
      flags = "n",
      desc = "Smooth the elevation in the selection",
      min = 0,
      max = 1)
  @CommandPermissions("worldedit.region.smooth")
  @Logging(REGION)
  public static void smooth(
      CommandContext args,
      WorldEdit we,
      LocalSession session,
      LocalPlayer player,
      EditSession editSession)
      throws WorldEditException {

    int iterations = 1;
    if (args.argsLength() > 0) {
      iterations = args.getInteger(0);
    }

    HeightMap heightMap =
        new HeightMap(editSession, session.getSelection(player.getWorld()), args.hasFlag('n'));
    HeightMapFilter filter = new HeightMapFilter(new GaussianKernel(5, 1.0));
    int affected = heightMap.applyFilter(filter, iterations);
    player.print("Terrain's height map smoothed. " + affected + " block(s) changed.");
  }
コード例 #5
0
    @Command(
        aliases = {"banip", "ipban"},
        usage = "<target> [reason...]",
        desc = "Ban an IP address",
        flags = "st:",
        min = 1,
        max = -1)
    @CommandPermissions({"commandbook.bans.ban.ip"})
    public void banIP(CommandContext args, CommandSender sender) throws CommandException {

      String message = args.argsLength() >= 2 ? args.getJoinedStrings(1) : "Banned!";
      long endDate = args.hasFlag('t') ? CommandBookUtil.matchFutureDate(args.getFlag('t')) : 0L;

      String addr =
          args.getString(0).replace("\r", "").replace("\n", "").replace("\0", "").replace("\b", "");

      // Need to kick + log
      for (Player player : CommandBook.server().getOnlinePlayers()) {
        if (player.getAddress().getAddress().getHostAddress().equals(addr)) {
          player.kickPlayer(message);
          getBanDatabase().logKick(player, sender, message);
        }
      }

      getBanDatabase().ban(null, addr, sender, message, endDate);

      sender.sendMessage(ChatColor.YELLOW + addr + " banned.");

      if (!getBanDatabase().save()) {
        sender.sendMessage(ChatColor.RED + "Bans database failed to save. See console.");
      }
    }
コード例 #6
0
  @Command(
      aliases = {"/copy"},
      flags = "e",
      desc = "Копирует выделенную территорию в буфер обмена",
      help =
          "Копирует выделенную территорию в буфер обмен\n"
              + "Флаги:\n"
              + "  -e определяет, будут ли объекты копироваться в буфер обмена\n"
              + "ПРЕДУПРЕЖДЕНИЕ: Вставленные объекты не могут быть отменены!",
      min = 0,
      max = 0)
  @CommandPermissions("worldedit.clipboard.copy")
  public void copy(
      CommandContext args, LocalSession session, LocalPlayer player, EditSession editSession)
      throws WorldEditException {

    Region region = session.getSelection(player.getWorld());
    Vector min = region.getMinimumPoint();
    Vector max = region.getMaximumPoint();
    Vector pos = session.getPlacementPosition(player);

    CuboidClipboard clipboard =
        new CuboidClipboard(max.subtract(min).add(new Vector(1, 1, 1)), min, min.subtract(pos));
    clipboard.copy(editSession);
    if (args.hasFlag('e')) {
      for (LocalEntity entity : player.getWorld().getEntities(region)) {
        clipboard.storeEntity(entity);
      }
    }
    session.setClipboard(clipboard);

    player.print("Блок(и) скопирован(ы).");
  }
コード例 #7
0
    @Command(
        aliases = {"kick"},
        usage = "<target> [reason...]",
        desc = "Kick a user",
        flags = "os",
        min = 1,
        max = -1)
    @CommandPermissions({"commandbook.kick"})
    public void kick(CommandContext args, CommandSender sender) throws CommandException {
      Iterable<Player> targets = PlayerUtil.matchPlayers(sender, args.getString(0));
      String message = args.argsLength() >= 2 ? args.getJoinedStrings(1) : "Kicked!";

      String broadcastPlayers = "";
      for (Player player : targets) {
        if (CommandBook.inst().hasPermission(player, "commandbook.kick.exempt")
            && !(args.hasFlag('o')
                && CommandBook.inst().hasPermission(sender, "commandbook.kick.exempt.override"))) {
          sender.sendMessage(
              ChatColor.RED
                  + "Player "
                  + player.getName()
                  + ChatColor.RED
                  + " is exempt from being kicked!");
          continue;
        }
        player.kickPlayer(message);
        broadcastPlayers += PlayerUtil.toColoredName(player, ChatColor.YELLOW) + " ";
        getBanDatabase().logKick(player, sender, message);
      }

      if (broadcastPlayers.length() > 0) {
        sender.sendMessage(ChatColor.YELLOW + "Player(s) kicked.");
        // Broadcast the Message
        if (config.broadcastKicks && !args.hasFlag('s')) {
          BasePlugin.server()
              .broadcastMessage(
                  ChatColor.YELLOW
                      + PlayerUtil.toColoredName(sender, ChatColor.YELLOW)
                      + " has kicked "
                      + broadcastPlayers
                      + " - "
                      + message);
        }
      }
    }
コード例 #8
0
  @Command(
      aliases = {"/stack"},
      usage = "[count] [direction]",
      flags = "sa",
      desc = "Repeat the contents of the selection",
      min = 0,
      max = 2)
  @CommandPermissions("worldedit.region.stack")
  @Logging(ORIENTATION_REGION)
  public static void stack(
      CommandContext args,
      WorldEdit we,
      LocalSession session,
      LocalPlayer player,
      EditSession editSession)
      throws WorldEditException {

    int count = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 1;
    Vector dir =
        we.getDiagonalDirection(
            player, args.argsLength() > 1 ? args.getString(1).toLowerCase() : "me");

    int affected =
        editSession.stackCuboidRegion(
            session.getSelection(player.getWorld()), dir, count, !args.hasFlag('a'));

    if (args.hasFlag('s')) {
      try {
        Region region = session.getSelection(player.getWorld());
        region.expand(dir.multiply(count));
        region.contract(dir.multiply(count));

        session.getRegionSelector().learnChanges();
        session.getRegionSelector().explainRegionAdjust(player, session);
      } catch (RegionOperationException e) {
        player.printError(e.getMessage());
      }
    }

    player.print(affected + " blocks changed. Undo with //undo");
  }
コード例 #9
0
  @Command(
      aliases = {"/cut"},
      usage = "[leave-id]",
      desc = "Вырезает выделенную территорию в буфер обмена",
      help =
          "Вырезает выделенную территорию в буфер обмена\n"
              + "Флаги:\n"
              + "  -e controls определяет, будут ли объекты копироваться в буфер обмена\n"
              + "ПРЕДУПРЕЖДЕНИЕ: Вырезанные и вставленные объекты не могут быть отменены!",
      flags = "e",
      min = 0,
      max = 1)
  @CommandPermissions("worldedit.clipboard.cut")
  @Logging(REGION)
  public void cut(
      CommandContext args, LocalSession session, LocalPlayer player, EditSession editSession)
      throws WorldEditException {

    BaseBlock block = new BaseBlock(BlockID.AIR);
    LocalWorld world = player.getWorld();

    if (args.argsLength() > 0) {
      block = we.getBlock(player, args.getString(0));
    }

    Region region = session.getSelection(world);
    Vector min = region.getMinimumPoint();
    Vector max = region.getMaximumPoint();
    Vector pos = session.getPlacementPosition(player);

    CuboidClipboard clipboard =
        new CuboidClipboard(max.subtract(min).add(new Vector(1, 1, 1)), min, min.subtract(pos));
    clipboard.copy(editSession);
    if (args.hasFlag('e')) {
      LocalEntity[] entities = world.getEntities(region);
      for (LocalEntity entity : entities) {
        clipboard.storeEntity(entity);
      }
      world.killEntities(entities);
    }
    session.setClipboard(clipboard);

    int affected = editSession.setBlocks(session.getSelection(world), block);
    player.print(
        affected
            + " "
            + StringUtil.plural(affected, "блок вырезан", "блока вырезано", "блоков вырезано")
            + ".");
  }
コード例 #10
0
    @Command(
        aliases = {"item", "i"},
        usage = "[target] <item[:data]> [amount]",
        desc = "Give an item",
        flags = "do",
        min = 1,
        max = 3)
    @CommandPermissions({"commandbook.give"})
    public void item(CommandContext args, CommandSender sender) throws CommandException {
      ItemStack item = null;
      int amt = config.defaultItemStackSize;
      Iterable<Player> targets = null;

      // How this command handles parameters depends on how many there
      // are, so the following code splits the incoming input
      // into three different possibilities

      // One argument: Just the item type and amount 1
      if (args.argsLength() == 1) {
        item = matchItem(sender, args.getString(0));
        targets = PlayerUtil.matchPlayers(PlayerUtil.checkPlayer(sender));
        // Two arguments: Item type and amount
      } else if (args.argsLength() == 2) {
        item = matchItem(sender, args.getString(0));
        amt = args.getInteger(1);
        targets = PlayerUtil.matchPlayers(PlayerUtil.checkPlayer(sender));
        // Three arguments: Player, item type, and item amount
      } else if (args.argsLength() == 3) {
        item = matchItem(sender, args.getString(1));
        amt = args.getInteger(2);
        targets = PlayerUtil.matchPlayers(sender, args.getString(0));

        // Make sure that this player has permission to give items to other
        /// players!
        CommandBook.inst().checkPermission(sender, "commandbook.give.other");
      }

      if (item == null) {
        throw new CommandException("Something went wrong parsing the item info!");
      }
      giveItem(
          sender,
          item,
          amt,
          targets,
          InventoryComponent.this,
          args.hasFlag('d'),
          args.hasFlag('o'));
    }
コード例 #11
0
  @Command(
      aliases = {"/move"},
      usage = "[count] [direction] [leave-id]",
      flags = "s",
      desc = "Move the contents of the selection",
      min = 0,
      max = 3)
  @CommandPermissions("worldedit.region.move")
  @Logging(ORIENTATION_REGION)
  public static void move(
      CommandContext args,
      WorldEdit we,
      LocalSession session,
      LocalPlayer player,
      EditSession editSession)
      throws WorldEditException {

    int count = args.argsLength() > 0 ? Math.max(1, args.getInteger(0)) : 1;
    Vector dir =
        we.getDirection(player, args.argsLength() > 1 ? args.getString(1).toLowerCase() : "me");
    BaseBlock replace;

    // Replacement block argument
    if (args.argsLength() > 2) {
      replace = we.getBlock(player, args.getString(2));
    } else {
      replace = new BaseBlock(BlockID.AIR);
    }

    int affected =
        editSession.moveCuboidRegion(
            session.getSelection(player.getWorld()), dir, count, true, replace);

    if (args.hasFlag('s')) {
      try {
        Region region = session.getSelection(player.getWorld());
        region.expand(dir.multiply(count));
        region.contract(dir.multiply(count));

        session.getRegionSelector().learnChanges();
        session.getRegionSelector().explainRegionAdjust(player, session);
      } catch (RegionOperationException e) {
        player.printError(e.getMessage());
      }
    }

    player.print(affected + " blocks moved.");
  }
コード例 #12
0
  @Command(
      aliases = {"addserver"},
      desc = "Add a BungeeCord server",
      usage = "<name> <address> [port]",
      flags = "r",
      min = 2,
      max = 4)
  @CommandPermissions("bungeeutils.addserver")
  public static void addserver(final CommandContext args, CommandSender sender)
      throws CommandException {
    String name = args.getString(0);
    String address = args.getString(1);
    int port = args.argsLength() > 2 ? args.getInteger(2) : 25565;
    boolean restricted = args.hasFlag('r');

    ServerInfo serverInfo =
        ProxyServer.getInstance()
            .constructServerInfo(name, new InetSocketAddress(address, port), "", restricted);
    ProxyServer.getInstance().getServers().put(name, serverInfo);

    sender.sendMessage(ChatColor.GREEN + "Added server " + ChatColor.GOLD + name);
  }
コード例 #13
0
  @Command(
      aliases = {"report"},
      desc = "Writes a report on WorldGuard",
      flags = "p",
      max = 0)
  @CommandPermissions({"worldguard.report"})
  public void report(CommandContext args, final CommandSender sender) throws CommandException {

    File dest = new File(plugin.getDataFolder(), "report.txt");
    ReportWriter report = new ReportWriter(plugin);

    try {
      report.write(dest);
      sender.sendMessage(
          ChatColor.YELLOW + "WorldGuard report written to " + dest.getAbsolutePath());
    } catch (IOException e) {
      throw new CommandException("Failed to write report: " + e.getMessage());
    }

    if (args.hasFlag('p')) {
      plugin.checkPermission(sender, "worldguard.report.pastebin");

      sender.sendMessage(ChatColor.YELLOW + "Now uploading to Pastebin...");
      PastebinPoster.paste(
          report.toString(),
          new PasteCallback() {

            public void handleSuccess(String url) {
              // Hope we don't have a thread safety issue here
              sender.sendMessage(ChatColor.YELLOW + "WorldGuard report (1 hour): " + url);
            }

            public void handleError(String err) {
              // Hope we don't have a thread safety issue here
              sender.sendMessage(ChatColor.YELLOW + "WorldGuard report pastebin error: " + err);
            }
          });
    }
  }
コード例 #14
0
  @Command(
      aliases = {"/replace"},
      usage = "[from-block] <to-block>",
      desc = "Replace all blocks in the selection with another",
      flags = "f",
      min = 1,
      max = 2)
  @CommandPermissions("worldedit.region.replace")
  @Logging(REGION)
  public static void replace(
      CommandContext args,
      WorldEdit we,
      LocalSession session,
      LocalPlayer player,
      EditSession editSession)
      throws WorldEditException {

    Set<BaseBlock> from;
    Pattern to;
    if (args.argsLength() == 1) {
      from = null;
      to = we.getBlockPattern(player, args.getString(0));
    } else {
      from = we.getBlocks(player, args.getString(0), true, !args.hasFlag('f'));
      to = we.getBlockPattern(player, args.getString(1));
    }

    int affected = 0;
    if (to instanceof SingleBlockPattern) {
      affected =
          editSession.replaceBlocks(
              session.getSelection(player.getWorld()), from, ((SingleBlockPattern) to).getBlock());
    } else {
      affected = editSession.replaceBlocks(session.getSelection(player.getWorld()), from, to);
    }

    player.print(affected + " block(s) have been replaced.");
  }
コード例 #15
0
  @Command(
      aliases = {"/flip"},
      usage = "[dir]",
      flags = "p",
      desc = "Переворачивает содержимое буфера обмена.",
      help =
          "Переворачивает содержимое буфера обмена.\n"
              + "Флаг -p переворачивает выделенную территорию вокруг игрока,\n"
              + "а не центра выделения.",
      min = 0,
      max = 1)
  @CommandPermissions("worldedit.clipboard.flip")
  public void flip(
      CommandContext args, LocalSession session, LocalPlayer player, EditSession editSession)
      throws WorldEditException {

    CuboidClipboard.FlipDirection dir =
        we.getFlipDirection(player, args.argsLength() > 0 ? args.getString(0).toLowerCase() : "me");

    CuboidClipboard clipboard = session.getClipboard();
    clipboard.flip(dir, args.hasFlag('p'));
    player.print("Содержимое буфера обмена перевернуто.");
  }
コード例 #16
0
  @Command(
      aliases = {"/replacenear", "replacenear"},
      usage = "<size> <from-id> <to-id>",
      desc = "Replace nearby blocks",
      flags = "f",
      min = 3,
      max = 3)
  @CommandPermissions("worldedit.replacenear")
  @Logging(PLACEMENT)
  public void replaceNear(
      CommandContext args, LocalSession session, LocalPlayer player, EditSession editSession)
      throws WorldEditException {

    int size = Math.max(1, args.getInteger(0));
    int affected;
    Set<BaseBlock> from;
    Pattern to;
    if (args.argsLength() == 2) {
      from = null;
      to = we.getBlockPattern(player, args.getString(1));
    } else {
      from = we.getBlocks(player, args.getString(1), true, !args.hasFlag('f'));
      to = we.getBlockPattern(player, args.getString(2));
    }

    Vector base = session.getPlacementPosition(player);
    Vector min = base.subtract(size, size, size);
    Vector max = base.add(size, size, size);
    Region region = new CuboidRegion(player.getWorld(), min, max);

    if (to instanceof SingleBlockPattern) {
      affected = editSession.replaceBlocks(region, from, ((SingleBlockPattern) to).getBlock());
    } else {
      affected = editSession.replaceBlocks(region, from, to);
    }
    player.print(affected + " block(s) have been replaced.");
  }
コード例 #17
0
  @Command(
      aliases = {"save"},
      desc = "Saves the selected area",
      usage = "[-n namespace ] <id>",
      flags = "n:",
      min = 1)
  public void saveArea(CommandContext context, CommandSender sender) throws CommandException {

    if (!(sender instanceof Player)) return;
    LocalPlayer player = plugin.wrapPlayer((Player) sender);

    String id;
    String namespace = player.getName();
    boolean personal = true;

    if (context.hasFlag('n')
        && player.hasPermission("craftbook.mech.area.save." + context.getFlag('n'))) {
      namespace = context.getFlag('n');
      personal = false;
    } else if (!player.hasPermission("craftbook.mech.area.save.self"))
      throw new CommandPermissionsException();

    if (plugin.getConfiguration().areaShortenNames && namespace.length() > 14)
      namespace = namespace.substring(0, 14);

    if (!CopyManager.isValidNamespace(namespace))
      throw new CommandException("Invalid namespace. Needs to be between 1 and 14 letters long.");

    if (personal) {
      namespace = "~" + namespace;
    }

    id = context.getString(0);

    if (!CopyManager.isValidName(id))
      throw new CommandException("Invalid area name. Needs to be between 1 and 13 letters long.");

    try {
      WorldEditPlugin worldEdit = CraftBookPlugin.plugins.getWorldEdit();

      World world = ((Player) sender).getWorld();
      Selection sel = worldEdit.getSelection((Player) sender);
      if (sel == null) {
        sender.sendMessage(ChatColor.RED + "You have not made a selection!");
        return;
      }
      Vector min = BukkitUtil.toVector(sel.getMinimumPoint());
      Vector max = BukkitUtil.toVector(sel.getMaximumPoint());
      Vector size = max.subtract(min).add(1, 1, 1);

      // Check maximum size
      if (config.areaMaxAreaSize != -1
          && size.getBlockX() * size.getBlockY() * size.getBlockZ() > config.areaMaxAreaSize) {
        throw new CommandException(
            "Area is larger than allowed " + config.areaMaxAreaSize + " blocks.");
      }

      // Check to make sure that a user doesn't have too many toggle
      // areas (to prevent flooding the server with files)
      if (config.areaMaxAreaPerUser >= 0 && !namespace.equals("global")) {
        int count = copyManager.meetsQuota(world, namespace, id, config.areaMaxAreaPerUser);

        if (count > -1) {
          throw new CommandException(
              "You are limited to "
                  + config.areaMaxAreaPerUser
                  + " toggle area(s). "
                  + "You have "
                  + count
                  + " areas.");
        }
      }

      // Copy
      CuboidCopy copy;

      if (config.areaUseSchematics) {
        copy = new MCEditCuboidCopy(min, size, world);
      } else {
        copy = new FlatCuboidCopy(min, size, world);
      }

      copy.copy();

      plugin
          .getServer()
          .getLogger()
          .info(
              player.getName()
                  + " saving toggle area with folder '"
                  + namespace
                  + "' and ID '"
                  + id
                  + "'.");

      // Save
      try {
        CopyManager.getInstance().save(world, namespace, id.toLowerCase(Locale.ENGLISH), copy);
        player.print("Area saved as '" + id + "' under the '" + namespace + "' namespace.");
      } catch (IOException e) {
        player.printError("Could not save area: " + e.getMessage());
      } catch (DataException e) {
        player.print(e.getMessage());
      }
    } catch (NoClassDefFoundError e) {
      throw new CommandException(
          "WorldEdit.jar does not exist in plugins/, or is outdated. (Or you are using an outdated version of CraftBook)");
    }
  }
コード例 #18
0
  @Command(
      aliases = {"list"},
      desc = "Lists the areas of the given namespace or lists all areas.",
      usage = "[-n namespace] [page #]",
      flags = "an:")
  public void list(CommandContext context, CommandSender sender) throws CommandException {

    if (!(sender instanceof Player)) return;
    LocalPlayer player = CraftBookPlugin.inst().wrapPlayer((Player) sender);

    String namespace = "~" + player.getName();

    // get the namespace from the flag (if set)
    if (context.hasFlag('n')
        && player.hasPermission("craftbook.mech.area.list." + context.getFlag('n'))) {
      namespace = context.getFlag('n');
    } else if (context.hasFlag('a') && player.hasPermission("craftbook.mech.area.list.all")) {
      namespace = "";
    } else if (!player.hasPermission("craftbook.mech.area.list.self"))
      throw new CommandPermissionsException();

    if (plugin.getConfiguration().areaShortenNames && namespace.length() > 14)
      namespace = namespace.substring(0, 14);

    int page = 1;
    try {
      page = context.getInteger(0);
    } catch (Exception ignored) {
      // use default page: 1
    }

    // get the areas for the defined namespace
    File areas = new File(CraftBookPlugin.inst().getDataFolder(), "areas");

    if (!areas.exists()) throw new CommandException("There are no saved areas.");

    File folder = null;
    if (!namespace.isEmpty()) {
      folder = new File(areas, namespace);
    }

    if (folder != null && !folder.exists())
      throw new CommandException("The namespace '" + namespace + "' does not exist.");

    List<String> areaList = new ArrayList<String>();

    FilenameFilter fnf =
        new FilenameFilter() {

          @Override
          public boolean accept(File dir, String name) {

            return config.areaUseSchematics
                ? name.endsWith(".schematic")
                : name.endsWith(".cbcopy");
          }
        };

    if (folder != null && folder.exists()) {
      for (File area : folder.listFiles(fnf)) {
        String areaName = area.getName();
        areaName = areaName.replace(".schematic", "");
        areaName = areaName.replace(".cbcopy", "");
        areaList.add(ChatColor.AQUA + folder.getName() + "   :   " + ChatColor.YELLOW + areaName);
      }
    } else {
      for (File file : areas.listFiles()) {
        if (file.isDirectory()) {
          for (File area : file.listFiles(fnf)) {
            String areaName = area.getName();
            areaName = areaName.replace(".schematic", "");
            areaName = areaName.replace(".cbcopy", "");
            areaList.add(
                ChatColor.AQUA + folder.getName() + "   :   " + ChatColor.YELLOW + areaName);
          }
        }
      }
    }

    // now lets list the areas with a nice pagination
    if (!areaList.isEmpty()) {
      String tmp = namespace.isEmpty() ? "All Areas " : "Areas for " + namespace;
      player.print(
          ChatColor.GREEN + tmp + " - Page " + Math.abs(page) + " of " + (areaList.size() / 8 + 1));
      // list the areas one by one
      for (String str : ArrayUtil.getArrayPage(areaList, page)) {
        if (str != null && !str.isEmpty()) {
          player.print(str);
        }
      }
    } else {
      player.printError("There are no saved areas in the '" + namespace + "' namespace.");
    }
  }
コード例 #19
0
  @Command(
      aliases = {"butcher"},
      usage = "[radius]",
      flags = "plangbf",
      desc = "Kill all or nearby mobs",
      help =
          "Kills nearby mobs, based on radius, if none is given uses default in configuration.\n"
              + "Flags:"
              + "  -p also kills pets.\n"
              + "  -n also kills NPCs.\n"
              + "  -g also kills Golems.\n"
              + "  -a also kills animals.\n"
              + "  -b also kills ambient mobs.\n"
              + "  -f compounds all previous flags.\n"
              + "  -l strikes lightning on each killed mob.",
      min = 0,
      max = 1)
  @CommandPermissions("worldedit.butcher")
  @Logging(PLACEMENT)
  @Console
  public void butcher(
      CommandContext args, LocalSession session, LocalPlayer player, EditSession editSession)
      throws WorldEditException {

    LocalConfiguration config = we.getConfiguration();

    // technically the default can be larger than the max, but that's not my problem
    int radius = config.butcherDefaultRadius;

    // there might be a better way to do this but my brain is fried right now
    if (args.argsLength() > 0) { // user inputted radius, override the default
      radius = args.getInteger(0);
      if (config.butcherMaxRadius != -1) { // clamp if there is a max
        if (radius == -1) {
          radius = config.butcherMaxRadius;
        } else { // Math.min does not work if radius is -1 (actually highest possible value)
          radius = Math.min(radius, config.butcherMaxRadius);
        }
      }
    }

    FlagContainer flags = new FlagContainer(player);
    flags.or(KillFlags.FRIENDLY, args.hasFlag('f'));
    flags.or(KillFlags.PETS, args.hasFlag('p'), "worldedit.butcher.pets");
    flags.or(KillFlags.NPCS, args.hasFlag('n'), "worldedit.butcher.npcs");
    flags.or(KillFlags.GOLEMS, args.hasFlag('g'), "worldedit.butcher.golems");
    flags.or(KillFlags.ANIMALS, args.hasFlag('a'), "worldedit.butcher.animals");
    flags.or(KillFlags.AMBIENT, args.hasFlag('b'), "worldedit.butcher.ambient");
    flags.or(KillFlags.WITH_LIGHTNING, args.hasFlag('l'), "worldedit.butcher.lightning");

    int killed;
    if (player.isPlayer()) {
      killed =
          player.getWorld().killMobs(session.getPlacementPosition(player), radius, flags.flags);
    } else {
      killed = 0;
      for (LocalWorld world : we.getServer().getWorlds()) {
        killed += world.killMobs(new Vector(), radius, flags.flags);
      }
    }

    if (radius < 0) {
      player.print("Killed " + killed + " mobs.");
    } else {
      player.print("Killed " + killed + " mobs in a radius of " + radius + ".");
    }
  }
コード例 #20
0
    @Command(
        aliases = {"ban"},
        usage = "[-t end ] <target> [reason...]",
        desc = "Ban a user or IP address (with the -i flag)",
        flags = "set:o",
        min = 1,
        max = -1)
    @CommandPermissions({"commandbook.bans.ban"})
    public void ban(CommandContext args, CommandSender sender) throws CommandException {
      String banName;
      String banAddress = null;
      long endDate = args.hasFlag('t') ? CommandBookUtil.matchFutureDate(args.getFlag('t')) : 0L;
      String message = args.argsLength() >= 2 ? args.getJoinedStrings(1) : "Banned!";

      final boolean hasExemptOverride =
          args.hasFlag('o')
              && CommandBook.inst().hasPermission(sender, "commandbook.bans.exempt.override");
      // Check if it's a player in the server right now
      try {
        Player player;

        // Exact mode matches names exactly
        if (args.hasFlag('e')) {
          player = PlayerUtil.matchPlayerExactly(sender, args.getString(0));
        } else {
          player = PlayerUtil.matchSinglePlayer(sender, args.getString(0));
        }

        if (CommandBook.inst().hasPermission(player, "commandbook.bans.exempt")
            && !hasExemptOverride) {
          throw new CommandException(
              "This player is exempt from being banned! "
                  + "(use -o flag to override if you have commandbook.bans.exempt.override)");
        }

        // Need to kick + log
        player.kickPlayer(message);
        getBanDatabase().logKick(player, sender, message);

        banName = player.getName();

        sender.sendMessage(
            ChatColor.YELLOW
                + player.getName()
                + " ("
                + player.getDisplayName()
                + ChatColor.YELLOW
                + ") banned and kicked.");
      } catch (CommandException e) {
        banName =
            args.getString(0)
                .replace("\r", "")
                .replace("\n", "")
                .replace("\0", "")
                .replace("\b", "");

        sender.sendMessage(ChatColor.YELLOW + banName + " banned.");
      }

      // Broadcast the Message
      if (config.broadcastBans && !args.hasFlag('s')) {
        CommandBook.server()
            .broadcastMessage(
                ChatColor.YELLOW
                    + PlayerUtil.toColoredName(sender, ChatColor.YELLOW)
                    + " has banned "
                    + banName
                    + " - "
                    + message);
      }

      getBanDatabase().ban(banName, banAddress, sender, message, endDate);

      if (!getBanDatabase().save()) {
        sender.sendMessage(ChatColor.RED + "Bans database failed to save. See console.");
      }
    }
コード例 #21
0
    @Command(
        aliases = {"more"},
        usage = "[player]",
        desc = "Gets more of an item",
        flags = "aio",
        min = 0,
        max = 1)
    @CommandPermissions({"commandbook.more"})
    public void more(CommandContext args, CommandSender sender) throws CommandException {

      Iterable<Player> targets = null;
      boolean moreAll = args.hasFlag('a');
      boolean infinite = args.hasFlag('i');
      boolean overrideStackSize = args.hasFlag('o');
      if (infinite) {
        CommandBook.inst().hasPermission(sender, "commandbook.more.infinite");
      } else if (overrideStackSize) {
        CommandBook.inst().hasPermission(sender, "commandbook.override.maxstacksize");
      }

      boolean included = false;

      if (args.argsLength() == 0) {
        targets = PlayerUtil.matchPlayers(PlayerUtil.checkPlayer(sender));
        // A different player
      } else {
        targets = PlayerUtil.matchPlayers(sender, args.getString(0));

        // Make sure that this player can 'more' other players!
        CommandBook.inst().checkPermission(sender, "commandbook.more.other");
      }

      for (Player player : targets) {
        Inventory inventory = player.getInventory();

        if (moreAll) {
          for (int i = 0; i < 39; i++) {
            CommandBookUtil.expandStack(inventory.getItem(i), infinite, overrideStackSize);
          }
        } else {
          CommandBookUtil.expandStack(player.getItemInHand(), infinite, overrideStackSize);
        }

        // Tell the user about the given item
        if (player.equals(sender)) {
          player.sendMessage(ChatColor.YELLOW + "Your item(s) has been expanded in stack size.");

          // Keep track of this
          included = true;
        } else {
          player.sendMessage(
              ChatColor.YELLOW
                  + "Your item(s) has been expanded in stack size by "
                  + PlayerUtil.toName(sender));
        }
      }

      // The player didn't receive any items, then we need to send the
      // user a message so s/he know that something is indeed working
      if (!included) {
        sender.sendMessage(ChatColor.YELLOW + "Stack sizes increased.");
      }
    }
コード例 #22
0
    @Command(
        aliases = {"time"},
        usage = "[world] <time|\"current\">",
        desc = "Get/change the world time",
        flags = "l",
        min = 0,
        max = 2)
    public void time(CommandContext args, CommandSender sender) throws CommandException {

      World world;
      String timeStr;
      boolean onlyLock = false;

      // Easy way to get the time
      if (args.argsLength() == 0) {
        world = PlayerUtil.checkPlayer(sender).getWorld();
        timeStr = "current";
        // If no world was specified, get the world from the sender, but
        // fail if the sender isn't player
      } else if (args.argsLength() == 1) {
        world = PlayerUtil.checkPlayer(sender).getWorld();
        timeStr = args.getString(0);
      } else { // A world was specified!
        world = LocationUtil.matchWorld(sender, args.getString(0));
        timeStr = args.getString(1);
      }

      // Let the player get the time
      if (timeStr.equalsIgnoreCase("current")
          || timeStr.equalsIgnoreCase("cur")
          || timeStr.equalsIgnoreCase("now")) {

        // We want to lock to the current time
        if (!args.hasFlag('l')) {
          CommandBook.inst().checkPermission(sender, "commandbook.time.check");
          sender.sendMessage(
              ChatColor.YELLOW + "Time: " + CommandBookUtil.getTimeString(world.getTime()));
          return;
        }

        onlyLock = true;
      }

      CommandBook.inst().checkPermission(sender, "commandbook.time");

      if (!onlyLock) {
        unlock(world);
        world.setTime(matchTime(timeStr));
      }

      String verb = "set";

      // Locking
      if (args.hasFlag('l')) {
        CommandBook.inst().checkPermission(sender, "commandbook.time.lock");
        lock(world);
        verb = "locked";
      }

      if (CommandBook.inst().broadcastChanges) {
        CommandBook.server()
            .broadcastMessage(
                ChatColor.YELLOW
                    + PlayerUtil.toName(sender)
                    + " "
                    + verb
                    + " the time of '"
                    + world.getName()
                    + "' to "
                    + CommandBookUtil.getTimeString(world.getTime())
                    + ".");
      } else {
        sender.sendMessage(
            ChatColor.YELLOW
                + "Time "
                + verb
                + " to "
                + CommandBookUtil.getTimeString(world.getTime())
                + ".");
      }
    }
コード例 #23
0
    @Command(
        aliases = {"playertime"},
        usage = "[filter] <time|\"current\">",
        desc = "Get/change a player's time",
        flags = "rsw",
        min = 0,
        max = 2)
    public void playertime(CommandContext args, CommandSender sender) throws CommandException {
      Iterable<Player> players = null;
      String timeStr = "current";
      boolean included = false;
      boolean reset = args.hasFlag('r');

      if (args.argsLength() < 2) {
        if (args.argsLength() == 1) {
          timeStr = args.getString(0);
          if (reset) {
            players = PlayerUtil.matchPlayers(sender, timeStr);
          }
        }

        if (players == null) {
          players = PlayerUtil.matchPlayers(PlayerUtil.checkPlayer(sender));
        }
      } else {
        players = PlayerUtil.matchPlayers(sender, args.getString(0));
        timeStr = args.getString(1);
      }

      for (Player player : players) {
        if (player != sender) {
          CommandBook.inst().checkPermission(sender, "commandbook.time.player.other");
          break;
        } else {
          CommandBook.inst().checkPermission(sender, "commandbook.time.player");
        }
      }

      if (args.hasFlag('r')) {
        for (Player player : players) {
          player.resetPlayerTime();
          if (!args.hasFlag('s')) {
            player.sendMessage(ChatColor.YELLOW + "Your time was reset to world time");
          }
          if (sender instanceof Player && sender.equals(player)) {
            included = true;
          }
        }
        if (!included) {
          sender.sendMessage(ChatColor.YELLOW + "Player times reset");
        }
        return;
      }

      if (timeStr.equalsIgnoreCase("current")
          || timeStr.equalsIgnoreCase("cur")
          || timeStr.equalsIgnoreCase("now")) {
        CommandBook.inst().checkPermission(sender, "commandbook.time.player.check");
        sender.sendMessage(
            ChatColor.YELLOW
                + "Player Time: "
                + CommandBookUtil.getTimeString(
                    PlayerUtil.matchSinglePlayer(
                            sender, args.getString(0, PlayerUtil.checkPlayer(sender).getName()))
                        .getPlayerTime()));
        return;
      }

      for (Player player : players) {
        if (!player.equals(sender)) {
          player.sendMessage(
              ChatColor.YELLOW
                  + "Your time set to "
                  + CommandBookUtil.getTimeString(player.getPlayerTime()));
        } else {
          player.sendMessage(
              ChatColor.YELLOW
                  + "Your time set to "
                  + CommandBookUtil.getTimeString(player.getPlayerTime()));
          included = true;
        }
        player.setPlayerTime(
            args.hasFlag('w') ? Integer.parseInt(timeStr) : matchTime(timeStr), args.hasFlag('w'));
      }
      if (!included) {
        sender.sendMessage(
            ChatColor.YELLOW
                + "Player times set to "
                + CommandBookUtil.getTimeString(matchTime(timeStr)));
      }
    }
コード例 #24
0
    @Command(
        aliases = {"clear"},
        usage = "[target]",
        desc = "Clear your inventory",
        flags = "as",
        min = 0,
        max = 1)
    @CommandPermissions({"commandbook.clear"})
    public void clear(CommandContext args, CommandSender sender) throws CommandException {

      Iterable<Player> targets = null;
      boolean clearAll = args.hasFlag('a');
      boolean clearSingle = args.hasFlag('s');
      boolean included = false;

      if (args.argsLength() == 0) {
        targets = PlayerUtil.matchPlayers(PlayerUtil.checkPlayer(sender));
        // A different player
      } else {
        targets = PlayerUtil.matchPlayers(sender, args.getString(0));

        // Make sure that this player can clear other players!
        CommandBook.inst().checkPermission(sender, "commandbook.clear.other");
      }

      for (Player player : targets) {
        Inventory inventory = player.getInventory();

        if (clearSingle) {
          player.setItemInHand(null);
        } else {
          for (int i = (clearAll ? 0 : 9); i < 36; i++) {
            inventory.setItem(i, null);
          }

          if (clearAll) {
            // Armor slots
            for (int i = 36; i <= 39; i++) {
              inventory.setItem(i, null);
            }
          }
        }

        // Tell the user about the given item
        if (player.equals(sender)) {
          if (clearAll) {
            player.sendMessage(ChatColor.YELLOW + "Your inventory has been cleared.");
          } else {
            player.sendMessage(
                ChatColor.YELLOW + "Your inventory has been cleared. Use -a to clear ALL.");
          }

          // Keep track of this
          included = true;
        } else {
          player.sendMessage(
              ChatColor.YELLOW + "Your inventory has been cleared by " + PlayerUtil.toName(sender));
        }
      }

      // The player didn't receive any items, then we need to send the
      // user a message so s/he know that something is indeed working
      if (!included) {
        sender.sendMessage(ChatColor.YELLOW + "Inventories cleared.");
      }
    }