added a logger and ported chayapaks ansi parser from chomens

This commit is contained in:
Parker2991
2026-03-12 14:48:31 -05:00
parent 288fbba036
commit b39148b53e
16 changed files with 8508 additions and 48 deletions
+3
View File
@@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml
+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="25" />
</component>
</project>
+17
View File
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="25 (3)" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinJpsPluginSettings">
<option name="externalSystemId" value="Gradle" />
<option name="version" value="2.3.10" />
</component>
</project>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_25" default="true" project-jdk-name="25 (4)" project-jdk-type="JavaSDK" />
</project>
Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
+6 -2
View File
@@ -28,10 +28,14 @@ repositories {
kotlin {
dependencies {
implementation("org.geysermc.mcprotocollib:protocol:1.21.11-SNAPSHOT")
implementation("org.tinylog:tinylog-api-kotlin:2.7.0")
implementation("org.slf4j:slf4j-api:2.0.13")
implementation("org.tinylog:slf4j-tinylog:2.7.0")
implementation("org.tinylog:tinylog-impl:2.7.0")
implementation("org.slf4j:slf4j-api:2.0.12")
implementation("org.yaml:snakeyaml:2.2")
implementation("net.kyori:adventure-text-serializer-ansi:4.26.1")
implementation("net.kyori:adventure-text-serializer-plain:4.26.1")
implementation("net.kyori:adventure-text-serializer-legacy:4.26.1")
implementation("net.kyori:adventure-text-serializer-gson:4.26.1")
}
}
@@ -8,6 +8,8 @@ import org.geysermc.mcprotocollib.network.factory.ClientNetworkSessionFactory;
public class Bot extends SessionAdapter {
public ClientNetworkSession session;
//public final Config.bots options;
public String host = "opt.chipmunk.land";
public int port = 25565;
@@ -16,29 +18,24 @@ public class Bot extends SessionAdapter {
public final Object obj = new Object();
public void Bot () {
System.out.println("meow");
final MinecraftProtocol protocol = new MinecraftProtocol(this.username);
public Bot (Config.Options options, Config config) {
System.out.println(options);
final MinecraftProtocol protocol = new MinecraftProtocol(options.username);
session = ClientNetworkSessionFactory.factory()
.setAddress(
this.host,
this.port
options.host,
options.port
)
.setProtocol(protocol)
.create();
session.addListener(this);
session.connect();
try {
synchronized(obj) {
obj.wait();
};
} catch (final InterruptedException ignored) {
}
session.addListener(this);
this.connect();
};
public void connect () {
session.connect();
try {
synchronized(obj) {
obj.wait();
@@ -0,0 +1,17 @@
package land.chipmunk.parker2991.nitoribot;
import java.util.ArrayList;
import java.util.List;
public class Config {
//public List Bots = new ArrayList<>();
public Options[] bots = new Options[]{};
public static class Options {
public String host;
public int port;
public String username;
};
}
//Configuration.BotOption[] botsOptions = config.bots;
@@ -1,6 +1,9 @@
// Thanks Blackilykat and OptmisticDev and PthePro777 helping me with the client creation
package land.chipmunk.parker2991.nitoribot;
import land.chipmunk.parker2991.nitoribot.Config;
import land.chipmunk.parker2991.nitoribot.logger.LoggerManager;
import org.yaml.snakeyaml.Yaml;
import java.io.IOException;
@@ -13,49 +16,45 @@ import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
// throws URISyntaxException
public class Main {
public Object config;
public Config config;
public static final List<Bot> Bots = new ArrayList<>();
public final List<Bot> Bots = new ArrayList<>();
public void loadConfig() {
private Config loadConfig() throws IOException {
// Blackilykat helped me with the file coping and PthePro777 helped me with reading the file
try {
final Yaml yaml = new Yaml();
final Path path = Path.of("config.yaml");
final Yaml yaml = new Yaml();
final Path path = Path.of("config.yaml");
if (!Files.exists(path)) {
System.out.println("config not found making config now");
if (!Files.exists(path)) {
System.out.println("config not found making config now");
InputStream defaultConfig = Main.class.getClassLoader().getResourceAsStream("default_config.yaml");//.getResource("default_config.yaml");//.getResource("default_config.yaml");
Files.copy(defaultConfig, Paths.get("config.yaml"));
}
InputStream defaultConfig = Main.class.getClassLoader().getResourceAsStream("default_config.yaml");//.getResource("default_config.yaml");//.getResource("default_config.yaml");
Files.copy(defaultConfig, Paths.get("config.yaml"));
}
InputStream configFile = Files.newInputStream(path);
Object config = yaml.load(configFile);
this.config = config;
} catch (final IOException error) {}
InputStream configFile = Files.newInputStream(path);
return yaml.load(configFile);
};
public void main(String[] args) {
this.loadConfig();
config = this.config;
// System.out.print("meow");
try {
Config config = loadConfig();
Config.Options[] bots = config.bots;
Bot
Main.Bots bots = config.bots;
//bots[] = config.bots;
//config = this.config;
//bots = config.bots;
for (this.config.bots Bots: options) {
System.out.println();
};
//Bot bot = new Bot(config);
//System.out.println(this.config);
for (Config.Options options : bots) {
System.out.println(options);
final Bot bot = new Bot(options, config);
System.out.println(bot);
System.out.println("meow");
Bots.add(bot);
}
} catch (Exception e) {
String Error = e.getStackTrace();//.getStackTrace();
LoggerManager.ERROR("NitoriBot Jar", Error);
}
};
}
@@ -0,0 +1,77 @@
package land.chipmunk.parker2991.nitoribot.logger;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.serializer.ansi.ANSIComponentSerializer;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class LoggerManager {
private static final Logger logger = LoggerFactory.getLogger(LoggerManager.class);
private static final DateTimeFormatter formatTime = DateTimeFormatter.ofPattern("HH:mm:ss");
private static final DateTimeFormatter formatDate = DateTimeFormatter.ofPattern("dd/MM/yyyy");
public static String prefix (Component type, String host, String message) {
Component component;
ZoneId timezone = ZoneId.of("America/Chicago");
ZonedDateTime ZoneDate = ZonedDateTime.now(timezone);
LocalDate date = ZoneDate.toLocalDate();
LocalTime time = ZoneDate.toLocalTime();
component = Component.translatable(
"[%s %s %s] [%s] %s",
Component.translatable(formatTime.format(time)).color(NamedTextColor.BLUE),
Component.translatable(formatDate.format(date)).color(NamedTextColor.DARK_BLUE),
type,
Component.translatable(host).color(NamedTextColor.AQUA),
Component.translatable(message).color(NamedTextColor.WHITE)
).color(NamedTextColor.DARK_GRAY);
return ComponentUtil.stringifyAnsi(component);
};
public static void LOG (String host, String message) {
Component type = Component.text("log").color(NamedTextColor.GOLD);
logger.atInfo().log(prefix(type, host, message));
};
public static void INFO (String host, String message) {
Component type = Component.text("info").color(NamedTextColor.GREEN);
logger.atInfo().log(prefix(type, host, message));
};
public static void COMMAND (String host, String message) {
Component type = Component.text("command").color(NamedTextColor.YELLOW);
logger.atInfo().log(prefix(type, host, message));
};
public static void WARN (String host, String message) {
Component type = Component.text("warn").color(NamedTextColor.YELLOW);
logger.atInfo().log(prefix(type, host, message));
};
public static void ERROR (String host, String message) {
Component type = Component.text("error").color(NamedTextColor.DARK_RED);
System.out.println(prefix(type, host, message));
};
}
@@ -0,0 +1,188 @@
package land.chipmunk.parker2991.nitoribot.util;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextColor;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
// credits to chayapak, i ported this from a source of chomens java have because i do not want to write a ansi parser
public class ColorUtil {
private static final Map<Integer, String> ansiToIrcMap = new HashMap<>();
private static final Map<Integer, String> ansiStyleToIrcMap = new HashMap<>();
public static TextColor getColorByString (String _color) {
final String color = _color.toLowerCase();
if (color.startsWith("#")) return TextColor.fromHexString(color);
else {
// am i reinventing the wheel here?
return switch (color) {
case "black" -> NamedTextColor.BLACK;
case "dark_blue" -> NamedTextColor.DARK_BLUE;
case "dark_green" -> NamedTextColor.DARK_GREEN;
case "dark_aqua" -> NamedTextColor.DARK_AQUA;
case "dark_red" -> NamedTextColor.DARK_RED;
case "dark_purple" -> NamedTextColor.DARK_PURPLE;
case "gold" -> NamedTextColor.GOLD;
case "gray" -> NamedTextColor.GRAY;
case "dark_gray" -> NamedTextColor.DARK_GRAY;
case "blue" -> NamedTextColor.BLUE;
case "green" -> NamedTextColor.GREEN;
case "aqua" -> NamedTextColor.AQUA;
case "red" -> NamedTextColor.RED;
case "light_purple" -> NamedTextColor.LIGHT_PURPLE;
case "yellow" -> NamedTextColor.YELLOW;
default -> NamedTextColor.WHITE;
};
}
}
// Author: ChatGPT
public static int hsvToRgb (int hue, int saturation, int value) {
Color color = Color.getHSBColor(hue / 360.0f, saturation / 100.0f, value / 100.0f);
return color.getRGB() & 0xFFFFFF;
}
private static final ChatColor[] COLORS = {
new ChatColor("0", 0x000000),
new ChatColor("1", 0x0000aa),
new ChatColor("2", 0x00aa00),
new ChatColor("3", 0x00aaaa),
new ChatColor("4", 0xaa0000),
new ChatColor("5", 0xaa00aa),
new ChatColor("6", 0xffaa00),
new ChatColor("7", 0xaaaaaa),
new ChatColor("8", 0x555555),
new ChatColor("9", 0x5555ff),
new ChatColor("a", 0x55ff55),
new ChatColor("b", 0x55ffff),
new ChatColor("c", 0xff5555),
new ChatColor("d", 0xff55ff),
new ChatColor("e", 0xffff55),
new ChatColor("f", 0xffffff)
};
public static String getClosestChatColor(int rgb) {
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
ChatColor closest = null;
int smallestDiff = 0;
for (ChatColor color : COLORS) {
if (color.rgb == rgb) {
return color.colorName;
}
// Check by the greatest diff of the 3 values
int rAverage = (color.r + r) / 2;
int rDiff = color.r - r;
int gDiff = color.g - g;
int bDiff = color.b - b;
int diff = ((2 + (rAverage >> 8)) * rDiff * rDiff)
+ (4 * gDiff * gDiff)
+ ((2 + ((255 - rAverage) >> 8)) * bDiff * bDiff);
if (closest == null || diff < smallestDiff) {
closest = color;
smallestDiff = diff;
}
}
return closest.colorName;
}
// Author: ChatGPT
static {
ansiToIrcMap.put(0, "0"); // Reset -> IRC White (is this correct?)
ansiToIrcMap.put(30, "1"); // Black -> IRC Black
ansiToIrcMap.put(31, "40"); // Red -> IRC Red
ansiToIrcMap.put(32, "32"); // Green -> IRC Green
ansiToIrcMap.put(33, "53"); // Yellow -> IRC Yellow
ansiToIrcMap.put(34, "60"); // Blue -> IRC Blue
ansiToIrcMap.put(35, "49"); // Magenta -> IRC Magenta (Purple)
ansiToIrcMap.put(36, "46"); // Cyan -> IRC Cyan
ansiToIrcMap.put(37, "96"); // Gray -> IRC Gray
ansiToIrcMap.put(39, "0"); // White -> IRC White
ansiToIrcMap.put(90, "92"); // Dark Gray -> IRC Dark Gray
ansiToIrcMap.put(92, "56"); // Green -> IRC Green
ansiToIrcMap.put(96, "58"); // Blue -> IRC Blue
ansiToIrcMap.put(91, "52"); // Red -> IRC Red
ansiToIrcMap.put(94, "60"); // Blue -> IRC Blue
ansiToIrcMap.put(95, "61"); // Magenta -> IRC Magenta (Purple)
ansiToIrcMap.put(93, "54"); // Yellow -> IRC Yellow
ansiToIrcMap.put(97, "0"); // White -> IRC White
final Map<Integer, String> clone = new HashMap<>(ansiToIrcMap);
for (Map.Entry<Integer, String> entry : clone.entrySet()) {
ansiToIrcMap.put(entry.getKey() + 10, ansiToIrcMap.get(entry.getKey()));
}
ansiToIrcMap.put(49, "01");
// Styles
ansiStyleToIrcMap.put(1, "\u0002"); // Bold
ansiStyleToIrcMap.put(3, "\u001d"); // Italic
ansiStyleToIrcMap.put(4, "\u001f"); // Underlined
}
public static String convertAnsiToIrc(String input) {
StringBuilder result = new StringBuilder();
boolean insideEscape = false;
StringBuilder ansiCode = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (insideEscape) {
if (c == 'm') {
insideEscape = false;
// Parse the ANSI color code and map it to IRC color
String[] codes = ansiCode.toString().split(";");
for (String code : codes) {
try {
int ansiColorCode = Integer.parseInt(code);
if (ansiToIrcMap.containsKey(ansiColorCode)) {
result.append("\u0003").append(ansiToIrcMap.get(ansiColorCode));
} else if (ansiStyleToIrcMap.containsKey(ansiColorCode)) {
result.append(ansiStyleToIrcMap.get(ansiColorCode));
}
} catch (NumberFormatException ignored) {
}
}
ansiCode.setLength(0); // Clear the buffer
} else {
ansiCode.append(c); // Collect the rest of the ANSI sequence
}
} else {
if (c == '\u001B' && i + 1 < input.length() && input.charAt(i + 1) == '[') {
insideEscape = true;
i++; // Skip the '[' character
} else {
result.append(c); // Append non-ANSI characters directly
}
}
}
return result.toString();
}
public static final class ChatColor {
private final String colorName;
private final int rgb;
private final int r, g, b;
public ChatColor(String colorName, int rgb) {
this.colorName = colorName;
this.rgb = rgb;
r = (rgb >> 16) & 0xFF;
g = (rgb >> 8) & 0xFF;
b = rgb & 0xFF;
}
}
}
@@ -0,0 +1,322 @@
package land.chipmunk.parker2991.nitoribot.util;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.kyori.adventure.text.*;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.Style;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.format.TextDecoration;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// credits to chayapak, i ported this from a source of chomens java have because i do not want to write a ansi parser
// totallynotskidded™ from chipmunkbot and added colors (ignore the ohio code please,..,.)
public class ComponentUtil {
// is this the best way to check?
public static boolean isEqual (Component component1, Component component2) {
return component1.toString().equals(component2.toString());
}
// component parsing
public static final Map<String, String> language = loadJsonStringMap("language.json");
private static final Map<String, String> keybinds = loadJsonStringMap("keybinds.json");
public static final Pattern ARG_PATTERN = Pattern.compile("%(?:(\\d+)\\$)?([s%])");
public static final Map<String, String> ansiMap = new HashMap<>();
static {
// map totallynotskidded™ from https://github.com/PrismarineJS/prismarine-chat/blob/master/index.js#L10
ansiMap.put("0", "\u001b[30m");
ansiMap.put("1", "\u001b[34m");
ansiMap.put("2", "\u001b[32m");
ansiMap.put("3", "\u001b[36m");
ansiMap.put("4", "\u001b[31m");
ansiMap.put("5", "\u001b[35m");
ansiMap.put("6", "\u001b[33m");
ansiMap.put("7", "\u001b[37m");
ansiMap.put("8", "\u001b[90m");
ansiMap.put("9", "\u001b[94m");
ansiMap.put("a", "\u001b[92m");
ansiMap.put("b", "\u001b[96m");
ansiMap.put("c", "\u001b[91m");
ansiMap.put("d", "\u001b[95m");
ansiMap.put("e", "\u001b[93m");
ansiMap.put("f", "\u001b[97m");
ansiMap.put("l", "\u001b[1m");
ansiMap.put("o", "\u001b[3m");
ansiMap.put("n", "\u001b[4m");
ansiMap.put("m", "\u001b[9m");
ansiMap.put("k", "\u001b[6m");
ansiMap.put("r", "\u001b[0m");
}
public record PartiallyStringified(
String output,
String lastColor
) {}
private ComponentUtil () {
}
private static Map<String, String> loadJsonStringMap (String name) {
Map<String, String> map = new HashMap<>();
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(name);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
JsonObject json = JsonParser.parseReader(reader).getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : json.entrySet()) {
map.put(entry.getKey(), json.get(entry.getKey()).getAsString());
}
return map;
}
private static String getOrReturnFallback (TranslatableComponent component) {
final String key = component.key();
final String minecraftKey = language.get(key);
if (minecraftKey != null) return minecraftKey;
else return component.fallback() != null ? component.fallback() : key;
}
public static String stringify (Component message) { return stringify(message, null); }
private static String stringify (Component message, String lastColor) {
try {
final StringBuilder builder = new StringBuilder();
final PartiallyStringified output = stringifyPartially(message, false, false, lastColor, false);
builder.append(output.output);
for (Component child : message.children()) builder.append(stringify(child, output.lastColor));
return builder.toString();
} catch (Exception e) {
return "";
}
}
public static String stringifyMotd (Component message) { return stringifyMotd(message, null); }
private static String stringifyMotd (Component message, String lastColor) {
try {
final StringBuilder builder = new StringBuilder();
final PartiallyStringified output = stringifyPartially(message, true, false, lastColor, false);
builder.append(output.output);
for (Component child : message.children()) builder.append(stringifyMotd(child, output.lastColor));
return builder.toString();
} catch (Exception e) {
return "";
}
}
public static String stringifyAnsi (Component message) { return stringifyAnsi(message, null, false); }
public static String stringifyAnsi (Component message, boolean noHex) { return stringifyAnsi(message, null, noHex); }
private static String stringifyAnsi (Component message, String lastColor, boolean noHex) {
try {
final StringBuilder builder = new StringBuilder();
final PartiallyStringified output = stringifyPartially(message, false, true, lastColor, noHex);
builder.append(output.output);
for (Component child : message.children()) builder.append(stringifyAnsi(child, output.lastColor, noHex));
return builder.toString();
} catch (Exception e) {
return "";
}
}
public static PartiallyStringified stringifyPartially (Component message, boolean motd, boolean ansi, String lastColor, boolean noHex) {
if (message instanceof TextComponent) return stringifyPartially((TextComponent) message, motd, ansi, lastColor, noHex);
else if (message instanceof TranslatableComponent) return stringifyPartially((TranslatableComponent) message, motd, ansi, lastColor, noHex);
else if (message instanceof SelectorComponent) return stringifyPartially((SelectorComponent) message, motd, ansi, lastColor, noHex);
else if (message instanceof KeybindComponent) return stringifyPartially((KeybindComponent) message, motd, ansi, lastColor, noHex);
return new PartiallyStringified("", null);
}
public static String getStyle (Style textStyle, boolean motd) {
if (textStyle == null) return null;
StringBuilder style = new StringBuilder();
for (Map.Entry<TextDecoration, TextDecoration.State> decorationEntry : textStyle.decorations().entrySet()) {
final TextDecoration decoration = decorationEntry.getKey();
final TextDecoration.State state = decorationEntry.getValue();
if (state == TextDecoration.State.NOT_SET || state == TextDecoration.State.FALSE) continue;
if (!motd) {
switch (decoration) {
case BOLD -> style.append(ansiMap.get("l"));
case ITALIC -> style.append(ansiMap.get("o"));
case OBFUSCATED -> style.append(ansiMap.get("k"));
case UNDERLINED -> style.append(ansiMap.get("n"));
case STRIKETHROUGH -> style.append(ansiMap.get("m"));
}
} else {
switch (decoration) {
case BOLD -> style.append("§l");
case ITALIC -> style.append("§o");
case OBFUSCATED -> style.append("§k");
case UNDERLINED -> style.append("§n");
case STRIKETHROUGH -> style.append("§m");
}
}
}
return style.toString();
}
public static String getColor (TextColor color, boolean motd, boolean ansi, boolean noHex) {
if (color == null) return null;
// map totallynotskidded™ too from https://github.com/PrismarineJS/prismarine-chat/blob/master/index.js#L299
String code;
if (color == NamedTextColor.BLACK) code = "0";
else if (color == NamedTextColor.DARK_BLUE) code = "1";
else if (color == NamedTextColor.DARK_GREEN) code = "2";
else if (color == NamedTextColor.DARK_AQUA) code = "3";
else if (color == NamedTextColor.DARK_RED) code = "4";
else if (color == NamedTextColor.DARK_PURPLE) code = "5";
else if (color == NamedTextColor.GOLD) code = "6";
else if (color == NamedTextColor.GRAY) code = "7";
else if (color == NamedTextColor.DARK_GRAY) code = "8";
else if (color == NamedTextColor.BLUE) code = "9";
else if (color == NamedTextColor.GREEN) code = "a";
else if (color == NamedTextColor.AQUA) code = "b";
else if (color == NamedTextColor.RED) code = "c";
else if (color == NamedTextColor.LIGHT_PURPLE) code = "d";
else if (color == NamedTextColor.YELLOW) code = "e";
else if (color == NamedTextColor.WHITE) code = "f";
else {
try {
code = color.asHexString();
} catch (NullPointerException e) {
code = ""; // mabe...,,.,..,
}
}
if (motd) {
return "§" + code;
} else if (ansi) {
String ansiCode = ansiMap.get(code);
if (ansiCode == null) {
if (noHex) {
final int rgb = Integer.parseInt(code.substring(1), 16);
final String chatColor = ColorUtil.getClosestChatColor(rgb);
ansiCode = ansiMap.get(chatColor);
} else {
ansiCode = "\u001b[38;2;" +
color.red() +
";" +
color.green() +
";" +
color.blue() +
"m";
}
}
return ansiCode;
} else return null;
}
public static PartiallyStringified stringifyPartially (TextComponent message, boolean motd, boolean ansi, String lastColor, boolean noHex) {
if ((motd || ansi) && /* don't color big messages -> */ message.content().length() < 25_000) {
final String color = getColor(message.color(), motd, ansi, noHex);
final String style = getStyle(message.style(), motd);
String replacedContent = message.content();
// seems very mabe mabe
if (ansi && replacedContent.contains("§")) {
// is try-catch a great idea?
try {
replacedContent = Pattern
.compile("(§.)")
.matcher(message.content())
.replaceAll(m -> ansiMap.get(m.group(0).substring(1)));
} catch (Exception ignored) {}
}
// messy af
return new PartiallyStringified((lastColor != null ? lastColor : "") + (color != null ? color : "") + (style != null ? style : "") + replacedContent + (ansi ? ansiMap.get("r") : ""), color);
}
return new PartiallyStringified(message.content(), null);
}
public static PartiallyStringified stringifyPartially (TranslatableComponent message, boolean motd, boolean ansi, String lastColor, boolean noHex) {
String format = getOrReturnFallback(message);
// totallynotskidded™️ from HBot (and changed a bit)
Matcher matcher = ARG_PATTERN.matcher(format);
StringBuilder sb = new StringBuilder();
final String style = getStyle(message.style(), motd);
final String _color = getColor(message.color(), motd, ansi, noHex);
String color;
if (_color == null) color = "";
else color = _color;
int i = 0;
while (matcher.find()) {
if (matcher.group().equals("%%")) {
matcher.appendReplacement(sb, "%");
} else {
String idxStr = matcher.group(1);
int idx = idxStr == null ? i++ : (Integer.parseInt(idxStr) - 1);
if (idx >= 0 && idx < message.arguments().size()) {
matcher.appendReplacement(
sb,
Matcher.quoteReplacement(
motd ?
stringifyMotd(message.arguments().get(idx).asComponent()) + color :
(
ansi ?
stringifyAnsi(message.arguments().get(idx).asComponent()) + color :
stringify(message.arguments().get(idx).asComponent())
)
)
);
} else {
matcher.appendReplacement(sb, "");
}
}
}
matcher.appendTail(sb);
return new PartiallyStringified((lastColor != null ? lastColor : "") + color + (style != null && ansi ? style : "") + sb + (ansi ? ansiMap.get("r") : ""), _color);
}
public static PartiallyStringified stringifyPartially (SelectorComponent message, boolean motd, boolean ansi, String lastColor, boolean noHex) {
final String style = getStyle(message.style(), motd);
final String _color = getColor(message.color(), motd, ansi, noHex);
String color;
if (_color == null) color = "";
else color = _color;
return new PartiallyStringified((lastColor != null ? lastColor : "") + color + (style != null && ansi ? style : "") + message.pattern(), _color); // * Client-side selector components are equivalent to text ones, and do NOT list entities.
}
public static PartiallyStringified stringifyPartially (KeybindComponent message, boolean motd, boolean ansi, String lastColor, boolean noHex) {
String keybind = message.keybind();
Component component = keybinds.containsKey(keybind) ? Component.translatable(keybind) : Component.text(keybind); // TODO: Fix some keys like `key.keyboard.a`
return stringifyPartially(component, motd, ansi, lastColor, noHex);
}
}
+36
View File
@@ -0,0 +1,36 @@
{
"key.attack": "key.mouse.left",
"key.use": "key.mouse.right",
"key.forward": "key.keyboard.w",
"key.left": "key.keyboard.a",
"key.back": "key.keyboard.s",
"key.right": "key.keyboard.d",
"key.jump": "key.keyboard.space",
"key.sneak": "key.keyboard.left.shift",
"key.sprint": "key.keyboard.left.control",
"key.drop": "key.keyboard.q",
"key.inventory": "key.keyboard.e",
"key.chat": "key.keyboard.t",
"key.playerlist": "key.keyboard.tab",
"key.pickItem": "key.mouse.middle",
"key.command": "key.keyboard.slash",
"key.socialInteractions": "key.keyboard.p",
"key.screenshot": "key.keyboard.f2",
"key.togglePerspective": "key.keyboard.f5",
"key.smoothCamera": "key.keyboard.unknown",
"key.fullscreen": "key.keyboard.f11",
"key.spectatorOutlines": "key.keyboard.unknown",
"key.swapOffhand": "key.keyboard.f",
"key.saveToolbarActivator": "key.keyboard.c",
"key.loadToolbarActivator": "key.keyboard.x",
"key.advancements": "key.keyboard.l",
"key.hotbar.1": "key.keyboard.1",
"key.hotbar.2": "key.keyboard.2",
"key.hotbar.3": "key.keyboard.3",
"key.hotbar.4": "key.keyboard.4",
"key.hotbar.5": "key.keyboard.5",
"key.hotbar.6": "key.keyboard.6",
"key.hotbar.7": "key.keyboard.7",
"key.hotbar.8": "key.keyboard.8",
"key.hotbar.9": "key.keyboard.9"
}
File diff suppressed because it is too large Load Diff