Java Code Examples for org.bukkit.event.player.PlayerCommandPreprocessEvent#getPlayer()

The following examples show how to use org.bukkit.event.player.PlayerCommandPreprocessEvent#getPlayer() . 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: PlayerListener.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
    String cmd = event.getMessage().split(" ")[0].toLowerCase();
    if (settings.getProperty(HooksSettings.USE_ESSENTIALS_MOTD) && "/motd".equals(cmd)) {
        return;
    }
    if (settings.getProperty(RestrictionSettings.ALLOW_COMMANDS).contains(cmd)) {
        return;
    }
    final Player player = event.getPlayer();
    if (!quickCommandsProtectionManager.isAllowed(player.getName())) {
        event.setCancelled(true);
        player.kickPlayer(messages.retrieveSingle(player, MessageKey.QUICK_COMMAND_PROTECTION_KICK));
        return;
    }
    if (listenerService.shouldCancelEvent(player)) {
        event.setCancelled(true);
        messages.send(player, MessageKey.DENIED_COMMAND);
    }
}
 
Example 2
Source File: DeathListener.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler
public void onPlayerCommand(PlayerCommandPreprocessEvent event) {
    Player player = event.getPlayer();
    Location location = player.getLocation();
    Civilian civilian = CivilianManager.getInstance().getCivilian(player.getUniqueId());

    long jailTime = ConfigManager.getInstance().getJailTime();
    if (civilian.getLastJail() + jailTime < System.currentTimeMillis()) {
        return;
    }
    long timeRemaining = civilian.getLastJail() + jailTime - System.currentTimeMillis();

    Region region = RegionManager.getInstance().getRegionAt(location);
    if (region == null || !region.getEffects().containsKey("jail")) {
        return;
    }
    event.setCancelled(true);
    player.sendMessage(Civs.getPrefix() + LocaleManager.getInstance().getTranslationWithPlaceholders(player,
            "no-commands-in-jail").replace("$1", (int) (timeRemaining / 1000) + "s"));
}
 
Example 3
Source File: CommandUseEvent.java    From WildernessTp with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onCmd(PlayerCommandPreprocessEvent e) {
    String command = e.getMessage().toLowerCase();
    List<String> blockedCmds = wild.getConfig().getStringList("BlockCommands");
    if (TeleportTarget.cmdUsed.contains(e.getPlayer().getUniqueId())) {
        for (String cmd : blockedCmds) {
            if (command.contains(cmd)) {
                e.getPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', wild.getConfig().getString("Blocked_Command_Message")));
                e.setCancelled(true);
                break;
            }
        }
    }
    if (e.getMessage().equalsIgnoreCase("/wild") && wild.getConfig().getBoolean("FBasics") && (wild.usageMode != UsageMode.COMMAND_ONLY && wild.usageMode != UsageMode.BOTH)) {
        e.setCancelled(true);
        CheckPerms check = new CheckPerms(wild);
        Checks checks = new Checks(wild);
        Player p = e.getPlayer();
        if (!checks.world(p))
            p.sendMessage(ChatColor.translateAlternateColorCodes('&', wild.getConfig().getString("WorldMsg")));
        else
            check.check(p,p.getWorld().getName());
    }
}
 
Example 4
Source File: ListenerMenuOpenCommands.java    From TrMenu with MIT License 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onCommand(PlayerCommandPreprocessEvent e) {
    Player p = e.getPlayer();
    String[] cmd = e.getMessage().substring(1).split(" ");
    if (cmd.length > 0) {
        for (int i = 0; i < cmd.length; i++) {
            String[] read = read(cmd, i);
            String command = read[0];
            String[] args = ArrayUtils.remove(read, 0);
            Menu menu = TrMenuAPI.getMenuByCommand(command);
            if (menu != null) {
                if (menu.isTransferArgs()) {
                    if (args.length < menu.getForceTransferArgsAmount()) {
                        TLocale.sendTo(p, "MENU.NOT-ENOUGH-ARGS", menu.getForceTransferArgsAmount());
                        e.setCancelled(true);
                        return;
                    }
                } else if (args.length > 0) {
                    return;
                }
                menu.open(p, args);
                e.setCancelled(true);
                break;
            }
        }
    }
}
 
Example 5
Source File: PlayerCommand.java    From FunnyGuilds with Apache License 2.0 5 votes vote down vote up
@EventHandler
public void onCommand(PlayerCommandPreprocessEvent event) {
    Player player = event.getPlayer();
    if (player.hasPermission("funnyguilds.admin")) {
        return;
    }

    String[] splited = event.getMessage().split("\\s+");
    if (splited.length == 0) {
        return;
    }
    String command = splited[0];
    for (String s : FunnyGuilds.getInstance().getPluginConfiguration().regionCommands) {
        if (("/" + s).equalsIgnoreCase(command)) {
            command = null;
            break;
        }
    }
    if (command != null) {
        return;
    }

    Region region = RegionUtils.getAt(player.getLocation());
    if (region == null) {
        return;
    }

    Guild guild = region.getGuild();
    User user = User.get(player);
    if (guild.getMembers().contains(user)) {
        return;
    }

    event.setCancelled(true);
    player.sendMessage(FunnyGuilds.getInstance().getMessageConfiguration().regionCommand);
}
 
Example 6
Source File: MainListener.java    From ArmorStandTools with MIT License 5 votes vote down vote up
@EventHandler
public void onPlayerCommand(final PlayerCommandPreprocessEvent event) {
    Player p = event.getPlayer();
    String cmd = event.getMessage().split(" ")[0].toLowerCase();
    while(cmd.length() > 0 && cmd.charAt(0) == '/') {
        cmd = cmd.substring(1);
    }
    if(cmd.length() > 0 && Config.deniedCommands.contains(cmd) && Utils.hasAnyTools(p)) {
        event.setCancelled(true);
        p.sendMessage(ChatColor.RED + Config.cmdNotAllowed);
    }
}
 
Example 7
Source File: PlayerListener.java    From BedwarsRel with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onCommand(PlayerCommandPreprocessEvent pcpe) {
  Player player = pcpe.getPlayer();
  Game game = BedwarsRel.getInstance().getGameManager().getGameOfPlayer(player);

  if (game == null) {
    return;
  }

  if (game.getState() == GameState.STOPPED) {
    return;
  }

  String message = pcpe.getMessage();
  if (!message.startsWith("/bw")) {

    for (String allowed : BedwarsRel.getInstance().getAllowedCommands()) {
      if (!allowed.startsWith("/")) {
        allowed = "/" + allowed;
      }

      if (message.startsWith(allowed.trim())) {
        return;
      }
    }

    if (player.hasPermission("bw.cmd")) {
      return;
    }

    pcpe.setCancelled(true);
    return;
  }
}
 
Example 8
Source File: ListenerCommandBlocker.java    From CombatLogX with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority=EventPriority.LOWEST, ignoreCancelled=true)
public void beforeCommand(PlayerCommandPreprocessEvent e) {
    Player player = e.getPlayer();
    ICombatManager combatManager = this.plugin.getCombatManager();
    if(!combatManager.isInCombat(player) && !isInCooldown(player)) return;

    String command = e.getMessage();
    String actualCommand = convertCommand(command);
    if(!isBlocked(actualCommand) || isAllowed(actualCommand)) return;

    e.setCancelled(true);
    String message = this.plugin.getLanguageMessageColoredWithPrefix("cheat-prevention.command-blocked").replace("{command}", actualCommand);
    this.plugin.sendMessage(player, message);
}
 
Example 9
Source File: CustomCommand.java    From CombatLogX with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled=true)
public void beforeCommand(PlayerCommandPreprocessEvent e) {
    Player player = e.getPlayer();
    String message = e.getMessage();
    String[] split = message.split(" ");

    String commandName = split[0];
    if(commandName.startsWith("/")) commandName = commandName.substring(1);
    if(commandName.equals(this.getName()) || this.getAliases().contains(commandName)) {
        e.setCancelled(true);

        String[] args = split.length > 1 ? Arrays.copyOfRange(split, 1, split.length) : new String[0];
        execute(player, commandName, args);
    }
}
 
Example 10
Source File: CommandsPerformedListener.java    From Statz with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPerformCommand(final PlayerCommandPreprocessEvent event) {

	final PlayerStat stat = PlayerStat.COMMANDS_PERFORMED;

	// Get player
	final Player player = event.getPlayer();

	// Do general check
	if (!plugin.doGeneralCheck(player, stat))
		return;
	
	String message = event.getMessage();
	
	int subString = message.indexOf(" ");

	String command = "";
	String arguments = "";

	if (subString > 0) {
		command = message.substring(0, subString).trim();
		arguments = message.substring(subString).trim();

		// Cut off string so it's not too long
		if (arguments.length() > 100) {
			arguments = arguments.substring(0, 99);
		}
	} else {
		command = message.trim();
	}

	PlayerStatSpecification specification = new CommandsPerformedSpecification(player.getUniqueId(), 1,
			player.getWorld().getName(), command, arguments);

	// Update value to new stat.
	plugin.getDataManager().setPlayerInfo(player.getUniqueId(), stat, specification.constructQuery());

}
 
Example 11
Source File: ChatEvent.java    From MCAuthenticator with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerCommand(PlayerCommandPreprocessEvent event) {
    Player player = event.getPlayer();
    User user = instance.getCache().get(player.getUniqueId());

    if (user != null && user.authenticated()) return;
    instance.getC().send(player, instance.getC().message("notAuthed"));
    event.setCancelled(true);
}
 
Example 12
Source File: XPMain.java    From AnnihilationPro with MIT License 5 votes vote down vote up
@EventHandler(priority = EventPriority.NORMAL)
public void test(PlayerCommandPreprocessEvent e)
{
	Player player = e.getPlayer();
	String[] args = e.getMessage().split(" ");
	if(args[0].equals("/test") && player.getName().equalsIgnoreCase("Mr_Little_Kitty"))
	{
		AnniPlayer p = AnniPlayer.getPlayer(player.getUniqueId());
		if(p != null)
		{
			Object obj = p.getData("Kits");
			if(obj != null)
			{
				if(obj instanceof List)
				{
					@SuppressWarnings("unchecked")
					List<String> list = (List<String>)obj;
					if(!list.isEmpty())
					{
						for(String str : list)
							player.sendMessage("Has: "+str);
					}
					else player.sendMessage("Nope 4");
				}
				else player.sendMessage("Nope 3");
			}
			else player.sendMessage("Nope 2");
		}
		else player.sendMessage("Nope 1");
	}
}
 
Example 13
Source File: BukkitChatListener.java    From Parties with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Auto command listener
 */
@EventHandler
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
	if (!event.isCancelled()) {
		String result = super.onPlayerCommandPreprocess(new BukkitUser(plugin, event.getPlayer()), event.getMessage());
		if (result != null) {
			event.setMessage(result);
		}
	}
}
 
Example 14
Source File: PlayerCommandPreprocess.java    From StaffPlus with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onCommand(PlayerCommandPreprocessEvent event)
{
	Player player = event.getPlayer();
	UUID uuid = player.getUniqueId();
	String command = event.getMessage().toLowerCase();
	
	if(command.startsWith("/help staffplus") || command.startsWith("/help staff+"))
	{
		sendHelp(player);
		event.setCancelled(true);
		return;
	}
	
	if(options.blockedCommands.contains(command) && permission.hasOnly(player, options.permissionBlock))
	{
		message.send(player, messages.commandBlocked, messages.prefixGeneral);
		event.setCancelled(true);
	}else if(modeCoordinator.isInMode(uuid) && options.blockedModeCommands.contains(command))
	{
		message.send(player, messages.modeCommandBlocked, messages.prefixGeneral);
		event.setCancelled(true);
	}else if(freezeHandler.isFrozen(uuid) && (!options.modeFreezeChat || (freezeHandler.isLoggedOut(uuid)) && !command.startsWith("/" + options.commandLogin)))
	{
		message.send(player, messages.chatPrevented, messages.prefixGeneral);
		event.setCancelled(true);
	}
}
 
Example 15
Source File: Updater.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onCommand(PlayerCommandPreprocessEvent e){
    if (!e.getMessage().equalsIgnoreCase("/uhccore update")){
        return;
    }
    e.setCancelled(true);

    Player player = e.getPlayer();
    GameManager gm = GameManager.getGameManager();

    if (gm.getGameState() == GameState.PLAYING || gm.getGameState() == GameState.DEATHMATCH){
        player.sendMessage(ChatColor.RED + "You can not update the plugin during games as it will restart your server.");
        return;
    }

    player.sendMessage(ChatColor.GREEN + "Updating plugin ...");

    try{
        updatePlugin(true);
    }catch (Exception ex){
        player.sendMessage(ChatColor.RED + "Failed to update plugin, check console for more info.");
        ex.printStackTrace();
    }
}
 
Example 16
Source File: GameListeners.java    From AnnihilationPro with MIT License 4 votes vote down vote up
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
	public void AnniPlayersInit(PlayerCommandPreprocessEvent event)
	{
		final String[] args = event.getMessage().split(" ");
		if(args[0].equalsIgnoreCase("/tp"))
		{
			Player player = event.getPlayer();
			if(player.hasPermission("A.anni"))
			{
				if(args.length > 1)
				{
					AnniTeam team = AnniTeam.getTeamByName(args[1]);
					if(team != null)
					{
						Loc loc = team.getSpectatorLocation();
						if(loc != null)
						{
							event.setCancelled(true);
							player.teleport(loc.toLocation());
						}
					}
					else if(args[1].equalsIgnoreCase("lobby"))
					{
						if(Game.LobbyMap != null)
						{
							Location lobby = Game.LobbyMap.getSpawn();
							if(lobby != null)
							{
								event.setCancelled(true);
								player.teleport(lobby);
							}
						}
					}
//					else if(args[1].equalsIgnoreCase("map") && player.getName().equals("Mr_Little_Kitty"))
//					{
//						if(args.length > 2)
//						{
//							World w = Game.getWorld(args[2]);
//							if(w != null)
//							{
//								event.setCancelled(true);
//								player.teleport(w.getSpawnLocation());
//							}
//						}
//						else
//						{
//							for(World w : Bukkit.getWorlds())
//								player.sendMessage(w.getName());
//						}
//					}
				}
			}
		}
	}
 
Example 17
Source File: ChatEventListener.java    From ChatItem with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.LOWEST)
public void onCommand(final PlayerCommandPreprocessEvent e){
    if(e.getMessage().indexOf(SEPARATOR)!=-1){  //If the BELL character is found, we have to remove it
        String msg = e.getMessage().replace(Character.toString(SEPARATOR), "");
        e.setMessage(msg);
    }
    String commandString = e.getMessage().split(" ")[0].replaceAll("^/+", ""); //First part of the command, without leading slashes and without arguments
    Command cmd = Bukkit.getPluginCommand(commandString);
    if(cmd==null){ //not a plugin command
        if(!c.ALLOWED_DEFAULT_COMMANDS.contains(commandString)){
            return;
        }
    }else{
        if(!c.ALLOWED_PLUGIN_COMMANDS.contains(cmd)){
            return;
        }
    }

    Player p = e.getPlayer();
    boolean found = false;

    for (String rep : c.PLACEHOLDERS) {
        if (e.getMessage().contains(rep)) {
            found = true;
            break;
        }
    }

    if (!found) {
        return;
    }

    if (!p.hasPermission("chatitem.use")) {
        if(!c.NO_PERMISSION_MESSAGE.isEmpty() && c.SHOW_NO_PERM_COMMAND){
            p.sendMessage(c.NO_PERMISSION_MESSAGE);
        }
        e.setCancelled(true);
        return;
    }

    if (e.getPlayer().getItemInHand().getType().equals(Material.AIR)) {
        if (c.DENY_IF_NO_ITEM) {
            e.setCancelled(true);
            if (!c.DENY_MESSAGE.isEmpty()) {
                e.getPlayer().sendMessage(c.DENY_MESSAGE);
            }
        }
        if(c.HAND_DISABLED) {
            return;
        }
    }

    if(c.COOLDOWN > 0 && !p.hasPermission("chatitem.ignore-cooldown")){
        if(COOLDOWNS.containsKey(p.getName())){
            long start = COOLDOWNS.get(p.getName());
            long current = System.currentTimeMillis()/1000;
            long elapsed = current - start;
            if(elapsed >= c.COOLDOWN){
                COOLDOWNS.remove(p.getName());
            }else{
                if(!c.LET_MESSAGE_THROUGH) {
                    e.setCancelled(true);
                }
                if(!c.COOLDOWN_MESSAGE.isEmpty()){
                    long left = (start + c.COOLDOWN) - current;
                    p.sendMessage(c.COOLDOWN_MESSAGE.replace(LEFT, calculateTime(left)));
                }
                return;
            }
        }
    }

    String s = e.getMessage();
    for(String placeholder : c.PLACEHOLDERS){
        s = s.replace(placeholder, c.PLACEHOLDERS.get(0));
    }
    int occurrences = countOccurrences(c.PLACEHOLDERS.get(0), s);

    if(occurrences>c.LIMIT){
        e.setCancelled(true);
        if(c.LIMIT_MESSAGE.isEmpty()){
           return;
        }
        e.getPlayer().sendMessage(c.LIMIT_MESSAGE);
        return;
    }

    StringBuilder sb = new StringBuilder(e.getMessage());
    sb.append(SEPARATOR).append(e.getPlayer().getName());
    e.setMessage(sb.toString());
    if(!p.hasPermission("chatitem.ignore-cooldown")) {
        COOLDOWNS.put(p.getName(), System.currentTimeMillis() / 1000);
    }
}
 
Example 18
Source File: DPlayerListener.java    From DungeonsXL with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
    Player player = event.getPlayer();
    if (isCitizensNPC(player)) {
        return;
    }

    if (DPermission.hasPermission(player, DPermission.BYPASS)) {
        return;
    }

    if (!(dPlayers.get(player) instanceof DInstancePlayer)) {
        return;
    }
    InstancePlayer dPlayer = dPlayers.getInstancePlayer(player);

    String command = event.getMessage().toLowerCase();
    ArrayList<String> commandWhitelist = new ArrayList<>();

    if (dPlayer instanceof DEditPlayer) {
        if (DPermission.hasPermission(player, DPermission.CMD_EDIT)) {
            return;

        } else {
            commandWhitelist.addAll(config.getEditCommandWhitelist());
        }

    } else {
        commandWhitelist.addAll(dPlayer.getGroup().getDungeon().getRules().getState(GameRule.GAME_COMMAND_WHITELIST));
    }

    commandWhitelist.add("dungeonsxl");
    commandWhitelist.add("dungeon");
    commandWhitelist.add("dxl");

    event.setCancelled(true);

    for (String whitelistEntry : commandWhitelist) {
        if (command.equals('/' + whitelistEntry.toLowerCase()) || command.startsWith('/' + whitelistEntry.toLowerCase() + ' ')) {
            event.setCancelled(false);
        }
    }

    if (event.isCancelled()) {
        MessageUtil.sendMessage(player, DMessage.ERROR_CMD.getMessage());
    }
}
 
Example 19
Source File: PlayerCommandListener.java    From ExploitFixer with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerCommand(final PlayerCommandPreprocessEvent event) {
	final Player player = event.getPlayer();
	final ExploitPlayer exploitPlayer = exploitPlayerManager.get(player);

	if (!exploitPlayer.isLogged()) {
		event.setCancelled(true);
	} else if (commandsModule.isEnabled()) {
		final Server server = plugin.getServer();
		final String message = event.getMessage().replaceAll("[\\w]+:", "").toLowerCase();
		final String playerName = player.getName();

		for (final String command : commandsModule.getCommands()) {
			if (message.startsWith(command + " ")) {
				for (final String punishment : commandsModule.getPunishments()) {
					if (command.equals("kick")) {
						final String locale = VersionUtil.getLocale(player);
						final String kickMessage = messagesModule.getKickMessage(commandsModule, locale);
						final HamsterPlayer hamsterPlayer = HamsterAPI.getInstance().getHamsterPlayerManager()
								.get(player);

						hamsterPlayer.disconnect(kickMessage);
						hamsterPlayer.closeChannel();
						exploitPlayerManager.addPunishment();
					} else if (command.equals("notification")) {
						final String moduleName = commandsModule.getName();

						notificationsModule.sendNotification(moduleName, player, 1);
					} else {
						if (server.isPrimaryThread()) {
							server.dispatchCommand(server.getConsoleSender(),
									punishment.replace("%player%", playerName));
						} else {
							server.getScheduler().runTask(plugin, () -> {
								server.dispatchCommand(server.getConsoleSender(),
										punishment.replace("%player%", playerName));
							});
						}
					}
				}

				event.setCancelled(true);
				break;
			}
		}
	}
}