Using permission nodes throughout your plugins

In some cases, you may want to check whether a player has a specific permission from within your code. With the addition of a universal permission system within Bukkit, this is very easy, regardless of the permission plugin that you are using. Looking at the Bukkit API documentation, you will see that the Player object contains a hasPermission method, which returns a Boolean response. The method requires a string value, which is the permission node that is being checked. We can place this method in an if statement, as shown in the following code:

if (player.hasPermission("enchanter.enchant")) {
  //Add a level 10 Knockback enchantment
  Enchantment enchant = Enchantment.KNOCKBACK;
  hand.addUnsafeEnchantment(enchant, 10);
  player.sendMessage("Your item has been enchanted!");
} else {
  player.sendMessage("You do not have permission to enchant");
}

This block of code is unnecessary for the plugin because Bukkit can automatically handle player permissions for commands. To have a look at how this is properly used, let's go back to MyFirstBukkitPlugin and add a permission check. The following code is the modified onEnable method, which will only say Hello to the players who have the necessary permission:

@Override
public void onEnable() {
  if (Bukkit.getOnlinePlayers().size() >= 1) {
    for (Player player : Bukkit.getOnlinePlayers()) {
      //Only say 'Hello' to each player that has permission
      if (player.hasPermission("myfirstbukkitplugin.greeting")) {
        player.sendMessage("Hello " + player.getName());
      }
    }
  } else {
    //Say 'Hello' to the Minecraft World
    broadcastToServer("Hello World!");
  }
}

Remember that you will also have to modify plugin.yml to add the permission node to your plugin.

You can also broadcast a message to only the players who have a specific permission node. The documentation on this can be found at https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Bukkit.html#broadcast(java.lang.String,%20java.lang.String).

Try adding some permission nodes to some other projects that were created in the previous chapters. For example, add the creeperhiss.scare permission node to the plugin that has the /scare <player> command. As an added challenge, add an option that allows a player to type /scare all if they want to scare all the players on the server. In this case, you could check each player for the creeperhiss.hear permission node. That way, only those players will hear the sound. This is a good example of a permission node that should be set to not op by default.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.220.114