Milo

Creame un plugin de keyall con todo lo necesario, configurable tanto por gui como por archivo, se pueda añadir mas keys y configurar los comandos para dar la key, que solamente se te de en los mudnos selecionados en la gui o en la config, como spawn, overworld, nether, end no en otros mundos no selecionados tenga un placeholder de cuando es el keyall (por defecto que sea 1 hora pero se pueda cambiar) (que rote entre 1 a 2 horas el keyall aleatoriamente) (configurable), el comando para dar las keys son los siguientes que no haya mensaje al dar las keys porque ya hay uno del plugin de crates, que solo haya un title que diga keyall se ha dado llaves a todo el servidor (la foto de los comandos ya te la pase, exceptuando la llave koth) ademas hace que se peuda forzar keyall con un comando tanto de llaves aleatorias por jugador como de llave en especifica, que se pueda forzar keyalls de mas llaves que tengan un titulo especial

Kodari AI
KodariNov 14 at 6:06 pm 5
KeyAllManager
KeyAllManager is a Minecraft plugin that automates periodic key giveaways to all online players. It features a fully configurable system with both GUI and file-based settings, allowing server admins to add unlimited custom keys and configure the giveaway commands for each key. The plugin restricts key distribution to selected worlds only (spawn, overworld, nether, end) via GUI or config. The keyall interval is configurable with a default of 1 hour, including an optional random rotation between 1-2 hours. When keys are distributed, no chat message is sent (to avoid conflicts with crates plugins); instead, a title announcement displays "KeyAll" indicating keys were given to the entire server. Admins can force keyall events via commands, either with random keys per player or a specific key, including special titles for forced multi-key giveaways.
  • Crearé el reparto automático con intervalo aleatorio configurable y mundos permitidos.

  • Añadiré un menú para editar mundos, llaves, comandos e intervalos, además de comandos para forzar repartos.

  • Incluiré el placeholder del próximo KeyAll y las llaves de la imagen, excepto KOTH.

Plugin creado con reparto automático aleatorio entre 60 y 120 minutos, mundos configurables, llaves de la imagen excepto KOTH y títulos normales o especiales.

  • /keyall abre la configuración; /keyall reload recarga el archivo.

  • /keyall force random 3 reparte tres llaves aleatorias por jugador.

  • /keyall force llave_epica 2 reparte dos llaves específicas.

  • Con PlaceholderAPI: %keyall_next% muestra la cuenta atrás y %keyall_next_seconds% los segundos restantes.

Los repartos forzados no reinician el temporizador automático. Los nombres de mundos deben coincidir exactamente con los del servidor.

Milo

que se puedan editar las probabilidades de cada llave tanto en la gui como en el config del plugin, y el skeyall next pueda ser cualquiera de las llaves no solo una en especifico si no que pueda ser cualquiera dependiendo de su probabilidad

Kodari AI
KodariNov 14 at 6:07 pm 3

Añadiré pesos configurables para que cada sorteo elija entre todas las llaves según su probabilidad, tanto en los KeyAll automáticos como en los aleatorios forzados.

Añadí probabilidades configurables mediante pesos en el archivo y en la GUI: abre Llaves y usa Mayús + clic izquierdo para editar el peso. La GUI muestra también la probabilidad resultante.

El próximo KeyAll puede dar cualquiera de las llaves, sorteada para cada jugador según su peso. Un peso de 0 la excluye del sorteo aleatorio, pero sigue disponible para repartos forzados específicos.

%keyall_next% sigue mostrando el tiempo restante; la llave se sortea cuando ocurre el reparto.

Milo

Añadi que las llaves que no te dan por no estar dentro de los mundos permitidos, el servidor espere a que estes en un mundo permitido y te las de con el comando respectivo, tambien cuente si quiteas en un mundo que no se puede obtener la llave y te reconectas

Kodari AI
KodariNov 14 at 6:08 pm 3

Guardaré las llaves pendientes por jugador y las entregaré al entrar en un mundo permitido, también después de reconectarse o reiniciar el servidor.

Las llaves de los jugadores conectados en mundos no permitidos quedan guardadas y se entregan al entrar en un mundo permitido. Se conservan si el jugador se desconecta o el servidor se reinicia.

Las llaves pendientes mantienen el comando configurado en el momento del sorteo. No se acumulan nuevos KeyAll mientras el jugador está desconectado.

Milo

no se dan las llaves por alguna razon, tampoco aparecen los titles, ademas quiero que los comandos esten en español y haya un keyall help para saber bien los comandos y lista de effectos

Kodari AI
KodariNov 14 at 6:15 pm 2
  1. Corregiré la entrega de llaves y los títulos.

  2. Adaptaré los comandos al español y añadiré /keyall help con la lista de efectos.

  • Los títulos ahora se muestran a todos los jugadores conectados, aunque sus llaves queden pendientes por estar en otro mundo.

  • Los comandos de entrega que fallen al despacharse se conservan como pendientes y registran el error en la consola.

  • Añadí /keyall help, /keyall recargar y /keyall forzar. Los comandos anteriores en inglés siguen funcionando.

Comprueba en /keyall gui que estén seleccionados los nombres reales de tus mundos; si no coinciden, las llaves quedarán pendientes. Si siguen sin entregarse en un mundo permitido, revisa la consola y confirma que el comando configurado funcione allí.

Milo

Añadi que el boton de añadir mundo te muestre el nombre exacto del mundo en el que estas o mejor directamente añada el mundo en el que estas a la lista

Kodari AI
KodariNov 14 at 6:24 pm 1

El botón añadirá directamente el mundo actual y mostrará su nombre exacto.

El botón Añadir mundo actual muestra el nombre exacto de tu mundo y lo añade a la lista de permitidos con un clic. También intenta entregar las llaves pendientes.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
settings.gradle
Code
6 548
src/main/java/com/kodari/keyall/KeyAllPlugin.java
package com.kodari.keyall;

import com.cryptomorin.xseries.XMaterial;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
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.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;

public final class KeyAllPlugin extends JavaPlugin implements Listener {
    private final Map<UUID, String> pending = new ConcurrentHashMap<>();
    private BukkitTask timer;
    private long nextTime;
    private KeyAllPlaceholder expansion;
    private File rewardsFile;
    private YamlConfiguration rewards;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        rewardsFile = new File(getDataFolder(), "pending-rewards.yml");
        rewards = YamlConfiguration.loadConfiguration(rewardsFile);
        getServer().getPluginManager().registerEvents(this, this);
        if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) {
            expansion = new KeyAllPlaceholder(this);
            expansion.register();
        }
        schedule();
        for (Player player : Bukkit.getOnlinePlayers()) deliverPending(player);
    }

    @Override
    public void onDisable() {
        if (timer != null) timer.cancel();
        if (expansion != null) expansion.unregister();
    }

    private String color(String text) {
        return ChatColor.translateAlternateColorCodes('&', text);
    }

    private List<String> keys() {
        ConfigurationSection section = getConfig().getConfigurationSection("keys");
        return section == null ? new ArrayList<>() : new ArrayList<>(section.getKeys(false));
    }

    private double weight(String key) {
        double value = getConfig().getDouble("keys." + key + ".weight", 1.0);
        return Double.isFinite(value) ? Math.max(0, Math.min(1000000, value)) : 0;
    }

    private double totalWeight(List<String> available) {
        double total = 0;
        for (String key : available) total += weight(key);
        return total;
    }

    private String randomKey(List<String> available, double total) {
        double roll = ThreadLocalRandom.current().nextDouble(total);
        String last = null;
        for (String key : available) {
            double current = weight(key);
            if (current <= 0) continue;
            last = key;
            roll -= current;
            if (roll < 0) return key;
        }
        return last;
    }

    private void schedule() {
        if (timer != null) timer.cancel();
        long min = Math.max(1, Math.min(525600, getConfig().getLong("interval.min-minutes", 60)));
        long max = Math.max(min, Math.min(525600, getConfig().getLong("interval.max-minutes", 120)));
        long minutes = ThreadLocalRandom.current().nextLong(min, max + 1);
        nextTime = System.currentTimeMillis() + minutes * 60_000L;
        timer = Bukkit.getScheduler().runTaskLater(this, () -> {
            distribute(null, 1, false);
            schedule();
        }, minutes * 1200L);
    }

    public long secondsRemaining() {
        return Math.max(0, (nextTime - System.currentTimeMillis() + 999) / 1000);
    }

    public String timeRemaining() {
        long seconds = secondsRemaining();
        return String.format(Locale.ROOT, "%02d:%02d:%02d", seconds / 3600, (seconds / 60) % 60, seconds % 60);
    }

    private void saveRewards() {
        try {
            rewards.save(rewardsFile);
        } catch (IOException ex) {
            getLogger().severe("No se pudieron guardar las llaves pendientes: " + ex.getMessage());
        }
    }

    private void deliverPending(Player player) {
        if (!player.isOnline() || !getConfig().getStringList("worlds").contains(player.getWorld().getName())) return;
        String path = player.getUniqueId().toString();
        List<String> commands = rewards.getStringList(path);
        if (commands.isEmpty()) return;
        List<String> failed = new ArrayList<>();
        for (String command : commands) {
            String resolved = command.replace("%player%", player.getName());
            try {
                if (!Bukkit.dispatchCommand(Bukkit.getConsoleSender(), resolved)) {
                    failed.add(command);
                    getLogger().warning("No se pudo ejecutar el comando de llave: " + resolved);
                }
            } catch (Exception ex) {
                failed.add(command);
                getLogger().warning("Error al ejecutar el comando de llave '" + resolved + "': " + ex.getMessage());
            }
        }
        rewards.set(path, failed.isEmpty() ? null : failed);
        saveRewards();
    }

    @EventHandler
    public void onJoin(PlayerJoinEvent event) {
        Bukkit.getScheduler().runTask(this, () -> deliverPending(event.getPlayer()));
    }

    @EventHandler
    public void onWorldChange(PlayerChangedWorldEvent event) {
        Bukkit.getScheduler().runTask(this, () -> deliverPending(event.getPlayer()));
    }

    private void distribute(String chosen, int amount, boolean special) {
        List<String> available = keys();
        if (available.isEmpty()) {
            getLogger().warning("No hay llaves configuradas para el KeyAll.");
            return;
        }
        double total = totalWeight(available);
        if (chosen == null && total <= 0) {
            getLogger().warning("No hay llaves con peso positivo para el KeyAll aleatorio.");
            return;
        }
        List<String> worlds = getConfig().getStringList("worlds");
        String titlePath = special ? "titles.special" : "titles.normal";
        String title = color(getConfig().getString(titlePath + ".title", "&6KEYALL").replace("%amount%", String.valueOf(amount)));
        String subtitle = color(getConfig().getString(titlePath + ".subtitle", "&eSe han dado llaves a todo el servidor").replace("%amount%", String.valueOf(amount)));
        for (Player player : Bukkit.getOnlinePlayers()) {
            boolean allowed = worlds.contains(player.getWorld().getName());
            String path = player.getUniqueId().toString();
            List<String> queued = rewards.getStringList(path);
            for (int i = 0; i < amount; i++) {
                String key = chosen == null ? randomKey(available, total) : chosen;
                String command = getConfig().getString("keys." + key + ".command", "").trim();
                if (command.isEmpty()) {
                    getLogger().warning("La llave " + key + " no tiene un comando configurado.");
                    continue;
                }
                if (command.startsWith("/")) command = command.substring(1);
                command = command.replace("%key%", key);
                queued.add(command);
            }
            if (!queued.isEmpty()) {
                rewards.set(path, queued);
                saveRewards();
                if (allowed) deliverPending(player);
            }
            player.sendTitle(title, subtitle, 10, 70, 20);
        }
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {