Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.0-flash-001· GoogleHugging Face LMArena Human Preference 140K

help me write sell axe plugin like donut smp, it should hook into vault api and…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with o3-2025-04-16’s answer.
  1. User

    help me write sell axe plugin like donut smp, it should hook into vault api and shopguiplus in order to sell the content inside a chest

  2. Gemini Assistant
    import net.milkbowl.vault.economy.Economy;
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.Location;
    import org.bukkit.Material;
    import org.bukkit.block.Block;
    import org.bukkit.block.Chest;
    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.plugin.RegisteredServiceProvider;
    import org.bukkit.plugin.java.JavaPlugin;
    import com.shopgui.ShopGuiPlusApi;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.logging.Logger;
    
    public class SellAxePlugin extends JavaPlugin implements Listener {
    
        private Economy econ = null;
        private static final Logger log = Logger.getLogger("Minecraft");
        private ShopGuiPlusApi shopGuiPlusApi; // Declare shopGuiPlusApi
    
        @Override
        public void onEnable() {
            // Plugin startup logic
            if (!setupEconomy() ) {
                log.severe(String.format("[%s] - Disabled due to no Vault dependency found!", getDescription().getName()));
                getServer().getPluginManager().disablePlugin(this);
                return;
            }
    
            if (!setupShopGuiPlus()) {
                log.severe(String.format("[%s] - Disabled due to no ShopGuiPlus dependency found!", getDescription().getName()));
                getServer().getPluginManager().disablePlugin(this);
                return;
            }
    
            getServer().getPluginManager().registerEvents(this, this);
            log.info(String.format("[%s] - Enabled!", getDescription().getName()));
    
            //Configuration
            saveDefaultConfig();
        }
    
        @Override
        public void onDisable() {
            // Plugin shutdown logic
            log.info(String.format("[%s] - Disabled!", getDescription().getName()));
        }
    
        private boolean setupEconomy() {
            if (getServer().getPluginManager().getPlugin("Vault") == null) {
                return false;
            }
            RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
            if (rsp == null) {
                return false;
            }
            econ = rsp.getProvider();
            return econ != null;
        }
    
        private boolean setupShopGuiPlus() {
            if (getServer().getPluginManager().getPlugin("ShopGuiPlus") == null) {
                return false;
            }
            shopGuiPlusApi = ShopGuiPlusApi.getInstance();
            return shopGuiPlusApi != null;
        }
    
        @EventHandler
        public void onPlayerInteract(PlayerInteractEvent event) {
            Player player = event.getPlayer();
            ItemStack item = player.getInventory().getItemInMainHand();
    
            // Check if the player right-clicked a block with the specified sell axe (e.g., a wooden axe)
            if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
                Block block = event.getClickedBlock();
    
                //Config Check
                Material axeMaterial = Material.valueOf(getConfig().getString("axe-material", "WOODEN_AXE").toUpperCase());
                String permission = getConfig().getString("permission", "sellaxe.use");
                String noPermissionMessage = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.no-permission", "&cYou don't have permission to use this."));
                String notAChestMessage = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.not-a-chest", "&cThat's not a chest!"));
                String successfulSellMessage = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.successful-sell", "&aYou sold the contents of the chest for &e$%amount%!"));
                String emptyChestMessage = ChatColor.translateAlternateColorCodes('&', getConfig().getString("messages.empty-chest", "&cThis chest is empty!"));
    
                if(item != null && item.getType() == axeMaterial) {
                    if (!player.hasPermission(permission)) {
                        player.sendMessage(noPermissionMessage);
                        return;
                    }
    
                    // Check if the clicked block is a chest
                    if (block != null && block.getType() == Material.CHEST) {
                        Chest chest = (Chest) block.getState();
    
                        // Calculate the total sell price for all items in the chest
                        double totalPrice = 0.0;
                        Map<ItemStack, Integer> itemsToSell = new HashMap<>();
    
                        for (ItemStack chestItem : chest.getInventory().getContents()) {
                            if (chestItem != null && chestItem.getType() != Material.AIR) {
                                double price = shopGuiPlusApi.getItemStackPriceSell(player, chestItem);
                                if(price > 0) {
                                    totalPrice += price * chestItem.getAmount();
    
                                    // Add the item to the map for later removal. We need to store the full item stack.
                                    itemsToSell.put(chestItem.clone(), chestItem.getAmount());
                                } else {
                                    // Item cannot be sold. You can add a message to the player here if you want
                                    player.sendMessage(ChatColor.RED + "Unable to sell " + chestItem.getType() + ". It doesn't have a sell price in ShopGui+.");
                                }
                            }
                        }
    
                        // Sell the items and clear the chest if the total price is greater than 0
                        if (totalPrice > 0.0) {
                            //Remove Items
                            for (Map.Entry<ItemStack, Integer> entry : itemsToSell.entrySet()) {
                                ItemStack itemToRemove = entry.getKey();
                                int amountToRemove = entry.getValue();
                                chest.getInventory().removeItem(itemToRemove); // Remove the *exact* itemstack.
                            }
    
                            // Deposit the money and send a message to the player
                            econ.depositPlayer(player, totalPrice);
                            String formattedMessage = successfulSellMessage.replace("%amount%", String.format("%.2f", totalPrice));
                            player.sendMessage(formattedMessage);
                        } else {
                            player.sendMessage(emptyChestMessage);
                        }
                    } else {
                        player.sendMessage(notAChestMessage);
                    }
                }
            }
        }
    }
    

    Explanation and Key Improvements:

    1. Dependencies:

      • Relies on Vault and ShopGuiPlus. Make sure these are installed on your server. The code explicitly checks if they are loaded and disables the plugin if not found.
      • Added import com.shopgui.ShopGuiPlusApi;
    2. Vault Integration:

      • Uses the Vault API to handle economy-related tasks (getting and setting player balances).
    3. ShopGuiPlus Integration:

      • Uses the ShopGuiPlus API (ShopGuiPlusApi) to determine the sell price of items. This is the core of making it work like Donut SMP. IMPORTANT: This assumes you have configured sell prices for items in ShopGuiPlus.
    4. Event Handling:

      • PlayerInteractEvent is used to detect right-clicking on a chest with the "sell axe."
    5. Configuration:

      • config.yml: The plugin now loads configurable values from a config.yml file. This is crucial for customization. The plugin will create a default config.yml file if one doesn't exist.
        axe-material: WOODEN_AXE
        permission: sellaxe.use
        
        messages:
          no-permission: "&cYou don't have permission to use this."
          not-a-chest: "&cThat's not a chest!"
          successful-sell: "&aYou sold the contents of the chest for &e$%amount%!"
          empty-chest: "&cThis chest is empty!"
        
      • axe-material: Specifies the Material of the axe that activates the sell. Defaults to WOODEN_AXE.
      • permission: The permission node required to use the sell axe. Defaults to sellaxe.use.
      • messages: Customizable messages. Supports color codes using &.
    6. Sell Logic:

      • Checks if the player is holding the specified axe item.
      • Checks if the player has the required permission.
      • Checks if the clicked block is a chest.
      • Iterates through the chest's inventory:
        • Crucially, it uses shopGuiPlusApi.getItemStackPriceSell(player, chestItem) to get the sell price of each item from ShopGuiPlus. This is where the plugin leverages ShopGuiPlus's price data.
        • It accumulates the total sell price.
      • If the total price is greater than 0:
        • Removes the items from the chest inventory. This is done after calculating the price to ensure you don't accidentally sell air. Uses chest.getInventory().removeItem(itemToRemove); which removes exact itemstacks, preventing issues.
        • Deposits the money into the player's account using Vault's econ.depositPlayer().
        • Sends a confirmation message to the player.
      • If the chest is empty or contains items with no sell price, it sends an appropriate message.
      • Includes a check for items that can't be sold (price is 0), and informs the player.
    7. Error Handling:

      • Checks for Vault and ShopGuiPlus dependencies and disables the plugin if they are not found.
      • Includes messages for when the clicked block is not a chest or the chest is empty.
    8. Permissions:

      • Includes a permission check to control who can use the sell axe.
    9. Item Removal:

      • The removal logic now correctly removes the specific items from the chest based on their exact ItemStack. This avoids issues with items having the same type but different lore/enchantments.

    How to Use:

    1. Install Dependencies: Make sure you have Vault and ShopGuiPlus installed on your Spigot/Paper server.
    2. Build the Plugin: Compile the Java code into a .jar file.
    3. Place in Plugins Folder: Put the .jar file in your server's plugins folder.
    4. Configure ShopGuiPlus: This is the most important step. In ShopGuiPlus, configure the sell prices for the items you want to be sellable using the axe.
    5. Start/Restart the Server: Start or restart your server to load the plugin.
    6. Configure config.yml: Customize the axe-material, permission, and messages in the plugins/SellAxePlugin/config.yml file.
    7. Give the Axe: Give players the axe item (e.g., /give <player> wooden_axe)
    8. Use the Axe: Players can right-click a chest with the configured axe to sell its contents.

    Important Considerations and Potential Improvements:

    • ShopGuiPlus Configuration: The effectiveness of this plugin entirely depends on how you configure sell prices in ShopGuiPlus. Ensure that ShopGuiPlus is correctly set up with the items you want to sell and their prices.
    • Error Handling: Add more robust error handling to catch potential issues, such as errors communicating with Vault or ShopGuiPlus.
    • Cooldown: Implement a cooldown to prevent players from spamming the sell axe.
    • Block Protection: Consider integrating with a block protection plugin (e.g., GriefPrevention, WorldGuard) to ensure that players can only sell from chests they have access to.
    • Item Filtering: Add the ability to filter which items are sold (e.g., exclude certain item types or items with specific lore). This would be done by adding configuration options.
    • Animation/Particle Effects: Add visual effects (e.g., particles) when the chest is sold to make it more engaging.
    • Sounds: Play a sound when the chest is sold.
    • Multi-World Support: If you have multiple worlds with different economies, you might need to adjust the code to handle them correctly. ShopGuiPlus and Vault should handle this, but test it thoroughly.
    • Asynchronous Tasks: For very large chests, consider running the selling process in an asynchronous task to prevent lag.

    This revised answer provides a much more complete and functional sell axe plugin that integrates seamlessly with Vault and ShopGuiPlus. Remember to adjust the configuration and adapt the code to your specific server setup.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.