Akshat Raj

Compile it

Kodari AI
KodariNov 12 at 4:36 am 1
  1. Click Compile in the top bar (on phone, tap ⋮ → Compile Project).

  2. Click Compile in the window that opens.

  3. When it succeeds, click Download on the build or Download {name}.jar in the chat.

Kodari can make mistakes. Review important code before using.
Files
src
pom.xml
Code
7 1,141
src/main/java/com/chatfilterbans/ChatFilterBans.java
package com.chatfilterbans;

import io.papermc.paper.event.player.AsyncChatEvent;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextReplacementConfig;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.TabExecutor;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;

/**
 * Threading rules in this plugin:
 * - The chat thread only reads: the immutable {@link Settings} snapshot, a small cache of player info,
 *   and the message text. It never calls other Bukkit/Paper API.
 * - Everything else (offense counting, running AdvancedBan commands, messages) runs on the main thread.
 */
public final class ChatFilterBans extends JavaPlugin implements Listener, TabExecutor {

    private static final LegacyComponentSerializer LEGACY = LegacyComponentSerializer.legacyAmpersand();
    private static final PlainTextComponentSerializer PLAIN = PlainTextComponentSerializer.plainText();
    private static final String BYPASS_PERMISSION = "chatfilterbans.bypass";
    private static final String NOTIFY_PERMISSION = "chatfilterbans.notify";

    /** After a failed punishment command, wait this long before trying again for the same player. */
    private static final long FAILURE_BACKOFF_MILLIS = 10_000L;

    /** Replaced as a whole on reload. */
    private volatile Settings settings;

    /** What the chat thread needs to know about a player. Written on the main thread only. */
    private record PlayerInfo(String name, boolean bypass) {
    }

    private final Map<UUID, PlayerInfo> playerInfo = new ConcurrentHashMap<>();

    /** Recent offenses per player. Main thread only. */
    private static final class PlayerState {
        final List<Long> offenses = new ArrayList<>();
        long ignoreUntil;
    }

    private final Map<UUID, PlayerState> states = new HashMap<>();

    @Override
    public void onEnable() {
        saveDefaultConfig();

        List<String> warnings = new ArrayList<>();
        boolean loaded = loadSettings(warnings);
        for (String warning : warnings) {
            if (loaded) {
                getLogger().warning(warning);
            } else {
                getLogger().severe(warning);
            }
        }
        if (!loaded) {
            getLogger().severe("ChatFilterBans is turning itself off until the config is fixed.");
            getServer().getPluginManager().disablePlugin(this);
            return;
        }

        if (getServer().getPluginManager().getPlugin("AdvancedBan") == null) {
            getLogger().warning("AdvancedBan was not found. Mutes and bans only work if the commands in config.yml exist.");
        }

        getServer().getPluginManager().registerEvents(this, this);

        PluginCommand command = getCommand("chatfilterbans");
        if (command != null) {
            command.setExecutor(this);
            command.setTabCompleter(this);
        }

        refreshPlayerInfo();
        // Keeps the permission cache used by the chat thread fresh (about 2 seconds).
        getServer().getScheduler().runTaskTimer(this, this::refreshPlayerInfo, 40L, 40L);
        // Forget old offenders every 10 minutes.
        getServer().getScheduler().runTaskTimer(this, this::cleanup, 12000L, 12000L);
    }

    // ------------------------------------------------------------------
    // Settings
    // ------------------------------------------------------------------

    /**
     * Reads config.yml and badwords.yml and builds a complete new Settings.
     * Only swaps it in if everything loaded, otherwise the previous settings stay active.
     */
    private boolean loadSettings(List<String> warnings) {
        try {
            YamlConfiguration config = readYaml("config.yml", true);
            YamlConfiguration words = readYaml("badwords.yml", false);
            this.settings = Settings.load(config, words, warnings);
            return true;
        } catch (IOException | InvalidConfigurationException e) {
            warnings.add("Could not read the config files: " + e.getMessage());
            return false;
        } catch (RuntimeException e) {
            warnings.add("Could not load the settings: " + e);
            return false;
        }
    }

    /** Loads a yml file strictly, so a typo is reported instead of silently using an empty config. */
    private YamlConfiguration readYaml(String name, boolean withDefaults)
            throws IOException, InvalidConfigurationException {
        File file = new File(getDataFolder(), name);
        if (!file.exists()) {
            saveResource(name, false);
        }
        YamlConfiguration yaml = new YamlConfiguration();
        yaml.load(file);

        if (withDefaults) {
            try (InputStream stream = getResource(name)) {
                if (stream != null) {
                    yaml.setDefaults(YamlConfiguration.loadConfiguration(
                            new InputStreamReader(stream, StandardCharsets.UTF_8)));
                }
            }
        }
        return yaml;
    }

    // ------------------------------------------------------------------
    // Player info cache (so the chat thread never has to ask Bukkit about a player)
    // ------------------------------------------------------------------

    private void remember(Player player) {
        playerInfo.put(player.getUniqueId(),
                new PlayerInfo(player.getName(), player.hasPermission(BYPASS_PERMISSION)));
    }

    private void refreshPlayerInfo() {
        for (Player player : Bukkit.getOnlinePlayers()) {
            remember(player);
        }
    }

    @EventHandler
    public void onJoin(PlayerJoinEvent event) {
        remember(event.getPlayer());
    }

    @EventHandler
    public void onQuit(PlayerQuitEvent event) {
        playerInfo.remove(event.getPlayer().getUniqueId());
    }

    // ------------------------------------------------------------------
    // Chat (chat thread)
    // ------------------------------------------------------------------

    /** HIGHEST so other plugins have already had their say; a cancelled message is never shown. */
    @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
    public void onChat(AsyncChatEvent event) {
        UUID id = event.getPlayer().getUniqueId();
        PlayerInfo info = playerInfo.get(id);
        if (info != null && info.bypass()) {
            return;
        }

        String message = PLAIN.serialize(event.message());
        String word = settings.matcher().findBadWord(message);
        if (word == null) {
            return;
        }

        event.setCancelled(true);

        String name = info != null ? info.name() : null;