Check if a player is vanished with VanishNoPacket

Discussion in 'Spigot Plugin Development' started by Whosker, May 26, 2015.

  1. Hello world.

    I'm starting in this world of developing plugins and I wanted to make a plugin that plays a sound to a player and changes his name's color when is mentioned in chat (I named it ChatManager).After days (literally) I've managed to do it, but now I want to disable this when the mentioned player is vanished.

    I think that the most used vanish plugin is VanishNoPacket, so I included their API to my code and called the class isVanished(player) to check if that player is vanished, but it didn't work.

    When I chat in-game the plugin crashes and the server console shows this message, which says that I have an error in line 58, which is this: if(vanish.getManager().isVanished(on.getName())){

    Code (Text):

    [13:40:49] [Async Chat Thread - #6/ERROR]: Could not pass event AsyncPlayerChatEvent to ChatManager v1.0
    org.bukkit.event.EventException
        at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:305) ~[spigot-1.8.jar:git-Spigot-4c7d0c0-96c2c39]
        at org.bukkit.plugin.RegisteredListener.callEvent(RegisteredListener.java:62) ~[spigot-1.8.jar:git-Spigot-4c7d0c0-96c2c39]
        at org.bukkit.plugin.SimplePluginManager.fireEvent(SimplePluginManager.java:502) [spigot-1.8.jar:git-Spigot-4c7d0c0-96c2c39]
        at org.bukkit.plugin.SimplePluginManager.callEvent(SimplePluginManager.java:484) [spigot-1.8.jar:git-Spigot-4c7d0c0-96c2c39]
        at net.minecraft.server.v1_8_R2.PlayerConnection.chat(PlayerConnection.java:1059) [spigot-1.8.jar:git-Spigot-4c7d0c0-96c2c39]
        at net.minecraft.server.v1_8_R2.PlayerConnection.a(PlayerConnection.java:997) [spigot-1.8.jar:git-Spigot-4c7d0c0-96c2c39]
        at net.minecraft.server.v1_8_R2.PacketPlayInChat$1.run(PacketPlayInChat.java:39) [spigot-1.8.jar:git-Spigot-4c7d0c0-96c2c39]
        at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:1.8.0_45]
        at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_45]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [?:1.8.0_45]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [?:1.8.0_45]
        at java.lang.Thread.run(Unknown Source) [?:1.8.0_45]
    Caused by: java.lang.NullPointerException
        at me.whosker.chatmanager.ChatManager.onChat(ChatManager.java:58) ~[?:?]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_45]
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_45]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_45]
        at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.8.0_45]
        at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:301) ~[spigot-1.8.jar:git-Spigot-4c7d0c0-96c2c39]
        ... 11 more
     
    And this is my code:
    Code (Text):
        @EventHandler
        public void onChat(AsyncPlayerChatEvent pe){
            Player p = pe.getPlayer();
            ChatColor color = ChatColor.WHITE;
            if(!p.hasPermission("chatmanager.nuevos")){
                p.sendMessage(ChatColor.RED + "Debes completar el proceso de admisión para poder hablar en el chat.");
                pe.setCancelled(true);
            } else if(pe.getPlayer().hasPermission("chatmanager.alertas")){
                for(Player on: Bukkit.getServer().getOnlinePlayers()){
                    Bukkit.broadcastMessage(on.getName() + "1"); //test
                    if(on != null && !on.equals(pe.getPlayer())){
                        if(on.hasPermission("chatmanager.staff")){
                            Bukkit.broadcastMessage(on.getName() + "2"); //test
                            color = ChatColor.GOLD;
                            if(vanish.getManager().isVanished(on.getName())){
                                Bukkit.broadcastMessage(on.getName() + " es invisible."); //test
                            }

                            Bukkit.broadcastMessage(on.getName() + "3"); //test
                        }
                        String mes = pe.getMessage();
                        if(org.apache.commons.lang.StringUtils.containsIgnoreCase(mes, " " + on.getName() + " ")){
                            mes = mes.replaceAll(" (?i)" + on.getName() + " ", " " + ChatColor.BLUE+on.getName()+ChatColor.RESET + " " + color);
                            playSound(on);
                        } else if(org.apache.commons.lang.StringUtils.equalsIgnoreCase(mes, on.getName())){
                            mes = mes.replaceAll("(?i)" + on.getName(), ChatColor.BLUE+on.getName()+ChatColor.RESET + color);
                            playSound(on);
                        } else if(org.apache.commons.lang.StringUtils.endsWithIgnoreCase(mes, " " + on.getName())){
                            mes = mes.replaceAll(" (?i)" + on.getName(), " " + ChatColor.BLUE+on.getName()+ChatColor.RESET + color);
                            playSound(on);
                        } else if(org.apache.commons.lang.StringUtils.startsWithIgnoreCase(mes, on.getName() + " ")){
                            mes = mes.replaceFirst("(?i)" + on.getName(), ChatColor.BLUE+on.getName()+ChatColor.RESET + color);
                            playSound(on);
                        }
                        pe.setMessage(mes);
                    }
                }
            }
        }
    I'm sorry if my dumb errors annoys anyone, I am starting to develop plugins same than developing in Java, and I've only programmed in C and C++.
     
  2. Dumb question - have you initialized your vanish variable?

    Edit: And was Vanish already initialized when you initialized your vanish variable? Please add the dependency "Vanish" to your plugin.yml if not done already
     
  3. Could you please pastebin the whole class so we can use the line numbers of the stacktrace?
    Also it would be really cool if you can support my vanish plugin SuperVanish, too, it has a really simple api.
    Just make sure SuperVanish is enabled before using it.
     
  4. Yep, I did, since Eclipse won't let me compile if I don't initialize it.
    I didn't add the dependency to the plugin.yml file. Now, at least, the sent message is shown, but the error persists and it don't works if the player has the permission "chatmanager.staff", which makes the plugin check if the player is vanished.
    The stack-trace still says the error is in the line 58.

    Thank you for your reply :)

    EDIT: Here is my whole code:
    Code (Text):
    package me.whosker.chatmanager;

    import java.util.Timer;
    import java.util.TimerTask;
    import java.util.logging.Logger;

    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.Instrument;
    import org.bukkit.Note;
    import org.bukkit.Note.Tone;
    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;
    import org.kitteh.vanish.*;


    public class ChatManager extends JavaPlugin implements Listener{
        public final static Logger logger = Logger.getLogger("Minecraft");
        private VanishPlugin vanish;
     
        String header = ChatColor.RED + "[" + ChatColor.YELLOW + "*" + ChatColor.RED + "]" + ChatColor.YELLOW;
     
        public void onEnable(){
            getServer().getPluginManager().registerEvents(this, this);
            loadConfiguration();
            ChatManager.logger.info("Plugin activado correctamente");
        }
     
        public void onDisable(){
            ChatManager.logger.info("Plugin desactivado");
         
        }
     
        public void loadConfiguration(){
             getConfig().options().copyDefaults(true);
             saveConfig();
        }
     
        @EventHandler
        public void onChat(AsyncPlayerChatEvent pe){
            Player p = pe.getPlayer();
            ChatColor color = ChatColor.WHITE;
            if(!p.hasPermission("chatmanager.nuevos")){
                p.sendMessage(ChatColor.RED + "Debes completar el proceso de admisión para poder hablar en el chat.");
                pe.setCancelled(true);
            } else if(pe.getPlayer().hasPermission("chatmanager.alertas")){
                for(Player on: Bukkit.getServer().getOnlinePlayers()){
                    Bukkit.broadcastMessage(on.getName() + "1"); //test
                    if(on != null && !on.equals(pe.getPlayer())){
                        if(on.hasPermission("chatmanager.staff")){
                            Bukkit.broadcastMessage(on.getName() + "2"); //test
                            color = ChatColor.GOLD;
                            if(vanish.getManager().isVanished(on)){
                                Bukkit.broadcastMessage(on.getName() + " es invisible."); //test
                            }

                            Bukkit.broadcastMessage(on.getName() + "3"); //test
                        }
                        String mes = pe.getMessage();
                        if(org.apache.commons.lang.StringUtils.containsIgnoreCase(mes, " " + on.getName() + " ")){
                            mes = mes.replaceAll(" (?i)" + on.getName() + " ", " " + ChatColor.BLUE+on.getName()+ChatColor.RESET + " " + color);
                            playSound(on);
                        } else if(org.apache.commons.lang.StringUtils.equalsIgnoreCase(mes, on.getName())){
                            mes = mes.replaceAll("(?i)" + on.getName(), ChatColor.BLUE+on.getName()+ChatColor.RESET + color);
                            playSound(on);
                        } else if(org.apache.commons.lang.StringUtils.endsWithIgnoreCase(mes, " " + on.getName())){
                            mes = mes.replaceAll(" (?i)" + on.getName(), " " + ChatColor.BLUE+on.getName()+ChatColor.RESET + color);
                            playSound(on);
                        } else if(org.apache.commons.lang.StringUtils.startsWithIgnoreCase(mes, on.getName() + " ")){
                            mes = mes.replaceFirst("(?i)" + on.getName(), ChatColor.BLUE+on.getName()+ChatColor.RESET + color);
                            playSound(on);
                        }
                        pe.setMessage(mes);
                    }
                }
            }
        }
     
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
            if(label.equalsIgnoreCase("cm") || label.equalsIgnoreCase("chatmanager")){
                if(sender instanceof Player){
                    Player p = (Player) sender;
                 
                    switch(args.length){
                    case 0:
                        help(p);
                        break;
                    case 1:
                        switch (args[0]){
                        case "help":
                            help(p);
                            break;
                        case "aprobar":
                            p.sendMessage(header + ChatColor.RED + " Para aprobar a un jugador debes escribir '/cm a (nombre).");
                            break;
                        case "a":
                            p.sendMessage(header + ChatColor.RED + " Para aprobar a un jugador debes escribir '/cm a (nombre).");
                            break;
                        case "reload":
                            reloadConfig();
                            p.sendMessage(header + " Configuración actualizada.");
                            break;
                        default:
                            p.sendMessage(ChatColor.RED + "1Uso incorrecto. Escribe '/cm help' para ver una lista de comandos.");
                        }
                        break;
                    case 2:
                        switch (args[0]){
                        case "aprobar":
                            aprobar(p, args);
                            break;
                        case "a":
                            aprobar(p, args);
                            break;
                        default:
                            p.sendMessage(header + ChatColor.RED + " 2Uso incorrecto. Escribe '/cm help' para ver una lista de comandos.");
                        }
                        break;
                    default:
                        p.sendMessage(header + ChatColor.RED + " 3Uso incorrecto. Escribe '/cm help' para ver una lista de comandos.");
                    }
                } else sender.sendMessage(header + ChatColor.RED + "Este comando no se puede ejecutar desde la consola (no se como hacerlo, alomeho en la siguiente version).");
            }
            return true;
        }
     
        public void aprobar(Player sender, String[] args){
            if(sender.hasPermission("chatmanager.aprobar")){
                boolean encontrado=false;
                for(Player on: Bukkit.getServer().getOnlinePlayers()){
                    if(on.getName().equalsIgnoreCase(args[1])){
                        encontrado=true;
                        String aprobar = getConfig().getString("aprobar").replaceAll("%JUGADOR%", on.getName());
                        aprobar = ChatColor.translateAlternateColorCodes('&', aprobar);
                        Bukkit.broadcastMessage(aprobar);
                        Bukkit.getServer().dispatchCommand(sender.getServer().getConsoleSender(), "manuadd " + on.getName() + " default world");
                        Bukkit.getServer().dispatchCommand(sender.getServer().getConsoleSender(), "spawn " + on.getName());
                        break;
                    }
                }
                if(!encontrado) sender.sendMessage(header + ChatColor.RED + "No se ha podido encontrar al jugador \"" + args[0] + "\".");
            } else sender.sendMessage(ChatColor.RED + "No tienes permisos suficientes para ejecutar este comando.");
         
        }
     
        public void help(Player p){
            p.sendMessage("");
            p.sendMessage(ChatColor.YELLOW + "---- " + header + ChatColor.GRAY + " ChatManager " + header + " ----");
            p.sendMessage(ChatColor.RED + "/cm a (jugador)" + ChatColor.RESET + ": Aprueba al jugador, envía un mensaje de bienvenida, lo añade al grupo 'user' y lo mueve al spawn.");
            p.sendMessage(ChatColor.RED + "/cm reload" + ChatColor.RESET + ": Actualiza la config del plugin");
            p.sendMessage("");
        }
     
        public void playSound(final Player p){
            Timer t = new Timer();
            t.schedule(new TimerTask() {
                @Override
                public void run() {
                    p.playNote(p.getLocation(), Instrument.PIANO, Note.natural(1, Tone.A));

                }
            }, 200);
            p.playNote(p.getLocation(), Instrument.PIANO, Note.natural(1, Tone.D));
        }
    }
     

    The class makes other different things that work and I have no problem with.

    MyzelYam, I won't pubish this plugin and I will use it for a friend's server that uses VanishNoPacket, so it wouldn't be useful to add your plugin to mine. Anyway, I'll check it out and support it if I make another similar plugin or decide to publish it. Thank you for your interest :)
     
    #4 Whosker, May 26, 2015
    Last edited: May 26, 2015
  5. Try the following in line 58:

    Code (Text):
     org.kitteh.vanish.staticaccess.VanishNoPacket.getManager().isVanished(on.getName())
    Edit: Like i told you, you didn't initialize your vanish variable.
     
  6. How can I do that?

    This is what happens when I change it:

    [​IMG]
     
  7. Surround it :)
     
    • Like Like x 1
  8. It works! Thank you :D