Tutorial Semi-Advanced Command Template

Discussion in 'Resources' started by UnRatable, Dec 22, 2014.

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

    UnRatable

    Ok so i've tried to make the easiest and most convenient template.

    Heres the full template:
    Code:
    package me.unratable;
    
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.permissions.Permission;
    
    public class _Template implements CommandExecutor {
       
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
           
            if (sender instanceof Player) {
                Player player = (Player) sender;
                //Messages
                String prefix = ChatColor.GRAY + "CMD" + ChatColor.DARK_GRAY + "> ";
                String info = ChatColor.GRAY + "Info" + ChatColor.DARK_GRAY + "> ";
                String syntaxerror = ChatColor.YELLOW + "Incorrect Syntax";
                String noperm = ChatColor.YELLOW + "No permission";
                String notfound = ChatColor.YELLOW + "Player not found";
                String success = ChatColor.YELLOW + "CMD";
               
                //if uses arguments
                Player target = Bukkit.getServer().getPlayerExact(args[0]);
               
                //command and permission
                    if(cmd.getName().equalsIgnoreCase("CMD")) {
                        if(player.isOp() || player.hasPermission(new Permission("pluginname.CMD"))) {
                            //too few arguments
                            if(args.length == 0) {
                                player.sendMessage(prefix + syntaxerror);
                                return true;
                            }
                            //target is offline or cannot be found
                            if(target == null) {
                                player.sendMessage(prefix + notfound);
                            }
                                //What this CMD does:
                               
                                    //
                           
                            //success
                            player.sendMessage(prefix + success);
                           
                        } else {
                            //deny permission
                            player.sendMessage(info + noperm);
                        }
                    }
                }
            return true;
        }
    }
    So heres the breakdown..
    Code:
    package me.unratable;
    
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.permissions.Permission;
    This is where all your imports go, this is mandatory in all plugins if you did not know.

    Code:
    public class _Template implements CommandExecutor 
    This implements the command executor that we used in the main class which is under this text
    Code:
    gmc gmc = new gmc();
    getCommand("gmc").setExecutor(gmc);
    For that we've used "gmc" as a command that changes the gamemode of a player to creative.
    That is the basic setup you can use as many of these as you want just dont forget that you have to use that same layout. Also when your making this make a class named "gmc" for example or whatever you typed. It could be
    Code:
    example example = new exmaple();
    getCommand("example").setExecutor(example);
    So instead of making a class named "gmc" your class will be named "example" or whatever you call your command.

    So now we move on to the command.
    Code:
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    This is if you are making a command plugin, if your reading this you most likely are.

    Next comes the instance of the player
    Code:
            if (sender instanceof Player) {
                Player player = (Player) sender;
    This is to check if the player is executing the command or the console etc. So if the player is executing the command then it will move along, and if not. Well.. it wont do anything.

    Code:
                String prefix = ChatColor.GRAY + "CMD" + ChatColor.DARK_GRAY + "> ";
                String info = ChatColor.GRAY + "Info" + ChatColor.DARK_GRAY + "> ";
                String syntaxerror = ChatColor.YELLOW + "Incorrect Syntax";
                String noperm = ChatColor.YELLOW + "No permission";
                String notfound = ChatColor.YELLOW + "Player not found";
                String success = ChatColor.YELLOW + "CMD";
    Strings or "Messages" come next. These are at the top so you would not need to scroll down and find the line that that message was on and so on. This is also easily interchangeable if you named a string noperm and the player doesent have the permission it will output the message that is at the top by simply putting the name (in this case being noperm) instead of your message. Combining these works aswell, just a plus sign in-between these strings.

    Code:
        //if uses arguments
                Player target = Bukkit.getServer().getPlayerExact(args[0]);
    This is only if your command does things to other players. For example: /gmc Bob it will change "Bob's" gamemode to creative. But if your command just changes the gamemode of the player that types in the command, this is not needed.

    Code:
                //command and permission
                    if(cmd.getName().equalsIgnoreCase("CMD")) {
                        if(player.isOp() || player.hasPermission(new Permission("pluginname.CMD")))
    Ok this is quite basic aswell. It handles the command name and permission. the first line checks whats the command name for this example it is "CMD" so the player will have to type /cmd to execute it. The second line handles permissions.
    Code:
    if(player.isOp()
    Will make the command work if the player does not have the permission but is op and
    Code:
    || player.hasPermission(new Permission("pluginname.CMD)))
    Checks if the player has the permission. It will work if the player does have the permission or is opped. But if the player does not have the permission or is not oped the plugin will send the player the message "Info> No permission" as we set earlier with the strings.
    Code:
                            //too few arguments
                            if(args.length == 0) {
                                player.sendMessage(prefix + syntaxerror);
                                return true;
                            }
    This checks if the player has just put in the command and no arguments. If your command does not use arguments then you can just delete this line. Also there is a example of the Strings in the 3rd line: player.sendMessage(prefix + syntaxerror);
    Code:
                            //target is offline or cannot be found
                            if(target == null) {
                                player.sendMessage(prefix + notfound);
                            }
    This checks if the player can or cannot be found. Also if your command does not use arguments, just delete this part.
    Code:
                                //What this CMD does:
                               
                                    //
    Here is what your command will do so in our example of changing gamemode.. It will be player.setGameMode(GameMode.CREATIVE);
    Code:
                            //success
                            player.sendMessage(prefix + success);
                           
                        } else {
                            //deny permission
                            player.sendMessage(info + noperm);
                        }
                    }
                }
            return true;
        }
    }
    Success sends out a success message if the command was successful. the other message is when the player does not have the permission.

    So thats basically it sorry for making this soo long.

    Command with arguments template:
    Code:
    package me.unratable;
    
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.permissions.Permission;
    
    public class _Template implements CommandExecutor {
       
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
           
            if (sender instanceof Player) {
                Player player = (Player) sender;
                //Messages
                String prefix = ChatColor.GRAY + "CMD" + ChatColor.DARK_GRAY + "> ";
                String info = ChatColor.GRAY + "Info" + ChatColor.DARK_GRAY + "> ";
                String syntaxerror = ChatColor.YELLOW + "Incorrect Syntax";
                String noperm = ChatColor.YELLOW + "No permission";
                String notfound = ChatColor.YELLOW + "Player not found";
                String success = ChatColor.YELLOW + "CMD";
               
                //if uses arguments
                Player target = Bukkit.getServer().getPlayerExact(args[0]);
               
                //command and permission
                    if(cmd.getName().equalsIgnoreCase("CMD")) {
                        if(player.isOp() || player.hasPermission(new Permission("pluginname.CMD"))) {
                            //too few arguments
                            if(args.length == 0) {
                                player.sendMessage(prefix + syntaxerror);
                                return true;
                            }
                            //target is offline or cannot be found
                            if(target == null) {
                                player.sendMessage(prefix + notfound);
                            }
                                //What this CMD does:
                               
                                    //
                           
                            //success
                            player.sendMessage(prefix + success);
                           
                        } else {
                            //deny permission
                            player.sendMessage(info + noperm);
                        }
                    }
                }
            return true;
        }
    }
    Template if your command just applies to the player executing it
    Code:
    package me.unratable;
    
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.permissions.Permission;
    
    public class _Template implements CommandExecutor {
       
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
           
            if (sender instanceof Player) {
                Player player = (Player) sender;
                //Messages
                String prefix = ChatColor.GRAY + "CMD" + ChatColor.DARK_GRAY + "> ";
                String info = ChatColor.GRAY + "Info" + ChatColor.DARK_GRAY + "> ";
                String noperm = ChatColor.YELLOW + "No permission";
                String success = ChatColor.YELLOW + "CMD";
               
                //command and permission
                    if(cmd.getName().equalsIgnoreCase("CMD")) {
                        if(player.isOp() || player.hasPermission(new Permission("pluginname.CMD"))) {
                                //What this CMD does:
                               
                                    //
                           
                            //success
                            player.sendMessage(prefix + success);
                           
                        } else {
                            //deny permission
                            player.sendMessage(info + noperm);
                        }
                    }
                }
            return true;
        }
    }
    This ends my tutorial if this was not the easiest to read im very sorry I was up for around 40 hours without any sleep and barely any food. Tell me how I could improve if you want to, all up to you :)
     
    ChipDev likes this.
  2. Offline

    Shawckz

    You forgot to return true, if you don't return true if the target is null, the code will still run.
    This isn't bad to use, but remember players are lazy. using Bukkit#getPlayer will find a player even if the case isn't exact or if the name isn't typed fully. Ex getPlayer("Shock") could find me if my IGN is Shockz__.

    I wouldn't put this on this specific template, it would be OK in player-only commands for example sethome,
    but here it is unnecessary.
    If you are going to use this, at least do
    Code:
    if (sender instanceof Player) {
    //player code
    }
    else{
    sender.sendMessage("Only players may use this command");
    }
    So that the console will at least get a message instead of just ignoring the sender if it is not a player.

    can be simplified to

    Code:
    if(player.hasPermission("pluginname.cmd")
    can be simplified to

    Code:
    getCommand("example").setExecutor(new Example());
    Also, class names should not be lowercase.

    Code:
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    
                //command and permission
                if(cmd.getName().equalsIgnoreCase("someCommand")) {
                    if(sender.hasPermission("some.permission")) {
    
                        //Insert your code here that will execute when a player types /someCommand and has some.permission
    
                        sender.sendMessage("Some success message");
    
                    } else {
                        sender.sendMessage("Some you do not have permissions message");
                    }
            }
            return true;
        }
    Forgive me for typos or small mistakes, wrote this on my phone.
     
  3. Offline

    Dragonphase

    @UnRatable

    This isn't as convenient as it could be. When parsing lots of commands and command args, the template you provided will quickly become hard to follow and will lose its structure.

    There are ways to achieve convenience using a structure. For example, create methods to handle individual command arguments. Remove the first element of args when passing them to subcommand handler methods.
     
  4. Offline

    UnRatable

    @Dragonphase As I said I was up for 40 hours with barely any sleep I could've made this simpler but I was really tired.
     
  5. Offline

    bob7

    Quick tip:

    If you are going to use the same String over and over again, put it on final field to avoid creating a new string instance every time.
     
  6. Offline

    Experminator

    @bob7 Or make a message manager with constants. Like:
    Code:
    public class Message {
      
       public static String NO_PERM = "You do not have permission.";
       public static String NO_ARGS = "No arguments specified.";
    }
    Can be accessed by: Message.NO_PERM.
     
  7. Offline

    Shawckz

    You're burning my eyes.
    finalize static pls .-.
     
    xTrollxDudex likes this.
  8. Offline

    Dragonphase

    @UnRatable

    It was more of an observation that you state it's a "Semi-Advanced" tutorial in the thread title, when it's more of a basic tutorial.
     
  9. Offline

    Shawckz

    Pretty sure an enum might be better

    Code:
    public enum MessageType{
    
    NO_PERM("You do not have permission to do this."),
    INCORRECT_SYNTAX("Incorrect syntax!"); //etc
    
    private String message;
    
    MessageType(String message){
    this.message = message;
    }
    
    public String getMessage(){
    return message;
    }
    
    }
    
    and then

    Code:
    public class Msg{
    
    public void sendMsg(Player p, MessageType type, String... s){//string is optional
    if(s!=null){
    p.sendMessage(type.getMessage());
    }
    else{
    p.sendMessage(type.getMessage() + " " + s);//or something alike
    }
    }
    
    }
     
  10. Offline

    Experminator

    @Shawckz You're right, but i said that, because not everyone understand enumerators.
    And second point,
    If you add 'String.... s'
    In your 'sendMsg()' method, then get the player (for example) the no permission message.. + the String.

    Conclusion: You could remove the 'String... s' argument.
     
  11. Offline

    Shawckz

    I know, I wrote it quickly lol
     
Thread Status:
Not open for further replies.

Share This Page