Запомни код плагина


/* Decompiler 33ms, total 773ms, lines 42 */
package wtf.n1zamu.listener;

import java.util.Iterator;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.potion.PotionEffect;
import wtf.n1zamu.Items;
import wtf.n1zamu.NItems;

public class ClearArrowListener implements Listener {
    @EventHandler
    public void onHit(ProjectileHitEvent event) {
        if (event.getHitEntity() instanceof Player) {
            if (event.getEntity().hasMetadata(Items.CLEAR_ARROW.getMetaId())) {
                Player player = (Player)event.getHitEntity();
                Iterator var3 = player.getActivePotionEffects().iterator();

                while(var3.hasNext()) {
                    PotionEffect type = (PotionEffect)var3.next();
                    player.removePotionEffect(type.getType());
                }

            }
        }
    }

    @EventHandler
    public void onLaunch(EntityShootBowEvent event) {
        if (event.getEntity() instanceof Player) {
            if (Items.getItem(event.getConsumable(), Items.CLEAR_ARROW) != null) {
                event.getProjectile().setMetadata(Items.CLEAR_ARROW.getMetaId(), new FixedMetadataValue(NItems.getInstance(), Items.CLEAR_ARROW.getMetaId()));
                event.setProjectile(event.getProjectile());
            }

        }
    }
}


package wtf.n1zamu.listener;

import java.lang.reflect.Field;
import java.util.Random;
import java.util.UUID;

import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;

import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;

import wtf.n1zamu.NItems;
import wtf.n1zamu.util.NBTUtil;

public class DraculaListener implements Listener {

    private static final Random RANDOM = new Random();
    private static final String SPAWN_WORLD_NAME = NItems.config().getString("spawnWorld");
    private static final int RANDOM_BOUND = 100;
    private static final int RANDOM_CHANCE = 7;
    private static final double MAX_HEALTH = 20.0D;
    private static final double HEALTH_REGEN = 2.0D;
    private static final int FIRE_TICKS = 2500;
    private static final int REGEN_DURATION = 35;
    private static final int REGEN_AMPLIFIER = 0;

    @EventHandler
    public void onHit(EntityDamageByEntityEvent event) {
        if (!(event.getDamager() instanceof Player) || !(event.getEntity() instanceof Player)) {
            return;
        }

        Player damager = (Player) event.getDamager();
        Player damagedPlayer = (Player) event.getEntity();
        ItemStack offHandItem = damager.getInventory().getItemInOffHand();

        if (isDraculaHead(offHandItem) && damager.getHealth() < MAX_HEALTH && !isInSpawnWorld(damager)) {
            if (RANDOM.nextInt(RANDOM_BOUND) <= RANDOM_CHANCE) {
                damager.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, REGEN_DURATION, REGEN_AMPLIFIER));
                adjustPlayerHealth(damager, damagedPlayer);
            }
        }
    }

    @EventHandler
    public void onMove(PlayerMoveEvent event) {
        Player player = event.getPlayer();
        ItemStack helmet = player.getInventory().getHelmet();

        if (isDraculaHead(helmet) && !isInSpawnWorld(player)) {
            player.setFireTicks(FIRE_TICKS);
            setDraculaSkin(helmet);
        }
    }

    private boolean isDraculaHead(ItemStack itemStack) {
        return itemStack != null &&
                itemStack.getType() == Material.PLAYER_HEAD &&
                NBTUtil.hasItemNBT(itemStack, "dracula_head");
    }

    private boolean isInSpawnWorld(Player player) {
        return player.getWorld().getName().contains(SPAWN_WORLD_NAME);
    }

    private void adjustPlayerHealth(Player damager, Player damagedPlayer) {
        damagedPlayer.setHealth(Math.max(0.0D, damagedPlayer.getHealth() - HEALTH_REGEN));
        damager.setHealth(Math.min(MAX_HEALTH, damager.getHealth() + HEALTH_REGEN));
    }

    private void setDraculaSkin(ItemStack skull) {
        if (skull == null || skull.getType() != Material.PLAYER_HEAD) return;

        SkullMeta meta = (SkullMeta) skull.getItemMeta();

        String texture = NItems.config().getString("draculaTexture");
        String name = NItems.config().getString("draculaName");

        if (meta != null && texture != null && name != null) {
            GameProfile profile = new GameProfile(UUID.randomUUID(), name);
            profile.getProperties().put("textures", new Property("textures", texture, ""));
            try {
                Field profileField = meta.getClass().getDeclaredField("profile");
                profileField.setAccessible(true);
                profileField.set(meta, profile);
            } catch (IllegalArgumentException | NoSuchFieldException | SecurityException | IllegalAccessException e) {
                e.printStackTrace();
            }
            skull.setItemMeta(meta);
        }
    }
}





/* Decompiler 86ms, total 378ms, lines 104 */
package wtf.n1zamu.listener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Block;
import org.bukkit.block.data.Ageable;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.player.PlayerToggleSneakEvent;
import wtf.n1zamu.Items;
import wtf.n1zamu.NItems;

public class FarmListener implements Listener {
    private final HashMap<Player, Long> playerCooldowns = new HashMap();

    @EventHandler
    public void onBlockBreak(BlockBreakEvent event) {
        if (Items.getItem(event.getPlayer().getInventory().getItemInOffHand(), Items.FARM_BALL) != null) {
            if (!event.getBlock().getWorld().getName().contains(NItems.config().getString("spawnWorld"))) {
                if (event.getBlock().getBlockData() instanceof Ageable) {
                    Material block = event.getBlock().getType();
                    if (((Ageable)event.getBlock().getBlockData()).getAge() == ((Ageable)event.getBlock().getBlockData()).getMaximumAge()) {
                        if ((new Random()).nextInt(10) < 8) {
                            Bukkit.getScheduler().runTaskLater(NItems.getInstance(), () -> {
                                event.getBlock().setType(block);
                            }, 3L);
                        }

                    }
                }
            }
        }
    }

    @EventHandler
    public void onShift(PlayerToggleSneakEvent event) {
        Player player = event.getPlayer();
        long currentTime = System.currentTimeMillis();
        long lastUse = (Long)this.playerCooldowns.getOrDefault(player, 0L);
        if (currentTime - lastUse < (long)NItems.config().getInt("farmCooldown") * 1000L && Items.getItem(player.getInventory().getItemInOffHand(), Items.FARM_BALL) != null) {
            long remainingTime = (long)NItems.config().getInt("farmCooldown") * 1000L - (currentTime - lastUse);
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', NItems.config().getString("farmBallCooldown")).replace("%time%", Long.toString(remainingTime / 1000L)));
        } else if (Items.getItem(player.getInventory().getItemInOffHand(), Items.FARM_BALL) != null) {
            Iterator var7 = this.getBlocksInRadius(player.getLocation(), NItems.config().getInt("farmRadius")).iterator();

            while(var7.hasNext()) {
                Block block = (Block)var7.next();
                BlockData blockData = block.getBlockData();
                if (blockData instanceof Ageable) {
                    ((Ageable)blockData).setAge(((Ageable)blockData).getMaximumAge());
                    block.setBlockData(blockData);
                }
            }

            this.playerCooldowns.put(player, currentTime);
            notification(player);
        }

    }

    public List<Block> getBlocksInRadius(Location location, int radius) {
        List<Block> blocks = new ArrayList();

        for(int x = -radius; x <= radius; ++x) {
            for(int y = -radius; y <= radius; ++y) {
                for(int z = -radius; z <= radius; ++z) {
                    Block block = location.getWorld().getBlockAt(location.getBlockX() + x, location.getBlockY() + y, location.getBlockZ() + z);
                    if (location.distance(block.getLocation()) <= (double)radius) {
                        blocks.add(block);
                    }
                }
            }
        }

        return blocks;
    }

    private static void notification(Player player) {
        if (NItems.config().getBoolean("notification.sound")) {
            player.playSound(player.getLocation(), Sound.valueOf(NItems.config().getString("notification.soundType")), 1.0F, 1.0F);
        }

        if (NItems.config().getBoolean("notification.title")) {
            player.sendTitle(ChatColor.GOLD + "Шар Огородника", ChatColor.translateAlternateColorCodes('&', NItems.config().getString("notification.titleText")));
        }

        if (NItems.config().getBoolean("notification.message")) {
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', NItems.config().getString("notification.messageText")));
        }

    }
}





/* Decompiler 45ms, total 363ms, lines 38 */
package wtf.n1zamu.listener;

import java.util.Random;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerItemConsumeEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import wtf.n1zamu.Items;

public class PotionsListener implements Listener {
    PotionEffectType[] potionEffects;

    public PotionsListener() {
        this.potionEffects = new PotionEffectType[]{PotionEffectType.FIRE_RESISTANCE, PotionEffectType.ABSORPTION, PotionEffectType.BLINDNESS, PotionEffectType.DAMAGE_RESISTANCE, PotionEffectType.INCREASE_DAMAGE, PotionEffectType.SPEED, PotionEffectType.HEALTH_BOOST, PotionEffectType.JUMP, PotionEffectType.REGENERATION, PotionEffectType.LUCK, PotionEffectType.UNLUCK, PotionEffectType.LEVITATION, PotionEffectType.LUCK, PotionEffectType.CONFUSION, PotionEffectType.NIGHT_VISION, PotionEffectType.INVISIBILITY, PotionEffectType.WATER_BREATHING};
    }

    @EventHandler
    public void onPotionDrink(PlayerItemConsumeEvent event) {
        if (event.getItem().getType() == Material.POTION && Items.getItem(event.getItem(), Items.RANDOM_POTION) != null) {
            this.randomPotionEffect(event.getPlayer(), 15, 80, 0, 2, this.potionEffects);
            this.randomPotionEffect(event.getPlayer(), 15, 80, 0, 2, this.potionEffects);
            this.randomPotionEffect(event.getPlayer(), 15, 80, 0, 2, this.potionEffects);
        }

    }

    public void randomPotionEffect(Player player, int minDuration, int maxDuration, int minAmplifier, int maxAmplifier, PotionEffectType... effects) {
        Random rand = new Random();
        PotionEffectType type = effects[rand.nextInt(effects.length)];
        int duration = rand.nextInt(maxDuration - minDuration + 1) + minDuration;
        int amplifier = rand.nextInt(maxAmplifier - minAmplifier + 1) + minAmplifier;
        player.addPotionEffect(new PotionEffect(type, duration * 20, amplifier));
    }
}






/* Decompiler 44ms, total 352ms, lines 65 */
package wtf.n1zamu.listener;

import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.RegionContainer;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import java.util.Iterator;
import java.util.Random;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import wtf.n1zamu.Items;
import wtf.n1zamu.NItems;

public class RandomEggListener implements Listener {
    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent event) {
        if (event.getItem() != null) {
            if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
                if (event.getClickedBlock() != null) {
                    if (event.getClickedBlock().getType() == Material.SPAWNER) {
                        if (Items.getItem(event.getPlayer().getInventory().getItemInMainHand(), Items.RANDOM_EGG) != null) {
                            EntityType[] mobTypes = new EntityType[]{EntityType.COW, EntityType.CHICKEN, EntityType.SLIME, EntityType.BLAZE, EntityType.SHEEP, EntityType.ENDERMAN, EntityType.CREEPER, EntityType.MAGMA_CUBE, EntityType.VINDICATOR, EntityType.WITCH, EntityType.WITHER_SKELETON, EntityType.HOGLIN, EntityType.RABBIT, EntityType.PHANTOM, EntityType.PILLAGER, EntityType.TROPICAL_FISH, EntityType.STRIDER, EntityType.ZOMBIE_VILLAGER, EntityType.GHAST, EntityType.ZOMBIFIED_PIGLIN};
                            Location loc = BukkitAdapter.adapt(event.getClickedBlock().getLocation());
                            RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
                            RegionQuery query = container.createQuery();
                            ApplicableRegionSet set = query.getApplicableRegions(loc);
                            Iterator var7 = set.iterator();

                            ProtectedRegion region;
                            do {
                                if (!var7.hasNext()) {
                                    ItemStack item = event.getPlayer().getInventory().getItemInMainHand();
                                    event.setCancelled(true);
                                    CreatureSpawner spawner = (CreatureSpawner)event.getClickedBlock().getState();
                                    spawner.setSpawnedType(mobTypes[(new Random()).nextInt(mobTypes.length)]);
                                    spawner.update();
                                    event.getPlayer().setCooldown(Items.RANDOM_EGG.getMaterial(), 20);
                                    item.setAmount(item.getAmount() - 1);
                                    event.getPlayer().getInventory().setItemInMainHand(item);
                                    return;
                                }

                                region = (ProtectedRegion)var7.next();
                            } while(region.getMembers().contains(event.getPlayer().getUniqueId()) || region.getOwners().contains(event.getPlayer().getUniqueId()));

                            event.setCancelled(true);
                            event.getPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', NItems.config().getString("region")));
                        }
                    }
                }
            }
        }
    }
}







/* Decompiler 87ms, total 352ms, lines 80 */
package wtf.n1zamu.listener;

import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.RegionContainer;
import com.sk89q.worldguard.protection.regions.RegionQuery;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import wtf.n1zamu.Items;
import wtf.n1zamu.NItems;

public class ScissorsListener implements Listener {
    private final HashMap<Player, Long> playerCooldowns = new HashMap();

    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent event) {
        Player player = event.getPlayer();
        Action action = event.getAction();
        ItemStack item = event.getItem();
        if (item != null) {
            long currentTime = System.currentTimeMillis();
            long lastScissorsTime = (Long)this.playerCooldowns.getOrDefault(player, 0L);
            this.playerCooldowns.entrySet().removeIf((entry) -> {
                return currentTime - (Long)entry.getValue() >= 25000L;
            });
            if (currentTime - lastScissorsTime < 25000L && action == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock().getType() == Material.SPAWNER && Items.getItem(item, Items.SHEARS) != null && event.getPlayer().getInventory().getItemInOffHand().getType() != Material.SHEARS) {
                long remainingTime = 25000L - (currentTime - lastScissorsTime);
                player.sendMessage(ChatColor.translateAlternateColorCodes('&', NItems.config().getString("items.shears.isBreaked")).replace("%time%", Long.toString(remainingTime / 1000L)));
            } else if (action == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock().getType() == Material.SPAWNER && Items.getItem(item, Items.SHEARS) != null && event.getPlayer().getInventory().getItemInOffHand().getType() != Material.SHEARS) {
                ItemMeta meta = item.getItemMeta();
                if (meta != null) {
                    Location loc = BukkitAdapter.adapt(event.getClickedBlock().getLocation());
                    RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
                    RegionQuery query = container.createQuery();
                    ApplicableRegionSet set = query.getApplicableRegions(loc);
                    Iterator var14 = set.iterator();

                    ProtectedRegion region;
                    do {
                        if (!var14.hasNext()) {
                            if (NItems.getUsesLeft(meta) <= 1) {
                                event.getClickedBlock().setType(Material.AIR);
                                player.getInventory().addItem(new ItemStack[]{new ItemStack(Material.SPAWNER)});
                                player.getInventory().removeItem(new ItemStack[]{item});
                                player.sendMessage(ChatColor.translateAlternateColorCodes('&', NItems.config().getString("items.shears.breakMessage")));
                                return;
                            }

                            event.getClickedBlock().setType(Material.AIR);
                            player.getInventory().addItem(new ItemStack[]{new ItemStack(Material.SPAWNER)});
                            meta.setLore(Collections.singletonList(ChatColor.translateAlternateColorCodes('&', "&7Использований: &6" + (NItems.getUsesLeft(meta) - 1))));
                            item.setItemMeta(meta);
                            this.playerCooldowns.put(player, currentTime);
                            return;
                        }

                        region = (ProtectedRegion)var14.next();
                    } while(region.getMembers().contains(event.getPlayer().getUniqueId()) || region.getOwners().contains(event.getPlayer().getUniqueId()));

                    event.setCancelled(true);
                    player.sendMessage(ChatColor.translateAlternateColorCodes('&', NItems.config().getString("items.shears.inRegion")));
                }
            }
        }
    }
}






/* Decompiler 54ms, total 717ms, lines 94 */
package wtf.n1zamu.listener;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityResurrectEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.scheduler.BukkitScheduler;
import wtf.n1zamu.Items;
import wtf.n1zamu.NItems;

public class TotemsListener implements Listener {
    private final Map<UUID, PotionEffect[]> playerEffects = new HashMap();

    @EventHandler(
            priority = EventPriority.HIGHEST,
            ignoreCancelled = true
    )
    public void onDraconidTotem(EntityDamageEvent e) {
        if (e.getEntity() instanceof Player) {
            Player p = (Player)e.getEntity();
            if (e.getFinalDamage() >= p.getHealth()) {
                int draconidTotemSlot = -1;

                ItemStack handItem;
                for(int i = 0; i < p.getInventory().getSize(); ++i) {
                    handItem = p.getInventory().getItem(i);
                    if (handItem != null && handItem.getType() == Material.TOTEM_OF_UNDYING && Items.getItem(p.getInventory().getItemInOffHand(), Items.DRACONID_TOTEM) == null && Items.getItem(handItem, Items.DRACONID_TOTEM) != null && !handItem.isSimilar(p.getInventory().getItem(EquipmentSlot.HEAD))) {
                        draconidTotemSlot = i;
                        break;
                    }
                }

                if (draconidTotemSlot != -1) {
                    ItemStack totem = p.getInventory().getItem(draconidTotemSlot);
                    p.getInventory().removeItem(new ItemStack[]{totem});
                    handItem = p.getInventory().getItemInOffHand().clone();
                    p.getInventory().setItemInOffHand(totem);
                    BukkitScheduler scheduler = Bukkit.getScheduler();
                    ItemStack finalHandItem = handItem;
                    scheduler.runTaskLater(NItems.getProvidingPlugin(NItems.class), () -> {
                        p.getInventory().setItemInOffHand(finalHandItem);
                    }, 1L);
                }
            }
        }
    }

    @EventHandler(
            priority = EventPriority.HIGHEST,
            ignoreCancelled = true
    )
    public void onResurrect(EntityResurrectEvent e) {
        if (e.getEntity() instanceof Player) {
            Player p = (Player)e.getEntity();
            p.getInventory().getItemInOffHand();
            if (Items.getItem(p.getInventory().getItemInOffHand(), Items.WITCH_TOTEM) != null || Items.getItem(p.getInventory().getItemInMainHand(), Items.WITCH_TOTEM) != null) {
                this.playerEffects.put(p.getUniqueId(), (PotionEffect[])p.getActivePotionEffects().toArray(new PotionEffect[0]));
                BukkitScheduler scheduler = Bukkit.getScheduler();
                scheduler.runTaskLater(NItems.getProvidingPlugin(NItems.class), () -> {
                    this.restorePlayerEffects(p);
                }, 1L);
            }

        }
    }

    private void restorePlayerEffects(Player player) {
        PotionEffect[] effects = (PotionEffect[])this.playerEffects.get(player.getUniqueId());
        if (effects != null) {
            PotionEffect[] var3 = effects;
            int var4 = effects.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                PotionEffect effect = var3[var5];
                player.addPotionEffect(effect, true);
            }

            this.playerEffects.remove(player.getUniqueId());
            player.sendMessage(ChatColor.translateAlternateColorCodes('&', NItems.getInstance().getConfig().getString("witchTotemMessage")));
        }

    }
}




package wtf.n1zamu.util;

import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.NamespacedKey;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.persistence.PersistentDataType;
import wtf.n1zamu.Items;

public class ItemStackUtil {
    public void handleItem(Items items, Player player, List<String> lore, Enchantment enchantment, int amount) {
        ItemStack item = new ItemStack(items.getMaterial());
        ItemMeta meta = item.getItemMeta();
        meta.getPersistentDataContainer().set(NamespacedKey.minecraft(items.getMetaId()), PersistentDataType.STRING, items.name());
        meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', items.getName()));
        if (lore != null) {
            lore.replaceAll((textToTranslate) -> {
                return ChatColor.translateAlternateColorCodes('&', textToTranslate);
            });
            meta.setLore(lore);
        }

        if (enchantment != null) {
            meta.addEnchant(enchantment, 1, false);
        }

        item.setItemMeta(meta);
        item.setAmount(amount);
        player.getInventory().addItem(new ItemStack[]{item});
    }

    public void handleHeadItem(Player player, List<String> lore, Items items, String headId) {
        ItemStack item = new ItemStack(items.getMaterial());
        ItemMeta meta = item.getItemMeta();
        SkullMeta skullMeta = (SkullMeta)meta;
        GameProfile gameProfile = new GameProfile(UUID.randomUUID(), (String)null);
        gameProfile.getProperties().put("textures", new Property("textures", headId));

        try {
            Method method = skullMeta.getClass().getDeclaredMethod("setProfile", GameProfile.class);
            method.setAccessible(true);
            method.invoke(skullMeta, gameProfile);
        } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException var10) {
            var10.printStackTrace();
        }

        meta.getPersistentDataContainer().set((NamespacedKey)Objects.requireNonNull(NamespacedKey.minecraft(items.getMetaId())), PersistentDataType.STRING, items.name());
        meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', items.getName()));
        lore.replaceAll((textToTranslate) -> {
            return ChatColor.translateAlternateColorCodes('&', textToTranslate);
        });
        meta.setLore(lore);
        item.setDurability((short)3);
        item.setItemMeta(meta);
        item.setItemMeta(skullMeta);
        player.getInventory().addItem(new ItemStack[]{item});
    }

    public void enchantItem(Player player) {
        ItemStack item = player.getInventory().getItemInMainHand();
        NBTUtil.addItemNBT(item, "dracula_head", "");
        player.getInventory().addItem(new ItemStack[]{item});
    }

    public void handleArrow(Items items, Player player, List<String> lore, int amount) {
        ItemStack item = new ItemStack(items.getMaterial());
        PotionMeta potionMeta = (PotionMeta)item.getItemMeta();
        potionMeta.setColor(Color.WHITE);
        potionMeta.getPersistentDataContainer().set(NamespacedKey.minecraft(items.getMetaId()), PersistentDataType.STRING, items.name());
        potionMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', items.getName()));
        if (lore != null) {
            lore.replaceAll((textToTranslate) -> {
                return ChatColor.translateAlternateColorCodes('&', textToTranslate);
            });
            potionMeta.setLore(lore);
        }

        item.setItemMeta(potionMeta);
        item.setAmount(amount);
        player.getInventory().addItem(new ItemStack[]{item});
    }
}




package wtf.n1zamu.util;

import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
import wtf.n1zamu.NItems;

public class NBTUtil {
    public static void addItemNBT(ItemStack item, String key, String value) {
        ItemMeta meta = item.hasItemMeta() ? item.getItemMeta() : Bukkit.getItemFactory().getItemMeta(item.getType());
        meta.getPersistentDataContainer().set(new NamespacedKey(NItems.getInstance(), key), PersistentDataType.STRING, value);
        item.setItemMeta(meta);
    }

    public static boolean hasItemNBT(ItemStack item, String key) {
        return item.hasItemMeta() && item.getItemMeta().getPersistentDataContainer().has(new NamespacedKey(NItems.getInstance(), key), PersistentDataType.STRING);
    }

    public static String getNBTvalue(ItemStack item, String key) {
        ItemMeta meta = item.getItemMeta();
        PersistentDataContainer tag = meta.getPersistentDataContainer();
        return (String)tag.get(NamespacedKey.minecraft(key), PersistentDataType.STRING);
    }
}





package wtf.n1zamu;

import java.util.Objects;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;

public enum Items {
    SHEARS(ChatColor.translateAlternateColorCodes('&', NItems.config().getString("shearsName")), Material.SHEARS, "nshears"),
    DRACONID_TOTEM(ChatColor.translateAlternateColorCodes('&', NItems.config().getString("draconidName")), Material.TOTEM_OF_UNDYING, "draconid_totem"),
    WITCH_TOTEM(ChatColor.translateAlternateColorCodes('&', NItems.config().getString("witchName")), Material.TOTEM_OF_UNDYING, "witch_totem"),
    FARM_BALL(ChatColor.translateAlternateColorCodes('&', NItems.config().getString("farmName")), Material.PLAYER_HEAD, "farm_ball"),
    RANDOM_EGG(ChatColor.translateAlternateColorCodes('&', NItems.config().getString("randomEggName")), Material.PIG_SPAWN_EGG, "random_egg"),
    CLEAR_ARROW(ChatColor.translateAlternateColorCodes('&', NItems.config().getString("clearName")), Material.TIPPED_ARROW, "clear_arrow"),
    RANDOM_POTION(ChatColor.translateAlternateColorCodes('&', NItems.config().getString("randomPotName")), Material.POTION, "random_potion");

    private String name;
    private Material material;
    private String metaId;

    private Items(String name, Material material, String metaId) {
        this.name = name;
        this.material = material;
        this.metaId = metaId;
    }

    public Material getMaterial() {
        return this.material;
    }

    public String getMetaId() {
        return this.metaId;
    }

    public String getName() {
        return this.name;
    }

    public void setMaterial(Material material) {
        this.material = material;
    }

    public void setMetaId(String metaId) {
        this.metaId = metaId;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static Items getItem(ItemStack itemStack, Items item) {
        if (itemStack.getItemMeta() != null) {
            ItemMeta meta = itemStack.getItemMeta();
            if (meta != null) {
                String name = (String)meta.getPersistentDataContainer().get((NamespacedKey)Objects.requireNonNull(NamespacedKey.minecraft(item.getMetaId())), PersistentDataType.STRING);
                if (name == null) {
                    return null;
                }

                return valueOf(name);
            }
        }

        return null;
    }

    // $FF: synthetic method
    private static Items[] $values() {
        return new Items[]{SHEARS, DRACONID_TOTEM, WITCH_TOTEM, FARM_BALL, RANDOM_EGG, CLEAR_ARROW, RANDOM_POTION};
    }
}





package wtf.n1zamu;

import java.util.Arrays;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.event.Listener;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import wtf.n1zamu.listener.ClearArrowListener;
import wtf.n1zamu.listener.DraculaListener;
import wtf.n1zamu.listener.FarmListener;
import wtf.n1zamu.listener.PotionsListener;
import wtf.n1zamu.listener.RandomEggListener;
import wtf.n1zamu.listener.ScissorsListener;
import wtf.n1zamu.listener.TotemsListener;

public final class NItems extends JavaPlugin implements Listener {
    public void onEnable() {
        this.saveDefaultConfig();
        this.getLogger().info("=====NItems loaded successfully=====");
        this.getCommand("nitems").setExecutor(new NItemsCommand());
        Arrays.asList(new RandomEggListener(), new FarmListener(), new ScissorsListener(), new TotemsListener(), new DraculaListener(), new PotionsListener(), new ClearArrowListener()).forEach((listener) -> {
            Bukkit.getPluginManager().registerEvents((Listener) listener, this);
        });
    }

    public void onDisable() {
        this.getLogger().info("=====NItems unloaded successfully=====");
    }

    public static int getUsesLeft(ItemMeta meta) {
        if (meta.hasLore()) {
            String loreString = ChatColor.stripColor((String)meta.getLore().get(0));
            int index = loreString.indexOf(":");
            if (index != -1) {
                try {
                    return Integer.parseInt(loreString.substring(index + 1).trim());
                } catch (NumberFormatException var4) {
                    return 0;
                }
            }
        }

        return 0;
    }

    public static NItems getInstance() {
        return (NItems)getPlugin(NItems.class);
    }

    public static FileConfiguration config() {
        return getInstance().getConfig();
    }
}





package wtf.n1zamu;

import java.util.Arrays;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import org.jetbrains.annotations.NotNull;
import wtf.n1zamu.util.ItemStackUtil;
import wtf.n1zamu.util.NBTUtil;

public class NItemsCommand implements CommandExecutor {
    public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, @NotNull String[] strings) {
        if (strings.length >= 1) {
            Player player;
            if (strings[0].equalsIgnoreCase("enchant")) {
                if (strings.length != 6) {
                    commandSender.sendMessage("Неправильное использование");
                    return false;
                }

                player = null;
                if (commandSender instanceof Player) {
                    player = (Player)commandSender;
                }

                if (PotionEffectType.getByName(strings[1]) == null) {
                    commandSender.sendMessage("Эффект не найден!");
                    return false;
                }

                int duration;
                int chance;
                int amplifier;
                try {
                    duration = Integer.parseInt(strings[2]);
                    amplifier = Integer.parseInt(strings[3]);
                    chance = Integer.parseInt(strings[5]);
                } catch (NumberFormatException var10) {
                    commandSender.sendMessage("Неверный формат чисел!");
                    return false;
                }

                if (!Arrays.asList("DAMAGE", "SIMPLE").contains(strings[4])) {
                    commandSender.sendMessage("Не найдено такого модификатора! Доступные: DAMAGE, SIMPLE");
                    return false;
                }

                NBTUtil.addItemNBT(player.getInventory().getItemInMainHand(), "neffect", "neffect_" + strings[1] + "_" + duration + "_" + amplifier + "_" + strings[4] + "_" + chance);
                player.sendMessage("Предмет был зачарован!");
                return false;
            }

            player = Bukkit.getPlayerExact(strings[1]);
            ItemStackUtil itemStackUtil = new ItemStackUtil();
            Items items = null;

            try {
                items = Items.valueOf(strings[0]);
            } catch (IllegalArgumentException var11) {
                if (strings[0].equalsIgnoreCase("DRACULA_HEAD")) {
                    player.sendMessage("Предмет был зачарован!");
                    NBTUtil.addItemNBT(player.getInventory().getItemInMainHand(), "dracula_head", "");
                } else if (!Arrays.asList(Items.values()).contains(items)) {
                    player.sendMessage("Предмет не найден");
                    return false;
                }
            }

            if (!player.isOnline()) {
                return false;
            }

            String var8 = strings[0];
            byte var9 = -1;
            switch(var8.hashCode()) {
                case -1850133582:
                    if (var8.equals("SHEARS")) {
                        var9 = 0;
                    }
                    break;
                case -1599136503:
                    if (var8.equals("WITCH_TOTEM")) {
                        var9 = 2;
                    }
                    break;
                case -913272689:
                    if (var8.equals("RANDOM_POTION")) {
                        var9 = 3;
                    }
                    break;
                case 602012265:
                    if (var8.equals("RANDOM_EGG")) {
                        var9 = 5;
                    }
                    break;
                case 865727372:
                    if (var8.equals("DRACONID_TOTEM")) {
                        var9 = 1;
                    }
                    break;
                case 929362341:
                    if (var8.equals("DRACULA_HEAD")) {
                        var9 = 7;
                    }
                    break;
                case 1700829288:
                    if (var8.equals("FARM_BALL")) {
                        var9 = 4;
                    }
                    break;
                case 1809614679:
                    if (var8.equals("CLEAR_ARROW")) {
                        var9 = 6;
                    }
            }

            switch(var9) {
                case 0:
                    itemStackUtil.handleItem(items, player, NItems.config().getStringList("shearsLore"), (Enchantment)null, 1);
                    break;
                case 1:
                    itemStackUtil.handleItem(items, player, NItems.config().getStringList("draconidLore"), Enchantment.VANISHING_CURSE, 1);
                    break;
                case 2:
                    itemStackUtil.handleItem(items, player, NItems.config().getStringList("witchLore"), Enchantment.VANISHING_CURSE, 1);
                    break;
                case 3:
                    itemStackUtil.handleItem(items, player, NItems.config().getStringList("randomPotLore"), (Enchantment)null, 1);
                    break;
                case 4:
                    itemStackUtil.handleHeadItem(player, NItems.config().getStringList("farmBallLore"), Items.FARM_BALL, NItems.config().getString("farmTexture"));
                    break;
                case 5:
                    itemStackUtil.handleItem(items, player, NItems.config().getStringList("randomEggLore"), (Enchantment)null, 3);
                    break;
                case 6:
                    itemStackUtil.handleArrow(items, player, NItems.config().getStringList("clearLore"), 1);
                    break;
                case 7:
                    itemStackUtil.enchantItem(player);
                    break;
                default:
                    commandSender.sendMessage("/nitems [Item] [Name]");
            }
        }

        return true;
    }
}



CONFIG.YML
# %time% - плэйсхолдер для ножниц!

# Наименование аур и предметов в плагине
farmName: "&aШар огородника" # Название предмета-шара огородника
witchName: "&5&lТотем ведьмы" # Название предмета-тотема ведьмы
draconidName: "&6&lТотем драконида" # Название предмета-тотема драконида
randomPotName: "&b&lРандомное зелье" # Название предмета-рандомного зелья
shearsName: "&6&lСупер Ножницы &7- &63 &7использований" # Название предмета-ножниц
randomEggName: "&b&lРандомное яйцо" # Название предмета-рандомного яйца
clearName: "&fКлирик"
region: "&fВы в регионе!"
spawnWorld: "spawn"
witchTotemMessage: "&fВы сохранили свои эффекты."
clearLore:
  - "&9Очищает все эффекты с врага"
draconidLore:
  - "&7Срабатывает, когда"
  - "&7лежит в инвентаре"
witchLore:
  - "&7Сохраняет эффекты"
randomPotLore:
  - "&k&9Ещкереы писюы"
  - "&9Дает 3 случайных эффекта"
randomEggLore:
  - ""
  - " &9Призывает: &kмамку"
  - ""
farmBallLore:
  - "&cПроклятье утраты"
  - "&7Удача III (На растения)"
  - ""
  - "&7Когда во второй руке:"
  - "&7При нажатии SHIFT:"
  - "&9Выращивает растения вокруг вас"
  - ""
shearsLore:
  - "&7Этими ножницами можно &6ломать &7спавнера"
  - "&7Использований: &6&l3" # Важная строка, вместо 3 ставить количество использований
  - "&7Время ломания: &625 секунд"
draculaName: "зывфщзв"
draculaTexture: "фывзыфщвзыф"
draculaLore:
  - "афыва"
  - "дфвфл"

# Параметры для шара огородника
farmRadius: 15 # Радиус действия шара огородника
farmCooldown: 30 # Время перезарядки шара огородника
farmTexture: "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOWFmMzI4Yzg3YjA2ODUwOWFjYTk4MzRlZmFjZTE5NzcwNWZlNWQ0ZjA4NzE3MzFiN2IyMWNkOTliOWZkZGMifX19" # Текстура шара огородника
farmBallCooldown: "&aШар огородника &8» &fПерезарядка &b%time% &fсек"
# Сообщения для действий с ножницами
items:
  shears:
    inRegion: "&6Ножницы &7» &fВы в регионе!" # Сообщение для случая, когда игрок не может разрушить спаунер ножницами из-за региональных ограничений
    isBreaked: "&6Ножницы &7» &fПодождите еще &6%time% &fсекунд" # Сообщение о необходимости подождать определенное время перед повторным использованием ножниц
    cantBreak: "&6Ножницы &7» &fВы больше не можете использовать ножницы." # Сообщение о невозможности разрушения спаунера ножницами из-за отсутствия использований
    breakMessage: "&6Ножницы &7» &fНожницы поломались." # Сообщение об успешном разрушении спаунера ножницами

notification: # Оповещение игрока о шаре огородника

  sound: true # Звук при оповещении игрока
  soundType: "ENTITY_EXPERIENCE_ORB_PICKUP" # Тип звука при оповещении

  message: true # В виде сообщения в чат
  messageText: "&aШар огородника &8» &fВы использовали шар огородника"

  title: false # В виде сообщения на весь экран
  titleText: "Маладец растения выращены!"

plugin.yml
name: nItems
version: '1'
author: n1zamu
main: wtf.n1zamu.NItems
api-version: '1.16'
commands:
  nshears:
    permission: nItems.handle
    permission-message: "У тебя нет прав для этого действия!"
    aliases:
      - nitems