How to use args from an onCommand with AysncPlayerChatEvent

Discussion in 'Plugin Development' started by PumpMelon, Aug 20, 2016.

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

    PumpMelon

    Hello!
    I'm trying to get the args from my onCommand and take those and use them in AysncPlayerChatEvent.

    Code:
    package com.PumpMelon.EasyPrefix;
    
    import java.util.logging.Logger;
    
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.AsyncPlayerChatEvent;
    import org.bukkit.plugin.java.JavaPlugin;
    
    public class Main extends JavaPlugin implements Listener{
     
        Logger log = Logger.getLogger("Minecraft");
    
        public void onEnable(){
            this.log.info("EasyPrefix has been enabled!");
         
        }
     
        public static void EasyPrefixColors(){
            String prefix = "§e[§fEasyPrefix§3] ";
        }
        public static String format(String format){
            return ChatColor.translateAlternateColorCodes('&', format);
            }
        public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
            String prefix = "§e[§fEasyPrefix§3] ";
    
            if(cmd.getName().equalsIgnoreCase("author")){
                sender.sendMessage("PumpMelon developed EasyPrefix (");
            }
            if(cmd.getName().equalsIgnoreCase("/setprefix") && sender.hasPermission("easyprefix.set")){
                if(args.length == 0){
                    sender.sendMessage(prefix + "Please specify a player!");
                }
                if(args.length == 1){
                    sender.sendMessage(prefix + "Please specify a prefix!");
                 
                }
                if(args.length == 2){
                    String playername = args[1];
                    String playerprefix = args[2];
                 
                    sender.sendMessage(prefix + "Prefix has been set!");
                    }
            }
            return false;
         
        }
     
        @EventHandler
        public void PlayerChat(AsyncPlayerChatEvent e){
            Player p = e.getPlayer();
            if(playername == p.getName()){
                p.setDisplayName(playerprefix + p.getName());
            }
        }
     
    
     
    }
    
    //I've tried nesting the AsyncChat inside of the onCommand but to no avail..
    
    //Thanks for the help!
     
    Last edited by a moderator: Aug 25, 2016
  2. Offline

    Zombie_Striker

    Don't steal minecraft's logger. Use getLogger if you need the logger (which you don't)
    1. You don't own pumpmelon.com, so don't use it as your package. Use me.<name>.<project> instead.
    2. package names should be lower case.
    1. Bukkit logs your plugins for you, so you can remove the logger here
    2. You need to register your class in order for the events to work.

    Why not just store the instance of the prefix as a field? It will reduce the amount of instances you create, and will be easier to manage. BTW: This method is never even used. You can delete it without any problems.

    This was in your onCommand. You should use a field (stated above) for prefix.

    Unless you specified that there should be two slashes (//setprefix), you should delete that extra slash.

    These are all youjr if statements. Since there is no way for args to be both 0, 1, or 2 at the same time, use else if statements for these.

    Return true if the command worked as it should. Return false if something failed/command did not work as it was inteneded.

    This will never be true. the variable "playername" does not exist, and you can't compare strings using ==. Use .equals instead.

    Your main issue:
    You should create a Map to store the prefixs in. Create a map where the keys are UUIDs, and the values are Strings. The UUIDS represent the UUID of the player, while the String represents the prefix. When you want to set a prefix, put the prefix into the map. When a player types something in chat, get their prefix from the map and add it to the message (only if there is a prefix in the map. You will need to check if they are in the map, because trying to get their prefix will return a null value if they are not)
     
    DuaneTheDev_ likes this.
  3. Offline

    PumpMelon

    Thanks!
    I've restarted it because it was just a mess and took your tips. I think I have it except for adding the values to the hashmap..

    Code:
    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
            if(cmd.getName().equalsIgnoreCase("author")){
                sender.sendMessage("The developer of EasyPrefix is PumpMelon (");
                return true;
            }
            if(cmd.getName().equalsIgnoreCase("setprefix") && sender.hasPermission("easyprefix.set")){
                if(args.length == 0){
                    sender.sendMessage(prefix + "§cProper usage: /setprefix <player> <prefix> ");
                    return false;
                }
                else if(args.length == 1){
                    sender.sendMessage(prefix + "§cProper usage: /setprefix <player> <prefix> ");
                    return false;
                }
                else if(args.length == 2){
                 
                    Player pname = Bukkit.getPlayer(args[1]);
                UUID pUUID = pname.getUniqueId();
                String prefixstr = args[2].toString();
                info.add(pUUID, prefixstr);
             
                }
             
    
             
             
            }
            return false;
        }
    The ".add" at the end is undefined for type HashMap, and when I cast info object it does nothing.
     
    Last edited by a moderator: Aug 25, 2016
  4. Offline

    Zombie_Striker

    @PumpMelon
    Hashmaps have the method "put" instead of add. Just replace "add" with "put".
     
  5. Offline

    PumpMelon

    Last thing I believe, after checking if its UUID is in the map how would I match it with its prefix...?
    Heres my code
    Code:
    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
            if(cmd.getName().equalsIgnoreCase("author")){
                sender.sendMessage("The developer of EasyPrefix is PumpMelon (");
                return true;
            }
            if(cmd.getName().equalsIgnoreCase("setprefix") && sender.hasPermission("easyprefix.set")){
                if(args.length == 0){
                    sender.sendMessage(prefix + "§cProper usage: /setprefix <player> <prefix> ");
                    return false;
                }
                else if(args.length == 1){
                    sender.sendMessage(prefix + "§cProper usage: /setprefix <player> <prefix> ");
                    return false;
                }
                else if(args.length == 2){
                  
                    Player pname = Bukkit.getPlayer(args[1]);
                UUID pUUID = pname.getUniqueId();
                String prefixstr = args[2].toString();
                info.put(pUUID, prefixstr);
              
                }
              
              
                }
              
    
      
    
    
              
              
          
            return false;
            }
          
      
        @EventHandler
        public void onPlayerChat(AsyncPlayerChatEvent e){
            Player p = e.getPlayer();
            if(info.containsKey(p.getUniqueId())){
                p.setDisplayName(prefixstr + p.getName());
            }
          
        }
      
      
    
    }
     
    Last edited by a moderator: Aug 25, 2016
  6. @PumpMelon
    Use the Map's "get()" method. Since your map is keyed by UUID's you would put in "get(thePlayersUUID)" and that would return you the "prefixstr" string in the map.
     
  7. Offline

    PumpMelon

    How would I put the prefix in their display name? \

    Code:
    @EventHandler
        public void onPlayerChat(AsyncPlayerChatEvent e){
            Player p = e.getPlayer();
            if(info.get(p.getUniqueId()) != null){
                p.setDisplayName(info.get(key)){
                   
                }
                }
           
        }
       
       
    
    }
    
    It's the last line I need help with, thanks!
     
  8. @PumpMelon
    "info.get(playerUUID)" is what you need to do, it'll return you with the String from the map.
     
  9. Offline

    PumpMelon

    Ok thanks!
    Code:
    @EventHandler
        public void onPlayerChat(AsyncPlayerChatEvent e){
            Player p = e.getPlayer();
            if(info.get(p.getUniqueId()) != null){
                p.setDisplayName(info.get(p.getUniqueId()) + p.getName());
                }
                }
           
        }
       
    
    Is that what you mean?
     
  10. Offline

    DuaneTheDev_

    @PumpMelon

    You don't need all that args.length checking. Just check if it's less than 2 or greater than 2 else do stuff.

    Code:
    if(args.length < 2)  || if(args.length > 2) {
      sender.sendMessage(prefix + "§cProper usage: /setprefix <player> <prefix> ");
      return true; //It wouldn't be false as it properly sent the message for less arguments.
    } else {
       //do stuff
    }
     
    Last edited by a moderator: Aug 25, 2016
  11. Offline

    PumpMelon

    Ok, I've done this and when testing I get an error of

    [17:08:55 ERROR]: null org.bukkit.command.CommandException: Unhandled exception executing command 'settitle' in plugin SetTitle v1.0 at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52] at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:140) ~[craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52] at org.bukkit.craftbukkit.v1_8_R3.CraftServer.dispatchCommand(CraftServer.java:620) ~[craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52] at net.minecraft.server.v1_8_R3.PlayerConnection.handleCommand(PlayerConnection.java:1106) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52] at net.minecraft.server.v1_8_R3.PlayerConnection.a(PlayerConnection.java:966) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52] at net.minecraft.server.v1_8_R3.PacketPlayInChat.a(SourceFile:37) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52] at net.minecraft.server.v1_8_R3.PacketPlayInChat.a(SourceFile:9) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52] at net.minecraft.server.v1_8_R3.PlayerConnectionUtils$1.run(SourceFile:13) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52] at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_72] at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_72] at net.minecraft.server.v1_8_R3.SystemUtils.a(SourceFile:44) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52] at net.minecraft.server.v1_8_R3.MinecraftServer.B(MinecraftServer.java:673) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52] at net.minecraft.server.v1_8_R3.DedicatedServer.B(DedicatedServer.java:335) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52] at net.minecraft.server.v1_8_R3.MinecraftServer.A(MinecraftServer.java:629) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52] at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:537) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52] at java.lang.Thread.run(Thread.java:745) [?:1.8.0_72] Caused by: java.lang.NullPointerException at me.PumpMelon.SetTitle.Main.onCommand(Main.java:42) ~[?:?] at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52] ... 15 more
     
  12. Offline

    Zombie_Striker

    If you do not know how to read error logs, please read the following thread:
    https://bukkit.org/threads/how-to-r...ubleshoot-your-own-plugins-by-yourself.32457/

    Your issue is that something is null on line 42. To solve this issue, look at all the variables on line 42, and null check them. One (or more) of those variables are null. Once you find the variable that is null, figure out a way to make sure that variable will never be null.
     
  13. Offline

    PumpMelon

    Right... the only thing is there is nothing on line 42!

    [​IMG]
    https://gyazo.com/57d9740603af05710da75c427b777800
     
  14. Offline

    DuaneTheDev_

    @PumpMelon

    > = Greater than
    < = Less than

    Why would you check if args.length > 2 then send proper usage. If proper usage equals /settitle <player> <prefix> you wanna check if args.length < 3. Also return true, the plugin did as it was told and preformed the message.

    Then check if args.length == 3
     
  15. Offline

    PumpMelon

    Isn't it /command arg0 arg1 arg2 arg3?
    Why would I check if args.length ==3?
     
  16. Offline

    DuaneTheDev_

    @PumpMelon

    Oops yeah that's right it would be 2. I miss read a class on my eclipse project.
     
  17. @PumpMelon
    My bet is that the version you're running on your test server is not the same as in your IDE. If you compile the code and run it, does the error still come on the same line?
     
  18. Offline

    Roborack17

    You could save player's prefix to a config, it would be easier i guess, and then at AsyncPlayerChatEvent you just use a prefix that is saved to config.
     
  19. Offline

    PumpMelon

    [​IMG]
    https://gyazo.com/511f416e4156df44d6955faa6162cfa2
    @AlvinB
    I think theres something wrong with my run configuration...
    The output of the ConsoleRunner is shown in the picture,

    When I try using the compiler I get a JVM error telling me to check my installations..


    I've decided to do this now, thanks!
     
    Last edited: Aug 25, 2016
  20. Offline

    PumpMelon

    bump, still need help with this
     
  21. @PumpMelon
    I don't usually work in Eclipse, but I do believe "Main" in the CraftBukkit jar should be selected as the main class.

    Also, is there not a JAR application option to run in eclipse? I know there is in IntelliJ..
     
  22. @PumpMelon Don't run the server in the IDE, just run it locally and reload when you export the plugin.
     
  23. Offline

    PumpMelon

    Thanks!

    now how would I save the player and their prefix to a config.yml? I've tried all sorts of things but am getting an empty path error.

    my loadConfiguration
    Code:
    public void loadConfiguration(){
            String path = "Player.Prefix";
            getConfig().addDefault(path, "prefixstring");
            getConfig().options().copyDefaults(true);
            saveConfig();
        }
    
    my setting of player & prefix
    Code:
    else if(args.length == 2){
                   
                    @SuppressWarnings("deprecation")
                    UUID pname = Bukkit.getPlayer(args[0]).getUniqueId(); 
                    if(pname == null){
                        sender.sendMessage(prefix + "§cThat player's UUID does not exist!");
                        return false; 
                    }else{
                    String prefixstr = args[1].toString(); 
                    getConfig().set("Player.", pname);
                    getConfig().set("Player.Prefix", prefixstr);
                    saveConfig();
                   
                    return true; 
                    }
                }
    
    Thanks! (I'm not to good with configs,)
     
  24. @PumpMelon
    In this line you have a "." after Player. This is probably the problem. If it's not the problem, then please post the error you're getting.
     
  25. Offline

    PumpMelon

    @AlvinB
    Tried that, still the same error.

    Stack trace
    Code:
    [12:15:02 ERROR]: null org.bukkit.command.CommandException: Unhandled exception executing command 'settitle' in plugin SetTitle v1.0         at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:140) ~[craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         at org.bukkit.craftbukkit.v1_8_R3.CraftServer.dispatchCommand(CraftServer.java:620) ~[craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         at net.minecraft.server.v1_8_R3.PlayerConnection.handleCommand(PlayerConnection.java:1106) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         at net.minecraft.server.v1_8_R3.PlayerConnection.a(PlayerConnection.java:966) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         at net.minecraft.server.v1_8_R3.PacketPlayInChat.a(SourceFile:37) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         at net.minecraft.server.v1_8_R3.PacketPlayInChat.a(SourceFile:9) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         at net.minecraft.server.v1_8_R3.PlayerConnectionUtils$1.run(SourceFile:13) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_72]         at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_72]         at net.minecraft.server.v1_8_R3.SystemUtils.a(SourceFile:44) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         at net.minecraft.server.v1_8_R3.MinecraftServer.B(MinecraftServer.java:673) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         at net.minecraft.server.v1_8_R3.DedicatedServer.B(DedicatedServer.java:335) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         at net.minecraft.server.v1_8_R3.MinecraftServer.A(MinecraftServer.java:629) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:537) [craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         at java.lang.Thread.run(Thread.java:745) [?:1.8.0_72] Caused by: java.lang.IllegalArgumentException: Cannot set to an empty path         at org.apache.commons.lang.Validate.notEmpty(Validate.java:321) ~[craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         at org.bukkit.configuration.MemorySection.set(MemorySection.java:163) ~[craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         at org.bukkit.configuration.MemorySection.set(MemorySection.java:193) ~[craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         at me.PumpMelon.SetTitle.SetTitle.onCommand(SetTitle.java:51) ~[?:?]         at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[craftbukkit-1.8.8.jar:git-Bukkit-e1ebe52]         ... 15 more
     
  26. @PumpMelon
    And can you show me the code, after you fixed the . thing?

    And also, which line is line 51 of the "SetTitle" class?
     
  27. Offline

    PumpMelon

  28. Offline

    Zombie_Striker

    The path you provided does not or cannot exist. Make sure your path exists in the config, and that it does not end with a period, colon, simi colon, ect.
     
  29. @PumpMelon
    Well, you did not remove the dot after "Player", did you?
     
Thread Status:
Not open for further replies.

Share This Page