19802703dima-ai

Create a client-side Minecraft Fabric mod for version 1.21.4 (using Fabric API). The mod must monitor incoming server chat messages in real-time, parse the sender's username, and check the message content against a configurable JSON file (config/raidkp_automute.json).

In the JSON config, store a list of rule entries. Each entry should have: a list of trigger words/regex patterns, a mute duration (e.g., "15m", "1h"), and a reason (e.g., "Оскорбления", "Спам").

When a player's message matches any trigger, the client must automatically send the command /tempmute <player_name> <duration> <reason> to the server chat. Add a 1-second delay before sending the command to avoid server anti-spam kicks, and ensure the mod ignores its own messages or system alerts.

Also add client-side commands /automute toggle (to turn auto-mute on/off in-game) and /automute reload (to reload the JSON config without restarting Minecraft).

Kodari AI
KodariToday at 9:36 pm 3
AutoMuteClient
Client-side Fabric mod for 1.21.4 that monitors incoming chat messages, parses sender usernames, and checks content against configurable JSON rules. On trigger match, automatically sends /tempmute command with a 1-second delay to avoid anti-spam. Includes /automute toggle and /automute reload commands, ignores own messages and system alerts.
  • Match player chat against case-insensitive regex rules in the JSON config.

  • Queue mute commands at least one second apart, and discard them on disconnect or when disabled.

  • Add client-side toggle and reload commands, with validation before applying a config.

Created the client-side AutoMute mod. It creates config/raidkp_automute.json with an empty rule list on first launch. For example:

JSON
{
  "rules": [
    {
      "triggers": ["insult", "spam\\s+link"],
      "duration": "15m",
      "reason": "Оскорбления"
    }
  ]
}

Triggers are case-insensitive regex patterns. Use /automute reload after editing the file and /automute toggle to enable or disable moderation. The server must allow your account to use /tempmute.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
gradle.properties
settings.gradle
Code
5 223
src/main/java/dev/kodari/automute/AutoMuteClient.java
package dev.kodari.automute;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mojang.authlib.GameProfile;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.MinecraftClient;
import net.minecraft.text.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.regex.Pattern;

public final class AutoMuteClient implements ClientModInitializer {
    private static final Logger LOGGER = LoggerFactory.getLogger("raidkp_automute");
    private static final Path CONFIG = FabricLoader.getInstance().getConfigDir().resolve("raidkp_automute.json");
    private static final long DELAY_NANOS = 1_000_000_000L;
    private static final Pattern USERNAME = Pattern.compile("[A-Za-z0-9_]{1,16}");
    private static final Pattern DURATION = Pattern.compile("[1-9][0-9]*[smhdw]", Pattern.CASE_INSENSITIVE);
    private final Queue<PendingMute> pending = new ArrayDeque<>();
    private List<Rule> rules = List.of();
    private boolean enabled = true;
    private Object connection;
    private long lastSend;

    @Override
    public void onInitializeClient() {
        try {
            reload();
        } catch (Exception e) {
            LOGGER.error("Could not load AutoMute configuration; no rules are active", e);
        }

        ClientReceiveMessageEvents.CHAT.register((message, signedMessage, sender, params, timestamp) -> {
            MinecraftClient client = MinecraftClient.getInstance();
            if (!enabled || client.player == null || client.getNetworkHandler() == null || sender == null
                    || sender.getId().equals(client.player.getUuid())) {
                return;
            }
            String name = sender.getName();
            if (name == null || !USERNAME.matcher(name).matches()) {
                return;
            }
            String content = signedMessage == null ? message.getString() : signedMessage.getSignedContent();
            for (Rule rule : rules) {
                if (rule.patterns().stream().anyMatch(pattern -> pattern.matcher(content).find())) {
                    String command = "tempmute " + name + " " + rule.duration() + " " + rule.reason();
                    if (command.length() <= 256) {
                        pending.add(new PendingMute(command, System.nanoTime(), client.getNetworkHandler()));
                    } else {
                        LOGGER.warn("AutoMute command for {} exceeds the chat command limit", name);
                    }
                    break;
                }
            }
        });

        ClientTickEvents.END_CLIENT_TICK.register(client -> {
            Object current = client.getNetworkHandler();
            if (current != connection) {
                pending.clear();
                connection = current;
                lastSend = 0;
            }
            if (!enabled || current == null || client.player == null || pending.isEmpty()) {
                return;
            }
            PendingMute next = pending.peek();
            long now = System.nanoTime();
            if (next.connection() != current) {
                pending.remove();
            } else if (now - next.queuedAt() >= DELAY_NANOS && (lastSend == 0 || now - lastSend >= DELAY_NANOS)) {
                pending.remove();
                client.getNetworkHandler().sendChatCommand(next.command());
                lastSend = now;
            }
        });

        ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> dispatcher.register(
                ClientCommandManager.literal("automute")
                        .then(ClientCommandManager.literal("toggle").executes(context -> {
                            enabled = !enabled;
                            if (!enabled) pending.clear();
                            context.getSource().sendFeedback(Text.literal("AutoMute " + (enabled ? "enabled" : "disabled") + "."));
                            return 1;
                        }))
                        .then(ClientCommandManager.literal("reload").executes(context -> {
                            try {
                                reload();
                                pending.clear();
                                context.getSource().sendFeedback(Text.literal("AutoMute config reloaded: " + rules.size() + " rules."));
                                return 1;
                            } catch (Exception e) {
                                LOGGER.error("Could not reload AutoMute configuration", e);
                                context.getSource().sendError(Text.literal("AutoMute reload failed: " + e.getMessage()));
                                return 0;
                            }
                        }))));
    }

    private void reload() throws IOException {
        if (Files.notExists(CONFIG)) {
            Files.createDirectories(CONFIG.getParent());
            Files.writeString(CONFIG, "{\n  \"rules\": []\n}\n", StandardCharsets.UTF_8);
        }
        JsonObject root = JsonParser.parseString(Files.readString(CONFIG, StandardCharsets.UTF_8)).getAsJsonObject();
        JsonArray entries = root.getAsJsonArray("rules");
        if (entries == null) throw new IllegalArgumentException("Missing rules array");
        List<Rule> loaded = new ArrayList<>();
        for (JsonElement entry : entries) {
            JsonObject object = entry.getAsJsonObject();
            JsonArray triggers = object.getAsJsonArray("triggers");
            if (triggers == null || triggers.isEmpty()) throw new IllegalArgumentException("Each rule needs triggers");
            List<Pattern> patterns = new ArrayList<>();
            for (JsonElement trigger : triggers) {
                String expression = trigger.getAsString();
                if (expression.isBlank()) throw new IllegalArgumentException("Triggers cannot be blank");
                patterns.add(Pattern.compile(expression, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE));
            }
            String duration = object.get("duration").getAsString();
            String reason = object.get("reason").getAsString();
            if (!DURATION.matcher(duration).matches()) throw new IllegalArgumentException("Invalid duration: " + duration);
            if (reason.isBlank() || reason.chars().anyMatch(Character::isISOControl)) {
                throw new IllegalArgumentException("Reason must be nonempty and contain no control characters");
            }
            loaded.add(new Rule(List.copyOf(patterns), duration, reason));
        }
        rules = List.copyOf(loaded);
    }

    private record Rule(List<Pattern> patterns, String duration, String reason) {}
    private record PendingMute(String command, long queuedAt, Object connection) {}
}