[TUT] Using sk89q's command framework

Discussion in 'Resources' started by molenzwiebel, Oct 20, 2013.

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

    molenzwiebel

    When looking through GitHub some time ago, I stumbled upon @sk89q's command framework. I have used it in a lot of my plugins now and I can say that it is a awesome system. Here is how to use it!

    Step 1: Installing the framework
    Option 1: Depending on WorldEdit. This is probably the easiest way to include the framework, but the downside is that the server owner needs WorldEdit installed.
    Option 2: Copy all the files from OvercastNetwork/sk89q-command-framework to your project. A way to do it, but not recommended (by me).
    Option 3: Add it as a maven dependency and shade it:
    pom.xml (open)

    Code:
    //Add the oc.tc (Overcast Network) repo
     
    <repository>
        <id>repo.oc.tc</id>
        <url>http://repo.oc.tc/content/repositories/releases/</url>
    </repository>
     
     
    //Add the dependency
     
    <dependency>
        <groupId>com.sk89q</groupId>
        <artifactId>sk89q-command-framework</artifactId>
        <version>0.5</version>
    </dependency>
     
    


    Step 2: Adding the onCommand handler
    Start by defining a variable in your main class:
    Code:java
    1. private CommandsManager<CommandSender> commands;

    After that, add this method to initiate your manager
    Code:java
    1. private void setupCommands() {
    2. this.commands = new CommandsManager<CommandSender>() {
    3. @Override
    4. public boolean hasPermission(CommandSender sender, String perm) {
    5. return sender instanceof ConsoleCommandSender || sender.hasPermission(perm);
    6. }
    7. };
    8. CommandsManagerRegistration cmdRegister = new CommandsManagerRegistration(this, this.commands);
    9. //Register your commands here
    10. }

    Almost done! Now you need one more thing. The onCommand:
    Code:java
    1. @Override
    2. public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
    3. try {
    4. this.commands.execute(cmd.getName(), args, sender, sender);
    5. } catch (CommandPermissionsException e) {
    6. sender.sendMessage(ChatColor.RED + "You don't have permission.");
    7. } catch (MissingNestedCommandException e) {
    8. sender.sendMessage(ChatColor.RED + e.getUsage());
    9. } catch (CommandUsageException e) {
    10. sender.sendMessage(ChatColor.RED + e.getMessage());
    11. sender.sendMessage(ChatColor.RED + e.getUsage());
    12. } catch (WrappedCommandException e) {
    13. if (e.getCause() instanceof NumberFormatException) {
    14. sender.sendMessage(ChatColor.RED + "Number expected, string received instead.");
    15. } else {
    16. sender.sendMessage(ChatColor.RED + "An error has occurred. See console.");
    17. e.printStackTrace();
    18. }
    19. } catch (CommandException e) {
    20. sender.sendMessage(ChatColor.RED + e.getMessage());
    21. }
    22.  
    23. return true;
    24. }

    That's all the code you'll need in your main class, lets go on and make some commands!

    Step 3: The Commands
    First, create a new class. You can name it whatever you want.
    The Command Structure
    Every command method has a @Command annotation, which defines certain aspects of the command. Have a look at this example:
    Code:
    @Command(aliases = { "hello", "hey" }, desc = "Says hello", usage = "[player] - The player to say hello to", min = 1, max = 1)
    This will create a command that can be called with either hello or hey, has the description of "Says hello" in the help list, has a min of 1 arguments and a max of 1 arguments (set to -1 for infinite) and prints the usage ("Usage: /hello [player] - The player to say hello to") on incorrect usage.

    After the @Command, you'll need a method like this
    Code:java
    1. public static void hello(final CommandContext args, CommandSender sender) throws Exception {

    Note that the method can be called anything, as long as it is after a @Command.

    Here is an example of the hello command:
    Code:java
    1. @Command(aliases = { "hello", "hey" }, desc = "Says hello", usage = "[player] - The player to say hello to", min = 1, max = 1)
    2. public static void hello(final CommandContext args, CommandSender sender) throws CommandException {
    3. Player target = Bukkit.getPlayer(args.getString(0)); //0 is the index
    4. if (target == null) throw new CommandException("Player "+args.getString(0)+" not found!");
    5. target.sendMessage("Hello!");
    6. }


    Step 4: Registering your commands
    This is probably the easiest step. Remember the setupCommands method in your main class? After all the code that's already in there, call
    Code:
    cmdRegister.register(MYCOMMANDCLASS.class);

    Step 3b: Command tricks
    The CommandContext
    The CommandContext is an advanced version of String[] args. It allows for some really cool usages. Here are the methods you are most likely using most:
    args.getString(index) Gets the string at a certain index
    args.getInt(index) Gets the int at a certain index, throws an error message (see the onCommand) if the index is not a string
    args.getJoinedStrings(index) Joins all the strings after index. For example, if the player did /hello <player> I am awesome and you are not, args.getJoinedStrings(1) will return I am....
    For every get<TYPE> command, you can also supply a default value. For example, if you do args.getInt(0, 10) it'll be 10 if the player did not pass an int at index 0.
    For a full documentation on CommandContext, have a look here

    Flags!
    @Command also allows you to specify flags for the player to pass in! Just add flags="a" in your @Command to allow the player to do /hello -a <player>. You can also require a flag to have a value by adding a : in front of it. For example, flags=":ab" will allow you to pass in -b and -a <value>.
    The CommandContext also has the method hasFlag('b') and getFlag('a') for getting the flags.

    Nested commands
    You can allow for nested commands (/myplugin <command>) by adding a @NestedCommand. An example of this is here.

    Conclusion
    I feel that the real power of sk89q's command framework lies in the NestedCommands, but overall it is a really powerful system for handling commands. I hope you try it out :)
     
  2. Offline

    SacredWaste

    I alway's wanted a better command framework I could actually understand, the other ones always confused me somewheres along the road, and never saw a tutorial on how to use this yet. Thank you.
     
  3. Offline

    ejzz

    This is a really good tutorial, great job molenz.
     
  4. I hate to bump, but the Maven setup in the OP is no longer working.
     
  5. Offline

    RainoBoy97

    Incomprehendable likes this.
  6. RainoBoy97
    I do believe that has fixed the issue, but the Overcast Network is currently down. Is there some other maven repo with the standalone framework?
     
  7. Offline

    RainoBoy97

    Incomprehendable
    I dont think there is. I'm also waiting for Overcast's repository to go live again, can't build my plugin without it :p
     
    Incomprehendable likes this.
  8. RainoBoy97
    Back to depending on WorldEdit, then. Let's hope it's back up soon enough. Thanks for your help!
    EDIT: I asked the owner of the network on Twitter. He doesn't know of any alternatives and has no ETA.
     
  9. Offline

    ejzz

    For all future visitors, repo.oc.tc is up again.
     
  10. While the Overcast Network's Maven repository is back up, the shading part of the OP is now horribly incorrect. I'm pretty sure that the new repository link is https://repo.oc.tc/content/groups/public/, and I'm still unaware of the actual artifact ID. But I'm sure that the version is now 0.5-SNAPSHOT. Any help on this would be appreciated.
     
  11. Offline

    Gamecube762

    Din't know sk89q had a framework like this, looking into using this for some of my bigger projects. :D
     
  12. Offline

    RainoBoy97

    Incomprehendable
    This is what I use, I'm not sure if this is the "correct" one to use.
    Code:
    <dependency>
    <groupId>com.sk89q</groupId>
    <artifactId>sk89q-command-framework</artifactId>
    <version>0.4-SNAPSHOT</version>
    </dependency>
    
     
  13. RainoBoy97
    That doesn't seem to be working. When you go to repo.oc.tc, click "Repositories", and then click "Releases", there's no "com" directory. There's one in the "Public" repository though, but in that one, there is no "0.4-SNAPSHOT" version, only a "0.5-SNAPSHOT" one. The artifacts in the public repository are:

    • command-framework-bukkit
    • command-framework-bungee
    • command-framework-core
    • command-framework-parent
    Sorry if I'm making any nooby mistakes, I'm a bit new to Maven.

    EDIT: Fixed.
    I managed to solve this on my own.

    For all of those who may have had this issue, here are the details you want to put in your pom.xml:
    REPO ID: repo.oc.tc
    REPO URL: https://repo.oc.tc/content/groups/public/
    DEPENDENCY GROUP ID: com.sk89q
    DEPENDENCY ARTIFACT ID: command-framework-bukkit
    DEPENDENCY VERSION: 0.5-SNAPSHOT
     
  14. I hate to double post, but I did resolve this issue. Look in my post above. ^
     
  15. For future reference here's a POM.xml for my PVPMoney plugin and it works absolutely fine:
    Code:
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.frostcore</groupId>
        <artifactId>PVPMoney</artifactId>
        <version>0.7</version>
        <build>
            <defaultGoal>clean install</defaultGoal>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-shade-plugin</artifactId>
                    <version>2.3</version>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>shade</goal>
                            </goals>
                            <configuration>
                                <finalName>PVPMoney</finalName>
                                <useBaseVersion>true</useBaseVersion>
                                <shadedClassifierName/>
                                <outputDirectory>${project.basedir}</outputDirectory>
                                <artifactSet>
                                    <includes>
                                        <include>net.gravitydevelopment.updater:updater</include>
                                        <include>com.sk89q:command-framework-bukkit</include>
                                        <include>org.mcstats.bukkit:metrics</include>
                                    </includes>
                                </artifactSet>
                                <relocations>
                                    <relocation>
                                        <pattern>net.gravitydevelopment.updater</pattern>
                                        <shadedPattern>com.frostcore.pvpmoney.updater</shadedPattern>
                                    </relocation>
                                    <relocation>
                                        <pattern>com.sk89q:command-framework-bukkit</pattern>
                                        <shadedPattern>com.frostcore.pvpmoney.commands</shadedPattern>
                                    </relocation>
                                    <relocation>
                                        <pattern>org.mcstats.bukkit:metrics</pattern>
                                        <shadedPattern>com.frostcore.pvpmoney.metrics</shadedPattern>
                                    </relocation>
                                </relocations>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
        <repositories>
            <repository>
                <id>bukkit-repo</id>
                <url>http://repo.bukkit.org/content/groups/public/</url>
            </repository>
            <repository>
                <id>vault-repo</id>
                <url>http://nexus.theyeticave.net/content/repositories/pub_releases/</url>
            </repository>
            <repository>
                <id>Plugin Metrics</id>
                <url>http://repo.mcstats.org/content/repositories/public</url>
            </repository>
            <repository>
                <id>repo.oc.tc</id>
                <url>http://repo.oc.tc/content/repositories/public/</url>
            </repository>
            <repository>
                <id>gravity-repo</id>
                <url>http://repo.gravitydevelopment.net</url>
            </repository>
        </repositories>
        <dependencies>
            <dependency>
                <groupId>org.bukkit</groupId>
                <artifactId>bukkit</artifactId>
                <version>LATEST</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.mcstats.bukkit</groupId>
                <artifactId>metrics</artifactId>
                <version>R7</version>
            </dependency>
            <dependency>
                <groupId>net.milkbowl.vault</groupId>
                <artifactId>VaultAPI</artifactId>
                <version>1.4</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>com.sk89q</groupId>
                <artifactId>command-framework-bukkit</artifactId>
                <version>0.5-SNAPSHOT</version>
            </dependency>
            <dependency>
                <groupId>net.gravitydevelopment.updater</groupId>
                <artifactId>updater</artifactId>
                <version>2.1</version>
            </dependency>
        </dependencies>
    </project>
     
  16. Offline

    raGan.

    Incomprehendable
    You don't need to wait for repos to come online to build, you can always build it yourself. Fetch the code from github and do a clean install with maven. You will end up with perfectly usable build in your local maven repo. It's even written in readme.
     
  17. raGan.
    "Complaining > Competence"
    In seriousness, I wasn't aware of that, thanks for letting me know!
     
  18. Offline

    IDragonfire

    Is there any fancy way to differ player vs. Console command?
     
  19. Offline

    techboy291

    No, I don't think so. I usually do something like:
    Code:
    if (!(sender instanceof Player))
    throw new CommandException("You must be a player to use this command.");
    
    And if you don't put a @ Console annotation before your command method, I don't think it will be called if the command was issued by the console. I'm not sure if the method will be called by a command block or not though.
     
Thread Status:
Not open for further replies.

Share This Page