Exemplos do ShPunish
Exemplos completos escritos contra a API do ShPunish: consulta de histórico, punição a partir de outro sistema, reação a eventos e bloqueio por regra.
Os exemplos usam java.util.logging.Logger e um Executor que roda tarefas na thread do servidor (no Paper, r -> Bukkit.getScheduler().runTask(plugin, r); no Folia, r -> Bukkit.getGlobalRegionScheduler().execute(plugin, r)).
Exemplo1. Ficha do jogador#
Monta a ficha de um jogador (punições ativas, total de banimentos e avisos valendo) sem bloquear a thread do servidor. A saída é um Consumer<String>, então a mesma classe serve para um comando, um menu ou o console.
package com.exemplo.ficha;
import dev.singlehope.shpunish.api.ShPunish;
import dev.singlehope.shpunish.api.ShPunishAPI;
import dev.singlehope.shpunish.api.player.PlayerHistory;
import dev.singlehope.shpunish.api.punishment.Punishment;
import dev.singlehope.shpunish.api.punishment.PunishmentCategory;
import java.time.Instant;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
public final class Ficha {
private final Executor threadDoServidor;
public Ficha(Executor threadDoServidor) {
this.threadDoServidor = threadDoServidor;
}
/** Busca a ficha e entrega as linhas na thread do servidor. */
public void mostrar(String nome, Consumer<String> saida) {
ShPunishAPI api = ShPunish.find().orElse(null);
if (api == null) {
saida.accept("§cShPunish indisponível.");
return;
}
api.players().findByName(nome)
.thenCompose(encontrado -> encontrado
.map(api.players()::history)
.orElseThrow(() -> new IllegalArgumentException(nome + " nunca entrou no servidor.")))
.whenComplete((historico, erro) -> threadDoServidor.execute(() -> {
if (erro != null) {
Throwable causa = erro.getCause() != null ? erro.getCause() : erro;
saida.accept("§c" + causa.getMessage());
} else {
escrever(historico, saida);
}
}));
}
private static void escrever(PlayerHistory h, Consumer<String> saida) {
Instant agora = Instant.now();
saida.accept("§e" + h.player().name() + (h.isClean() ? " §anunca foi punido." : ""));
for (Punishment p : h.punishments().active(agora)) {
String fim = p.expiresAt().map(Instant::toString).orElse("permanente");
saida.accept(" §7" + p.id() + " §f" + p.type() + " §7- " + p.reason() + " §8(" + fim + ")");
}
saida.accept(" §7Banimentos no total: §f" + h.punishments().count(PunishmentCategory.BAN)
+ " §7| avisos valendo: §f" + h.warnings().active(agora).size());
}
}Exemplo2. Punição a partir de um sistema externo#
Um anticheat (ou painel web) detecta uma infração e pede uma punição temporária com prova, respeitando as regras do motivo configurado.
package com.exemplo.anticheat;
import dev.singlehope.shpunish.api.ShPunishAPI;
import dev.singlehope.shpunish.api.evidence.Evidence;
import dev.singlehope.shpunish.api.exception.ValidationException;
import dev.singlehope.shpunish.api.player.PlayerIdentity;
import dev.singlehope.shpunish.api.punishment.PunishmentActor;
import dev.singlehope.shpunish.api.punishment.PunishmentRequest;
import dev.singlehope.shpunish.api.punishment.PunishmentResult;
import dev.singlehope.shpunish.api.reason.Reason;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class PunidorAutomatico {
private static final PunishmentActor AUTOR = PunishmentActor.api("MeuAntiCheat");
private final ShPunishAPI api;
private final Logger log;
private final String idMotivo; // vindo da configuração do SEU plugin
public PunidorAutomatico(ShPunishAPI api, Logger log, String idMotivo) {
this.api = api;
this.log = log;
this.idMotivo = idMotivo;
}
public CompletionStage<PunishmentResult> punir(UUID uuid, String nome, String linkReplay) {
Reason motivo = api.reasons().find(idMotivo).orElse(null);
if (motivo == null) {
log.warning("Motivo '" + idMotivo + "' não existe em punishments.yml");
return CompletableFuture.completedFuture(null);
}
try {
// Evidence.of e build() validam e podem lançar ValidationException.
PunishmentRequest.Builder pedido = PunishmentRequest.builder()
.player(PlayerIdentity.of(uuid, nome))
.type(motivo.type())
.reason(motivo)
.actor(AUTOR)
.requireApproval(motivo.approvalRequired())
.evidence(Evidence.of(linkReplay));
motivo.duration().ifPresent(pedido::duration);
return api.punishments().punish(pedido.build()).whenComplete((r, erro) -> {
if (erro != null) {
log.log(Level.SEVERE, "Falha ao punir " + nome, erro);
} else if (r.outcome() == PunishmentResult.Outcome.ALREADY_PUNISHED) {
// Já punido: anexa a nova prova à punição existente.
r.punishment().ifPresent(p ->
api.punishments().addEvidence(p.id(), Evidence.of(linkReplay), AUTOR));
} else {
log.info(nome + ": " + r.outcome());
}
});
} catch (ValidationException e) {
log.warning("Pedido inválido (" + e.field() + "): " + e.getMessage());
return CompletableFuture.completedFuture(null);
}
}
}Exemplo3. Log central de punições#
Grava cada punição aplicada, revogada ou vencida num sistema externo uma única vez na rede, ignorando eventos remotos.
package com.exemplo.log;
import dev.singlehope.shplugins.api.EventPriority;
import dev.singlehope.shplugins.api.Subscribe;
import dev.singlehope.shpunish.api.event.punishment.PunishmentApplyEvent;
import dev.singlehope.shpunish.api.event.punishment.PunishmentEvent;
import dev.singlehope.shpunish.api.event.punishment.PunishmentExpireEvent;
import dev.singlehope.shpunish.api.event.punishment.PunishmentRevokeEvent;
import java.util.logging.Logger;
public final class LogCentralListener {
private final Logger log;
public LogCentralListener(Logger log) {
this.log = log;
}
@Subscribe(priority = EventPriority.MONITOR)
public void onApply(PunishmentApplyEvent e) { registrar("APLICADA", e); }
@Subscribe(priority = EventPriority.MONITOR)
public void onRevoke(PunishmentRevokeEvent e) { registrar("REVOGADA", e); }
@Subscribe(priority = EventPriority.MONITOR)
public void onExpire(PunishmentExpireEvent e) { registrar("VENCIDA", e); }
private void registrar(String acao, PunishmentEvent e) {
if (e.isRemote()) {
return; // o servidor de origem já registrou
}
String linha = String.join(";",
acao,
e.punishment().id().toString(),
e.player().uniqueId().toString(),
e.player().name(),
e.punishment().type().name(),
e.reason(),
e.actor().type() + ":" + e.actor().name(),
e.scope().key(),
e.originServer().orElse("?"));
// Já estamos fora da thread do servidor: IO aqui é aceitável.
enviarParaSistemaExterno(linha);
}
private void enviarParaSistemaExterno(String linha) {
log.info(linha);
}
}Registro no seu plugin:
@Override
public void onEnable() {
ShEvents.register(new LogCentralListener(getLogger()), getName());
}
@Override
public void onDisable() {
ShEvents.unregisterAll(getName());
}Exemplo4. Regra de negócio com evento cancelável#
Impede que um jogador em evento (por exemplo, um torneio do seu plugin) seja silenciado durante a partida, mas permite banimentos.
package com.exemplo.torneio;
import dev.singlehope.shplugins.api.EventPriority;
import dev.singlehope.shplugins.api.Subscribe;
import dev.singlehope.shpunish.api.event.punishment.PunishmentPreCreateEvent;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public final class TorneioProtecao {
// Acessado da thread do servidor e das threads do ShPunish: precisa ser thread-safe.
private final Set<UUID> emPartida = ConcurrentHashMap.newKeySet();
public void entrou(UUID jogador) { emPartida.add(jogador); }
public void saiu(UUID jogador) { emPartida.remove(jogador); }
@Subscribe(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPreCreate(PunishmentPreCreateEvent event) {
if (event.request().type().isMute() && emPartida.contains(event.player().uniqueId())) {
event.cancel("Jogador em partida de torneio; silencie depois da partida");
}
}
}Quem aplicou recebe CANCELLED (pela API) ou a mensagem de cancelamento (pelo comando), e o motivo vai para o log do ShPunish.