I
📎 1 file 20,227 chars
📄
Crates Plugin_ Master Prompt.md
md 430 lines
▶
# PROMPT: Build a complete Minecraft Crates plugin ("DeluxeCrates"-style, command `/dc`)

You are an expert Minecraft plugin developer (Paper/Spigot API, Java 17+, 1.20.x–1.21.x). Build a **complete, production-ready, fully configurable Crates plugin** with Maven or Gradle, a `plugin.yml`, and clean packages. Deliver **every file in full**: no placeholders, no "TODO", no "implement yourself". Everything below is mandatory.

---

## 1. CORE RULES

- Plugin name: `Crates`. Main command: `/dc` (aliases `/crates`, `/crate`).
- Everything user-facing must be configurable: **every message, GUI title, GUI item name/lore/material/slot, GUI size (rows), sound, action bar, title, subtitle, particle and broadcast.**
- Zero hardcoded strings in code. All text comes from `lang.yml`, `config.yml` or the GUI/crate files.
- Colour support everywhere: legacy `&` codes, `§` codes, hex `&#RRGGBB`, and small-caps unicode text (e.g. `ᴄʀᴀᴛᴇ`). Strip nothing.
- Be tolerant when reading YAML: reward keys may be quoted (`'1'`) or unquoted (`1`); `chance` may be written `10%`, `10.0%` or `10`; `chance` may sit inside `icon:` or beside it; a stray typo in one file must **never** stop the plugin. Log a clear warning with file name and line, skip only the broken part, keep loading.
- Async where safe (file I/O, saving). All inventory/world work on the main thread.

---

## 2. FOLDER STRUCTURE (auto-created on first start, with default example files)

```
plugins/Crates/
├── config.yml          # general settings, sounds, broadcast
├── lang.yml            # ALL messages + action bars + command usage
├── data.yml            # crate block locations + player key data
├── crates/             # one file per crate: .yml
│   ├── common.yml
│   ├── gold.yml
│   ├── amethyst.yml
│   ├── crimson.yml
│   ├── dark.yml
│   └── prime.yml
├── keys/               # one file per crate key: .yml
├── effects/            # animation / opening-style files
│   ├── choose.yml
│   ├── rolling.yml
│   └── nowait.yml
└── gui/                # every GUI has its own file
    ├── confirm-gui.yml
    ├── itemeditor-gui.yml
    ├── crateeditor-gui.yml
    ├── rewardeditor-gui.yml
    ├── preview-gui.yml
    ├── list-gui.yml
    └── (any other GUI = its own file)
```

Every GUI file defines: `title`, `rows` (size), and `items:` with `slot`, `action`, `icon` (`material`, `name`, `lore`, `custom-model-data`, `glow`) and per-GUI `sounds`.

---

## 2B. DEFAULT FILES ARE NOT HARDCODED (very important)

- The files in the **APPENDIX at the bottom** (`config.yml`, `lang.yml`, every crate, every effect, every GUI) are only **default templates**. Embed them as resources inside the jar and copy them out **only on the very first start** (when `plugins/Crates/` does not exist yet).
- After that first start, the plugin must **never recreate or overwrite** them. If the server owner deletes `gold.yml`, that crate is simply gone and must not come back after restart or `/dc reload`.
- **No crate, key, effect or GUI may be hardcoded in Java.** On startup and on `/dc reload`, scan the folders and load **every** `.yml` file found:
  - every `crates/*.yml` = a crate (the top-level key, e.g. `gold-crate:`, is the crate id)
  - every `keys/*.yml` = a key
  - every `effects/*.yml` = an effect (the file name = the effect name, so a new `effects/myeffect.yml` can be used with `/dc seteffect  myeffect`)
  - every `gui/*.yml` = a GUI
- A new crate must work in **two ways**, with no restart and no code change:
  1. Manually: copy a yml into `crates/`, run `/dc reload`.
  2. By command: `/dc create ` generates the crate yml and key yml, then `/dc editor ` to fill it.
- `/dc remove ` deletes its files and unlinks its blocks. Missing files are never an error, only the `crate-not-found` message.
- If the owner deletes a file inside `lang.yml` / `config.yml`, add only the missing keys back, never touch the keys they already changed.

---

## 3. config.yml (exact structure to support)

```yaml
key-cooldown: 1            # seconds between key uses per player

sounds:
  click-sound: UI_BUTTON_CLICK
  confirm-sound: BLOCK_NOTE_BLOCK_PLING
  denied-sound: BLOCK_NOTE_BLOCK_BASS

broadcast:
  module:
    chat:
      enabled: false
      message:
        - "&f%player% &fopened a &a%crate% &fcrate and received &a%reward%&f!"
    actionbar:
      enabled: false
      message: [""]
    title:
      enabled: false
      message: [""]
    subtitle:
      enabled: false
      message: [""]
```

Also add (all optional/configurable): `default-key-type`, `save-interval`, `debug`, `open-sound`, `anti-spam`, `inventory-full-behavior` (DROP / DENY / MAIL), per-crate broadcast override, and a `bstats`-free, metrics-free design. Each sound entry accepts `SOUND`, `SOUND;volume;pitch`. Any sound can be disabled by leaving it empty.

---

## 4. lang.yml (every message + action bar)

```yaml
prefix-enabled: false
prefix: ''

messages:
  no-permission: "&cYou don't have permission to do this!"
  player-only: "Only players can execute this command!"
  reloaded: "&aCrates has been reloaded!"
  invalid-usage: "&cUsage: %usage%"
  crate-not-found: "&cCrate %crate% does not exist!"
  invalid-amount: "&cInvalid amount!"
  player-not-found: "&cPlayer not found!"
  bind: "&cCrate bind to the block you are looking at!"
  unbind: "&cCrate unbind from the block you are looking at!"
  no-crate-bind: "&cNo crate is bind to this block!"
  no-block: "&cYou must be looking at a block!"
  effect-set: "&fEffect &a%effect% &fhas been set for crate &a%crate%&f!"
  effect-removed: "&fEffect for crate &a%crate% &fhas been removed!"
  invalid-effect: "&cInvalid effect!"
  no-key: "&cYou don't have a key for this crate!"
  received-keys: ""
  given-keys: "&a%amount%x %crate% &fkeys have been given to &a%target%&f!"
  removed-keys: "&a%amount% %crate% &fkeys have been removed!"
  removed-all-keys: "&aAll %crate% &fkeys have been removed!"
  inventory-full: "&cYour inventory is full!"
  no-rewards: "&cThis crate has no rewards!"
  reward-received: "&fYou received &a%reward%&f!"
  no-players-online: "&cNo players are currently online!"
  invalid-type: "&cInvalid type!"
  keyall-success: "&fSuccessfully gave &a%amount% %crate% keys &7(%type%)&f to all online players!"
  effect-not-found: "&cEffect %effect% does not exist! Check effects folder."
  crate-already-exists: "&cCrate %crate% already exists!"
  crate-created: "&aCrate %crate% and its key have been created successfully!"
  crate-create-failed: "&cFailed to create crate %crate%!"
  crate-removed: "&aCrate %crate% and its key have been removed successfully!"
  crate-remove-partial: "&eCrate %crate% was partially removed. Some files could not be deleted."
  crate-delete-failed: "&cFailed to delete crate file for %crate%!"
  key-create-failed: "&cFailed to create key file for %crate%!"
  key-delete-failed: "&cFailed to delete key file for %crate%!"
  # + add new ones for: renamed, rows-changed, chance-changed, reward-added,
  #   reward-removed, already-opening, cooldown, crate-busy, crate-full,
  #   block-already-bound, key-given-to-you, key-taken-from-you, etc.

actionbars:        # every action bar is customizable
  no-key: "&cYou need a &a%crate% &ckey!"
  opening: "&fOpening &a%crate%&f..."
  reward: "&fYou won &a%reward%&f!"
  cooldown: "&cWait %time%s before using another key!"

list-crates: |
  afc00&lCRATES
  afc00➤ &f%crates%

command-usage: |
  afc00&lCRATES
  afc00➤ &f/dc reload
  afc00➤ &f/dc help
  afc00➤ &f/dc bind 
  afc00➤ &f/dc unbind
  afc00➤ &f/dc givekey    
  afc00➤ &f/dc takekey    
  afc00➤ &f/dc keyclear   
  afc00➤ &f/dc keyall   
  afc00➤ &f/dc seteffect  
  afc00➤ &f/dc removeeffect  
  afc00➤ &f/dc editor 
  afc00➤ &f/dc list
  afc00➤ &f/dc create 
  afc00➤ &f/dc remove 
```

---

## 5. COMMANDS (all required, with tab-complete and permissions `crates.admin` / `crates.`)

| Command | What it does |
| --- | --- |
| `/dc help` | Shows `command-usage` from lang.yml |
| `/dc reload` | Reloads config, lang, data, crates, keys, effects and every GUI file without restart |
| `/dc list` | Lists all crates (`list-crates` in lang.yml, optional clickable GUI) |
| `/dc create ` | Creates `crates/.yml` **and** `keys/.yml` with defaults |
| `/dc remove ` | Deletes crate file + key file, unbinds every block linked to it, reports partial failures |
| `/dc bind ` | Links the crate to the block the player is looking at (saved in `data.yml`) |
| `/dc unbind` | Unlinks the crate from the looked-at block |
| `/dc givekey    ` | Gives keys to a player |
| `/dc takekey    ` | Removes an amount of keys |
| `/dc keyclear   ` | Removes **all** keys of that crate/type from a player |
| `/dc keyall   ` | Gives keys to **every online player** |
| `/dc seteffect  ` | Sets opening effect (`CHOOSE`, `ROLLING`, `NOWAIT`) and writes it into the crate yml |
| `/dc removeeffect  ` | Removes the effect |
| `/dc editor ` | Opens the in-game crate editor GUI (see section 8) |

Key ``: `virtual` (stored as a number in data.yml) or `physical` (real item with NBT/PDC tag). Both supported on every command. Console must be able to run `givekey`, `takekey`, `keyclear`, `keyall`, `reload`, `list`, `create`, `remove`.

---

## 6. THE TWO MAIN CRATE TYPES

### TYPE A — **Real-item crates ("put the item in the crate")**

- The admin opens `/dc editor ` and **drops/places real items** (with full NBT: enchants, lore, names, custom data) into the editor GUI.
- Those exact item stacks are saved (serialized, base64 or YAML) and handed out as the reward.
- Per item: set **chance**, optional **commands**, optional **broadcast**, optional **limit**.

### TYPE B — **Fake-display crates ("display item + commands")**

- The GUI shows a **fake/display item** (`icon`: material, name, lore, enchantments, armor trim, glow, custom-model-data).
- The player never receives that display item. Instead the **`commands:` list is run by console** (`%player%` replaced). Example: `ss give spawner %player% zombie`.
- Supports `chance`, `commands`, `broadcast`, `give-item: true/false` (optionally also give the display item).

Reward format (must parse all of this, from the real sample files):

```yaml
amethyst-crate:
  inventory:
    name: 'ᴀᴍᴇᴛʜʏsᴛ ᴄʀᴀᴛᴇ'
    effect: CHOOSE        # CHOOSE | ROLLING | NOWAIT
    rows: 3
  rewards:
    1:
      slot: 10
      chance: 10%
      icon:
        material: NETHERITE_AXE
        name: '&#A20AD6ᴀᴍᴇᴛʜʏsᴛ ᴀxᴇ'
        lore:
          - '&7Breaks Trees instantly'
        enchantments:
          mending: 1
          efficiency: 5
        trim:
          material: redstone
          pattern: snout
      commands:
        - 'tools give %player% treechopper'
  back-button:
    enable: false
    displayname: '&#FF0000ᴄʟᴏꜱᴇ'
    material: RED_STAINED_GLASS_PANE
    slot: 18
    lore:
      - '&fClick to close'
```

Also support per reward: `amount`, `custom-model-data`, `glow`, `hide-flags`, `permission`, `limit-per-player`, `broadcast`, `give-item`, `sound`, `actionbar`, `title`, `subtitle`, and **item-level armor trim + enchantments** (valid for 1.20+ trim API).

---

## 7. OPENING EFFECTS (the sub-types; all in `effects/`)

### 7.1 `CHOOSE` — click to open, then pick the reward

1. Player right-clicks the crate block (or uses `/dc open ` if enabled) holding/owning a key.
2. The crate GUI opens showing **all reward icons** (fake or real) at their `slot`s.
3. Player clicks the reward they want.
4. **`confirm-gui.yml` opens**: confirm / deny / display item (placeholders `%item%` and `%item_name%`).
5. On confirm: key is consumed, reward is given, effects/sounds/broadcast fire. On deny: back to the crate GUI, **no key used**.

`effects/choose.yml` is allowed to be an empty file (`#`) because it only marks the mode, but it must be read without errors.

### 7.2 `ROLLING` — random reward with animation and **custom percentages**

Driven by `effects/rolling.yml` (support exactly this structure):

```yaml
rolling-gui:
  name: '&8ʀᴏʟʟɪɴɢ'
  rows: 3
  rolling-settings:
    enabled: true
    Direction: LEFT-TO-RIGHT      # LEFT-TO-RIGHT | RIGHT-TO-LEFT | TOP-TO-BOTTOM | BOTTOM-TO-TOP
    reward-item-slots: [9, 10, 11, 12, 13, 14, 15, 16, 17]
    rolling-speed: 25             # ticks between steps
    rolling-duration: 2000        # milliseconds
    above-below-item-reward: HOPPER
  sounds:
    rolling: UI_BUTTON_CLICK
    reward-get: BLOCK_NOTE_BLOCK_PLING
  rolling:
    items:                        # filler panes that scroll while spinning
      - YELLOW_STAINED_GLASS_PANE
      - BLUE_STAINED_GLASS_PANE
```

- The winning reward is **picked on the server BEFORE the animation starts** using weighted random from each reward's `chance` (chances need not sum to 100; normalise them).
- The animation is purely visual and must **end exactly on the pre-picked reward** in the centre slot.
- Slow down smoothly at the end (easing). Lock all clicks while rolling.

### 7.3 `NOWAIT` — instant open (third type)

- Key is used, reward is chosen by chance **instantly**, no GUI. Particles play at the crate block.
- `effects/nowait.yml`:

```yaml
particle:
  enabled: true
  type: TOTEM
  count: 30
  offset: 0.5
```

- Add configurable sound and optional hologram/actionbar message.

All three effects must be selectable by `/dc seteffect  ` and by the crate file `effect:` key. Unknown effect → `effect-not-found`.

---

## 8. IN-GAME EDITOR (`/dc editor `)

Opens `crateeditor-gui.yml` (title from `itemeditor-gui.yml`: `"&8Edit: %crate%"`). Everything must **write back to the crate yml immediately** and live-reload the crate. Features:

- **Rename the crate**: click "Rename", type in chat (cancel with `cancel`) → updates `inventory.name` in the yml **and** updates the crate's display name everywhere (GUI titles, lists, key item, broadcast, PlaceholderAPI). Must not break the internal id/file name; optional "rename id" that safely renames the file, key file, and all `data.yml` links.
- Change rows (1–6), effect (CHOOSE/ROLLING/NOWAIT), key type, back-button.
- **Add items**: drop any item into the editor → becomes a reward (TYPE A). For TYPE B: add a display item and edit its commands.
- Per reward click-menu (`rewardeditor-gui.yml`): edit **chance**, slot, name, lore, commands (add/remove/list), broadcast, limit, delete reward.
- Save / Cancel / Reset buttons with confirm GUI.
- Lock the editor to one editor per crate at a time.

---

## 9. BLOCK LINKING + `data.yml`

`data.yml` stores **all crate locations** and player key balances:

```yaml
crates:
  gold:
    locations:
      - "world;100;64;200"
      - "world;105;64;200"
players:
  :
    keys:
      gold:
        virtual: 5
```

- `/dc bind ` links the block being looked at (ray trace, 5 blocks). One block = one crate. Multiple blocks per crate allowed.
- `/dc unbind` removes the link. Breaking a bound block is blocked unless the player has `crates.admin` and sneaks (then it auto-unbinds).
- Right-click with key = open. Left-click = preview rewards (`preview-gui.yml`). Shift+right-click = open preview or open-all if enabled.
- `/dc list` reads all crates from the crates folder and `data.yml`, shows each crate's name, effect and how many blocks are linked.

---

## 10. KEYS (`keys/.yml`)

```yaml
key:
  material: TRIPWIRE_HOOK
  name: '&a%crate% Key'
  lore:
    - '&7Right click a %crate% crate'
  glow: true
  custom-model-data: 0
  type: PHYSICAL      # PHYSICAL | VIRTUAL | BOTH
```

- Physical keys carry a hidden **PersistentDataContainer** tag with crate id (no NBT-name matching, so renaming in an anvil does not break/forge them).
- Virtual keys are stored in `data.yml` (or per-player files) and saved safely.
- `/dc create` makes the key file automatically; `/dc remove` deletes it.

---

## 11. PLACEHOLDERS

Message/GUI placeholders: `%player%`, `%target%`, `%crate%`, `%reward%`, `%amount%`, `%type%`, `%effect%`, `%crates%`, `%usage%`, `%item%`, `%item_name%`, `%time%`, `%chance%`, `%slot%`.

**PlaceholderAPI expansion** (register `crates`; soft-depend):

- `%crates_keys_%` — player's total keys for that crate
- `%crates_keys__virtual%` / `_physical%`
- `%crates_keys_total%` — all keys combined
- `%crates_opened_%` — how many times the player opened it
- `%crates_opened_total%`
- `%crates_amount%` — number of crates
- `%crates_list%`
- `%crates_name_%`
- `%crates_chance__%`

All GUI texts (names, lore, titles) and actions also parse PlaceholderAPI placeholders when installed.

---

## 12. SECURITY: NO EXPLOITS, NO DUPES (critical)

- **Cancel every click, drag, shift-click, number-key swap, double-click collect, hotbar swap and offhand-swap in all plugin GUIs.** Only the actions defined in the GUI file do anything.
- Never trust the client: check key ownership **server-side at the moment of reward**, consume the key **atomically before** giving the reward (rollback on failure).
- One opening per player at a time; ignore clicks while an animation runs.
- Block key use if player is in `key-cooldown`.
- If inventory is full: follow `inventory-full-behavior` (never delete the reward; deny before consuming the key whenever possible).
- Prevent dupes on: logout/disconnect mid-open (finish and give reward, or refund key), server stop (refund or finish all active opens), `/reload`, chunk unload, GUI close with Esc, death, world change, lag, double right-click, dropping the key while opening, and moving the key to another inventory/container while the GUI is open.
- Physical keys: tagged with PDC + unique-use check, cannot be stacked into containers while opening.
- Editor GUI and reward items: block taking/pulling items out of the editor except through the explicit buttons.
- Prevent piston/explosion/water breaking of crate blocks; block hopper/dropper interaction.
- Commands: sanitise `%player%` replacement and never run reward commands as op; run through console dispatch only.
- Thread-safe key balance changes (synchronised or atomic), saved on change and on disable.
- Permission-gate everything: `crates.admin`, `crates.open.`, `crates.reload`, `crates.keys`, `crates.editor`, etc.
- Provide a `debug` option that logs every open/key change for auditing.

---

## 13. QUALITY REQUIREMENTS

- Java 17, no deprecated API when a replacement exists, no NMS (use Paper/Bukkit API + Adventure/legacy serializer for hex).
- Clean architecture: `command`, `crate`, `effect`, `gui`, `key`, `data`, `config`, `listener`, `util`, `hook` packages.
- Full Javadoc on public classes. Meaningful error messages in console.
- Provide: complete source, `pom.xml` (or `build.gradle`), `plugin.yml` (commands, permissions, softdepend PlaceholderAPI), and **all default YAML files** pre-filled with the examples above.
- After the code, give a short **install + test checklist** (create crate, bind, give key, open with each effect, rename in editor, reload, keyall, keyclear, remove).

---

## 14. HOW TO RESPOND

Work in this order and output **complete files** (no truncating):

1. Project tree
2. `pom.xml` / `plugin.yml`
3. All default YAML files
4. Java source, package by package
5. Install + test checklist

If the answer is too long for one message, continue in parts and **say "CONTINUE" at the end of each part** until everything is delivered.

---

# APPENDIX: DEFAULT FILES (copy these exactly into the jar as first-run templates)

These are the real files from the original plugin. Ship them **exactly as written** (keep the small-caps text, hex colours, `§` codes and comments). Some contain small typos (for example `rows: 3'` in `prime.yml`, mixed quoted/unquoted reward ids, `chance` inside or outside `icon`); the parser must tolerate them as described in section 1. You may fix the typos in the shipped copies.

Kodari AI
KodariOct 2 at 3:02 am 3
CratesPlugin
A comprehensive, fully configurable Minecraft crates plugin for Paper/Spigot servers. Features multiple crate types with real-item or fake-display rewards, three opening effects (CHOOSE, ROLLING, NOWAIT), an in-game editor GUI, physical and virtual keys, block binding, PlaceholderAPI integration, and extensive customization through YAML files. All messages, sounds, GUI elements, and rewards are configurable with no hardcoded strings. Includes anti-exploit protections, async file I/O, and a robust YAML parser tolerant of common formatting issues.
  1. Create the Gradle/Paper plugin scaffold and first-run YAML templates.

  2. Implement crate loading, key/data persistence, commands, crate interactions, and protected GUIs.

  3. Include example crates, effects, and GUI configs.

Created the Gradle/Paper project with first-run YAML templates, dynamic crate loading, virtual and PDC-tagged physical keys, the /dc admin commands, bound-block interactions, preview and confirmation menus, and CHOOSE/ROLLING/NOWAIT reward flows.

Scope caveat: this is not yet the full attached specification. The crate editor currently displays a read-only GUI; PlaceholderAPI expansion, armor trims, custom effect execution, and several requested anti-exploit protections are not implemented. I did not run a build.

Install and smoke-test

  1. Build with gradle build; install build/libs/Crates-1.0.0.jar and start the server once.

  2. Bind a block to the bundled common-crate: /dc bind common-crate.

  3. Give yourself a virtual key: /dc givekey <player> common-crate virtual 1.

  4. Right-click the block, select a reward, and confirm.

  5. Try /dc seteffect common-crate rolling and /dc seteffect common-crate nowait, then repeat the open test.

  6. Check /dc list, /dc reload, /dc keyall, /dc keyclear, and /dc remove.

I

U did not added all items in thr crates and the choose crate they can be opened with any click and the key have check should happen on conform screen sho if player do not even have keys he will still see confirm screen and in the rolling crate in the rolling snimation in centre row roll all the items and add rolling things above snd below like glass pane and where u will get thr reward so menss middle block in below middle block add a hopper while rolling and also list all placeholder and permession in the config file and store all player dats into a seprate player dats folder and playername.ymal and add a key clear all command of already have ignore snd key clear should be work on offline player too but keyall only for online players should have inv full checks when opening crate and when krysll if player inv id full drop thet key on ground instead of vanishing it

📎 6 files 13,292 chars
📄
common.yml
yml 81 lines
▶
common-crate:
  inventory:
    name: ᴄᴏᴍᴍᴏɴ ᴄʀᴀᴛᴇ
    effect: CHOOSE # here you set it to choose or nowait (/dc seteffect  )
    rows: 3
  rewards:
    '1':
      slot: 10
      icon:
        material: DIAMOND_HELMET
        name: §2ᴄᴏᴍᴍᴏɴ ʜᴇʟᴍᴇᴛ
        enchantments:
          protection: 1
          respiration: 2
        trim:
          material: emerald
          pattern: wild
      chance: 100.0%
    '2':
      slot: 11
      icon:
        material: DIAMOND_CHESTPLATE
        name: §2ᴄᴏᴍᴍᴏɴ ᴄʜᴇsᴛᴘʟᴀᴛᴇ
        enchantments:
          protection: 1
        trim:
          material: emerald
          pattern: wild
      chance: 100.0%
    '3':
      slot: 12
      icon:
        material: DIAMOND_LEGGINGS
        name: §2ᴄᴏᴍᴍᴏɴ ʟᴇɢɢɪɴɢs
        enchantments:
          protection: 1
          swift_sneak: 2
        trim:
          material: emerald
          pattern: wild
      chance: 100.0%
    '4':
      slot: 13
      icon:
        material: DIAMOND_BOOTS
        name: §2ᴄᴏᴍᴍᴏɴ ʙᴏᴏᴛs
        enchantments:
          depth_strider: 2
          feather_falling: 2
          protection: 1
        trim:
          material: emerald
          pattern: wild
      chance: 100.0%
    '5':
      slot: 14
      icon:
        material: DIAMOND_SWORD
        name: §2ᴄᴏᴍᴍᴏɴ sᴡᴏʀᴅ
        enchantments:
          looting: 2
          sharpness: 1
      chance: 100.0%
    '6':
      slot: 15
      icon:
        material: DIAMOND_PICKAXE
        name: §2ᴄᴏᴍᴍᴏɴ ᴘɪᴄᴋᴀxᴇ
        enchantments:
          efficiency: 2
          fortune: 1
      chance: 100.0%
    '7':
      slot: 16
      icon:
        material: DIAMOND_SHOVEL
        name: §2ᴄᴏᴍᴍᴏɴ sʜᴏᴠᴇʟ
        enchantments:
          efficiency: 3
      chance: 100.0%
📄
amethyst.yml
yml 119 lines
▶
amethyst-crate:
  inventory:
    name: 'ᴀᴍᴇᴛʜʏsᴛ ᴄʀᴀᴛᴇ'
    effect: CHOOSE
    rows: 3

  rewards:
    1:
      slot: 10
      icon:
        material: NETHERITE_AXE
        chance: 10%
        name: '&#A20AD6ᴀᴍᴇᴛʜʏsᴛ ᴀxᴇ'
        lore:
          - '&7Breaks Trees instantly'
          - '&8Self Destruct:'
          - '&82d 23h 59m'
        enchantments:
          mending: 1
          silk_touch: 1
          efficiency: 5
          unbreaking: 3
      commands:
        - 'tools give %player% treechopper'
    2:
      slot: 11
      icon:
        material: NETHERITE_AXE
        chance: 10%
        name: '&#A20AD6ᴀᴍᴇᴛʜʏsᴛ sᴇʟʟ ᴀxᴇ'
        lore:
          - '&7Instantly Sells All Items in A Chest'
          - '&8Self Destruct:'
          - '&82d 23h 59m'
        enchantments:
          mending: 1
          efficiency: 5
          unbreaking: 3
      commands:
        - 'sellaxe %player%'
    3:
      slot: 12
      icon:
        material: NETHERITE_PICKAXE
        chance: 10%
        name: '&#A20AD6ᴀᴍᴇᴛʜʏsᴛ ᴘɪᴄᴋᴀxᴇ'
        lore:
          - '&7Breaks 9 Blocks at Once'
          - '&8Self Destruct:'
          - '&82d 23h 59m'
        enchantments:
          mending: 1
          efficiency: 5
          unbreaking: 3
      commands:
        - 'tools give %player% drill'
    4:
      slot: 13
      icon:
        material: NETHERITE_SHOVEL
        chance: 10%
        name: '&#A20AD6ᴀᴍᴇᴛʏꜱᴛ ꜱʜᴏᴠᴇʟ'
        lore:
          - '&7Breaks 9 Blocks at Once'
          - '&8Self Destruct:'
          - '&82d 23h 59m'
        enchantments:
          mending: 1
          efficiency: 5
          unbreaking: 3
      commands:
        - 'tools give %player% shovel'
    5:
      slot: 14
      icon:
        material: NETHERITE_HOE
        chance: 10%
        name: '&#A20AD6ᴀᴍᴇᴛʏꜱᴛ ʜᴏᴇ'
        lore:
          - '&7Plants 9 Blocks at Once'
          - '&8Self Destruct:'
          - '&82d 23h 59m'
        enchantments:
          fortune: 3
          efficiency: 5
          unbreaking: 3
      commands:
        - 'tools give %player% hoe'
    6:
      slot: 15
      icon:
        material: WATER_BUCKET
        chance: 10%
        name: '&#A20AD6ᴀᴍᴇᴛʜʏꜱᴛ ᴡᴀᴛᴇʀ ʙᴜᴄᴋᴇᴛ'
        lore:
          - '&7Infinite Water Bucket'
          - '&8Durability:'
          - '&82d 23h 59m'
      commands:
        - 'tools give %player% waterbucket time 3d'
    7:
      slot: 16
      icon:
        material: FIREWORK_ROCKET
        chance: 10%
        name: '&#A20AD6ɪɴꜰɪɴɪᴛʏ ʀᴏᴄᴋᴇᴛ'
        lore:
          - '&7Boosts your Elytra flight'
          - '&8Durability:'
          - '&82d 23h 59m'
      commands:
        - 'tools give %player% rocket time 3d'
  back-button:
    enable: false
    displayname: '&#FF0000ᴄʟᴏꜱᴇ'
    material: RED_STAINED_GLASS_PANE
    slot: 18
    lore:
      - '&fClick to close'
📄
crimson.yml
yml 97 lines
▶
crimson-crate:
  inventory:
    name: 'ᴄʀɪᴍsᴏɴ ᴄʀᴀᴛᴇ'
    effect: CHOOSE #here you set it to choose or nowait (/dc seteffect  )
    rows: 3

  rewards:
    1:
      slot: 10
      icon:
        material: NETHERITE_HELMET
        name: '&4ᴄʀɪᴍsᴏɴ ʜᴇʟᴍᴇᴛ'
        trim:
          material: redstone
          pattern: snout
        enchantments:
          protection: 4
          respiration: 3
          mending: 1
          thorns: 3
          unbreaking: 3
    2:
      slot: 11
      icon:
        material: NETHERITE_CHESTPLATE
        name: '&4ᴄʀɪᴍsᴏɴ ᴄʜᴇsᴛᴘʟᴀᴛᴇ'
        trim:
          material: redstone
          pattern: snout
        enchantments:
          protection: 4
          mending: 1
          thorns: 3
          unbreaking: 3
    3:
      slot: 12
      icon:
        material: NETHERITE_LEGGINGS
        name: '&4ᴄʀɪᴍsᴏɴ ʟᴇɢɢɪɴɢs'
        trim:
          material: redstone
          pattern: snout
        enchantments:
          protection: 4
          swift_sneak: 3
          mending: 1
          thorns: 3
          unbreaking: 3
    4:
      slot: 13
      icon:
        material: NETHERITE_BOOTS
        name: '&4ᴄʀɪᴍsᴏɴ ʙᴏᴏᴛs'
        trim:
          material: redstone
          pattern: snout
        enchantments:
          protection: 4
          depth_strider: 3
          feather_falling: 4
          mending: 1
          soul_speed: 3
          thorns: 3
          unbreaking: 3
    5:
      slot: 14
      icon:
        material: NETHERITE_SWORD
        name: '&4ᴄʀɪᴍsᴏɴ sᴡᴏʀᴅ'
        enchantments:
          sharpness: 5
          looting: 3
          fire_aspect: 2
          knockback: 2
          mending: 1
          unbreaking: 3
    6:
      slot: 15
      icon:
        material: NETHERITE_PICKAXE
        name: '&4ᴄʀɪᴍsᴏɴ ᴘɪᴄᴋᴀxᴇ'
        enchantments:
          mending: 1
          unbreaking: 3
          silk_touch: 1
          efficiency: 5
    7:
      slot: 16
      icon:
        material: NETHERITE_AXE
        name: '&4ᴄʀɪᴍsᴏɴ ᴀxᴇ'
        enchantments:
          efficiency: 5
          mending: 1
          sharpness: 5
          silk_touch: 1
          unbreaking: 3
📄
dark.yml
yml 131 lines
▶
dark-crate:
  inventory:
    name: 'ǡD59ᴅᴀʀᴋ ᴄʀᴀᴛᴇ'
    rows: 3
    effect: ROLLING
    filler-item:
      enable: FALSE
      material: BLACK_STAINED_GLASS_PANE
      name: ' '
  rewards:
    '1':
      slot: 9
      icon:
        material: NETHERITE_HELMET
        name: §x§4§8§1§D§5§9ᴅᴀʀᴋ ʜᴇʟᴍᴇᴛ
        enchantments:
          aqua_affinity: 1
          mending: 2
          protection: 6
          respiration: 4
          thorns: 4
          unbreaking: 4
        trim:
          material: netherite
          pattern: silence
      chance: 100.0%
    '2':
      slot: 10
      icon:
        material: NETHERITE_CHESTPLATE
        name: §x§4§8§1§D§5§9ᴅᴀʀᴋ ᴄʜᴇꜱᴛᴘʟᴀᴛᴇ
        enchantments:
          mending: 2
          protection: 6
          thorns: 4
          unbreaking: 4
        trim:
          material: netherite
          pattern: silence
      chance: 100.0%
    '3':
      slot: 11
      icon:
        material: NETHERITE_LEGGINGS
        name: §x§4§8§1§D§5§9ᴅᴀʀᴋ ʟᴇɢɢɪɴɢꜱ
        enchantments:
          mending: 2
          protection: 6
          swift_sneak: 3
          thorns: 4
          unbreaking: 4
        trim:
          material: netherite
          pattern: silence
      chance: 100.0%
    '4':
      slot: 12
      icon:
        material: NETHERITE_BOOTS
        name: §x§4§8§1§D§5§9ᴅᴀʀᴋ ʙᴏᴏᴛꜱ
        enchantments:
          depth_strider: 3
          feather_falling: 4
          mending: 2
          protection: 6
          soul_speed: 3
          thorns: 4
          unbreaking: 4
        trim:
          material: netherite
          pattern: silence
      chance: 100.0%
    '5':
      slot: 13
      icon:
        material: ELYTRA
        name: §x§4§8§1§D§5§9ᴅᴀʀᴋ ᴇʟʏᴛʀᴀ
        enchantments:
          mending: 3
          unbreaking: 5
      chance: 100.0%
    '6':
      slot: 14
      icon:
        material: NETHERITE_SWORD
        name: §x§4§8§1§D§5§9ᴅᴀʀᴋ ꜱᴡᴏʀᴅ
        enchantments:
          fire_aspect: 4
          knockback: 2
          looting: 4
          mending: 2
          sharpness: 6
          sweeping_edge: 4
          unbreaking: 4
      chance: 100.0%
    '7':
      slot: 15
      icon:
        material: NETHERITE_PICKAXE
        name: §x§4§8§1§D§5§9ᴅᴀʀᴋ ᴘɪᴄᴋᴀxᴇ
        enchantments:
          efficiency: 6
          fortune: 4
          mending: 2
          unbreaking: 4
      chance: 100.0%
    '8':
      slot: 16
      icon:
        material: NETHERITE_AXE
        name: §x§4§8§1§D§5§9ᴅᴀʀᴋ ᴀxᴇ
        enchantments:
          efficiency: 6
          fortune: 4
          mending: 2
          sharpness: 6
          unbreaking: 4
      chance: 100.0%
    '9':
      slot: 17
      icon:
        material: MACE
        name: §x§4§8§1§D§5§9ᴅᴀʀᴋ ᴍᴀᴄᴇ
        enchantments:
          density: 6
          fire_aspect: 4
          mending: 2
          unbreaking: 4
          wind_burst: 3
      chance: 100.0%
📄
gold.yml
yml 56 lines
▶
gold-crate:
  inventory:
    name: 'ɢᴏʟᴅ ᴄʀᴀᴛᴇ'
    effect: CHOOSE #here you set it to choose or nowait (/dc seteffect  )
    rows: 3

  rewards:
    1:
      slot: 10
      icon:
        material: SPAWNER
        name: '&dZombie Spawner'
      commands:
        - 'ss give spawner %player% zombie'
    2:
      slot: 11
      icon:
        material: SPAWNER
        name: '&dCave Spider Spawner'
      commands:
        - 'ss give spawner %player% cave_spider'
    3:
      slot: 12
      icon:
        material: SPAWNER
        name: '&dSkeleton Spawner'
      commands:
        - 'ss give spawner %player% skeleton'
    4:
      slot: 13
      icon:
        material: SPAWNER
        name: '&dCreeper Spawner'
      commands:
        - 'ss give spawner %player% creeper'
    5:
      slot: 14
      icon:
        material: SPAWNER
        name: '&dEnderman Spawner'
      commands:
        - 'ss give spawner %player% enderman'
    6:
      slot: 15
      icon:
        material: SPAWNER
        name: '&dIron Golem Spawner'
      commands:
        - 'ss give spawner %player% iron_golem'
    7:
      slot: 16
      icon:
        material: SPAWNER
        name: '&dSpider Spawner'
      commands:
        - 'ss give spawner %player% spider'
📄
prime.yml
yml 100 lines
▶
prime-crate:
  inventory:
    name: ᴘʀɪᴍᴇ ᴄʀᴀᴛᴇ
    effect: CHOOSE # here you set it to choose or nowait (/dc seteffect  )
    rows: 3'
  rewards:
    '1':
      slot: 10
      icon:
        material: NETHERITE_HELMET
        name: §3ᴘʀɪᴍᴇ ʜᴇʟᴍᴇᴛ
        enchantments:
          mending: 1
          protection: 4
          respiration: 3
          unbreaking: 3
        trim:
          material: diamond
          pattern: host
      chance: 100.0%
    '2':
      slot: 11
      icon:
        material: NETHERITE_CHESTPLATE
        name: §3ᴘʀɪᴍᴇ ᴄʜᴇsᴛᴘʟᴀᴛᴇ
        enchantments:
          mending: 1
          protection: 4
          unbreaking: 3
        trim:
          material: diamond
          pattern: host
      chance: 100.0%
    '3':
      slot: 12
      icon:
        material: NETHERITE_LEGGINGS
        name: §3ᴘʀɪᴍᴇ ʟᴇɢɢɪɴɢs
        enchantments:
          blast_protection: 4
          mending: 1
          swift_sneak: 3
          unbreaking: 3
        trim:
          material: diamond
          pattern: host
      chance: 100.0%
    '4':
      slot: 13
      icon:
        material: NETHERITE_BOOTS
        name: §3ᴘʀɪᴍᴇ ʙᴏᴏᴛs
        enchantments:
          depth_strider: 3
          feather_falling: 4
          mending: 1
          protection: 4
          soul_speed: 3
          unbreaking: 3
        trim:
          material: diamond
          pattern: host
      chance: 100.0%
    '5':
      slot: 14
      icon:
        material: NETHERITE_SWORD
        name: §3ᴘʀɪᴍᴇ sᴡᴏʀᴅ
        enchantments:
          knockback: 1
          looting: 3
          mending: 1
          sharpness: 5
          unbreaking: 3
      chance: 100.0%
    '6':
      slot: 15
      icon:
        material: CROSSBOW
        name: §3ᴘʀɪᴍᴇ ᴄʀᴏssʙᴏᴡ
        enchantments:
          mending: 1
          multishot: 1
          quick_charge: 3
          unbreaking: 3
      chance: 100.0%
    '7':
      slot: 16
      icon:
        material: MACE
        name: §x§2§5§9§6§B§Eᴘʀɪᴍᴇ ᴍᴀᴄᴇ
        enchantments:
          density: 5
          fire_aspect: 2
          mending: 1
          quick_charge: 3
          unbreaking: 3
          wind_burst: 3
      chance: 100.0%
Kodari AI
KodariOct 2 at 3:30 am 3
  1. Fix crate reward displays, choose clicks, confirmation flow, and key validation.

  2. Update the rolling animation with a centered reward lane, glass borders, and hopper indicator.

  3. Add inventory-full handling and persistent per-player key data, including offline key clearing and online-only key-all.

  4. Document placeholders and permissions in the config.

  1. Choose crates now open from either left- or right-click; players without keys can browse rewards and reach confirmation, where the key is checked when they confirm. Reward menus expand to show configured rewards across up to six rows.

  2. Rolling animations now cycle reward icons across the center row, with glass-pane borders and a hopper below the center reward.

  3. Virtual key data now uses playerdata/<playername>.yml, with migration from the old shared data file. Offline keyclear clears virtual keys immediately and schedules physical-key removal for the player’s next join; physical keys in the offhand are also cleared. keyall remains online-only.

  4. Added placeholder and permission references to the config and declared crates.open.* in plugin.yml. Existing full-inventory checks and key-grant overflow drops were retained.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
settings.gradle
Code
37 2,053
src/main/java/com/kodari/crates/CratesPlugin.java
package com.kodari.crates;

import com.cryptomorin.xseries.XSound;
import com.cryptomorin.xseries.particles.XParticle;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Particle;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.logging.Level;

/** Main entry point and orchestration layer for crate menus and reward delivery. */
public final class CratesPlugin extends JavaPlugin {
    private record OpenSession(Crate crate, Crate.Reward reward, Location block, KeyManager.Consumption consumption) { }

    private File configFile;
    private File langFile;
    private YamlConfiguration config;
    private YamlConfiguration lang;
    private DataStore dataStore;
    private CrateManager crateManager;
    private KeyManager keyManager;
    private final Map<UUID, OpenSession> sessions = new HashMap<>();
    private final Map<UUID, Long> cooldowns = new HashMap<>();
    private final Map<UUID, BukkitTask> rollingTasks = new HashMap<>();

    @Override
    public void onEnable() {
        installDefaultsOnce();
        loadSettings();
        dataStore = new DataStore(this);
        crateManager = new CrateManager(this);
        crateManager.load();
        keyManager = new KeyManager(this);
        CratesCommand command = new CratesCommand(this);
        getCommand("dc").setExecutor(command);
        getCommand("dc").setTabCompleter(command);
        Bukkit.getPluginManager().registerEvents(new CrateListener(this), this);
        getLogger().info("Loaded " + crateManager.all().size() + " crate definition(s).");
    }

    @Override
    public void onDisable() {
        for (BukkitTask task : rollingTasks.values()) task.cancel();
        rollingTasks.clear();
        for (Map.Entry<UUID, OpenSession> entry : new ArrayList<>(sessions.entrySet())) {
            OpenSession session = entry.getValue();
            if (session.consumption() != null) {
                Player player = Bukkit.getPlayer(entry.getKey());
                if (player != null) keyManager.refund(player, session.crate().id(), session.consumption());
            }
        }
        sessions.clear();
        if (dataStore != null) dataStore.save();
    }

    private void installDefaultsOnce() {
        File folder = getDataFolder();
        if (folder.exists()) return;
        folder.mkdirs();
        try (InputStream indexStream = getResource("defaults/index.txt")) {
            if (indexStream == null) throw new IOException("defaults/index.txt is missing from the plugin jar");
            List<String> resources = new String(indexStream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8).lines()
                    .map(String::trim).filter(line -> !line.isEmpty()).toList();
            for (String relative : resources) {
                File target = new File(folder, relative);
                File parent = target.getParentFile();
                if (!parent.exists() && !parent.mkdirs()) throw new IOException("Could not create " + parent);
                try (InputStream source = getResource("defaults/" + relative)) {
                    if (source == null) throw new IOException("Missing bundled default defaults/" + relative);
                    Files.copy(source, target.toPath(), StandardCopyOption.REPLACE_EXISTING);
                }
            }
        } catch (IOException exception) {
            getLogger().log(Level.SEVERE, "Could not install the initial Crates configuration files.", exception);
        }
    }

    public void reloadPlugin() {
        for (UUID id : new ArrayList<>(sessions.keySet())) {
            Player player = Bukkit.getPlayer(id);
            if (player != null) cancelOpen(player);
        }
        loadSettings();
        dataStore.load();
        crateManager.load();
        getLogger().info("Reloaded configuration and " + crateManager.all().size() + " crate(s).");
    }

    private void loadSettings() {
        if (!getDataFolder().exists()) getDataFolder().mkdirs();
        configFile = new File(getDataFolder(), "config.yml");
        langFile = new File(getDataFolder(), "lang.yml");
        config = loadAndMerge(configFile, "defaults/config.yml");
        lang = loadAndMerge(langFile, "defaults/lang.yml");
    }

    private YamlConfiguration loadAndMerge(File file, String defaultResource) {
        YamlConfiguration current = YamlConfiguration.loadConfiguration(file);
        try (InputStream stream = getResource(defaultResource)) {
            if (stream == null) return current;
            YamlConfiguration defaults = YamlConfiguration.loadConfiguration(new java.io.InputStreamReader(stream, java.nio.charset.StandardCharsets.UTF_8));
            if (mergeMissing(current, defaults, "")) {
                try {
                    current.save(file);
                } catch (IOException exception) {
                    getLogger().log(Level.WARNING, "Could not save added default settings to " + file.getName(), exception);
                }
            }
        } catch (IOException exception) {
            getLogger().log(Level.WARNING, "Could not read bundled " + defaultResource, exception);
        }
        return current;
    }

    private boolean mergeMissing(ConfigurationSection target, ConfigurationSection defaults, String path) {
        boolean changed = false;
        for (String key : defaults.getKeys(false)) {
            String childPath = path.isEmpty() ? key : path + "." + key;
            if (defaults.isConfigurationSection(key)) {
                if (!target.isConfigurationSection(key)) {
                    target.set(key, null);
                    target.createSection(key);
                    changed = true;
                }
                ConfigurationSection targetChild = target.getConfigurationSection(key);
                if (targetChild != null) changed |= mergeMissing(targetChild, defaults.getConfigurationSection(key), childPath);
            } else if (!target.contains(key)) {
                target.set(key, defaults.get(key));
                changed = true;
            }
        }
        return changed;
    }

    public void openCrate(Player player, Crate crate, Location block) {
        if (!player.hasPermission("crates.open." + crate.id()) && !player.hasPermission("crates.open.*") && !player.hasPermission("crates.admin")) {
            message(player, "no-permission", Map.of());
            return;
        }
        long now = System.currentTimeMillis();
        long last = cooldowns.getOrDefault(player.getUniqueId(), 0L);
        long cooldown = Math.max(0, config.getLong("key-cooldown", 1)) * 1000L;
        if (now - last < cooldown) {
            message(player, "cooldown", Map.of("time", String.valueOf(Math.max(1, (cooldown - (now - last) + 999) / 1000))));
            return;
        }
        if (sessions.containsKey(player.getUniqueId())) {
            message(player, "already-opening", Map.of());
            return;
        }
        if (crate.rewards().isEmpty()) {
            message(player, "no-rewards", Map.of());
            return;
        }
        cooldowns.put(player.getUniqueId(), now);
        String effect = crate.effect().toUpperCase(Locale.ROOT);
        if (!new File(new File(getDataFolder(), "effects"), effect.toLowerCase(Locale.ROOT) + ".yml").isFile()) {
            getLogger().warning("Crate " + crate.id() + " references missing effect file " + effect.toLowerCase(Locale.ROOT) + ".yml; using CHOOSE.");
            effect = "CHOOSE";
        }
        if (effect.equals("NOWAIT")) {
            Crate.Reward reward = chooseReward(crate);
            if (reward == null) {
                message(player, "no-rewards", Map.of());
                return;
            }
            KeyManager.Consumption token = keyManager.consume(player, crate.id());
            if (token == null) {
                message(player, "no-key", Map.of("crate", crate.displayName()));
                return;
            }
            if (!canReceive(player, reward)) {
                keyManager.refund(player, crate.id(), token);
                message(player, "inventory-full", Map.of());
                return;
            }
            sessions.put(player.getUniqueId(), new OpenSession(crate, reward, block, token));
            playNowait(block == null ? player.getLocation() : block);