Sending a command in console with colors

Discussion in 'Spigot Plugin Development' started by MaxNatural, Jun 7, 2016.

  1. I am trying to make it so when someone purchases an item on my Enjin store it will send the player a message saying the purchase went through and they received the items. I want the command to work in the console and send change the colors so you can customize and uses the & sign for the colors.

    Her is the code I have so far.
    Code (Text):
        public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
            Player p = (Player) sender;
            if (p.hasPermission("ch.shoppm")) {
                if (cmd.getName().equalsIgnoreCase("shoppm")) {
                    if (args.length < 2) {
                        p.sendMessage(Core.prefix + "/shoppn <Player_Name> <Msg>");
                        return true;
                    }

                    if(Bukkit.getPlayer(args[0]) == null) {
                        p.sendMessage(Core.prefix + "Player is not online!");
                    }

                    String msg = "";
                    for (String s : args) {
                        msg = msg + " " + s;

                    }

                    Bukkit.getPlayer(args[0]).sendMessage(Core.prefix + msg.replaceFirst(" " + args[0], ""));
                    return true;
                }

            }
            return true;
        }

    }
     
     
  2. All you have to do is remove the Player p = (Player) sender; line. Also, that is called blind casting. The sender may not be a player and you are trying to make them a player. That is a bad practice too. Since you're only using the sendMessage method and none from the Player interface you can replace "p" with the sender variable. Doing that will not cause errors when running that command from the console.
     
  3. You might want to check the JavaDocs.

    Bukkit#getConsoleSender();

    Don't blind cast

    Your for loop won't work properly so I suggest you review that. Try printing out what the msg thing is every time it loops ;)
     
  4. it's not really necessary he could use that in future, he is implying about purchasing an item which means he needs to use the PlayerInventory class to give him an item afterwards.