LogoyStore

API

Documentação completa da API do plugin yPunish, incluindo manipulação de eventos para aprovações de punições e integrações de sistema.

Obtendo Listeners de Eventos

Para ouvir eventos do yPunish, registre uma classe Listener no seu plugin:

import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import br.com.ystoreplugins.product.ypunish.event.PunishApprovedEvent;

public class MyPlugin extends JavaPlugin {
    
    @Override
    public void onEnable() {
        Bukkit.getPluginManager().registerEvents(new PunishListener(), this);
    }
}

Eventos

PunishApprovedEvent

Disparado quando uma punição é aprovada e aplicada a um jogador.

Métodos Disponíveis:

  • getTarget() - Retorna o nome de usuário do jogador alvo (String)
  • getPunish() - Retorna o PunishHolder contendo detalhes da punição
  • getPunishType() - Retorna o PunishType indicando o tipo de punição
  • getHandlers() - Retorna a HandlerList para gerenciamento de evento
  • getHandlerList() - Retorna a HandlerList estática

Observações:

  • Dispara quando uma punição é aprovada e se torna ativa
  • Tipos de punição podem incluir: BAN, MUTE, KICK, WARN e outros
  • PunishHolder contém informações detalhadas da punição (duração, motivo, etc.)
  • Este evento NÃO é cancelável (punição já foi aprovada)
  • Útil para logging, notificações e integração de sistema

Exemplo:

@EventHandler
public void onPunishApproved(PunishApprovedEvent event) {
    String target = event.getTarget();
    PunishHolder punish = event.getPunish();
    PunishType type = event.getPunishType();
    
    System.out.println(target + " recebeu punição: " + type);
}

Estruturas de Dados

PunishHolder

Contém informações detalhadas da punição. Mantém:

  • Duração da punição/expiração
  • Motivo da punição
  • Moderador que aplicou a punição
  • Timestamp de quando a punição foi criada
  • Qualquer nota adicional ou evidência

PunishType

Enumeração de tipos de punição. Inclui:

  • BAN - Ban permanente ou temporário
  • KICK - Remoção instantânea do servidor
  • MUTE - Restrição de chat
  • WARN - Sistema de avisos
  • E outros tipos de punição configurados

Boas Práticas

  1. Registre todas as punições no rastreamento de auditoria para transparência de moderação
  2. Notifique membros da equipe quando punições são aplicadas
  3. Sincronize com sistemas externos como Discord ou bases de dados
  4. Evite operações pesadas em manipuladores de evento (use tarefas assincronamente se necessário)
  5. Manipule diferentes tipos de punição apropriadamente
  6. Verifique detalhes da punição antes de agir em eventos
  7. Use metadados de punição para contexto em notificações

Exemplos de Uso

Exemplo 1: Logging Básico de Punição

import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import br.com.ystoreplugins.product.ypunish.event.PunishApprovedEvent;

public class PunishmentLogger implements Listener {
    
    @EventHandler
    public void onPunishApproved(PunishApprovedEvent event) {
        String target = event.getTarget();
        PunishType type = event.getPunishType();
        
        System.out.println("[PUNIÇÃO] " + target + " foi " + type);
    }
}

Exemplo 2: Notificação de Punição para Moderadores

@EventHandler
public void onPunishApproved(PunishApprovedEvent event) {
    String target = event.getTarget();
    PunishType type = event.getPunishType();
    
    // Notificar moderadores online
    for (org.bukkit.entity.Player player : org.bukkit.Bukkit.getOnlinePlayers()) {
        if (player.hasPermission("ypunish.mod")) {
            player.sendMessage("§c[PUNIÇÃO] " + target + " foi " + type);
        }
    }
}

Exemplo 3: Resposta Baseada em Tipo

@EventHandler
public void onPunishApproved(PunishApprovedEvent event) {
    String target = event.getTarget();
    PunishType type = event.getPunishType();
    
    switch (type.toString()) {
        case "BAN":
            handleBanPunishment(target, event.getPunish());
            break;
        case "MUTE":
            handleMutePunishment(target, event.getPunish());
            break;
        case "WARN":
            handleWarnPunishment(target, event.getPunish());
            break;
    }
}

private void handleBanPunishment(String target, PunishHolder punish) {
    System.out.println("Jogador banido: " + target);
}

private void handleMutePunishment(String target, PunishHolder punish) {
    System.out.println("Jogador silenciado: " + target);
}

private void handleWarnPunishment(String target, PunishHolder punish) {
    System.out.println("Jogador advertido: " + target);
}

Exemplo 4: Integração com Discord

public class PunishmentDiscordNotifier implements Listener {
    
    private final JavaPlugin plugin;
    private final String webhookUrl;
    
    public PunishmentDiscordNotifier(JavaPlugin plugin, String webhookUrl) {
        this.plugin = plugin;
        this.webhookUrl = webhookUrl;
    }
    
    @EventHandler
    public void onPunishApproved(PunishApprovedEvent event) {
        String target = event.getTarget();
        PunishType type = event.getPunishType();
        
        // Enviar notificação Discord assincronamente
        Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
            sendDiscordNotification(target, type);
        });
    }
    
    private void sendDiscordNotification(String target, PunishType type) {
        String message = "**" + target + "** recebeu uma punição de **" + type + "**";
        // Implementação para enviar ao webhook Discord
        System.out.println("[DISCORD] " + message);
    }
}

Exemplo 5: Contador de Punições

public class PunishmentStatistics implements Listener {
    
    private final Map<String, Integer> playerPunishCount = new HashMap<>();
    
    @EventHandler
    public void onPunishApproved(PunishApprovedEvent event) {
        String target = event.getTarget();
        int count = playerPunishCount.getOrDefault(target, 0) + 1;
        playerPunishCount.put(target, count);
        
        System.out.println("[ESTATÍSTICAS] " + target + " - Total de punições: " + count);
    }
    
    public int getPunishmentCount(String player) {
        return playerPunishCount.getOrDefault(player, 0);
    }
}

Exemplo 6: Estatísticas de Tipo de Punição

public class PunishmentTypeStatistics implements Listener {
    
    private final Map<String, Integer> typeCount = new HashMap<>();
    
    @EventHandler
    public void onPunishApproved(PunishApprovedEvent event) {
        PunishType type = event.getPunishType();
        String typeStr = type.toString();
        
        int count = typeCount.getOrDefault(typeStr, 0) + 1;
        typeCount.put(typeStr, count);
        
        System.out.println("[ESTATÍSTICAS-TIPO] " + typeStr + ": " + count);
    }
    
    public void printStatistics() {
        System.out.println("=== Estatísticas de Tipo de Punição ===");
        typeCount.forEach((type, count) -> {
            System.out.println("  " + type + ": " + count);
        });
    }
}

Exemplo 7: Logging de Trilha de Auditoria em Banco de Dados

public class PunishmentAuditLog implements Listener {
    
    private final JavaPlugin plugin;
    
    public PunishmentAuditLog(JavaPlugin plugin) {
        this.plugin = plugin;
    }
    
    @EventHandler
    public void onPunishApproved(PunishApprovedEvent event) {
        String target = event.getTarget();
        PunishType type = event.getPunishType();
        PunishHolder punish = event.getPunish();
        
        // Registrar em banco de dados assincronamente
        Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
            String logEntry = String.format(
                "[%s] Alvo: %s | Tipo: %s | Detalhes: %s",
                System.currentTimeMillis(),
                target,
                type,
                punish
            );
            
            plugin.getLogger().info(logEntry);
            // Escrever em banco de dados
        });
    }
}

Exemplo 8: Sistema de Escalação

public class PunishmentEscalation implements Listener {
    
    private final Map<String, Integer> escalationCount = new HashMap<>();
    
    @EventHandler
    public void onPunishApproved(PunishApprovedEvent event) {
        String target = event.getTarget();
        int current = escalationCount.getOrDefault(target, 0) + 1;
        escalationCount.put(target, current);
        
        if (current >= 3) {
            handleEscalation(target, current);
        }
    }
    
    private void handleEscalation(String target, int count) {
        System.out.println("[ESCALAÇÃO] " + target + " atingiu " + count + 
            " punições - possível ban recomendado");
    }
}

Exemplo 9: Rastreamento de Ações de Moderador

public class ModeratorActionTracker implements Listener {
    
    private final JavaPlugin plugin;
    private final Map<String, List<String>> moderatorActions = new HashMap<>();
    
    public ModeratorActionTracker(JavaPlugin plugin) {
        this.plugin = plugin;
    }
    
    @EventHandler
    public void onPunishApproved(PunishApprovedEvent event) {
        String target = event.getTarget();
        PunishType type = event.getPunishType();
        
        // Em um cenário real, você extrairia o moderador de PunishHolder
        String action = String.format("%s [%s]", target, type);
        
        // Rastrear ações para relatório
        System.out.println("[AÇÃO] " + action);
    }
}

Exemplo 10: Manipulador Abrangente de Punição

public class ComprehensivePunishmentHandler implements Listener {
    
    private final JavaPlugin plugin;
    private final PunishmentStatistics stats;
    private final PunishmentAuditLog auditLog;
    
    public ComprehensivePunishmentHandler(JavaPlugin plugin) {
        this.plugin = plugin;
        this.stats = new PunishmentStatistics();
        this.auditLog = new PunishmentAuditLog(plugin);
    }
    
    @EventHandler
    public void onPunishApproved(PunishApprovedEvent event) {
        String target = event.getTarget();
        PunishType type = event.getPunishType();
        PunishHolder punish = event.getPunish();
        
        // Registrar a ação
        auditLog.onPunishApproved(event);
        
        // Atualizar estatísticas
        stats.onPunishApproved(event);
        
        // Notificar moderadores
        notifyModerators(target, type);
        
        // Enviar notificação Discord (assincronamente)
        Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
            sendDiscordNotification(target, type, punish);
        });
        
        // Verificar escalação
        checkEscalation(target);
    }
    
    private void notifyModerators(String target, PunishType type) {
        for (org.bukkit.entity.Player player : Bukkit.getOnlinePlayers()) {
            if (player.hasPermission("ypunish.mod")) {
                player.sendMessage("§c[PUNIÇÃO] " + target + " - " + type);
            }
        }
    }
    
    private void sendDiscordNotification(String target, PunishType type, 
                                         PunishHolder punish) {
        System.out.println("[DISCORD] Jogador " + target + " foi " + type);
    }
    
    private void checkEscalation(String target) {
        int punishCount = stats.getPunishmentCount(target);
        if (punishCount >= 5) {
            plugin.getLogger().warning("[ESCALAÇÃO] " + target + 
                " atingiu " + punishCount + " punições");
        }
    }
}

Nesta página