📄
pasted-code-1776495948291.txt
txt
74 lines
▶
Create a Minecraft plugin with the following specifications:
Plugin Name: CommandItem
Minecraft Version: 1.21.11 (Paper/Spigot)
Java Version: Java 21
Core Functionality
The plugin allows players to convert the item in their hand into an executable item that runs a command when clicked.
Command
/ci [message]
Argument Details
The command to execute when the item is used
Must be wrapped in angle brackets
Example:
Should run as console by default
rightclick → Executes on right-click
leftclick → Executes on left-click
disappear → Item is removed after use
keep → Item stays after use
[message] (optional)
Message sent only to the player when used
Example: You claimed your reward!
Example Usage
/ci rightclick disappear You claimed your reward!
Behavior Requirements
The command converts the item in the player's main hand into a Command Item
Store data using PersistentDataContainer (NBT):
command
click type
consume type
message
Replace %player% with the player's name when executing
Interaction Logic
Detect:
PlayerInteractEvent
If item has stored data:
Check click type matches
Execute command from console
Send optional message (only to player)
Handle item:
disappear → remove 1 item
keep → do nothing
Additional Requirements
Prevent usage if player is in cooldown (optional but recommended)
Cancel event to prevent default behavior
Add colored feedback when creating item:
"Command item created successfully!"
Permissions
commanditem.use
commanditem.create
Code Requirements
Use modern Paper API (1.21.11)
Use Java 21 features where appropriate
Clean structure:
Main class
Command handler
Listener class
Utility class for item data
No deprecated methods
Optional Enhancements (if included)
Cooldown per item
Support MiniMessage formatting
Support multiple commands separated by ;
Output
Provide:
Full source code
plugin.yml
Clear package structure
Goal:
A lightweight, efficient plugin that allows creating clickable command-executing items with flexible behavior. :::
Main class + command handler + listener + PDC utility + cooldown manager + ColorUtil
Command parsing extracts
<command>from angle brackets then parses remaining argsMiniMessage for all formatting since user explicitly requested it and project is Paper 1.21
Here’s what was built:
CommandItemPlugin— main class, wires togetherCooldownManager, the/cicommand, and the interact listenerCreateCommand— parses/ci <cmd> clicktype consumetype [message], extracts the command from angle brackets, validates args, writes PDC data to the held itemItemListener— handlesPlayerInteractEvent, checks click type match, runs commands via console (supports multiple commands split by;), sends the optional message, handles item removal, and enforces a 3-second cooldownItemDataUtil— all PDC read/write logic using arecord CommandItemData(...)for clean data passingCooldownManager— per-player per-item cooldown using aMap<String, Long>ColorUtil— MiniMessage deserialization + plain-text stripping for logger output
Add /ci reload and /ci help and also /ci remove - removes the command action from the held item
CreateCommandhandles all routing — checkargs[0]forhelp,reload,removebefore falling through to create logicItemDataUtilneeds aremoveDatamethod to strip all PDC keys from an itemplugin.ymlneeds thecommanditem.reloadpermission added
Three subcommands added:
/ci help— formatted help menu showing all usage, placeholders, and multi-command syntax; also shown when/ciis run with too few args/ci reload— reloads config, requirescommanditem.reload(op by default)/ci remove— strips all PDC keys from the held item via the newItemDataUtil.removeData(), requirescommanditem.create; errors if the item isn’t a command itemTab completion on
args[0]suggestshelp,reload,remove
Add item.yml where shows all item which got commands and more things. We can edit things from there too.
Let me read all existing files before planning anything.
Now I have a complete picture. Here’s my plan:
New
ItemEntry(Lombok @Data) — data class holding all item config fieldsNew
ItemsManager— loads/savesitems.yml, holds aMap<String, ItemEntry>keyed by UUID item_idPatch
ItemDataUtil— storeci_idin PDC onapplyData; addgetItemId()helperPatch
CommandItemPlugin— addItemsManagerfield +@GetterPatch
CreateCommand— generate UUID on create → register inItemsManager; add/ci list;/ci removealso unregisters;/ci reloadalso reloads items.ymlPatch
ItemListener— look up live data fromItemsManagerby item_id (so edits initems.ymltake effect after reload), fallback to PDC if not found
Here’s what was added and how items.yml works end-to-end:
items.yml — structure
Every time you run /ci <command> ... on a held item, a UUID entry is written:
items:
a3f1bc7d-...:
item-type: DIAMOND_SWORD
item-name: Sword of Giving
command: give %player% diamond 1
click-type: rightclick
consume-type: keep
message: You claimed your reward!
cooldown: 3
created-by: Steve
created-at: 2024-06-01 14:32:00
You can freely edit any field (command, click-type, consume-type, message, cooldown, etc.) and run /ci reload — the listener will immediately read the updated values on next use, without touching the physical item.
New subcommand: /ci list
Shows all registered items with index, item type/name, short ID, full config, and a reminder to edit items.yml and reload.
Updated /ci reload
Now reloads both config.yml and items.yml in one call.
Updated /ci remove
Strips PDC data and removes the entry from items.yml + saves the file.
The command is only runnable by op?
The default: op in plugin.yml is what restricts everything to ops. The fix is straightforward — change defaults so normal players can create/use, while reload stays op-only.
Also remove the redundant permission check at the top of onCommand since plugin.yml already gates the /ci command itself with commanditem.create:
What changed:
commanditem.create—op→true(all players can create/remove command items)commanditem.list—op→true(all players can use/ci list)commanditem.reload— staysoponlyRemoved the now-redundant manual
hasPermission("commanditem.create")check in the create flow (Bukkit already blocks the command if the player lacks it, perplugin.yml)
Add hex and minecraft colour code login like. &a &b &l &#FFFFFF
The generation was stopped before any content could be produced.
Add hex and minecraft colour code logic like. &a &b &l &#FFFFFF
Simple fix — translate &a, &l, &#FFFFFF etc. into MiniMessage tags before passing to MiniMessage.deserialize().
[Generation stopped]
Add hex and minecraft colour code logic like. &a &b &l &#FFFFFF. Also add a sound effect on rightclick or left click. A more likely claim sound of minecraft.
ColorUtilneeds a pre-processor that converts&a/&#FFFFFFetc. into MiniMessage tags beforeMINI.deserialize()ItemListenerplays a XSound claim sound on successful useSound config key added to
ItemEntry+ItemsManagerso it can be set per-item initems.yml
Now find where ItemEntry is constructed in CreateCommand and add the default sound field:
Now I have everything. Here’s the plan:
ColorUtil— add a pre-processor that converts&a→<green>,&#RRGGBB→<#RRGGBB>,&l→<bold>, etc. before MiniMessage deserializesItemEntry+ItemsManager— add asoundfield so each item can have its own claim sound initems.ymlCreateCommand— pass default sound intoItemEntryItemListener— play the item’s sound via XSound on successful use
What changed:
ColorUtil.translate()— runs two passes before MiniMessage:&#RRGGBB→<#RRGGBB>via regex, then all&0–&f/&l/&o/&n/&m/&k/&r(upper and lower case) → their MiniMessage equivalents. Now any string passed toColorUtil.colorize()supports both formats alongside native MiniMessage tagsItemEntry+ItemsManager— newsoundfield (defaults toUI_TOAST_CHALLENGE_COMPLETE) stored and read fromitems.ymlundersound:— change it per-item and/ci reloadItemListener— plays the resolved XSound on the player after a successful command execution
Don't give everyone the colour code books only op. But once only. Never do again
Plan:
Create
BookGiftManager— tracks which op UUIDs already got the book, persisted indata/given-book.ymlCreate
PlayerJoinListener— on join, if player is op + hasn’t received book → give written book with full color code reference → mark as givenRegister both in
CommandItemPlugin
What was added:
BookGiftManager— persists op UUIDs who have already received the book inplugins/CommandItem/data/given-book.yml. Once written, that UUID is never gifted again, even across restartsPlayerJoinListener— fires on join, checksisOp()+hasReceived()— both must pass. Opens a 3-page AdventureBookdirectly (no item given, no inventory clutter) with full color code referencePage 1 —
&0–&9color codesPage 2 —
&a–&fcolors +&l &o &n &m &k &rformatting codesPage 3 — hex
&#RRGGBBexplanation with 6 live hex examples, each rendered in its own color
Make it /ci <command> rightclick/leftclick disappear/keep sound-true/false message
Add
soundEnabledboolean toItemEntry+ItemsManager(save/loadsound-enabled)Parse
sound-true/sound-falseas the 4th positional arg inCreateCommandItemListeneronly plays sound whensoundEnabledis trueUpdate tab completion and help text
Also need to fix the duplicate sound block in ItemListener — the first patch already removed the old block, but let me verify the file only has one sound section now. The two patches together replace both the old single block that had the duplicate logic. Done.
What changed:
Command syntax is now
/ci <command> rightclick|leftclick disappear|keep sound-true|sound-false [message]sound-trueplaysUI_TOAST_CHALLENGE_COMPLETEon use;sound-falsesilences it entirelyItemEntry+ItemsManagerpersistsound-enabled: true/falseinitems.ymlso it survives reloadsHelp text, usage, and confirmation message all reflect the new argument
package com.commanditem;
import com.commanditem.command.CreateCommand;
import com.commanditem.listener.ItemListener;
import com.commanditem.listener.PlayerJoinListener;
import com.commanditem.util.BookGiftManager;
import com.commanditem.util.CooldownManager;
import com.commanditem.util.ColorUtil;
import com.commanditem.util.ItemsManager;
import lombok.Getter;
import org.bukkit.plugin.java.JavaPlugin;
public class CommandItemPlugin extends JavaPlugin {
@Getter
private CooldownManager cooldownManager;
@Getter
private ItemsManager itemsManager;
@Getter
private BookGiftManager bookGiftManager;
@Override
public void onEnable() {
this.cooldownManager = new CooldownManager();
this.itemsManager = new ItemsManager(this);
this.bookGiftManager = new BookGiftManager(this);
CreateCommand createCommand = new CreateCommand(this);
var cmd = getCommand("ci");
cmd.setExecutor(createCommand);
cmd.setTabCompleter(createCommand);
getServer().getPluginManager().registerEvents(new ItemListener(this), this);
getServer().getPluginManager().registerEvents(new PlayerJoinListener(this), this);
getLogger().info(ColorUtil.strip("<green>CommandItem enabled successfully."));
}
@Override
public void onDisable() {
getLogger().info(ColorUtil.strip("<red>CommandItem disabled."));
}
}