Files
src
build.gradle
gradle.properties
settings.gradle
Code
5 339
src/client/java/com/kodari/chatbuttons/ChatButtonsClient.java
package com.kodari.chatbuttons;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents;
import net.fabricmc.fabric.api.client.screen.v1.ScreenEvents;
import net.fabricmc.fabric.api.client.screen.v1.Screens;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.ChatScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.network.PlayerListEntry;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.text.Text;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
public class ChatButtonsClient implements ClientModInitializer {
private static final Path CONFIG_PATH = Path.of("config", "chat_buttons.properties");
private static final int MAX_BUTTONS = 12;
private static final int MAX_TRIGGERS = 32;
private static final long TRIGGER_COOLDOWN_NANOS = 1_000_000_000L;
private static final Configuration CONFIG = loadConfiguration();
private static final Map<Integer, Long> LAST_TRIGGERED = new HashMap<>();
private static String selectedTarget = "";
@Override
public void onInitializeClient() {
MinecraftClient minecraftClient = MinecraftClient.getInstance();
ClientReceiveMessageEvents.CHAT.register((message, signedMessage, sender, params, receptionTimestamp) ->
processTriggers(minecraftClient, message.getString(), sender == null ? "" : sender.name()));
ClientReceiveMessageEvents.GAME.register((message, overlay) ->
processTriggers(minecraftClient, message.getString(), ""));
ScreenEvents.AFTER_INIT.register((client, screen, scaledWidth, scaledHeight) -> {
if (!(screen instanceof ChatScreen)) {
return;
}
int columns = Math.max(1, Math.min(6, (scaledWidth - 8) / 84));
int buttonWidth = Math.max(40, Math.min(80, (scaledWidth - 8 - (columns - 1) * 4) / columns));
int selectorWidth = Math.max(40, Math.min(160, scaledWidth - 8));
ButtonWidget targetSelector = ButtonWidget.builder(Text.literal(targetLabel(client)), button -> {
List<String> players = onlinePlayers(client);
int currentIndex = players.indexOf(selectedTarget);
selectedTarget = players.isEmpty() ? "" : players.get((currentIndex + 1) % players.size());
button.setMessage(Text.literal(targetLabel(client)));
}).dimensions(4, scaledHeight - 36, selectorWidth, 20).build();
Screens.getButtons(screen).add(targetSelector);
for (int index = 0; index < CONFIG.buttons().size(); index++) {
ChatButton chatButton = CONFIG.buttons().get(index);
int row = 1 + index / columns;
int column = index % columns;
int x = 4 + column * (buttonWidth + 4);
int y = scaledHeight - 36 - row * 22;
ButtonWidget button = ButtonWidget.builder(Text.literal(chatButton.label()), widget -> {
if (client.player == null) {
return;
}
if (chatButton.type() == ActionType.CHAT) {
client.player.networkHandler.sendChatMessage(chatButton.value());
} else if (chatButton.type() == ActionType.COMMAND) {
sendCommand(client, chatButton.value());
} else {
String target = currentTarget(client);
if (!target.isBlank()) {
sendCommand(client, chatButton.value().replace("{player}", target));
}
}
}).dimensions(x, y, buttonWidth, 20).build();
Screens.getButtons(screen).add(button);
}
});
}
private static void processTriggers(MinecraftClient client, String message, String sender) {
if (client.player == null || message.isBlank()) {
return;
}
String normalizedMessage = message.toLowerCase(Locale.ROOT);
long now = System.nanoTime();
for (int index = 0; index < CONFIG.triggers().size(); index++) {
TriggerRule trigger = CONFIG.triggers().get(index);
if (!normalizedMessage.contains(trigger.contains().toLowerCase(Locale.ROOT))) {
continue;
}
if (trigger.command().contains("{sender}") && sender.isBlank()) {
continue;
}
long lastTriggered = LAST_TRIGGERED.getOrDefault(index, 0L);
if (lastTriggered != 0L && now - lastTriggered < TRIGGER_COOLDOWN_NANOS) {
continue;
}
sendCommand(client, trigger.command().replace("{sender}", sender));
LAST_TRIGGERED.put(index, now);
}
}
private static void sendCommand(MinecraftClient client, String value) {
if (client.player == null) {
return;
}
String command = value.startsWith("/") ? value.substring(1) : value;
if (!command.isBlank()) {
client.player.networkHandler.sendChatCommand(command);
}
}
private static List<String> onlinePlayers(MinecraftClient client) {
if (client.getNetworkHandler() == null) {
return List.of();
}
String ownName = client.player == null ? "" : client.player.getName().getString();
return client.getNetworkHandler().getPlayerList().stream()
.map(entry -> entry.getProfile().name())
.filter(name -> !name.equalsIgnoreCase(ownName))
.sorted(String.CASE_INSENSITIVE_ORDER)
.toList();
}
private static String currentTarget(MinecraftClient client) {
List<String> players = onlinePlayers(client);
if (!players.contains(selectedTarget)) {
selectedTarget = "";
}
return selectedTarget;
}
private static String targetLabel(MinecraftClient client) {
String target = currentTarget(client);
return target.isBlank() ? "Цель: нет (нажми)" : "Цель: " + target;
}
private static Configuration loadConfiguration() {
try {
Files.createDirectories(CONFIG_PATH.getParent());
if (Files.notExists(CONFIG_PATH)) {
writeDefaultConfig();
}
Properties properties = new Properties();
try (Reader reader = Files.newBufferedReader(CONFIG_PATH, StandardCharsets.UTF_8)) {
properties.load(reader);
}
int count = readCount(properties, "buttons.count", MAX_BUTTONS);
List<ChatButton> buttons = new ArrayList<>();
for (int index = 1; index <= count; index++) {
String prefix = "button." + index + ".";
String label = properties.getProperty(prefix + "label", "").trim();
String value = properties.getProperty(prefix + "value", "").trim();
String type = properties.getProperty(prefix + "type", "").toLowerCase(Locale.ROOT);
if (label.isBlank() || value.isBlank()) {
continue;
}
if (type.equals("chat")) {
buttons.add(new ChatButton(label, ActionType.CHAT, value));
} else if (type.equals("command")) {
buttons.add(new ChatButton(label, ActionType.COMMAND, value));
} else if (type.equals("player_command")) {
buttons.add(new ChatButton(label, ActionType.PLAYER_COMMAND, value));
}
}
int triggerCount = readCount(properties, "triggers.count", MAX_TRIGGERS);
List<TriggerRule> triggers = new ArrayList<>();
for (int index = 1; index <= triggerCount; index++) {
String prefix = "trigger." + index + ".";
String contains = properties.getProperty(prefix + "contains", "").trim();
String command = properties.getProperty(prefix + "command", "").trim();
if (!contains.isBlank() && !command.isBlank()) {
triggers.add(new TriggerRule(contains, command));
}
}
return new Configuration(buttons, triggers);
} catch (IOException exception) {
System.err.println("[chat_buttons] Не удалось прочитать конфигурацию: " + exception.getMessage());