Solved PlayerCommandPreprocessEvent Commands blocking problem.

Discussion in 'Plugin Development' started by MrAndeos, Jan 11, 2018.

Thread Status:
Not open for further replies.
  1. Offline

    MrAndeos

    I want to make a class that will allow users to use only commands defined in config, I don't know how to get it working in this way, here is what i have now:

    Code:java
    1. @EventHandler
    2. public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
    3. Player player = event.getPlayer();
    4. if (AntyLogoutPvpManager.getPvPTime(player) != null) {
    5. for (String command : Main.plugin.getConfig().getStringList("antylogout-allowed-cmds")) {
    6. if (!event.getMessage().toLowerCase().startsWith("/" + command)) {
    7. event.setCancelled(true);
    8. player.sendMessage(ChatColor.RED + "You cannot use this command now!");
    9. }
    10. }
    11. }
    12. }


    Any ideas?

    Sorry for any mistakes, English is not my native language.
     
  2. Offline

    Zombie_Striker

    @MrAndeos
    What exactly does not work?
    1. Does getPVPTime return a value that is not null?
    2. Are you sure the list from the config contains all the commands?
    3. Are you sure the message starts with a "/"?
    BTW: You should add a Break; if the command has been found in the config. No need to loop through the rest of the commands if you already found the command that was sent.
     
    MrAndeos likes this.
  3. Offline

    MrAndeos

    @Zombie_Striker
    If I run a command, that's not in the list, it sends me a message two times, if I enter one that is in the list (currently there are two) it cancels the event and sends me message one time.

    1. Yes, if player starts combat it will return a integer.
    2. Yes.
    3. Yes.
     
    Last edited: Jan 12, 2018
  4. Offline

    Zombie_Striker

    @MrAndeos
    Okay, in that case, you need to check if the command is not in the list, not check if every command in the list is not equal to the command.

    What is currently happening is you are looping through all the commands, and then checking only if they do not match (which if you have multiple different commands stored, will always be the case) Basically, all you're doing is trying to make sure that the config only contains one command.

    To fix this:
    1. before creating the for loop, create a boolean. This represents if the command has been found in the config. Set this initially to false
    2. Inside the for loop, check if the command does match the string from the config.
    3. If so, set the boolean to true and break;
    4. Then, outside of the for loop, check if the boolean is false (that it still has not found the command)
    5. If that is true, then cancel the event and send a message.
     
    MrAndeos likes this.
  5. Offline

    MrAndeos

Thread Status:
Not open for further replies.

Share This Page