Kaboom
📎 1 file 3,617 chars
📄
pasted-code-1794089481651.txt
txt 41 lines
▶
Core feature: villager limit

There may be a maximum of 2 villagers on the entire server at any time (across all worlds).
Every additional villager must be prevented, no matter the source: spawn eggs, natural spawning, breeding, zombie villager curing, /summon, lightning conversion, dispensers, etc. (cancel CreatureSpawnEvent, EntityTransformEvent, and related events).
On server start and on chunk load, existing villagers are counted. If more than 2 exist, keep only 2 and remove the extras.
The limit is configurable in config.yml (default: 2).

Trades (OP only)

Only OPs (or players with the permission villagerlimit.admin) can configure what the villagers trade.
/villagertrade opens a GUI where the admin can edit the trades of Villager 1 and Villager 2:
input item 1, optional input item 2, output item
max uses (or unlimited)
add, edit, and delete trades
Alternative commands: /villagertrade add    and /villagertrade remove  .
Non-OPs get a “no permission” message.
Trades are saved in trades.yml and persist across restarts.
The trades are fixed: disable profession changes, level-ups, and restocking changes so that only the plugin controls the trades.

Villagers must never die, not even through commands

Make both villagers invulnerable and immune to all damage causes (fall, void, lava, explosions, players, mobs, etc.), including /kill, /damage, and /execute ... run kill.
Because vanilla /kill and /damage bypass invulnerability, add multiple layers of protection:
Command blocking: listen to PlayerCommandPreprocessEvent, ServerCommandEvent (console and command blocks), and Brigadier command events. Cancel any kill, damage, data merge/modify, tp into the void, execute, or minecraft:-prefixed variants whose selector could target the protected villagers (e.g. @e, @e[type=villager], UUID, name). Parse selectors and check whether the protected villagers would be affected. OPs are not exempt, but a config option allow-admin-bypass (default: false) can disable the protection for debugging.
Event cancelling: cancel EntityDamageEvent (all causes), EntityDeathEvent handling where possible, and EntityRemoveEvent for removal causes other than the plugin’s own.
Safety net (auto-respawn): if a protected villager is ever removed or killed anyway (e.g. by another plugin, a datapack, or /kill bypass), the plugin must immediately respawn it at its last saved location with the same name, the same trades, and the same settings. Save each villager’s UUID, location, and trade data in villagers.yml and update the location regularly (e.g. every few seconds and on chunk unload/shutdown).
Keep the villagers from being pushed, leashed, or moved into unsafe spots: set setAI(false) optionally (config freeze-villagers, default: true), prevent them from being picked up by vehicles, and cancel EntityPortalEvent.
Do not despawn them: set setPersistent(true) and setRemoveWhenFarAway(false).
Add a short note in the response about what cannot be 100% prevented in vanilla (for example, a datapack or another plugin that force-removes entities) and how the auto-respawn handles it.

Extra commands

/villagerlimit reload reloads the config (OP only).
/villagerlimit info shows how many villagers exist, their locations, and whether they’re alive (OP only).
/villagerlimit respawn <1|2> manually respawns a villager (OP only).
All messages must be customizable in config.yml.

Output

Full project structure (plugin.yml, pom.xml or build.gradle, main class, listeners, command classes, GUI class, data storage class)
Complete, compilable code with no placeholders
Kodari AI
KodariNov 7 at 10:13 pm 4
VillagerLimitGuard
A Minecraft Bukkit plugin enforcing a configurable global villager limit (default 2) by cancelling all spawn, breeding, transformation, and conversion events. Provides an OP-only GUI and commands to edit fixed trades for protected villagers, persisted in trades.yml. Makes the two designated villagers invulnerable through multi-layered protection: command blocking with selector parsing, damage/removal event cancellation, and an auto-respawn safety net that restores villagers from villagers.yml with their trades and location. Includes freeze, persistence, and portal prevention options, plus reload, info, and manual respawn commands with fully customizable messages.
  1. Enforce the server-wide limit and persist protected villager identities and locations.

  2. Add persistent trade editing and administrator commands.

  3. Protect villagers from damage, unsafe movement, and disruptive commands, with a respawn safety net.

Created the villager-limit plugin with persistent trades, an admin GUI, commands, protection listeners, and periodic recovery.

Limitations: Unloaded chunks aren’t scanned at startup, so the global limit is enforced as chunks load. Command protection blocks dangerous command types broadly rather than parsing selectors, and doesn’t cover every Brigadier or datapack path. A datapack or another plugin can still force-remove a villager; the safety check attempts to respawn it within five seconds when its saved chunk is loaded.

Kaboom

do not diable all commands, just make them immortal (also to /kill)

Kodari AI
KodariNov 7 at 10:23 pm 1
  • Remove the broad command filter.

  • Keep damage protection and restore a villager if /kill bypasses it.

Removed the broad command blocking. Villagers remain protected from damage; if /kill bypasses that protection, the plugin restores them on the next tick with their saved name and trades.

Force-removal can still bypass death events, so the periodic recovery remains as a fallback when the saved chunk is loaded.

Kaboom

how to use the plugin

Kodari AI
KodariNov 7 at 10:27 pm 1

Getting started

  1. Install the plugin and start the server. It manages up to two villagers by default.

  2. Spawn villagers or load chunks containing existing villagers. They’re assigned numbered slots.

  3. Run /villagerlimit info to see their slots, saved locations, and status.

You must be an OP or have villagerlimit.admin to use the commands and trade GUI.

Configure trades

Run /villagertrade and select a villager. Click Add to create a trade, or click an existing trade to edit it.

In the editor, click a field while holding the item on your cursor. The first input and output are required; the second input is optional. Click the max-uses button to cycle through its choices, then save.

You can also use:

  • /villagertrade add 1 EMERALD DIAMOND — add a one-item trade to villager 1.

  • /villagertrade remove 1 2 — remove villager 1’s second trade.

Trades persist across restarts in trades.yml.

Other commands

  • /villagerlimit reload — reload the configuration.

  • /villagerlimit respawn 1 — respawn villager 1 at its saved location.

Edit config.yml in the plugin’s data folder to change the limit, toggle freeze-villagers, or customize messages. Run the reload command afterward.

Villagers are protected from damage. If /kill or another removal bypasses protection, the plugin attempts to restore the villager; recovery may wait until its saved chunk is loaded.

Kaboom

the villagers are not spawning when i spawn them with spawn eggs

Kodari AI
KodariNov 7 at 10:32 pm 1

Spawn eggs are blocked when both villager slots are already assigned—even if those villagers are in unloaded chunks. This preserves the two-villager server-wide limit and their immortality.

Run /villagerlimit info to check the slots and saved locations. If it shows a free slot but spawn eggs still fail, send me the output and any server-console errors so I can pinpoint the cause.

Kaboom

do that no villager can spawn and they have to get spawned manualy

Kodari AI
KodariNov 7 at 10:37 pm 1
  • Block villager spawns and transformations from normal sources.

  • Add an admin command to spawn a protected villager at your location when a slot is free.

Villagers can no longer spawn through eggs, breeding, curing, or other normal sources.

Use /villagerlimit spawn in-game to spawn a protected villager at your location. You must be an OP or have villagerlimit.admin, and a slot must be free. Existing registered villagers remain in place.

Kaboom

there are villagers already on the map do that you have to do a command otherwise they are not spawning and every other villager is getting killed by loading

Kodari AI
KodariNov 7 at 10:50 pm 1

I’ll remove unregistered villagers as their chunks load, while keeping villagers already registered in the plugin’s slots. New villagers will require the spawn command.

Unregistered villagers are now removed when their chunks load or the server starts. Normal villager spawning remains blocked; use /villagerlimit spawn to create one.

Villagers already registered in the plugin’s slots are kept, including any registered by an earlier version.

Kaboom

how to kill the other old ones

Kodari AI
KodariNov 7 at 10:54 pm 1

Travel to the areas containing the old villagers to load their chunks. The plugin removes extra villagers as those chunks load; you don’t need to kill them manually.

Important: The current code may adopt an old villager into a free slot rather than remove it. Use /villagerlimit info to see which villagers are registered. Registered villagers are protected, and there is currently no command to permanently delete them.

Kaboom

they are not deleting on sight

Kodari AI
KodariNov 7 at 10:55 pm 1

I found that older villagers can remain protected if an earlier version registered them. I’ll also catch villagers when their entities finish loading, and add a way to clear a registered slot.

Fixed cleanup when villager entities load, with a periodic check for any missed villagers.

Old villagers already registered as protected must be removed manually:

  1. Run /villagerlimit info to identify their slots.

  2. Run /villagerlimit remove 1 or /villagerlimit remove 2.

Their slots will be freed, and they won’t respawn. Unregistered villagers are removed when their chunks load.

Kaboom

how to unfrezze it

Kodari AI
KodariNov 7 at 11:29 pm 1

In the plugin’s config.yml, change:

YAML
freeze-villagers: false

Then run /villagerlimit reload. This applies to all managed villagers.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
Code
5 612
src/main/java/com/kodari/villagerlimit/VillagerLimit.java
package com.kodari.villagerlimit;

import com.cryptomorin.xseries.XMaterial;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityPortalEvent;
import org.bukkit.event.entity.EntityTransformEvent;
import org.bukkit.event.entity.PlayerLeashEntityEvent;
import org.bukkit.event.entity.VillagerAcquireTradeEvent;
import org.bukkit.event.entity.VillagerCareerChangeEvent;
import org.bukkit.event.entity.VillagerReplenishTradeEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.event.world.EntitiesLoadEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.MerchantRecipe;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class VillagerLimit extends JavaPlugin implements Listener {
    private YamlConfiguration villagers;
    private YamlConfiguration trades;
    private File villagersFile;
    private File tradesFile;
    private boolean internalSpawn;
    private boolean stopping;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        villagersFile = new File(getDataFolder(), "villagers.yml");
        tradesFile = new File(getDataFolder(), "trades.yml");
        villagers = YamlConfiguration.loadConfiguration(villagersFile);
        trades = YamlConfiguration.loadConfiguration(tradesFile);
        Bukkit.getPluginManager().registerEvents(this, this);
        Bukkit.getPluginManager().registerEvents(new TradeMenu(this), this);
        for (World world : Bukkit.getWorlds()) {
            for (Entity entity : world.getEntities()) {
                if (entity instanceof Villager villager) handleLoadedVillager(villager);
            }
        }
        Bukkit.getScheduler().runTaskTimer(this, this::maintain, 20L, 100L);
    }

    @Override
    public void onDisable() {
        stopping = true;
        for (World world : Bukkit.getWorlds()) {
            for (Entity entity : world.getEntities()) {
                if (entity instanceof Villager villager && slotOf(villager) > 0) remember(villager);
            }
        }
        saveData();
    }

    public String message(String key) {
        return ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages." + key, key));
    }

    public int limit() {
        return Math.max(0, getConfig().getInt("limit", 2));
    }

    public boolean admin(CommandSender sender) {
        return sender.isOp() || sender.hasPermission("villagerlimit.admin");
    }

    private String path(int slot) { return "villagers." + slot; }

    public int slotOf(Villager villager) {
        String id = villager.getUniqueId().toString();
        for (int i = 1; i <= limit(); i++) {
            if (id.equals(villagers.getString(path(i) + ".uuid"))) return i;
        }
        return 0;
    }

    private int freeSlot() {
        for (int i = 1; i <= limit(); i++) {
            if (!villagers.contains(path(i) + ".uuid")) return i;
        }
        return 0;
    }

    private void register(Villager villager) {
        int slot = slotOf(villager);
        if (slot == 0) {
            slot = freeSlot();
            if (slot == 0) {
                villager.remove();
                return;
            }
            villagers.set(path(slot) + ".uuid", villager.getUniqueId().toString());
        }
        protect(villager, slot);
        remember(villager);
        saveData();
    }

    private void protect(Villager villager, int slot) {
        villager.setInvulnerable(true);
        villager.setPersistent(true);
        villager.setRemoveWhenFarAway(false);
        villager.setAI(!getConfig().getBoolean("freeze-villagers", true));
        villager.setRecipes(recipes(slot));
    }

    private void remember(Villager villager) {
        int slot = slotOf(villager);
        if (slot == 0) return;
        villagers.set(path(slot) + ".location", villager.getLocation());
        villagers.set(path(slot) + ".name", villager.getCustomName());
        villagers.set(path(slot) + ".name-visible", villager.isCustomNameVisible());
    }

    public List<MerchantRecipe> recipes(int slot) {
        List<MerchantRecipe> result = new ArrayList<>();
        String base = "villagers." + slot + ".trades";
        int count = trades.getInt(base + ".count");
        for (int i = 0; i < count; i++) {
            String p = base + "." + i;
            ItemStack first = trades.getItemStack(p + ".input1");
            ItemStack second = trades.getItemStack(p + ".input2");
            ItemStack output = trades.getItemStack(p + ".result");
            if (first == null || output == null) continue;
            MerchantRecipe recipe = new MerchantRecipe(output, Math.max(1, trades.getInt(p + ".max-uses", Integer.MAX_VALUE)));
            recipe.addIngredient(first);
            if (second != null) recipe.addIngredient(second);
            result.add(recipe);
        }
        return result;
    }

    public void setRecipes(int slot, List<MerchantRecipe> recipes) {
        String base = "villagers." + slot + ".trades";
        trades.set(base, null);
        trades.set(base + ".count", recipes.size());
        for (int i = 0; i < recipes.size(); i++) {
            MerchantRecipe recipe = recipes.get(i);
            String p = base + "." + i;
            trades.set(p + ".input1", recipe.getIngredients().get(0));
            if (recipe.getIngredients().size() > 1) trades.set(p + ".input2", recipe.getIngredients().get(1));
            trades.set(p + ".result", recipe.getResult());
            trades.set(p + ".max-uses", recipe.getMaxUses());
        }
        Villager villager = find(slot);
        if (villager != null) villager.setRecipes(recipes);
        saveData();
    }

    private Villager find(int slot) {
        String id = villagers.getString(path(slot) + ".uuid");
        if (id == null) return null;
        try {
            Entity entity = Bukkit.getEntity(UUID.fromString(id));
            return entity instanceof Villager ? (Villager) entity : null;
        } catch (IllegalArgumentException ex) { return null; }
    }

    private void saveData() {
        try {
            villagers.save(villagersFile);
            trades.save(tradesFile);
        } catch (IOException ex) { getLogger().severe("Could not save data: " + ex.getMessage()); }
    }

    private boolean respawn(int slot, boolean force) {
        Location location = villagers.getLocation(path(slot) + ".location");
        if (location == null || location.getWorld() == null) return false;
        if (!force && !location.isChunkLoaded()) return false;
        if (force) location.getChunk().load();
        Villager existing = find(slot);
        if (existing != null) {
            if (!force && existing.isValid() && !existing.isDead()) return true;
            existing.remove();
        }
        internalSpawn = true;
        try {
            Villager villager = location.getWorld().spawn(location, Villager.class);