Solved Citizens API Check if Player Clicking NPC

Discussion in 'Plugin Development' started by Xp10d3, Sep 20, 2020.

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

    Xp10d3

    So basically I am back yet another thread (sorry) and have a noob question: if I create an NPC with a random name using this:
    Code:java
    1.  
    2. public String randomGen() {
    3. int maxlength = 8;
    4. final String chars = "abcdefghijklmnopqrstuvwxyz123456789-";
    5. String word = "";
    6. while(word.length() < maxlength){
    7. Random rand = new Random();
    8. int x = rand.nextInt(36 - 1 + 1) +1 ;
    9. word = word + chars.charAt(x);
    10. System.out.println(word.toUpperCase());
    11. }
    12. return word;
    13. }
    14.  
    15. NPCRegistry registry = CitizensAPI.getNPCRegistry();
    16. NPC npc = registry.createNPC(EntityType.PLAYER, randomGen());
    17.  

    How would I check if the player is clicking that NPC? I am not sure whether the method I currently have works since I am calling the variable "npc" from another class, but that means it will just get a random NPC that has a random name. Example from my class:
    Code:java
    1.  
    2. @EventHandler
    3. public void click(NPCLeftClickEvent event) {
    4. Player player = event.getClicker(); // Get who left-clicked the NPC
    5.  
    6. if (event.getNPC() == core.npc) {
    7. }
    8. }
    9.  

    In this scenario, I'm just calling NPC npc = registry.createNPC(EntityType.PLAYER, randomGen()); rather than an actual Citizens NPC. I could store the data in a HashMap, but how would I do that? I don't use HashMaps unless I absolutely have to (since I'm horrible at them), but I believe there should be an easier way to do this. Yes, this is an anti-aura plugin and instead of using Armor Stands I'm using NPC's because I believe if you have a hacked client that only targets players, an NPC is technically considered a player and thus will attack it. Whereas an armor stand isn't a player, thus the hacked client will not attack it. Hope that makes sense.

    PlayerListeners.java (handles clicking the NPC):
    NOTE: I probably should put the two different hacks in separate classes (anti-reach and anti-aura) so don't tell me that; I know xD
    Code:java
    1.  
    2. package endran.voide.reach;
    3.  
    4. import java.text.SimpleDateFormat;
    5. import java.util.Date;
    6.  
    7. import org.bukkit.Bukkit;
    8. import org.bukkit.ChatColor;
    9. import org.bukkit.entity.Player;
    10. import org.bukkit.event.EventHandler;
    11. import org.bukkit.event.Listener;
    12. import org.bukkit.event.entity.EntityDamageByEntityEvent;
    13. import org.bukkit.util.Vector;
    14.  
    15. import net.citizensnpcs.api.event.NPCLeftClickEvent;
    16.  
    17. public class PlayerListeners implements Listener {
    18. // Get's the core variable.
    19. private Core core;
    20.  
    21. // Constructor
    22. public PlayerListeners(Core core) {
    23. this.core = core;
    24. }
    25.  
    26. // Get's the date + time to then write into core.otherLog()
    27. Date now = new Date();
    28. SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    29.  
    30. // Anti-Reach
    31. @EventHandler
    32. public void onDamage(EntityDamageByEntityEvent event) {
    33. if (core.getConfig().getString("enabled").equalsIgnoreCase("true")) {
    34.  
    35. // Get the damager
    36. Player player = (Player) event.getDamager();
    37.  
    38. Player entity = (Player) event.getEntity();
    39.  
    40. // If the damager damages the damaged...
    41. if (((event.getDamager() instanceof Player)) && ((event.getEntity() instanceof Player))) {
    42.  
    43. // Test for reach
    44. // Get the distance between the player's location and the victim's location
    45. // Credit to shanape ! on Discord for helping me with the vectors :)
    46. Vector from = player.getLocation().toVector().setY(1);
    47. Vector to = entity.getLocation().toVector().setY(1);
    48.  
    49. //Vector vector = to.subtract(from);
    50.  
    51. int checks = core.getConfig().getInt(player.getUniqueId().toString()); // Get the amount of checks a player has in the config file
    52. double distance = from.distance(to) - 0.4;
    53.  
    54. if (distance > 3) { // Since MC's default reach is 3, anything above that is considered reach
    55. int vl = core.getConfig().getInt("vl"); // Get the highest VL allowed
    56. String cmd = core.getConfig().getString("max-vl"); // What command to execute at that VL
    57. cmd = cmd.replace("{player}", player.getName()); // Replace {player} with the player's name
    58. ChatColor.translateAlternateColorCodes('&', cmd); // Allow &f instead of the weird thing like $f or whatever.
    59. int warningvl = core.getConfig().getInt("warning-vl"); // Get the amount of VL before sending a warning message.
    60.  
    61. if (checks >= vl) { // If the VL the player has is greater than or equal to the highest VL allowed...
    62. boolean check = core.getConfig().getBoolean("send-ban");
    63. if (check) {
    64. String banMsg = core.getConfig().getString("ban-msg"); // Get the ban message...
    65. banMsg = banMsg.replace("{player}", player.getName());
    66. ChatColor.translateAlternateColorCodes('&', banMsg);
    67. Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd); // Send the command
    68. Bukkit.broadcastMessage(banMsg + ChatColor.GOLD + " VL" + ChatColor.WHITE + ": " + checks); // Send the ban message.
    69. return;
    70. } else {
    71. String banMsg = core.getConfig().getString("ban-msg"); // Get the ban message...
    72. banMsg = banMsg.replace("{player}", player.getName());
    73. ChatColor.translateAlternateColorCodes('&', banMsg);
    74. Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd); // Send the command
    75. for (Player all : Bukkit.getServer().getOnlinePlayers()) {
    76. if (all.hasPermission("rgb.noti")) {
    77. all.sendMessage(ChatColor.GOLD + player.getName() + ChatColor.RED + " was banned for reach. Last hit: " + distance + " blocks." + ChatColor.GOLD + " VL: " + ChatColor.WHITE + ": " + checks);
    78. }
    79. }
    80. return;
    81. }
    82. } else if (checks >= warningvl && checks <= warningvl + 40 && checks < vl){
    83. boolean check = core.getConfig().getBoolean("send-warning");
    84. if (check) {
    85. // If the VL the player has is greater than or equal to the warning vl AND the checks is less than the warning vl + 20,
    86. // and the player's vl is NOT equal to the max vl allowed...
    87. String warningMsg = core.getConfig().getString("warning-msg"); // Get the warning message.
    88. warningMsg = warningMsg.replace("{player}", player.getName());
    89. ChatColor.translateAlternateColorCodes('&', warningMsg);
    90. // Set the player's VL equal to the current VL plus their current VL - 0.1.
    91. player.sendMessage("Your VL: " + checks + distance * 8); // <- For testing. Remove later.
    92. core.getConfig().set(player.getUniqueId().toString(), checks + distance * 8);
    93. core.otherLog(player.getName() + " might have reach. Violation Level: " + checks + ". Distance: " + distance);
    94. Bukkit.broadcastMessage(warningMsg + ChatColor.GOLD + " VL" + ChatColor.WHITE + ": " + checks); // Send the message.
    95. return;
    96. } else {
    97. // If the VL the player has is greater than or equal to the warning vl AND the checks is less than the warning vl + 20,
    98. // and the player's vl is NOT equal to the max vl allowed...
    99. String warningMsg = core.getConfig().getString("warning-msg"); // Get the warning message.
    100. warningMsg = warningMsg.replace("{player}", player.getName());
    101. ChatColor.translateAlternateColorCodes('&', warningMsg);
    102. // Set the player's VL equal to the current VL plus their current VL - 0.1.
    103. player.sendMessage("Your VL: " + checks + distance * 8); // <- For testing. Remove later.
    104. core.getConfig().set(player.getUniqueId().toString(), checks + distance * 8);
    105. core.otherLog(player.getName() + " might have reach. Violation Level: " + checks + ". Distance: " + distance);
    106. for (Player all : Bukkit.getServer().getOnlinePlayers()) {
    107. if (all.hasPermission("rgb.noti")) {
    108. all.sendMessage(ChatColor.GOLD + player.getName() + ChatColor.RED + " might be hacking. Last hit: " + distance + " blocks." + ChatColor.GOLD + " VL: " + ChatColor.WHITE + ": " + checks);
    109. }
    110. }
    111. return;
    112. }
    113. } else {
    114. // Otherwise, if the warning is not within parameters, add to the player's VL.
    115. player.sendMessage("Your VL: " + checks + distance * 8); // <- For testing. Remove later.
    116.  
    117. core.getConfig().set(player.getUniqueId().toString(), checks + distance * 8);
    118. core.otherLog(player.getName() + " might have reach. Violation Level: " + checks + ". Distance: " + distance);
    119. }
    120. } else {
    121. // If the player does not have reach, than reset their VL if it's less than 0 and slowly
    122. // decrease their VL by the amount specified.
    123. if (checks < 0) {
    124. core.getConfig().set(player.getUniqueId().toString(), 0);
    125. return;
    126. }
    127. int decreaseVL = core.getConfig().getInt("decrease-vl");
    128. core.getConfig().set(player.getUniqueId().toString(), checks - decreaseVL);
    129. }
    130. }
    131. }
    132. }
    133.  
    134. // Anti-aura/anti-killaura
    135. @EventHandler
    136. public void click(NPCLeftClickEvent event) {
    137. Player player = event.getClicker(); // Get who left-clicked the NPC
    138. int checks = core.getConfig().getInt("killaura." + player.getUniqueId().toString()); // Get the amount of checks a player has in the config file
    139.  
    140. if (event.getNPC() == core.npc) {
    141. int vl = core.getConfig().getInt("vl-ka"); // Get the highest VL allowed
    142. String cmd = core.getConfig().getString("max-vl-ka"); // What command to execute at that VL
    143. cmd = cmd.replace("{player}", player.getName()); // Replace {player} with the player's name
    144. ChatColor.translateAlternateColorCodes('&', cmd); // Allow &f instead of the weird thing like $f or whatever.
    145. int warningvl = core.getConfig().getInt("warning-vl-ka"); // Get the amount of VL before sending a warning message.
    146.  
    147. if (checks >= vl) { // If the VL the player has is greater than or equal to the highest VL allowed...
    148. boolean check = core.getConfig().getBoolean("send-ban-ka");
    149. if (check) {
    150. String banMsg = core.getConfig().getString("ban-msg-ka"); // Get the ban message...
    151. banMsg = banMsg.replace("{player}", player.getName());
    152. ChatColor.translateAlternateColorCodes('&', banMsg);
    153. Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd); // Send the command
    154. Bukkit.broadcastMessage(banMsg + ChatColor.GOLD + " VL" + ChatColor.WHITE + ": " + checks); // Send the ban message.
    155. return;
    156. } else {
    157. String banMsg = core.getConfig().getString("ban-msg-ka"); // Get the ban message...
    158. banMsg = banMsg.replace("{player}", player.getName());
    159. ChatColor.translateAlternateColorCodes('&', banMsg);
    160. Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), cmd); // Send the command
    161. for (Player all : Bukkit.getServer().getOnlinePlayers()) {
    162. if (all.hasPermission("rgb.noti")) {
    163. all.sendMessage(ChatColor.GOLD + player.getName() + ChatColor.RED + " was banned for killaura. "+ ChatColor.GOLD + " VL: " + ChatColor.WHITE + ": " + checks);
    164. }
    165. }
    166. return;
    167. }
    168. } else if (checks >= warningvl && checks <= warningvl + 40 && checks < vl){
    169. boolean check = core.getConfig().getBoolean("send-warning-ka");
    170. if (check) {
    171. // If the VL the player has is greater than or equal to the warning vl AND the checks is less than the warning vl + 20,
    172. // and the player's vl is NOT equal to the max vl allowed...
    173. String warningMsg = core.getConfig().getString("warning-msg-ka"); // Get the warning message.
    174. warningMsg = warningMsg.replace("{player}", player.getName());
    175. ChatColor.translateAlternateColorCodes('&', warningMsg);
    176. // Set the player's VL equal to the current VL plus their current VL - 0.1.
    177. player.sendMessage("Your VL: " + checks + 30); // <- For testing. Remove later.
    178. core.getConfig().set(player.getUniqueId().toString(), checks + 30);
    179. core.otherLog(player.getName() + " might have killaura. Violation Level: " + checks + ".");
    180. Bukkit.broadcastMessage(warningMsg + ChatColor.GOLD + " VL" + ChatColor.WHITE + ": " + checks); // Send the message.
    181. return;
    182. } else {
    183. // If the VL the player has is greater than or equal to the warning vl AND the checks is less than the warning vl + 20,
    184. // and the player's vl is NOT equal to the max vl allowed...
    185. String warningMsg = core.getConfig().getString("warning-msg-ka"); // Get the warning message.
    186. warningMsg = warningMsg.replace("{player}", player.getName());
    187. ChatColor.translateAlternateColorCodes('&', warningMsg);
    188. // Set the player's VL equal to the current VL plus their current VL - 0.1.
    189. player.sendMessage("Your VL: " + checks + 30); // <- For testing. Remove later.
    190. core.getConfig().set(player.getUniqueId().toString(), checks + 30);
    191. core.otherLog(player.getName() + " might have killaura. Violation Level: " + checks + ".");
    192. for (Player all : Bukkit.getServer().getOnlinePlayers()) {
    193. if (all.hasPermission("rgb.noti")) {
    194. all.sendMessage(ChatColor.GOLD + player.getName() + ChatColor.RED + " might have killaura. " + ChatColor.GOLD + " VL: " + ChatColor.WHITE + ": " + checks);
    195. }
    196. }
    197. return;
    198. }
    199. } else {
    200. // Otherwise, if the warning is not within parameters, add to the player's VL.
    201. player.sendMessage("Your VL: " + checks + 30); // <- For testing. Remove later.
    202.  
    203. core.getConfig().set(player.getUniqueId().toString(), checks + 30);
    204. core.otherLog(player.getName() + " might have killaura. Violation Level: " + checks + ".");
    205. }
    206. } else {
    207. // If the player does not have reach, than reset their VL if it's less than 0 and slowly
    208. // decrease their VL by the amount specified.
    209. int stopAura = core.getConfig().getInt("stop-aura");
    210. if (checks < 0) {
    211. core.getConfig().set(player.getUniqueId().toString(), 0);
    212. core.npc.despawn();
    213. return;
    214. } else if (checks < stopAura) {
    215. core.npc.despawn();
    216. return;
    217. }
    218. int decreaseVL = core.getConfig().getInt("decrease-vl");
    219. core.getConfig().set(player.getUniqueId().toString(), checks - decreaseVL);
    220. }
    221. }
    222. }
    223.  
    224.  


    Core.java (creates the NPC):
    Code:java
    1.  
    2. package endran.voide.reach;
    3.  
    4. import java.io.File;
    5. import java.io.FileWriter;
    6. import java.io.IOException;
    7. import java.io.PrintWriter;
    8. import java.text.SimpleDateFormat;
    9. import java.util.Date;
    10. import java.util.Random;
    11.  
    12. import org.bukkit.Bukkit;
    13. import org.bukkit.Location;
    14. import org.bukkit.World;
    15. import org.bukkit.configuration.file.FileConfiguration;
    16. //import org.bukkit.craftbukkit.v1_8_R3.CraftServer;
    17. //import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
    18. import org.bukkit.entity.EntityType;
    19. import org.bukkit.entity.Player;
    20. import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
    21. import org.bukkit.plugin.PluginDescriptionFile;
    22. import org.bukkit.plugin.java.JavaPlugin;
    23.  
    24. import net.citizensnpcs.api.CitizensAPI;
    25. import net.citizensnpcs.api.npc.NPC;
    26. import net.citizensnpcs.api.npc.NPCRegistry;
    27. //import net.minecraft.server.v1_8_R3.EntityPlayer;
    28. //import net.minecraft.server.v1_8_R3.MinecraftServer;
    29. //import net.minecraft.server.v1_8_R3.PlayerInteractManager;
    30. //import net.minecraft.server.v1_8_R3.WorldServer;
    31.  
    32. public class Core extends JavaPlugin {
    33. // Get's the config.yml file.
    34. FileConfiguration config = getConfig();
    35.  
    36. public String randomGen() {
    37. int maxlength = 8;
    38. final String chars = "abcdefghijklmnopqrstuvwxyz123456789-";
    39. String word = "";
    40. while(word.length() < maxlength){
    41. Random rand = new Random();
    42. int x = rand.nextInt(36 - 1 + 1) +1 ;
    43. word = word + chars.charAt(x);
    44. System.out.println(word.toUpperCase());
    45. }
    46. return word;
    47. }
    48.  
    49. NPCRegistry registry = CitizensAPI.getNPCRegistry();
    50. NPC npc = registry.createNPC(EntityType.PLAYER, randomGen());
    51.  
    52. // Get's the data + time for logging purposes.
    53. Date now = new Date();
    54. SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    55.  
    56. // Get plugin.yml file
    57. PluginDescriptionFile pdf = this.getDescription();
    58.  
    59. // When the server starts up...
    60. public void onEnable() {
    61.  
    62. // Send a log for loading the config...
    63. otherLog("[" + format.format(now) + "]" + " Attempting to load config...");
    64. // Load the config
    65. loadConfig();
    66.  
    67. // Config variable.
    68. config = getConfig();
    69.  
    70. getLogger().info("Reloaded all player data...");
    71. otherLog("Loaded all player data at " + "[" + format.format(now) + "]");
    72. // Register events in the PlayerListeners class.
    73. Bukkit.getServer().getPluginManager().registerEvents(new PlayerListeners(this), this);
    74. getLogger().info("Registered listeners in PlayerListeners...");
    75. otherLog("Registered listeners in PlayerListeners...");
    76. // For logging
    77. getLogger().info("Plugin " + pdf.getName() + " version " + pdf.getVersion() + "loaded! Server Version: " + Bukkit.getServer().getVersion());
    78. otherLog("Server version: " + Bukkit.getServer().getVersion());
    79. getLogger().info("Bukkit version: " + Bukkit.getBukkitVersion());
    80. otherLog("Bukkit version: " + Bukkit.getBukkitVersion());
    81. otherLog("Plugin " + pdf.getName() + " version " + pdf.getVersion() + "loaded by " + pdf.getAuthors() + ".");
    82. otherLog("Plugin description: " + pdf.getDescription());
    83. otherLog("Plugin permissions: " + pdf.getPermissions());
    84. otherLog("Server has started at " + "[" + format.format(now) + "]");
    85. }
    86.  
    87. // When the server stops...
    88. public void onDisable() {
    89. // Send a message saying that it's stopping the plugin.
    90. getLogger().info("Stopping plugin 'Connection'...");
    91. // Send log info.
    92. otherLog("Server has stopped at " + "[" + format.format(now) + "]");
    93. otherLog("------------");
    94. getLogger().info("Plugin stopped. Goodbye!");
    95. }
    96.  
    97. // Loading config
    98. public void loadConfig(){
    99. // Copy everything from the config.yml to the actual file in the folder.
    100. getConfig().options().copyDefaults(true);
    101. // Save the config.
    102. saveConfig();
    103. otherLog("[" + format.format(now) + "]" + "Successfully loaded config.");
    104. }
    105.  
    106.  
    107. // Logging method
    108. public void otherLog(String message) {
    109. try {
    110. // Get the folder of the plugin...
    111. File dataFolder = getDataFolder();
    112. // If the folder doesn't exist create it/get the directory.
    113. if (!dataFolder.exists()) {
    114. dataFolder.mkdir();
    115. }
    116.  
    117. // Where to save the file to/what the name of the file should be.
    118. File saveTo = new File(getDataFolder(), "debug_log.txt");
    119. if (!saveTo.exists()) { // If the file doesn't exist create it.
    120. saveTo.createNewFile();
    121. otherLog("[" + format.format(now) + "]" + "Successfully created debug_log.txt.");
    122. }
    123. // Writing the actual message.
    124. FileWriter fw = new FileWriter(saveTo, true);
    125. PrintWriter pw = new PrintWriter(fw);
    126. pw.println(message);
    127. pw.flush();
    128. pw.close();
    129. } catch (IOException e) {
    130. // If there are any errors log it.
    131. this.getLogger().info("Couldn't create debug_log.txt. Errors:");
    132. e.printStackTrace();
    133. }
    134. }
    135.  
    136. public boolean checkNPC(org.bukkit.entity.NPC entity) {
    137. boolean isCitizensNPC = entity.hasMetadata("NPC");
    138. if (isCitizensNPC) {
    139. return true;
    140. } else {
    141. return false;
    142. }
    143. }
    144.  
    145. /*
    146.   // Custom NPC's. Doesn't work in 1.16.3.
    147.   public void spawnCustom(Player player) {
    148.   String skinUuid = "5";
    149.   MinecraftServer minecraftServer = ((CraftServer) Bukkit.getServer()).getServer();
    150.   WorldServer worldServer = ((CraftWorld) player.getLocation().getWorld()).getHandle();
    151.   GameProfile gameProfile = new GameProfile(UUID.fromString(skinUuid), "npc");
    152.   EntityPlayer ep = new EntityPlayer(minecraftServer, worldServer, gameProfile, new PlayerInteractManager(worldServer));
    153.   worldServer.addEntity(ep);
    154.   //double backstab = player.getLocation().getDirection().angle(player.getLocation().getDirection()) / 180 * Math.PI;
    155.   }
    156.   */
    157.  
    158. public void auracheck(Player player, World world) {
    159. otherLog("Checking killaura for " + player.getName() + "...");
    160. // Get the location behind the player
    161. Location loc = player.getLocation().add(player.getLocation().getDirection().multiply(-1));
    162. for (int i = 0; i >= 0; i++) {
    163. npc.teleport(loc, TeleportCause.PLUGIN);
    164. }
    165. }
    166. }
    167.  
    168.  
     
  2. Offline

    Shqep

    Check if that NPC entity has the metadata called "NPC".
    [Source]
     
  3. Offline

    Xp10d3

    heck forgot about that. thanks; marking as solved :D
     
Thread Status:
Not open for further replies.

Share This Page