refracture pretty much everything

This commit is contained in:
Parker2991
2026-10-06 15:00:05 -05:00
parent dc03b5157f
commit 89dbac9974
67 changed files with 1986 additions and 2245 deletions
+5
View File
@@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DiscordProjectSettings">
<option name="show" value="PROJECT_FILES" />
<option name="description" value="" />
</component>
</project>
+1 -2
View File
@@ -5,13 +5,12 @@
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="25" />
<option name="gradleJvm" value="25 (2)" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
<option name="myGradleHome" value="/usr/share/java/gradle" />
</GradleProjectSettings>
</option>
</component>
+8
View File
@@ -0,0 +1,8 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="AutoCloseableResource" enabled="true" level="WARNING" enabled_by_default="true">
<option name="METHOD_MATCHER_CONFIG" value="java.util.Formatter,format,java.io.Writer,append,com.google.common.base.Preconditions,checkNotNull,org.hibernate.Session,close,java.io.PrintWriter,printf,java.io.PrintStream,printf,java.lang.foreign.Arena,ofAuto,java.lang.foreign.Arena,global,java.net.http.HttpClient.Builder,build,java.lang.ClassLoader,getResourceAsStream" />
</inspection_tool>
</profile>
</component>
+27
View File
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JsonSchemaMappingsProjectConfiguration">
<state>
<map>
<entry key="No JSON schema">
<value>
<SchemaInfo>
<option name="ignoredFile" value="true" />
<option name="name" value="No JSON schema" />
<option name="relativePathToSchema" value="" />
<option name="applicationDefined" value="true" />
<option name="patterns">
<list>
<Item>
<option name="path" value="file://$PROJECT_DIR$/src/main/resources/info.json" />
</Item>
</list>
</option>
<option name="isIgnoredFile" value="true" />
</SchemaInfo>
</value>
</entry>
</map>
</state>
</component>
</project>
+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/modules/NitoriBot.main.iml" filepath="$PROJECT_DIR$/.idea/modules/NitoriBot.main.iml" />
<module fileurl="file://$PROJECT_DIR$/.idea/modules/NitoriBot.test.iml" filepath="$PROJECT_DIR$/.idea/modules/NitoriBot.test.iml" />
</modules>
</component>
</project>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="FacetManager">
<facet type="minecraft" name="Minecraft">
<configuration>
<autoDetectTypes>
<platformType>ADVENTURE</platformType>
</autoDetectTypes>
<projectReimportVersion>1</projectReimportVersion>
</configuration>
</facet>
</component>
</module>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="FacetManager">
<facet type="minecraft" name="Minecraft">
<configuration>
<autoDetectTypes>
<platformType>ADVENTURE</platformType>
</autoDetectTypes>
<projectReimportVersion>1</projectReimportVersion>
</configuration>
</facet>
</component>
</module>
+57 -60
View File
@@ -7,77 +7,74 @@ version = "v9.0.0-alpha"
group = "nitoribot"
description = "NitoriBot"
plugins {
kotlin("jvm") version "2.3.10"
id("maven-publish")
kotlin("jvm") version "2.3.10"
id("maven-publish")
}
kotlin {
jvmToolchain(25)
jvmToolchain(25)
}
repositories {
mavenCentral()
maven("https://repo.opencollab.dev/maven-releases/")
maven("https://repo.opencollab.dev/maven-snapshots/")
maven("https://jitpack.io/")
maven("https://repo.opencollab.dev/main/")
maven("https://maven.maxhenkel.de/repository/public/")
maven("https://libraries.minecraft.net")
maven("https://code.chipmunk.land/api/packages/kaboomstandardsorganization/maven/")
repositories {
mavenCentral()
maven("https://repo.opencollab.dev/maven-releases/")
maven("https://repo.opencollab.dev/maven-snapshots/")
maven("https://jitpack.io/")
maven("https://repo.opencollab.dev/main/")
maven("https://maven.maxhenkel.de/repository/public/")
maven("https://code.chipmunk.land/api/packages/kaboomstandardsorganization/maven/")
}
dependencies {
implementation("org.geysermc.mcprotocollib:protocol:26.2-SNAPSHOT")
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.yaml:snakeyaml:2.2")
implementation("net.kyori:adventure-text-serializer-ansi:5.2.0")
implementation("net.kyori:adventure-text-serializer-plain:5.2.0")
implementation("net.kyori:adventure-text-serializer-legacy:5.2.0")
implementation("net.kyori:adventure-text-serializer-gson:5.2.0")
implementation("net.kyori:adventure-text-minimessage:5.2.0")
implementation("net.dv8tion:JDA:6.4.1")
implementation("org.jline:jline:4.1.0")
implementation("land.chipmunk.code.kaboomstandardsorganization.messaginglib:mcprotocollib:3.1.2")
implementation("com.mojang:brigadier:1.0.500")
implementation("org.geysermc.mcprotocollib:protocol:26.2-SNAPSHOT")
constraints {
implementation("io.netty:netty-codec-dns:4.2.16.Final") {
because("dos vulnerability!")
}
implementation("io.netty:netty-all:4.2.18.Final") {
because("vulnerability")
}
}
implementation("org.slf4j:slf4j-api:2.0.20")
implementation("org.tinylog:slf4j-tinylog:2.8.1")
implementation("org.tinylog:tinylog-impl:2.8.1")
implementation("org.yaml:snakeyaml:2.7")
implementation("net.kyori:adventure-text-serializer-ansi:5.2.0")
implementation("net.kyori:adventure-text-serializer-plain:5.2.0")
implementation("net.kyori:adventure-text-serializer-legacy:5.2.0")
implementation("net.kyori:adventure-text-serializer-gson:5.2.0")
implementation("net.kyori:adventure-text-minimessage:5.2.0")
implementation("net.dv8tion:JDA:6.7.0")
implementation("org.jline:jline:4.4.7")
}
tasks.jar {
val timeZone = ZoneId.of("America/Chicago");
val zoneDate = ZonedDateTime.now(timeZone);
val dateTimeFormatter = DateTimeFormatter.ofPattern("MMMM dd, yyyy hh:mm:ss a")
val dateTimeInfo = zoneDate.toLocalDateTime();
val timeZone = ZoneId.of("America/Chicago");
val zoneDate = ZonedDateTime.now(timeZone);
val dateTimeFormatter = DateTimeFormatter.ofPattern("MMMM dd, yyyy hh:mm:ss a")
val dateTimeInfo = zoneDate.toLocalDateTime();
manifest {
attributes["Main-Class"] = "land.chipmunk.parker2991.nitoribot.Main"
attributes("Build-Time" to dateTimeFormatter.format(dateTimeInfo))
attributes("Enable-Native-Access" to "ALL-UNNAMED")
}
archiveClassifier.set("all")
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(sourceSets.main.get().output)
dependsOn(configurations.runtimeClasspath)
from(
{
configurations.runtimeClasspath.get().filter {
it.name.endsWith("jar")
}.map {
zipTree(it)
}
manifest {
attributes["Main-Class"] = "land.chipmunk.parker2991.nitoribot.Main"
attributes("Build-Time" to dateTimeFormatter.format(dateTimeInfo))
attributes("Enable-Native-Access" to "ALL-UNNAMED")
}
)
archiveClassifier.set("all")
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(sourceSets.main.get().output)
dependsOn(configurations.runtimeClasspath)
from(
{
configurations.runtimeClasspath.get().filter {
it.name.endsWith("jar")
}.map {
zipTree(it)
}
}
)
}
@@ -1,11 +1,11 @@
package land.chipmunk.parker2991.nitoribot;
import land.chipmunk.parker2991.nitoribot.boot.GetProxiesList;
import land.chipmunk.parker2991.nitoribot.data.buildstring.BotBuildInfo;
import land.chipmunk.parker2991.nitoribot.data.buildstring.RepoCommitInfo;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import land.chipmunk.parker2991.nitoribot.listeners.ListenerManager;
import land.chipmunk.parker2991.nitoribot.logger.Logger;
import land.chipmunk.parker2991.nitoribot.boot.GetProxiesList;
import land.chipmunk.parker2991.nitoribot.modules.*;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
import net.kyori.adventure.text.Component;
@@ -22,190 +22,154 @@ import org.geysermc.mcprotocollib.protocol.MinecraftProtocol;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.ClientboundLoginPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.ServerboundPlayerLoadedPacket;
import org.geysermc.mcprotocollib.protocol.packet.login.clientbound.ClientboundLoginFinishedPacket;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.*;
public class Bot extends SessionAdapter {
public final ListenerManager listenerManager = new ListenerManager();
public final ListenerManager listenerManager = new ListenerManager();
public boolean loggedIn = false;
public int entityId;
public final ScheduledExecutorService executor = Main.executor;
public final ExecutorService executorService = Main.executorService;
public final ConcurrentMap<String, Future<?>> services = Main.services;
public final BotBuildInfo botBuildInfo = Main.botBuildInfo;
public final RepoCommitInfo repoCommitInfo = Main.repoCommitInfo;
public ClientNetworkSession session;
public GameProfile profile;
public final @NotNull Config config;
public final Config.Options options;
public final List<Bot> bots;
public final ChatModule chat;
public final PositionModule position;
public final CommandCoreModule core;
public final PlayerListModule players;
public final RegistryModule registry;
public CommandManagerModule commandManager;
public MCServerModule mcServer;
public List<?> modules;
//public static final List modulesList = new ArrayList<>();
public Bot (Config.Options options, List<Bot> bots, @NotNull Config config) throws IOException {
this.options = options;
this.bots = bots;
this.config = config;
public List<?> modules;
this.modules = List.of(
this.chat = new ChatModule(this),
new SelfcareModule(this),
this.position = new PositionModule(this),
this.core = new CommandCoreModule(this),
this.registry = new RegistryModule(this),
this.players = new PlayerListModule(this),
new LoggingModule(this),
new ChatCommandHandlerModule(this),
this.commandManager = new CommandManagerModule(this),
new TextDisplayModule(this),
this.mcServer = new MCServerModule(this),
new CommandSpyModule(this)
);
public boolean loggedIn = false;
public int entityId;
public final ScheduledExecutorService executor = Main.executor;
public final ExecutorService executorService = Main.executorService;
public final ConcurrentMap<String, Future<?>> services = Main.services;
public BotBuildInfo botBuildInfo = Main.botBuildInfo;
public RepoCommitInfo repoCommitInfo = Main.repoCommitInfo;
public ClientNetworkSession session;
public GameProfile profile;
public Config config;
public Config.Options options;
public List<Bot> bots;
public ChatModule chat;
public ConsoleModule console;
public SelfcareModule selfcare;
public PositionModule position;
public CommandCoreModule core;
public PlayerListModule players;
public RegistryModule registry;
public CommandManagerModule commandManager;
public ExtrasMessagingModule extrasMessaging;
public MCServerModule mcServer;
public void loadModules () {
try {
modules = List.of(
this.chat = new ChatModule(this),
this.selfcare = new SelfcareModule(this),
this.position = new PositionModule(this),
this.core = new CommandCoreModule(this),
this.registry = new RegistryModule(this),
this.players = new PlayerListModule(this),
new LoggingModule(this),
new ChatCommandHandlerModule(this),
this.commandManager = new CommandManagerModule(this),
this.extrasMessaging = new ExtrasMessagingModule(this),
new TextDisplayModule(this),
this.mcServer = new MCServerModule(this),
new CommandSpyModule(this)
);
} catch (Exception e) {
try {
connect();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
public Bot (Config.Options options, List<Bot> bots, Config config) {
this.options = options;
this.bots = bots;
this.config = config;
public void connect () throws IOException {
final MinecraftProtocol protocol = new MinecraftProtocol(options.username);
try {
connect();
} catch (Exception e) {
e.printStackTrace(System.err);
if (options.useProxy) session = ClientNetworkSessionFactory.factory()
.setAddress(
options.host,
options.port
)
.setProxy(new GetProxiesList().randomProxyIp())
.setProtocol(protocol)
.create();
else session = ClientNetworkSessionFactory.factory()
.setAddress(
options.host,
options.port
)
.setProtocol(protocol)
.create();
session.addListener(this);
session.connect(false);
}
}
public void connect () throws IOException {
final MinecraftProtocol protocol = new MinecraftProtocol(options.username);
if (options.useProxy) session = ClientNetworkSessionFactory.factory()
.setAddress(
options.host,
options.port
)
.setProxy(new GetProxiesList().randomProxyIp())
.setProtocol(protocol)
.create();
else session = ClientNetworkSessionFactory.factory()
.setAddress(
options.host,
options.port
)
.setProtocol(protocol)
.create();
session.addListener(this);
loadModules();
session.connect(false);
}
@Override
public void disconnecting (DisconnectingEvent event) {
String reason = event + "";
session.disconnect(reason);
}
@Override
public void packetSent (Session session, Packet packet) {
for (Listener listener : listenerManager.listeners) {
listener.packetSent(session, packet);
@Override
public void disconnecting (DisconnectingEvent event) {
Component component = event.getReason();
session.disconnect(component);
}
}
@Override
public void packetError (PacketErrorEvent error) {
error.setSuppress(true);
//System.out.println(error);
}
@Override
public void packetReceived (Session session, Packet packet) {
try {
if (packet instanceof ClientboundLoginPacket) this.session.send(
ServerboundPlayerLoadedPacket.INSTANCE
);
if (packet instanceof ServerboundPlayerLoadedPacket) {
System.out.println(packet);
}
for (Listener listener : listenerManager.listeners) {
listener.packetReceived(session, packet);
}
if (packet instanceof ClientboundLoginFinishedPacket) getProfile((ClientboundLoginFinishedPacket) packet);
else if (packet instanceof ClientboundLoginPacket) getEntityId((ClientboundLoginPacket) packet);
} catch (Exception e) {
@Override
public void packetSent (Session session, Packet packet) {
for (Listener listener : listenerManager.listeners) {
listener.packetSent();
}
}
@Override
public void packetError (PacketErrorEvent error) {
error.setSuppress(true);
}
@Override
public void packetReceived (Session session, Packet packet) {
try {
if (packet instanceof ClientboundLoginPacket) this.session.send(
ServerboundPlayerLoadedPacket.INSTANCE
);
if (packet instanceof ServerboundPlayerLoadedPacket) {
System.out.println(packet);
}
for (Listener listener : listenerManager.listeners) {
listener.packetReceived(packet);
}
if (packet instanceof ClientboundLoginFinishedPacket) getProfile((ClientboundLoginFinishedPacket) packet);
else if (packet instanceof ClientboundLoginPacket) getEntityId((ClientboundLoginPacket) packet);
} catch (Exception _) {
}
}
}
public void getProfile (ClientboundLoginFinishedPacket packet) {
profile = packet.getProfile();
public void getProfile (ClientboundLoginFinishedPacket packet) {
profile = packet.getProfile();
loggedIn = true;
}
loggedIn = true;
}
public void getEntityId (ClientboundLoginPacket packet) {
entityId = packet.getEntityId();
}
public void getEntityId (ClientboundLoginPacket packet) {
entityId = packet.getEntityId();
}
@Override
public void disconnected (DisconnectedEvent event) {
listenerManager.clearListener();
@Override
public void disconnected (DisconnectedEvent event) {
loggedIn = false;
Component component = event.getReason();
String reason = ComponentUtil.componentToAnsi(component);
loggedIn = false;
Logger.RECONNECT(this, reason);
Component component = event.getReason();
if (services.get("reconnect") != null) services.get("reconnect").cancel(true);
String reason = ComponentUtil.componentToAnsi(component);
int reconnectDelay = options.reconnectDelay;
Logger.RECONNECT(this, reason);
executor.schedule(() -> {
try {
connect();
} catch (IOException e) {
throw new RuntimeException(e);
}
}, reconnectDelay, TimeUnit.MILLISECONDS);
}
}
services.put(
"reconnect",
executor.schedule(() -> {
try {
connect();
} catch (IOException e) {
throw new RuntimeException(e);
}
}, options.reconnectDelay, TimeUnit.MILLISECONDS)
);
}
}
@@ -3,64 +3,65 @@ package land.chipmunk.parker2991.nitoribot;
import java.util.List;
public class Config {
public List<String> prefixes;
public List<String> prefixes;
public static class Core {
public Area area = new Area();
public String coreName;
}
public static class Core {
public final Area area = new Area();
public String coreName;
}
public static class Area {
public Position start = new Position();
public Position end = new Position();
}
public static class Area {
public final Position start = new Position();
public final Position end = new Position();
}
public static class Position {
public int x = 0;
public int y = 0;
public int z = 0;
}
public static class Position {
public int x;
public int y;
public int z;
}
public static class CommandColors {
public String primary = "blue";
public String secondary = "aqua";
public String tertiary = "dark_aqua";
}
public static class CommandColors {
public String primary;
public String secondary;
public String tertiary;
}
public static class HelpCommandColors {
public String Public = "blue";
public String trusted = "dark_aqua";
public String admin = "aqua";
public String owner = "light_purple";
public String console = "dark_purple";
}
public static class HelpCommandColors {
public String Public;
public String trusted;
public String admin;
public String owner;
public String console;
}
public static class Console {
public String prefix = "c.";
}
public static class Console {
public String prefix;
}
public static class Colors {
public String integer = "gold";
public CommandColors commands = new CommandColors();
public HelpCommandColors help = new HelpCommandColors();
}
public static class Colors {
public String integer;
public final CommandColors commands = new CommandColors();
public final HelpCommandColors help = new HelpCommandColors();
}
public Colors colors = new Colors();
public final Colors colors = new Colors();
public Core core = new Core();
public final Core core = new Core();
public Console console = new Console();
public final Console console = new Console();
public Options[] bots = new Options[]{};
public final Options[] bots = new Options[]{ };
public static class Options {
public String host;
public int port;
public boolean useProxy;
public String serverName;
public String username;
public int reconnectDelay;
public int selfcareInterval;
public String mode;
}
public static class Options {
public String host;
public int port;
public boolean useProxy;
public String serverName;
public String username;
public int reconnectDelay;
public int selfcareInterval;
public String mode;
};
}
@@ -1,6 +1,8 @@
package land.chipmunk.parker2991.nitoribot;
import land.chipmunk.parker2991.nitoribot.boot.*;
import land.chipmunk.parker2991.nitoribot.boot.GetBotBuildInfo;
import land.chipmunk.parker2991.nitoribot.boot.GetRepoInfo;
import land.chipmunk.parker2991.nitoribot.boot.LoadConfig;
import land.chipmunk.parker2991.nitoribot.data.buildstring.BotBuildInfo;
import land.chipmunk.parker2991.nitoribot.data.buildstring.RepoCommitInfo;
import land.chipmunk.parker2991.nitoribot.modules.ConsoleModule;
@@ -10,45 +12,37 @@ import java.util.List;
import java.util.concurrent.*;
public class Main {
public static final ExecutorService executorService = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors()
);
public static final ExecutorService executorService = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors()
);
public static final ExecutorService virtualThreads = Executors.newVirtualThreadPerTaskExecutor();
public static final ExecutorService virtualThreads = Executors.newVirtualThreadPerTaskExecutor();
public static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(
Runtime.getRuntime().availableProcessors()
);
public static final ConcurrentMap<String, Future<?>> services = new ConcurrentHashMap<>();
public static RepoCommitInfo repoCommitInfo = null;
public static BotBuildInfo botBuildInfo = null;
public Config config;
public static final List<Bot> Bots = new ArrayList<>();
public static ConsoleModule console;
public static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(
Runtime.getRuntime().availableProcessors()
);
void main (String[] args) {
try {
config = new LoadConfig().loadConfig();
Config.Options[] bots = config.bots;
public static final ConcurrentMap<String, Future<?>> services = new ConcurrentHashMap<>();
public static RepoCommitInfo repoCommitInfo = null;
public static BotBuildInfo botBuildInfo = null;
public Config config;
public static final List<Bot> Bots = new ArrayList<>();
public static ConsoleModule console;
public void main(String[] args) {
try {
config = new LoadConfig().loadConfig();
Config.Options[] bots = config.bots;
console = new ConsoleModule(config);
repoCommitInfo = new GetRepoInfo().getRepoInfo();
botBuildInfo = new GetBotBuildInfo().getBuildInfo();
for (Config.Options options : bots) {
final Bot bot = new Bot(options, Bots, config);
Bots.add(bot);
}
} catch (Exception e) {
console = new ConsoleModule();
repoCommitInfo = new GetRepoInfo().getRepoInfo();
botBuildInfo = new GetBotBuildInfo().getBuildInfo();
for (Config.Options options : bots) {
final Bot bot = new Bot(options, Bots, config);
Bots.add(bot);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
};
}
@@ -9,14 +9,14 @@ import java.io.Reader;
import java.util.Objects;
public class GetBotBuildInfo {
private static final Gson GSON = new Gson();
private static final Gson GSON = new Gson();
public BotBuildInfo getBuildInfo () {
Reader reader = new InputStreamReader(
Objects.requireNonNull(Main.class
.getResourceAsStream("/info.json"))
);
public BotBuildInfo getBuildInfo () {
Reader reader = new InputStreamReader(
Objects.requireNonNull(Main.class
.getResourceAsStream("/info.json"))
);
return GSON.fromJson(reader, BotBuildInfo.class);
}
return GSON.fromJson(reader, BotBuildInfo.class);
}
}
@@ -11,33 +11,33 @@ import java.util.List;
import java.util.Random;
public class GetProxiesList {
public ProxyInfo randomProxyIp () throws IOException {
Path proxiesPath = Paths.get("proxies.txt");
public ProxyInfo randomProxyIp () throws IOException {
Path proxiesPath = Paths.get("proxies.txt");
int countLines = Math.round(
Files.lines(proxiesPath).count()
);
int countLines = Math.round(
Files.lines(proxiesPath).count()
);
Random random = new Random();
Random random = new Random();
int randomIndex = random.nextInt(countLines);
int randomIndex = random.nextInt(countLines);
List<String> lines = Files.lines(proxiesPath).toList();//.toList();
List<String> lines = Files.lines(proxiesPath).toList();
String[] ip = lines.stream()
.skip(randomIndex)
.findAny()
.get()
.split(":");
String[] ip = lines.stream()
.skip(randomIndex)
.findAny()
.get()
.split(":");
InetSocketAddress address = new InetSocketAddress(
ip[0],
Integer.parseInt(ip[1])
);
InetSocketAddress address = new InetSocketAddress(
ip[0],
Integer.parseInt(ip[1])
);
return new ProxyInfo(
ProxyInfo.Type.SOCKS5,
address
);
}
return new ProxyInfo(
ProxyInfo.Type.SOCKS5,
address
);
}
}
@@ -12,34 +12,34 @@ import java.net.http.HttpResponse;
import java.time.Duration;
public class GetRepoInfo {
private static final Gson GSON = new Gson();
private static final Gson GSON = new Gson();
public RepoCommitInfo getRepoInfo () {
final String repo = "https://code.chipmunk.land/api/v1/repos/Parker2991/NitoriBot/commits?sha=main";
HttpClient client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(20))
.build();
public RepoCommitInfo getRepoInfo () {
final String repo = "https://code.chipmunk.land/api/v1/repos/Parker2991/NitoriBot/commits?sha=main";
HttpClient client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(20))
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(repo))
.timeout(Duration.ofSeconds(20))
.header("accept", "application/json")
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(repo))
.timeout(Duration.ofSeconds(20))
.header("accept", "application/json")
.build();
RepoCommitInfo info = null;
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String body = response.body();
JsonElement e = JsonParser.parseString(response.body());
RepoCommitInfo info = null;
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String body = response.body();
JsonElement e = JsonParser.parseString(response.body());
info = GSON.fromJson(e.getAsJsonArray().get(0), RepoCommitInfo.class);
info = GSON.fromJson(e.getAsJsonArray().get(0), RepoCommitInfo.class);
} catch (Exception e) {
e.printStackTrace(System.err);
} catch (Exception e) {
e.printStackTrace(System.err);
}
return info;
}
return info;
}
}
@@ -13,22 +13,22 @@ import java.nio.file.Files;
import java.nio.file.Path;
public class LoadConfig {
public Config loadConfig () throws IOException {
final Constructor yamlConfig = new Constructor(Config.class, new LoaderOptions());
final Yaml yaml = new Yaml(yamlConfig);
final Path configPath = Path.of("config.yaml");
if (! Files.exists(configPath)) {
public Config loadConfig () throws IOException {
final Constructor yamlConfig = new Constructor(Config.class, new LoaderOptions());
final Yaml yaml = new Yaml(yamlConfig);
final Path configPath = Path.of("config.yaml");
if (! Files.exists(configPath)) {
Logger.INFO(null, "config not found making config now");
Logger.INFO(null, "config not found making config now");
InputStream defaultConfig = Main.class.getClassLoader().getResourceAsStream("default_config.yaml");
Files.copy(defaultConfig, configPath);
InputStream defaultConfig = Main.class.getClassLoader().getResourceAsStream("default_config.yaml");
if (defaultConfig != null) {
Files.copy(defaultConfig, configPath);
}
}
InputStream configFile = Files.newInputStream(configPath);
return yaml.load(configFile);
}
InputStream configFile = Files.newInputStream(configPath);
//config = yaml.load(configFile);
return yaml.load(configFile);
}
}
@@ -1,53 +1,54 @@
package land.chipmunk.parker2991.nitoribot.chatparsers;
import java.util.List;
import land.chipmunk.parker2991.nitoribot.data.chat.*;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.data.PlayerProfileData;
import land.chipmunk.parker2991.nitoribot.data.chat.ParseChatData;
import land.chipmunk.parker2991.nitoribot.data.chat.PlayerMessageData;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import java.util.List;
public class KaboomChatParser implements ParseChatData {
private Bot bot;
private static Component SEPERATOR_COLON = Component.text(":");
private static Component SEPERATOR_COLON_RACCOON = Component.text("\u00a7f:"); // https://github.com/raccoonserver/extras/commit/315f704075db2f00e3e1bfbf55f858469c22880f
private static Component SEPERATOR_SPACE = Component.space();
private final Bot bot;
private static final Component SEPERATOR_COLON = Component.text(":");
private static final Component SEPERATOR_COLON_RACCOON = Component.text("§f:"); // https://github.com/raccoonserver/extras/commit/315f704075db2f00e3e1bfbf55f858469c22880f
private static final Component SEPERATOR_SPACE = Component.space();
public KaboomChatParser (Bot bot) {
this.bot = bot;
}
@Override
public PlayerMessageData parse (Component message) {
if (message instanceof TextComponent) return parse((TextComponent) message);
return null;
}
public PlayerMessageData parse (TextComponent message) {
List<Component> children = message.children();
if (!message.content().equals("") || !message.style().isEmpty() || children == null || children.size() < 3) return null;
final Component prefix = children.get(0);
Component displayName = Component.empty();
Component contents = Component.empty();
if (isSeperatorAt(children, 1)) { // Missing/blank display name
if (children.size() > 3) contents = children.get(3);
} else if (isSeperatorAt(children, 2)) {
displayName = children.get(1);
if (children.size() > 4) contents = children.get(4);
} else {
return null;
public KaboomChatParser (Bot bot) {
this.bot = bot;
}
PlayerProfileData sender = bot.players.getDisplayName(Component.empty().append(prefix).append(displayName));//getSender());
return new PlayerMessageData(sender, contents, "minecraft:chat", displayName);
}
@Override
public PlayerMessageData parse (Component message) {
if (message instanceof TextComponent) return parse((TextComponent) message);
return null;
}
private boolean isSeperatorAt (List<Component> children, int start) {
return (children.get(start).equals(SEPERATOR_COLON) || children.get(start).equals(SEPERATOR_COLON_RACCOON)) && children.get(start + 1).equals(SEPERATOR_SPACE);
}
public PlayerMessageData parse (TextComponent message) {
List<Component> children = message.children();
if (!message.content().isEmpty() || !message.style().isEmpty() || children.size() < 3)
return null;
final Component prefix = children.getFirst();
Component displayName = Component.empty();
Component contents = Component.empty();
if (isSeperatorAt(children, 1)) { // Missing/blank display name
if (children.size() > 3) contents = children.get(3);
} else if (isSeperatorAt(children, 2)) {
displayName = children.get(1);
if (children.size() > 4) contents = children.get(4);
} else {
return null;
}
PlayerProfileData sender = bot.players.getDisplayName(Component.empty().append(prefix).append(displayName));
return new PlayerMessageData(sender, contents, "minecraft:chat", displayName);
}
private boolean isSeperatorAt (List<Component> children, int start) {
return (children.get(start).equals(SEPERATOR_COLON) || children.get(start).equals(SEPERATOR_COLON_RACCOON)) && children.get(start + 1).equals(SEPERATOR_SPACE);
}
}
@@ -1,49 +0,0 @@
package land.chipmunk.parker2991.nitoribot.chatparsers;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.data.chat.ParseChatData;
import land.chipmunk.parker2991.nitoribot.data.chat.PlayerMessageData;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import org.w3c.dom.Text;
import java.util.List;
public class TotalFreedomChatParser implements ParseChatData {
private Bot bot;
public TotalFreedomChatParser (Bot bot) {
this.bot = bot;
}
@Override
public PlayerMessageData parse (Component message) {
if (message instanceof TextComponent) return parse((TextComponent) message);
return null;
}
/*
private boolean isSeperatorAt (List<Component> children, int start) {
return (children.get(start).equals(SEPERATOR_COLON)
|| children.get(start).equals(SEPERATOR_COLON_RACCOON)) && children.get(start + 1).equals(SEPERATOR_SPACE);
}
*/
private boolean isSeperatorAt (List<Component> children, int start) {
return (
children.get(start).equals(">")
||
children.get(start).equals(">")
);
}
public PlayerMessageData parse (TextComponent message) {
String content = message.content();
List<Component> children = message.children();//.toString();
// parsing total freedom chat is fucking horrid bro
for (Component component : children) {
TextComponent textComponent = (TextComponent) component;
//String e = textComponent.toString().split("[");
}
return null;
}
}
@@ -1,57 +0,0 @@
package land.chipmunk.parker2991.nitoribot.command;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.jline.shell.Command;
public class CommandArguments {
private CommandSource source;
private CommandInfo command;
public String[] arguments;
public CommandArguments (
CommandSource source,
CommandInfo command,
String[] arguments
) {
this.source = source;
this.command = command;
this.arguments = arguments;
}
/* public static void getArguments (
CommandSource source,
CommandInfo command,
String[] args
) throws CommandError {
System.out.println(args.length);
if (
args.length > command.maxArguments
) {
throw new CommandError(
Component.translatable(
"Too many arguments, expected %s max not %s",
Component.text(command.maxArguments),
Component.text(args.length)
).color(NamedTextColor.RED)
);
}
if (
args.length < command.minArguments
) {
throw new CommandError(
Component.translatable(
"Expected more than %s arguments recieved %s",
Component.text(command.maxArguments),
Component.text(args.length)
).color(NamedTextColor.RED)
);
}
}*/
//public void checkArgumentType ()
}
@@ -1,22 +1,6 @@
package land.chipmunk.parker2991.nitoribot.command;
import land.chipmunk.parker2991.nitoribot.Bot;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
public class CommandContext {
public Bot bot;
public String[] args;
public CommandSource source;
public CommandInfo commandData;
public CommandContext (Bot bot, String[] args, CommandSource source, CommandInfo commandData) {
this.bot = bot;
this.args = args;
this.source = source;
this.commandData = commandData;
}
public record CommandContext(Bot bot, String[] args, CommandSource source) {
}
@@ -3,14 +3,13 @@ package land.chipmunk.parker2991.nitoribot.command;
import net.kyori.adventure.text.Component;
public class CommandError extends Exception {
public String name = "CommandError";
public Component message;
public final Component message;
public CommandError (Component message) {
this.message = message;
}
public CommandError (Component message) {
this.message = message;
}
public Component message () {
return message;
}
public Component message () {
return message;
}
}
@@ -1,25 +1,25 @@
package land.chipmunk.parker2991.nitoribot.command;
public abstract class CommandInfo {
// probably could make this a record or interface
public String name;
public CommandTrustLevels trustlevel;
public String[] aliases;
public String description;
// probably could make this a record or interface
public final String name;
public final CommandTrustLevels trustlevel;
public final String[] aliases;
public final String description;
public CommandInfo (
String name,
CommandTrustLevels trustlevel,
String[] aliases,
String description
) {
this.name = name;
this.trustlevel = trustlevel;
this.aliases = aliases;
this.description = description;
}
public CommandInfo (
String name,
CommandTrustLevels trustlevel,
String[] aliases,
String description
) {
this.name = name;
this.trustlevel = trustlevel;
this.aliases = aliases;
this.description = description;
}
public abstract void execute (CommandContext context);
public abstract void execute (CommandContext context);
}
@@ -1,32 +1,29 @@
package land.chipmunk.parker2991.nitoribot.command;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.data.ParsedChatType;
import land.chipmunk.parker2991.nitoribot.data.PlayerProfileData;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
import net.kyori.adventure.text.Component;
import org.cloudburstmc.math.vector.Vector3d;
public class CommandSource {
private Bot bot;
private final Bot bot;
public PlayerProfileData sender;
public final PlayerProfileData sender;
public boolean inGame;
public boolean inGame;
public ParsedChatType parsedChatType;
public final ParsedChatType parsedChatType;
public CommandSource (Bot bot, ParsedChatType parsedChatType, PlayerProfileData sender) {
this.bot = bot;
this.parsedChatType = parsedChatType;
this.sender = sender;
}
public CommandSource (Bot bot, ParsedChatType parsedChatType, PlayerProfileData sender) {
this.bot = bot;
this.parsedChatType = parsedChatType;
this.sender = sender;
}
public void sendFeedback (Component message) {
String convertToJson = ComponentUtil.componentToJSON(message);
//Vector3d playerPos = sender.position.position();
public void sendFeedback (Component message) {
String convertToJson = ComponentUtil.componentToJSON(message);
//Vector3d playerPos = sender.position.position();
/* String formatCommand = String.format(
"minecraft:summon text_display %s %s %s {tag:[%s], text:%s}",
@@ -37,15 +34,15 @@ public class CommandSource {
convertToJson
);*/
String selector = String.format(
"@p[nbt={UUID:%s}]",
sender.entityUUID
);
String selector = String.format(
"@p[nbt={UUID:%s}]",
sender.entityUUID()
);
//System.out.println(sender.profile.getName());
//System.out.println(sender.profile.getName());
if (this.parsedChatType == ParsedChatType.NORMAL) bot.chat.tellraw("@a", message);
else bot.chat.tellraw(selector, message);
}
if (this.parsedChatType == ParsedChatType.NORMAL) bot.chat.tellraw("@a", message);
else bot.chat.tellraw(selector, message);
}
}
@@ -1,10 +1,10 @@
package land.chipmunk.parker2991.nitoribot.command;
public enum CommandTrustLevels {
PUBLIC,
TRUSTED,
ADMIN,
OWNER,
CONSOLE,
DISABLED
PUBLIC,
TRUSTED,
ADMIN,
OWNER,
CONSOLE,
DISABLED
}
@@ -6,23 +6,23 @@ import land.chipmunk.parker2991.nitoribot.command.CommandInfo;
import land.chipmunk.parker2991.nitoribot.command.CommandTrustLevels;
public class EchoCommand extends CommandInfo {
public EchoCommand () {
super(
"echo",
CommandTrustLevels.PUBLIC,
new String[]{ "say" },
"make the bot say a message"
);
}
@Override
public void execute (CommandContext context) {
Bot bot = context.bot;
String args = String.join(" ", context.args);
if (args.startsWith("/")) {
bot.chat.command(args.substring("/".length()));
} else {
bot.chat.message(args);
public EchoCommand () {
super(
"echo",
CommandTrustLevels.PUBLIC,
new String[]{ "say" },
"make the bot say a message"
);
}
@Override
public void execute (CommandContext context) {
Bot bot = context.bot();
String args = String.join(" ", context.args());
if (args.startsWith("/")) {
bot.chat.command(args.substring("/".length()));
} else {
bot.chat.message(args);
}
}
}
}
@@ -2,154 +2,147 @@ package land.chipmunk.parker2991.nitoribot.commands.Public;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.Config;
import land.chipmunk.parker2991.nitoribot.command.*;
import land.chipmunk.parker2991.nitoribot.command.CommandContext;
import land.chipmunk.parker2991.nitoribot.command.CommandInfo;
import land.chipmunk.parker2991.nitoribot.command.CommandSource;
import land.chipmunk.parker2991.nitoribot.command.CommandTrustLevels;
import land.chipmunk.parker2991.nitoribot.util.TranslationsUtil;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.TranslatableComponent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.JoinConfiguration;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.format.NamedTextColor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class HelpCommand extends CommandInfo {
public HelpCommand () {
super(
"help",
CommandTrustLevels.PUBLIC,
new String[]{ "heko", "hell", "?", "cmds" },
"see the list of commands"
);
}
public Component getCommands (Bot bot) {
List<Component> commandlist = new ArrayList<>();
List<Component> Public = new ArrayList<>();
List<Component> Trusted = new ArrayList<>();
List<Component> Admin = new ArrayList<>();
List<Component> Owner = new ArrayList<>();
for (CommandInfo commands : bot.commandManager.commands) {
switch (commands.trustlevel) {
case CommandTrustLevels.PUBLIC:
Public.add(
Component.text(commands.name + " ").color(NamedTextColor.BLUE)
);
break;
case CommandTrustLevels.TRUSTED:
Trusted.add(
Component.text(commands.name + " ").color(NamedTextColor.DARK_AQUA)
);
break;
}
public HelpCommand () {
super(
"help",
CommandTrustLevels.PUBLIC,
new String[]{ "heko", "hell", "?", "cmds" },
"see the list of commands"
);
}
Component component = Component.empty()
.append(Public)
.append(Component.text("\n"))
.append(Trusted);
// .append(Component.text("\n"));
return component;
}
public Component getCommands (Bot bot) {
List<Component> Public = new ArrayList<>();
List<Component> Trusted = new ArrayList<>();
private Component getCommand (Bot bot, String[] command) {
List<Component> list = new ArrayList<>();
for (CommandInfo commands : bot.commandManager.commands) {
switch (commands.trustlevel) {
case CommandTrustLevels.PUBLIC:
Public.add(
Component.text(commands.name + " ").color(NamedTextColor.BLUE)
);
break;
case CommandTrustLevels.TRUSTED:
Trusted.add(
Component.text(commands.name + " ").color(NamedTextColor.DARK_AQUA)
);
break;
}
}
Component component = null;
// .append(Component.text("\n"));
for (CommandInfo commands : bot.commandManager.commands) {
for (String aliases : commands.aliases) {
if (commands.name.equals(command[0]) || aliases.equals(command[0])) component = Component.empty()
.append(
TranslationsUtil.customTranslations(
"command.help.info.layout",
List.of(
TranslationsUtil.customTranslations("command.help.info.command", null).color(NamedTextColor.BLUE),
Component.text(commands.name).color(NamedTextColor.AQUA)
)
)
)
.append(
TranslationsUtil.customTranslations(
"command.help.info.layout",
List.of(
TranslationsUtil.customTranslations("command.help.info.aliases", null).color(NamedTextColor.BLUE),
Component.text(Arrays.toString(commands.aliases)).color(NamedTextColor.AQUA)
)
)
)
.append(
TranslationsUtil.customTranslations(
"command.help.info.layout",
List.of(
TranslationsUtil.customTranslations("command.help.info.description", null).color(NamedTextColor.BLUE),
Component.text(commands.description).color(NamedTextColor.AQUA)
)
)
)
.append(
TranslationsUtil.customTranslations(
"command.help.info.layout",
List.of(
TranslationsUtil.customTranslations("command.help.info.trust_level", null).color(NamedTextColor.BLUE),
Component.text(commands.trustlevel + "").color(NamedTextColor.AQUA)
)
)
)
.append(
TranslationsUtil.customTranslations(
"command.help.info.layout",
List.of(
TranslationsUtil.customTranslations("command.help.info.usages", null).color(NamedTextColor.BLUE),
Component.text("DUMMY String").color(NamedTextColor.AQUA)
)
)
);
}
}
return component;
}
@Override
public void execute (CommandContext context) {
Bot bot = context.bot;
String[] args = context.args;
CommandSource source = context.source;
Config config = bot.config;
Config.Colors colors = config.colors;
List<Component> list = new ArrayList<>();
if (args.length != 0) {
source.sendFeedback(getCommand(bot, args));
return;
return Component.empty()
.append(Public)
.append(Component.text("\n"))
.append(Trusted);
}
list = List.of(
Component.text("Commands").color(NamedTextColor.NAMES.value(colors.commands.primary)),
Component.text(bot.commandManager.commands.size()).color(NamedTextColor.NAMES.value(colors.integer)),
TranslationsUtil.customTranslations("command.help.trust_level.public", null).color(NamedTextColor.NAMES.value(colors.help.Public)),
TranslationsUtil.customTranslations("command.help.trust_level.trusted", null).color(NamedTextColor.NAMES.value(colors.help.trusted)),
TranslationsUtil.customTranslations("command.help.trust_level.admin", null).color(NamedTextColor.NAMES.value(colors.help.admin)),
TranslationsUtil.customTranslations("command.help.trust_level.owner", null).color(NamedTextColor.NAMES.value(colors.help.owner))
);
private Component getCommand (Bot bot, String[] command) {
Component helpLayout = TranslationsUtil.customTranslations(
"command.help.layout",
list
);
Component component = null;
Component component = Component.empty()
.append(helpLayout)
.append(Component.join(JoinConfiguration.separator(Component.space()), getCommands(bot)));
for (CommandInfo commands : bot.commandManager.commands) {
for (String aliases : commands.aliases) {
if (commands.name.equals(command[0]) || aliases.equals(command[0])) component = Component.empty()
.append(
TranslationsUtil.customTranslations(
"command.help.info.layout",
List.of(
TranslationsUtil.customTranslations("command.help.info.command", null).color(NamedTextColor.BLUE),
Component.text(commands.name).color(NamedTextColor.AQUA)
)
)
)
.append(
TranslationsUtil.customTranslations(
"command.help.info.layout",
List.of(
TranslationsUtil.customTranslations("command.help.info.aliases", null).color(NamedTextColor.BLUE),
Component.text(Arrays.toString(commands.aliases)).color(NamedTextColor.AQUA)
)
)
)
.append(
TranslationsUtil.customTranslations(
"command.help.info.layout",
List.of(
TranslationsUtil.customTranslations("command.help.info.description", null).color(NamedTextColor.BLUE),
Component.text(commands.description).color(NamedTextColor.AQUA)
)
)
)
.append(
TranslationsUtil.customTranslations(
"command.help.info.layout",
List.of(
TranslationsUtil.customTranslations("command.help.info.trust_level", null).color(NamedTextColor.BLUE),
Component.text(commands.trustlevel + "").color(NamedTextColor.AQUA)
)
)
)
.append(
TranslationsUtil.customTranslations(
"command.help.info.layout",
List.of(
TranslationsUtil.customTranslations("command.help.info.usages", null).color(NamedTextColor.BLUE),
Component.text("DUMMY String").color(NamedTextColor.AQUA)
)
)
);
}
}
return component;
}
source.sendFeedback(component);
}
@Override
public void execute (CommandContext context) {
Bot bot = context.bot();
String[] args = context.args();
CommandSource source = context.source();
Config config = bot.config;
Config.Colors colors;
colors = config.colors;
List<Component> list;
if (args.length != 0) {
source.sendFeedback(getCommand(bot, args));
return;
}
list = List.of(
Component.text("Commands").color(NamedTextColor.NAMES.value(colors.commands.primary)),
Component.text(bot.commandManager.commands.size()).color(NamedTextColor.NAMES.value(colors.integer)),
TranslationsUtil.customTranslations("command.help.trust_level.public", null).color(NamedTextColor.NAMES.value(colors.help.Public)),
TranslationsUtil.customTranslations("command.help.trust_level.trusted", null).color(NamedTextColor.NAMES.value(colors.help.trusted)),
TranslationsUtil.customTranslations("command.help.trust_level.admin", null).color(NamedTextColor.NAMES.value(colors.help.admin)),
TranslationsUtil.customTranslations("command.help.trust_level.owner", null).color(NamedTextColor.NAMES.value(colors.help.owner))
);
Component helpLayout = TranslationsUtil.customTranslations(
"command.help.layout",
list
);
Component component = Component.empty()
.append(helpLayout)
.append(Component.join(JoinConfiguration.separator(Component.space()), getCommands(bot)));
source.sendFeedback(component);
}
}
@@ -18,32 +18,32 @@ import java.util.jar.Attributes;
import java.util.jar.Manifest;
public class InfoCommand extends CommandInfo {
public InfoCommand () throws IOException {
super(
"info",
CommandTrustLevels.PUBLIC,
new String[]{ "information" },
"information about the bot"
);
}
public InfoCommand () throws IOException {
super(
"info",
CommandTrustLevels.PUBLIC,
new String[]{ "information" },
"information about the bot"
);
}
private final Enumeration<URL> resources = InfoCommand.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
private final Enumeration<URL> resources = InfoCommand.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
private final Manifest manifest = new Manifest(resources.nextElement().openStream());
private final Manifest manifest = new Manifest(resources.nextElement().openStream());
private final Attributes attributes = manifest.getMainAttributes();
private final Attributes attributes = manifest.getMainAttributes();
private final String buildTime = attributes.getValue("Build-Time");
private final String buildTime = attributes.getValue("Build-Time");
@Override
public void execute (CommandContext context) {
var bot = context.bot;
@Override
public void execute (CommandContext context) {
var bot = context.bot();
var source = context.source;
var source = context.source();
var args = context.args;
var args = context.args();
Component component = null;
Component component = null;
/*
Build: 3355
Repo Build: 242
@@ -51,49 +51,47 @@ Version Release Date: 10/22/2025, 11:24:04 AM
Commit: fcbd9f983c
11/22/22-9/10/2026
*/
GsonComponentSerializer gson = GsonComponentSerializer.gson();
GsonComponentSerializer gson = GsonComponentSerializer.gson();
switch (args[0].toLowerCase()) {
case "loaded" -> {
component = Component.translatable(
"%s: %s\n%s: %s\n%s: %s",
Component.text("Modules").color(NamedTextColor.BLUE),
Component.text(bot.modules.size()).color(NamedTextColor.GOLD),
Component.text("Commands").color(NamedTextColor.BLUE),
Component.text(bot.commandManager.commands.size()).color(NamedTextColor.GOLD),
Component.text("Chat Parsers").color(NamedTextColor.BLUE),
Component.text(bot.chat.chatParsers.size()).color(NamedTextColor.GOLD)
);
}
switch (args[0].toLowerCase()) {
case "loaded" -> component = Component.translatable(
"%s: %s\n%s: %s\n%s: %s",
Component.text("Modules").color(NamedTextColor.BLUE),
Component.text(bot.modules.size()).color(NamedTextColor.GOLD),
Component.text("Commands").color(NamedTextColor.BLUE),
Component.text(bot.commandManager.commands.size()).color(NamedTextColor.GOLD),
Component.text("Chat Parsers").color(NamedTextColor.BLUE),
Component.text(bot.chat.chatParsers.size()).color(NamedTextColor.GOLD)
);
case "version" -> {
BotBuildInfo info = bot.botBuildInfo;
case "version" -> {
BotBuildInfo info = bot.botBuildInfo;
RepoCommitInfo repoCommitInfo = bot.repoCommitInfo;
RepoCommitInfo repoCommitInfo = bot.repoCommitInfo;
ZonedDateTime dateTime = ZonedDateTime.parse(repoCommitInfo.created);
ZonedDateTime dateTime = ZonedDateTime.parse(repoCommitInfo.created);
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MMMM dd, yyyy hh:mm:ss a");
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MMMM dd, yyyy hh:mm:ss a");
component = Component.translatable(
"%s-%s-%s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s",
gson.deserialize(info.buildstring.botName.toString()),
Component.text(info.buildstring.version).color(NamedTextColor.AQUA),
gson.deserialize(info.buildstring.codename.toString()),
Component.text("Build").color(NamedTextColor.BLUE),
Component.text(info.buildstring.build).color(NamedTextColor.YELLOW),
Component.text("Commit").color(NamedTextColor.BLUE),
Component.text(repoCommitInfo.sha.substring(0, 8)).color(NamedTextColor.DARK_BLUE),
Component.text("Version release Date").color(NamedTextColor.BLUE),
Component.text(dateTime.format(dateTimeFormatter)).color(NamedTextColor.DARK_BLUE),
Component.text("Initial Bot Release").color(NamedTextColor.BLUE),
Component.text(info.buildstring.initialBotRelease).color(NamedTextColor.DARK_BLUE),
Component.text("Jar Compile Date").color(NamedTextColor.BLUE),
Component.text(buildTime).color(NamedTextColor.DARK_BLUE)
).color(NamedTextColor.GRAY);
}
component = Component.translatable(
"%s-%s-%s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s",
gson.deserialize(info.buildstring.botName.toString()),
Component.text(info.buildstring.version).color(NamedTextColor.AQUA),
gson.deserialize(info.buildstring.codename.toString()),
Component.text("Build").color(NamedTextColor.BLUE),
Component.text(info.buildstring.build).color(NamedTextColor.YELLOW),
Component.text("Commit").color(NamedTextColor.BLUE),
Component.text(repoCommitInfo.sha.substring(0, 8)).color(NamedTextColor.DARK_BLUE),
Component.text("Version release Date").color(NamedTextColor.BLUE),
Component.text(dateTime.format(dateTimeFormatter)).color(NamedTextColor.DARK_BLUE),
Component.text("Initial Bot Release").color(NamedTextColor.BLUE),
Component.text(info.buildstring.initialBotRelease).color(NamedTextColor.DARK_BLUE),
Component.text("Jar Compile Date").color(NamedTextColor.BLUE),
Component.text(buildTime).color(NamedTextColor.DARK_BLUE)
).color(NamedTextColor.GRAY);
}
}
source.sendFeedback(component);
}
source.sendFeedback(component);
}
}
@@ -3,30 +3,28 @@ package land.chipmunk.parker2991.nitoribot.commands.Public;
import land.chipmunk.parker2991.nitoribot.command.CommandContext;
import land.chipmunk.parker2991.nitoribot.command.CommandInfo;
import land.chipmunk.parker2991.nitoribot.command.CommandTrustLevels;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
public class MCServerCommand extends CommandInfo {
public MCServerCommand () {
super(
"mcserver",
CommandTrustLevels.PUBLIC,
new String[] { "minecraftserver" },
"ping a minecraft server"
);
}
public MCServerCommand () {
super(
"mcserver",
CommandTrustLevels.PUBLIC,
new String[]{ "minecraftserver" },
"ping a minecraft server"
);
}
@Override
public void execute (CommandContext context) {
var bot = context.bot;
var source = context.source;
String args = String.join(" ", context.args);
@Override
public void execute (CommandContext context) {
var bot = context.bot();
var source = context.source();
String args = String.join(" ", context.args());
var ip = args.split(":");
var ip = args.split(":");
var info = bot.mcServer.pingServer(ip);
var info = bot.mcServer.pingServer(ip);
System.out.println(info);
System.out.println(info);
/*source.sendFeedback(
Component.translatable(
@@ -46,8 +44,8 @@ public class MCServerCommand extends CommandInfo {
)
);*/
//source.sendFeedback(info.description());
}
//source.sendFeedback(info.description());
}
}
/*
[logs] [System Chat] Ip: kaboom.pw:25565
@@ -9,22 +9,22 @@ import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
public class RCCommand extends CommandInfo {
public RCCommand () {
super(
"rc",
CommandTrustLevels.PUBLIC,
new String[] { "refill", "refillcore" },
"refill the bot's core"
);
}
public RCCommand () {
super(
"rc",
CommandTrustLevels.PUBLIC,
new String[]{ "refill", "refillcore" },
"refill the bot's core"
);
}
@Override
public void execute (CommandContext context) {
Bot bot = context.bot;
CommandSource source = context.source;
@Override
public void execute (CommandContext context) {
Bot bot = context.bot();
CommandSource source = context.source();
bot.core.move();
bot.core.move();
source.sendFeedback(Component.text("Refilling core").color(NamedTextColor.BLUE));
}
source.sendFeedback(Component.text("Refilling core").color(NamedTextColor.BLUE));
}
}
@@ -14,40 +14,39 @@ it also makes the JSON so fucking big especially with gradients
this does remind me of how i did component.push shit in the JS build of my bot aka v8.0.0-Reignite
*/
public class TestCommand extends CommandInfo {
public TestCommand () {
super(
"test",
CommandTrustLevels.PUBLIC,
new String[]{ "t" },
"testing shit"
);
}
public TestCommand () {
super(
"test",
CommandTrustLevels.PUBLIC,
new String[]{ "t" },
"testing shit"
);
}
private static final MiniMessage MINI_MESSAGE = MiniMessage.miniMessage();
private static final MiniMessage MINI_MESSAGE = MiniMessage.miniMessage();
@Override
public void execute (CommandContext context) {
var bot = context.bot;
@Override
public void execute (CommandContext context) {
var args = String.join(" ", context.args);
var args = String.join(" ", context.args());
var source = context.source;
var source = context.source();
var component = MINI_MESSAGE.deserialize(
String.format(
"%s%s %s %s %s %s %s%s%s",
"<gradient:dark_aqua:aqua:blue:dark_blue:light_purple:dark_purple>", // gradient shenanigans
"Hello World! User:",
source.sender.profile.getName(),
"UUID:",
source.sender.uuid,
"Args:",
"<rainbow>", // we gotta turn the arguments gay!
args,
"</gradient>"
)
);
var component = MINI_MESSAGE.deserialize(
String.format(
"%s%s %s %s %s %s %s%s%s",
"<gradient:dark_aqua:aqua:blue:dark_blue:light_purple:dark_purple>", // gradient shenanigans
"Hello World! User:",
source.sender.profile().getName(),
"UUID:",
source.sender.uuid(),
"Args:",
"<rainbow>", // we gotta turn the arguments gay!
args,
"</gradient>"
)
);
source.sendFeedback(component);
}
source.sendFeedback(component);
}
}
@@ -1,21 +1,24 @@
package land.chipmunk.parker2991.nitoribot.commands.trusted;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.command.*;
import land.chipmunk.parker2991.nitoribot.command.CommandContext;
import land.chipmunk.parker2991.nitoribot.command.CommandInfo;
import land.chipmunk.parker2991.nitoribot.command.CommandTrustLevels;
public class ReconnectCommand extends CommandInfo {
public ReconnectCommand () {
super(
"reconnect",
CommandTrustLevels.TRUSTED,
new String[] { },
"reconnect the bot"
);
}
public ReconnectCommand () {
super(
"reconnect",
CommandTrustLevels.TRUSTED,
new String[]{ },
"reconnect the bot"
);
}
@Override
public void execute (CommandContext context) {
Bot bot = context.bot;
@Override
public void execute (CommandContext context) {
Bot bot = context.bot();
bot.session.disconnect("Reconnect Command");
}
bot.session.disconnect("Reconnect Command");
}
}
@@ -1,7 +1,7 @@
package land.chipmunk.parker2991.nitoribot.data;
public enum ChatType {
PLAYER,
SYSTEM,
DISGUISED
PLAYER,
SYSTEM,
DISGUISED
}
@@ -1,12 +1,6 @@
package land.chipmunk.parker2991.nitoribot.data;
import org.cloudburstmc.math.vector.Vector3i;
public class CommandCoreAreaData {
public Vector3i start;
public Vector3i end;
import org.cloudburstmc.math.vector.Vector3d;
public CommandCoreAreaData (Vector3i start, Vector3i end) {
this.start = start;
this.end = end;
}
public record CommandCoreAreaData(Vector3d start, Vector3d end) {
}
@@ -1,6 +1,6 @@
package land.chipmunk.parker2991.nitoribot.data;
public enum ParsedChatType {
COMMANDSPY,
NORMAL
COMMANDSPY,
NORMAL
}
@@ -2,15 +2,15 @@ package land.chipmunk.parker2991.nitoribot.data;
import net.kyori.adventure.text.Component;
public record PingServerData (
//String ip,
//int port,
String versionName,
long protocolVersion,
int playersOnline,
int maxPlayers,
Component description
//long latency
public record PingServerData(
//String ip,
//int port,
String versionName,
long protocolVersion,
int playersOnline,
int maxPlayers,
Component description
//long latency
) {
public void latency (long pingTime) { System.out.println(versionName); }
public void latency (long pingTime) {System.out.println(versionName);}
}
@@ -1,5 +0,0 @@
package land.chipmunk.parker2991.nitoribot.data;
import org.cloudburstmc.math.vector.Vector3d;
public record PlayerPositionData (float pitch, float yaw, Vector3d position) {}
@@ -1,42 +1,42 @@
package land.chipmunk.parker2991.nitoribot.data;
import land.chipmunk.parker2991.nitoribot.util.UUIDUtil;
import net.kyori.adventure.text.Component;
import org.geysermc.mcprotocollib.auth.GameProfile;
import org.geysermc.mcprotocollib.protocol.data.game.entity.player.GameMode;
import org.jspecify.annotations.Nullable;
import org.jetbrains.annotations.Nullable;
import java.util.UUID;
@Nullable
public class PlayerProfileData {
public UUID uuid;
public String entityUUID;
public final GameProfile profile;
public boolean listed;
public int latency;
public GameMode gameMode;
public Component displayName;
public boolean showHat;
public int listOrder;
public PlayerPositionData position;
public int entityId;
public String dimension;
public PlayerProfileData (
public record PlayerProfileData(
UUID uuid,
String entityUUID,
GameProfile profile,
boolean listed,
int latency,
GameMode gameMode,
Component displayName
) {
this.uuid = uuid;
this.entityUUID = UUIDUtil.snbt(uuid);
this.profile = profile;
this.listed = listed;
this.latency = latency;
this.gameMode = gameMode;
this.displayName = displayName;
}
Component displayName,
boolean showHat,
int listOrder,
PositionData position,
String dimension,
Integer entityId
) {
public void listed (boolean listed) {
}
public void gameMode (GameMode gameMode) {
}
public void latency (int latency) {
}
public void position (PositionData position) {
}
public void displayName (@Nullable Component displayName) {
}
public void entityId (int entityId) {
}
}
@@ -1,3 +1,6 @@
package land.chipmunk.parker2991.nitoribot.data;
public record PositionData (int x, int y, int z) {}
import org.cloudburstmc.math.vector.Vector3d;
public record PositionData(float pitch, float yaw, Vector3d position) {
}
@@ -5,23 +5,23 @@ import com.google.gson.JsonObject;
import java.util.List;
public class BotBuildInfo {
public static class BuildInfo {
public List<JsonObject> botName;
public String version;
public List<JsonObject> codename;
public String build;
public String versionReleaseDate;
public String initialBotRelease;
}
public static class BuildInfo {
public List<JsonObject> botName;
public String version;
public List<JsonObject> codename;
public String build;
public String versionReleaseDate;
public String initialBotRelease;
}
public BuildInfo buildstring = new BuildInfo();
public final BuildInfo buildstring = new BuildInfo();
public String owner;
public String owner;
public static class Contributors {
public String name;
public String reason;
}
public static class Contributors {
public String name;
public String reason;
}
public Contributors[] contributors = new Contributors[]{};
public Contributors[] contributors = new Contributors[]{ };
}
@@ -1,9 +1,9 @@
package land.chipmunk.parker2991.nitoribot.data.buildstring;
public class RepoCommitInfo {
public String sha;
public String sha;
public String created;
public String created;
public int commits;
public int commits;
}
@@ -3,5 +3,5 @@ package land.chipmunk.parker2991.nitoribot.data.chat;
import net.kyori.adventure.text.Component;
public interface ParseChatData {
PlayerMessageData parse (Component message);
PlayerMessageData parse (Component message);
}
@@ -1,20 +1,12 @@
package land.chipmunk.parker2991.nitoribot.data.chat;
import land.chipmunk.parker2991.nitoribot.data.PlayerProfileData;
import net.kyori.adventure.text.Component;
import land.chipmunk.parker2991.nitoribot.data.PlayerProfileData;
public class PlayerMessageData {
public PlayerProfileData sender;
public Component contents;
public String chatType;
public Component senderName;
public PlayerMessageData(PlayerProfileData sender, Component contents, String chatType, Component senderName) {
this.sender = sender;
this.contents = contents;
this.chatType = chatType;
this.senderName = senderName;
// return this;
}
}
public record PlayerMessageData(
PlayerProfileData sender,
Component contents,
String chatType,
Component senderName
) {
}
@@ -1,30 +1,24 @@
package land.chipmunk.parker2991.nitoribot.listeners;
import land.chipmunk.code.kaboomstandardsorganization.messaginglib.mcprotocollib.MCProtocolLibMessenger;
import land.chipmunk.parker2991.nitoribot.data.PlayerProfileData;
import land.chipmunk.parker2991.nitoribot.data.chat.PlayerMessageData;
import net.kyori.adventure.text.Component;
import org.geysermc.mcprotocollib.network.Session;
import org.geysermc.mcprotocollib.network.packet.Packet;
public class Listener {
public void packetSent (Session session, Packet packet) {}
public void packetSent () {}
public void packetReceived (Session session, Packet packet) {}
public void packetReceived (Packet packet) {}
public void extrasMessagingReceived (MCProtocolLibMessenger messenger) {}
public void playerChatReceived (Component message) {}
public void chatAttestationMessageReceived () {}
public void disguisedChatReceived (Component message) {}
public void playerChatReceived (Component message) {}
public void systemChatReceived (Component message) {}
public void disguisedChatReceived (Component message) {}
public void parsedMessage (PlayerMessageData data) {}
public void systemChatReceived (Component message) {}
public void botMoved () {}
public void parsedMessage (Component message, PlayerMessageData data) {}
public void botMoved () {}
public void commandSpyReceived (PlayerProfileData player, String command) {}
public void commandSpyReceived (PlayerProfileData player, String command) {}
}
@@ -4,17 +4,17 @@ import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class ListenerManager {
public final List<Listener> listeners = new CopyOnWriteArrayList<>();
public final List<Listener> listeners = new CopyOnWriteArrayList<>();
public void addListener (Listener listener) {
listeners.add(listener);
}
public void addListener (Listener listener) {
listeners.add(listener);
}
public void removeListener (Listener listener) {
listeners.remove(listener);
}
public void removeListener (Listener listener) {
listeners.remove(listener);
}
public void clearListener () {
listeners.clear();
}
public void clearListener () {
listeners.clear();
}
}
@@ -3,124 +3,121 @@ package land.chipmunk.parker2991.nitoribot.logger;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.Main;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Logger {
private final DateTimeFormatter formatTime = DateTimeFormatter.ofPattern("hh:mm:ss");
private final DateTimeFormatter formatTime = DateTimeFormatter.ofPattern("hh:mm:ss");
private final DateTimeFormatter formatDate = DateTimeFormatter.ofPattern("MM/dd/yyyy");
private final DateTimeFormatter formatDate = DateTimeFormatter.ofPattern("MM/dd/yyyy");
public Component getLoggerType (LoggerType type) {
Component logType = null;
switch (type) {
case LoggerType.LOG -> logType = Component.text("LOG").color(NamedTextColor.GOLD);
case LoggerType.COMMAND -> logType = Component.text("COMMAND").color(NamedTextColor.GREEN);
case LoggerType.ERROR -> logType = Component.text("ERROR").color(NamedTextColor.DARK_RED);
case LoggerType.WARN -> logType = Component.text("WARN").color(NamedTextColor.YELLOW);
case LoggerType.INFO -> logType = Component.text("INFO").color(NamedTextColor.DARK_GREEN);
case LoggerType.RECONNECT -> logType = Component.text("RECONNECT").color(NamedTextColor.AQUA);
case LoggerType.DEBUG -> logType = Component.text("DEBUG").color(NamedTextColor.GOLD);
public Component getLoggerType (LoggerType type) {
Component logType = null;
switch (type) {
case LoggerType.LOG -> logType = Component.text("LOG").color(NamedTextColor.GOLD);
case LoggerType.COMMAND -> logType = Component.text("COMMAND").color(NamedTextColor.GREEN);
case LoggerType.ERROR -> logType = Component.text("ERROR").color(NamedTextColor.DARK_RED);
case LoggerType.WARN -> logType = Component.text("WARN").color(NamedTextColor.YELLOW);
case LoggerType.INFO -> logType = Component.text("INFO").color(NamedTextColor.DARK_GREEN);
case LoggerType.RECONNECT -> logType = Component.text("RECONNECT").color(NamedTextColor.AQUA);
case LoggerType.DEBUG -> logType = Component.text("DEBUG").color(NamedTextColor.GOLD);
}
return logType;
}
private void prefix (LoggerType loggerType, @Nullable Bot bot, String message) {
Component component;
Component host;
return logType;
}
ZoneId timezone = ZoneId.of("America/Chicago");
ZonedDateTime zoneDate = ZonedDateTime.now(timezone);
LocalDate date = zoneDate.toLocalDate();
LocalTime time = zoneDate.toLocalTime();
private void prefix (LoggerType loggerType, Bot bot, String message) {
Component component = null;
Component host = null;
Component type = getLoggerType(loggerType);
ZoneId timezone = ZoneId.of("America/Chicago");
ZonedDateTime zoneDate = ZonedDateTime.now(timezone);
LocalDate date = zoneDate.toLocalDate();
LocalTime time = zoneDate.toLocalTime();
if (bot == null) host = Component.text("NitoriBot Jar").color(NamedTextColor.BLUE);
else host = Component.text(bot.options.host + ":" + bot.options.port).color(NamedTextColor.BLUE);
Component type = getLoggerType(loggerType);
component = Component.translatable(
"[%s %s %s] [%s] [%s] %s",
Component.translatable(formatTime.format(time)).color(NamedTextColor.BLUE),
Component.translatable(formatDate.format(date)).color(NamedTextColor.BLUE),
type,
Component.translatable(Thread.currentThread().getName()).color(NamedTextColor.BLUE),
host,
Component.translatable(message).color(NamedTextColor.WHITE)
).color(NamedTextColor.DARK_BLUE);
if (bot == null) host = Component.text("NitoriBot Jar").color(NamedTextColor.BLUE);
host = Component.text(bot.options.host + ":" + bot.options.port).color(NamedTextColor.BLUE);
String log = ComponentUtil.componentToAnsi(component);
component = Component.translatable(
"[%s %s %s] [%s] [%s] %s",
Component.translatable(formatTime.format(time)).color(NamedTextColor.BLUE),
Component.translatable(formatDate.format(date)).color(NamedTextColor.BLUE),
type,
Component.translatable(Thread.currentThread().getName()).color(NamedTextColor.BLUE),
host,
Component.translatable(message).color(NamedTextColor.WHITE)
).color(NamedTextColor.DARK_BLUE);
Main.console.reader.printAbove(log);
}
String log = ComponentUtil.componentToAnsi(component);
public static void LOG (Bot bot, String message) {
new Logger().prefix(
LoggerType.LOG,
bot,
message
);
}
if (bot == null) System.out.println(log);
else Main.console.reader.printAbove(log);
}
public static void DEBUG (Bot bot, String message) {
new Logger().prefix(
LoggerType.DEBUG,
bot,
message
);
}
public static void LOG (Bot bot, String message) {
new Logger().prefix(
LoggerType.LOG,
bot,
message
);
}
public static void ERROR (Bot bot, String message) {
new Logger().prefix(
LoggerType.ERROR,
bot,
message
);
}
public static void DEBUG (Bot bot, String message) {
new Logger().prefix(
LoggerType.DEBUG,
bot,
message
);
}
public static void WARN (Bot bot, String message) {
new Logger().prefix(
LoggerType.WARN,
bot,
message
);
}
public static void ERROR (Bot bot, String message) {
new Logger().prefix(
LoggerType.ERROR,
bot,
message
);
}
public static void COMMAND (Bot bot, String message) {
new Logger().prefix(
LoggerType.COMMAND,
bot,
message
);
}
public static void WARN (Bot bot, String message) {
new Logger().prefix(
LoggerType.WARN,
bot,
message
);
}
public static void RECONNECT (Bot bot, String message) {
new Logger().prefix(
LoggerType.RECONNECT,
bot,
message
);
}
public static void COMMAND (Bot bot, String message) {
new Logger().prefix(
LoggerType.COMMAND,
bot,
message
);
}
public static void INFO (Bot bot, String message) {
new Logger().prefix(
LoggerType.INFO,
bot,
message
);
}
public static void RECONNECT (Bot bot, String message) {
new Logger().prefix(
LoggerType.RECONNECT,
bot,
message
);
}
public Logger () {
public static void INFO (Bot bot, String message) {
new Logger().prefix(
LoggerType.INFO,
bot,
message
);
}
public Logger () {
}
}
}
@@ -1,11 +1,11 @@
package land.chipmunk.parker2991.nitoribot.logger;
public enum LoggerType {
LOG,
DEBUG,
INFO,
COMMAND,
WARN,
ERROR,
RECONNECT,
LOG,
DEBUG,
INFO,
COMMAND,
WARN,
ERROR,
RECONNECT,
}
@@ -6,54 +6,55 @@ import land.chipmunk.parker2991.nitoribot.command.CommandSource;
import land.chipmunk.parker2991.nitoribot.data.ParsedChatType;
import land.chipmunk.parker2991.nitoribot.data.PlayerProfileData;
import land.chipmunk.parker2991.nitoribot.data.chat.PlayerMessageData;
import land.chipmunk.parker2991.nitoribot.listeners.*;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
import net.kyori.adventure.text.Component;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class ChatCommandHandlerModule extends Listener {
private Bot bot;
private @NotNull final Bot bot;
private @NotNull final Config config;
@Override
public void parsedMessage (Component message, PlayerMessageData data) {
if (data.chatType != "minecraft:chat") return;
@Override
public void parsedMessage ( PlayerMessageData data) {
if (!data.chatType().equals("minecraft:chat")) return;
List<String> prefixes = bot.config.prefixes;
List<String> prefixes = config.prefixes;
for (String prefix : prefixes) {
String plainMessage = ComponentUtil.componentToString(data.contents);
for (String prefix : prefixes) {
String plainMessage = ComponentUtil.componentToString(data.contents());
if (!plainMessage.startsWith(prefix)) return;
if (!plainMessage.startsWith(prefix)) return;
String command = plainMessage.substring(prefix.length());
String command = plainMessage.substring(prefix.length());
CommandSource source = new CommandSource(bot, ParsedChatType.NORMAL, data.sender);
CommandSource source = new CommandSource(bot, ParsedChatType.NORMAL, data.sender());
bot.commandManager.executeString(source, command);
bot.commandManager.executeString(source, command);
}
}
}
@Override
public void commandSpyReceived (PlayerProfileData player, String message) {
List<String> prefixes = bot.config.prefixes;
@Override
public void commandSpyReceived (PlayerProfileData player, String message) {
List<String> prefixes = config.prefixes;
for (String prefix : prefixes) {
if (!message.startsWith(prefix)) return;
for (String prefix : prefixes) {
if (!message.startsWith(prefix)) return;
String command = message.substring(prefix.length());
String command = message.substring(prefix.length());
CommandSource source = new CommandSource(bot, ParsedChatType.COMMANDSPY, player);
CommandSource source = new CommandSource(bot, ParsedChatType.COMMANDSPY, player);
bot.commandManager.executeString(source, command);
bot.commandManager.executeString(source, command);
}
}
}
public ChatCommandHandlerModule (Bot bot) {
this.bot = bot;
public ChatCommandHandlerModule (Bot bot) {
this.bot = bot;
this.config = bot.config;
bot.listenerManager.addListener(this);
}
bot.listenerManager.addListener(this);
}
}
@@ -1,13 +1,13 @@
package land.chipmunk.parker2991.nitoribot.modules;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.listeners.*;
import land.chipmunk.parker2991.nitoribot.chatparsers.*;
import land.chipmunk.parker2991.nitoribot.data.chat.*;
import land.chipmunk.parker2991.nitoribot.data.PlayerProfileData;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
import org.geysermc.mcprotocollib.network.Session;
import land.chipmunk.parker2991.nitoribot.chatparsers.KaboomChatParser;
import land.chipmunk.parker2991.nitoribot.data.chat.ParseChatData;
import land.chipmunk.parker2991.nitoribot.data.chat.PlayerMessageData;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.ClientboundDisguisedChatPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.ClientboundPlayerChatPacket;
@@ -15,158 +15,157 @@ import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.Clientbound
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.ServerboundChatCommandPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.ServerboundChatPacket;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import java.util.ArrayList;
import java.util.List;
import java.time.Instant;
import java.util.BitSet;
import java.util.List;
import java.util.Objects;
public class ChatModule extends Listener {
private Bot bot;
private final Bot bot;
public final List<ParseChatData> chatParsers = new ArrayList<>();
public final List<ParseChatData> chatParsers;
@Override
public void packetReceived (Session session, Packet packet) {
if (packet instanceof ClientboundSystemChatPacket) systemChat((ClientboundSystemChatPacket) packet);
else if (packet instanceof ClientboundPlayerChatPacket) playerChat((ClientboundPlayerChatPacket) packet);
else if (packet instanceof ClientboundDisguisedChatPacket) diguisedChat((ClientboundDisguisedChatPacket) packet);
}
public String parseChatTypes (int chatType) {
String getTranslation = bot.registry.chatTypes.get(chatType);
return getTranslation;
}
public void systemChat (ClientboundSystemChatPacket packet) {
final Component message = packet.getContent();
for (Listener listener : bot.listenerManager.listeners) {
listener.systemChatReceived(message);
}
}
public void diguisedChat (ClientboundDisguisedChatPacket packet) {
Component getMessage = packet.getMessage();
Component targetUsername = packet.getName();
Component message;
final String parseChatTypes = parseChatTypes(packet.getChatType().id());
if (packet.getChatType().id() == 4) {
message = getMessage;
} else {
message = Component.translatable(
parseChatTypes,
targetUsername,
getMessage
);
@Override
public void packetReceived (Packet packet) {
if (packet instanceof ClientboundSystemChatPacket) systemChat((ClientboundSystemChatPacket) packet);
else if (packet instanceof ClientboundPlayerChatPacket) playerChat((ClientboundPlayerChatPacket) packet);
else if (packet instanceof ClientboundDisguisedChatPacket)
diguisedChat((ClientboundDisguisedChatPacket) packet);
}
for (Listener listener : bot.listenerManager.listeners) {
listener.disguisedChatReceived(message);
public String parseChatTypes (int chatType) {
return bot.registry.chatTypes.get(chatType);
}
TextComponent textComponent = (TextComponent) targetUsername;
public void systemChat (ClientboundSystemChatPacket packet) {
final Component message = packet.getContent();
parseMessage(
message,
new PlayerMessageData(
bot.players.getPlayerByUsername(textComponent.content()),
packet.getMessage(),
"minecraft:chat",
bot.players.getPlayerByUsername(textComponent.content()).displayName
)
);
}
public void playerChat (ClientboundPlayerChatPacket packet) {
final Component unsignedContent = packet.getUnsignedContent();
final Component content = Component.text(packet.getContent());
for (Listener listener : bot.listenerManager.listeners) {
listener.playerChatReceived(unsignedContent);
for (Listener listener : bot.listenerManager.listeners) {
listener.systemChatReceived(message);
}
}
parseMessage(
unsignedContent,
new PlayerMessageData(
bot.players.getPlayerUUID(packet.getSender()),
content,
"minecraft:chat",
bot.players.getPlayerUUID(packet.getSender()).displayName
)
);
}
public void diguisedChat (ClientboundDisguisedChatPacket packet) {
Component getMessage = packet.getMessage();
Component targetUsername = packet.getName();
public void parseMessage (Component message, PlayerMessageData data) {
try {
PlayerMessageData parsed = null;
Component message;
for (ParseChatData parser : chatParsers) {
parsed = parser.parse(message);
if (parsed != null) break;
};
final String parseChatTypes = parseChatTypes(packet.getChatType().id());
if (parsed == null) return;
if (packet.getChatType().id() == 4) {
message = getMessage;
} else {
message = Component.translatable(
parseChatTypes,
targetUsername,
getMessage
);
}
for (Listener listener : bot.listenerManager.listeners) {
listener.parsedMessage(message, data);
}
for (Listener listener : bot.listenerManager.listeners) {
listener.disguisedChatReceived(message);
}
} catch (Exception ignore) {}
}
TextComponent textComponent = (TextComponent) targetUsername;
public void message (String message) {
bot.session.send(
new ServerboundChatPacket(
message,
Instant.now().toEpochMilli(),
0,
null,
0,
new BitSet(),
0
)
);
}
parseMessage(
message,
new PlayerMessageData(
bot.players.getPlayerByUsername(textComponent.content()),
packet.getMessage(),
"minecraft:chat",
Objects.requireNonNull(bot.players.getPlayerByUsername(textComponent.content())).displayName()
)
);
}
public void command (String command) {
bot.session.send(
new ServerboundChatCommandPacket(
command
)
);
}
public void playerChat (ClientboundPlayerChatPacket packet) {
final Component unsignedContent = packet.getUnsignedContent();
final Component content = Component.text(packet.getContent());
public void send (String message) {
if (message.startsWith("/")) bot.chat.command(message.substring(1));
for (Listener listener : bot.listenerManager.listeners) {
listener.playerChatReceived(unsignedContent);
}
else bot.chat.message(message);
}
parseMessage(
unsignedContent,
new PlayerMessageData(
bot.players.getPlayerUUID(packet.getSender()),
content,
"minecraft:chat",
Objects.requireNonNull(bot.players.getPlayerUUID(packet.getSender())).displayName()
)
);
}
public void tellraw (String selector, Component message) {
bot.core.run(
String.format(
"%s %s %s",
"minecraft:tellraw",
selector,
GsonComponentSerializer.gson().serialize(message).trim()
)
);
}
public void parseMessage (Component message, PlayerMessageData data) {
try {
PlayerMessageData parsed = null;
public ChatModule (Bot bot) {
this.bot = bot;
for (ParseChatData parser : chatParsers) {
parsed = parser.parse(message);
if (parsed != null) break;
}
chatParsers.add(new KaboomChatParser(bot));
chatParsers.add(new TotalFreedomChatParser(bot));
if (parsed == null) return;
for (Listener listener : bot.listenerManager.listeners) {
listener.parsedMessage(data);
}
} catch (Exception ignore) {
}
}
public void message (String message) {
bot.session.send(
new ServerboundChatPacket(
message,
Instant.now().toEpochMilli(),
0,
null,
0,
new BitSet(),
0
)
);
}
public void command (String command) {
bot.session.send(
new ServerboundChatCommandPacket(
command
)
);
}
public void send (String message) {
if (message.startsWith("/")) bot.chat.command(message.substring(1));
else bot.chat.message(message);
}
public void tellraw (String selector, Component message) {
bot.core.run(
String.format(
"%s %s %s",
"minecraft:tellraw",
selector,
GsonComponentSerializer.gson().serialize(message).trim()
)
);
}
public ChatModule (Bot bot) {
this.bot = bot;
this.chatParsers = List.of(
new KaboomChatParser(bot)
);
bot.listenerManager.addListener(this);
}
bot.listenerManager.addListener(this);
};
}
@@ -1,277 +1,270 @@
package land.chipmunk.parker2991.nitoribot.modules;
import java.util.HashMap;
import java.util.Map;
import land.chipmunk.parker2991.nitoribot.logger.Logger;
import org.cloudburstmc.math.vector.Vector3d;
import org.cloudburstmc.math.vector.Vector3i;
import org.cloudburstmc.nbt.NbtMap;
import org.cloudburstmc.nbt.NbtType;
import org.cloudburstmc.nbt.NbtMapBuilder;
import org.geysermc.mcprotocollib.protocol.data.game.entity.object.Direction;
import org.geysermc.mcprotocollib.protocol.data.game.level.block.BlockEntityType;
import org.geysermc.mcprotocollib.protocol.data.game.entity.player.Hand;
import org.geysermc.mcprotocollib.protocol.data.game.entity.player.PlayerAction;
import org.geysermc.mcprotocollib.protocol.data.game.item.ItemStack;
import org.geysermc.mcprotocollib.protocol.data.game.item.component.DataComponent;
import org.geysermc.mcprotocollib.protocol.data.game.item.component.DataComponentType;
import org.geysermc.mcprotocollib.protocol.data.game.item.component.DataComponentTypes;
import org.geysermc.mcprotocollib.protocol.data.game.item.component.DataComponents;
import org.geysermc.mcprotocollib.protocol.data.game.item.component.TypedEntityData;
import org.geysermc.mcprotocollib.protocol.data.game.item.component.TypedEntityData.TypedEntityDataBuilder;
import org.geysermc.mcprotocollib.protocol.data.game.level.block.CommandBlockMode;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.inventory.ServerboundSetCommandBlockPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.inventory.ServerboundSetCreativeModeSlotPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.player.ServerboundPlayerActionPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.player.ServerboundUseItemOnPacket;
import net.kyori.adventure.text.Component;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.data.CommandCoreAreaData;
import land.chipmunk.parker2991.nitoribot.data.PositionData;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
import org.cloudburstmc.math.vector.Vector3d;
import org.cloudburstmc.math.vector.Vector3i;
import org.cloudburstmc.nbt.NbtMap;
import org.cloudburstmc.nbt.NbtMapBuilder;
import org.geysermc.mcprotocollib.protocol.data.game.entity.object.Direction;
import org.geysermc.mcprotocollib.protocol.data.game.entity.player.Hand;
import org.geysermc.mcprotocollib.protocol.data.game.entity.player.PlayerAction;
import org.geysermc.mcprotocollib.protocol.data.game.item.ItemStack;
import org.geysermc.mcprotocollib.protocol.data.game.item.component.*;
import org.geysermc.mcprotocollib.protocol.data.game.level.block.BlockEntityType;
import org.geysermc.mcprotocollib.protocol.data.game.level.block.CommandBlockMode;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.inventory.ServerboundSetCommandBlockPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.inventory.ServerboundSetCreativeModeSlotPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.player.ServerboundPlayerActionPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.player.ServerboundUseItemOnPacket;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public class CommandCoreModule extends Listener {
private Bot bot;
private @NotNull final Bot bot;
public CommandCoreAreaData area;
public final CommandCoreAreaData area;
@Override
public void botMoved () {
move();
}
public Vector3i position;
public Vector3i itemPosition;
public void move () {
Vector3d botPos = bot.position.positionAsVector;
position = Vector3i.from(
Math.floor(botPos.getX() / 16) * 16,
0,
Math.floor(botPos.getZ() / 16) * 16
);
itemPosition = Vector3i.from(
botPos.getX(),
botPos.getY() - 1,
botPos.getZ()
);
chatRefill();
};
public void chatRefill () {
Vector3i pos = position;
CommandCoreAreaData coreArea = area;
int startPosX = pos.getX() - coreArea.start.getX();
int startPosY = pos.getY() - coreArea.start.getY();
int startPosZ = pos.getZ() - coreArea.start.getZ();
int endPosX = pos.getX() - coreArea.end.getX();
int endPosY = pos.getY() - coreArea.end.getY();
int endPosZ = pos.getZ() - coreArea.end.getZ();
String command = String.format(
"minecraft:fill %s %s %s %s %s %s command_block{CustomName:%s} destroy",
startPosX,
startPosY,
startPosZ,
endPosX,
endPosY,
endPosZ,
bot.config.core.coreName
);
bot.chat.command(command);
}
public void itemRefill () {
final NbtMapBuilder blockEntityTagBuilder = NbtMap.builder();
Vector3i pos = position;
CommandCoreAreaData coreArea = area;
int startPosX = pos.getX() - coreArea.start.getX();
int startPosY = pos.getY() - coreArea.start.getY();
int startPosZ = pos.getZ() - coreArea.start.getZ();
int endPosX = pos.getX() - coreArea.end.getX();
int endPosY = pos.getY() - coreArea.end.getY();
int endPosZ = pos.getZ() - coreArea.end.getZ();
String command = String.format(
"minecraft:fill %s %s %s %s %s %s command_block{CustomName:%s} replace",
startPosX,
startPosY,
startPosZ,
endPosX,
endPosY,
endPosZ,
bot.config.core.coreName
);
blockEntityTagBuilder.putString("Command", command)
.putByte("auto", (byte) 1)
.putByte("TrackOutput", (byte) 1);
final NbtMap blockEntityTag = blockEntityTagBuilder.build();
final Map<DataComponentType<?>, DataComponent<?, ?>> map = new HashMap<>();
map.put(
DataComponentTypes.BLOCK_ENTITY_DATA,
DataComponentTypes.BLOCK_ENTITY_DATA
.getDataComponentFactory()
.create(
DataComponentTypes.BLOCK_ENTITY_DATA,
TypedEntityData.<BlockEntityType>builder()
.type(BlockEntityType.COMMAND_BLOCK)
.tag(blockEntityTag)
.build()
)
);
map.put(
DataComponentTypes.ITEM_NAME,
DataComponentTypes.ITEM_NAME
.getDataComponentFactory()
.create(
DataComponentTypes.ITEM_NAME,
ComponentUtil.componentFromJSON(bot.config.core.coreName)
)
);
map.put(
DataComponentTypes.CUSTOM_NAME,
DataComponentTypes.CUSTOM_NAME
.getDataComponentFactory()
.create(
DataComponentTypes.CUSTOM_NAME,
ComponentUtil.componentFromJSON(bot.config.core.coreName)
)
);
final DataComponents dataComponents = new DataComponents(map);
bot.session.send(
new ServerboundSetCreativeModeSlotPacket(
(short) 36,
new ItemStack(
482,
64,
dataComponents
)
)
);
bot.session.send(
new ServerboundPlayerActionPacket(
PlayerAction.START_DIGGING,
itemPosition,
Direction.NORTH,
0
)
);
bot.session.send(
new ServerboundUseItemOnPacket(
itemPosition,
Direction.NORTH,
Hand.MAIN_HAND,
0.5f,
0.5f,
0.5f,
false,
false,
1
)
);
}
public Vector3i currentBlockRelative = Vector3i.from(0, 0, 0);
public PositionData currentBlock () {
Vector3i relativePosition = currentBlockRelative;
Vector3i corePosition = position;
if (corePosition == null) return null;
return new PositionData(
relativePosition.getX() + corePosition.getX(),
relativePosition.getY() + corePosition.getY(),
relativePosition.getZ() + corePosition.getZ()
);
}
public void incrementCurrentBlock () {
Vector3i relativePosition = currentBlockRelative;
CommandCoreAreaData coreArea = area;
int posX = relativePosition.getX();
int posY = relativePosition.getY();
int posZ = relativePosition.getZ();
posX++;
if (posX > coreArea.end.getX()) {
posX = coreArea.start.getX();
posZ++;
@Override
public void botMoved () {
move();
}
if (posZ > coreArea.end.getZ()) {
posZ = coreArea.start.getZ();
posY++;
public Vector3i position;
public Vector3i itemPosition;
public void move () {
Vector3d botPos = bot.position.positionData.position();
position = Vector3i.from(
Math.floor(botPos.getX() / 16) * 16,
0,
Math.floor(botPos.getZ() / 16) * 16
);
itemPosition = Vector3i.from(
botPos.getX(),
botPos.getY() - 1,
botPos.getZ()
);
chatRefill();
}
if (posY > coreArea.end.getY()) {
posX = coreArea.start.getX();
posY = coreArea.start.getY();
posZ = coreArea.start.getZ();
public void chatRefill () {
Vector3i pos = position;
CommandCoreAreaData coreArea = area;
int startPosX = (int) Math.floor(pos.getX() - coreArea.start().getX());
int startPosY = (int) Math.floor(pos.getY() - coreArea.start().getY());
int startPosZ = (int) Math.floor(pos.getZ() - coreArea.start().getZ());
int endPosX = (int) Math.floor(pos.getX() - coreArea.end().getX());
int endPosY = (int) Math.floor(pos.getY() - coreArea.end().getY());
int endPosZ = (int) Math.floor(pos.getZ() - coreArea.end().getZ());
String command = String.format(
"minecraft:fill %s %s %s %s %s %s command_block{CustomName:%s} destroy",
startPosX,
startPosY,
startPosZ,
endPosX,
endPosY,
endPosZ,
bot.config.core.coreName
);
bot.chat.command(command);
}
}
public void commandBlock (String command, boolean doesTrackOutput, boolean conditional, boolean automatic) {
if (command.length() > 32767 || position == null) return;
bot.session.send(
new ServerboundSetCommandBlockPacket(
position,
command,
CommandBlockMode.AUTO,
doesTrackOutput,
conditional,
automatic
)
);
}
public void itemRefill () {
final NbtMapBuilder blockEntityTagBuilder = NbtMap.builder();
public void run (String command) {
String command = getCommand();
commandBlock(command, true, false, true);
blockEntityTagBuilder.putString("Command", command)
.putByte("auto", (byte) 1)
.putByte("TrackOutput", (byte) 1);
incrementCurrentBlock();
}
final NbtMap blockEntityTag = blockEntityTagBuilder.build();
public CommandCoreModule (Bot bot) {
this.bot = bot;
final Map<DataComponentType<?>, DataComponent<?, ?>> map = new HashMap<>();
this.area = new CommandCoreAreaData(
Vector3i.from(
bot.config.core.area.start.x,
bot.config.core.area.start.y,
bot.config.core.area.start.z
),
Vector3i.from(
bot.config.core.area.end.x,
bot.config.core.area.end.y,
bot.config.core.area.end.z
)
);
map.put(
DataComponentTypes.BLOCK_ENTITY_DATA,
DataComponentTypes.BLOCK_ENTITY_DATA
.getDataComponentFactory()
.create(
DataComponentTypes.BLOCK_ENTITY_DATA,
TypedEntityData.<BlockEntityType>builder()
.type(BlockEntityType.COMMAND_BLOCK)
.tag(blockEntityTag)
.build()
)
);
bot.listenerManager.addListener(this);
}
map.put(
DataComponentTypes.ITEM_NAME,
DataComponentTypes.ITEM_NAME
.getDataComponentFactory()
.create(
DataComponentTypes.ITEM_NAME,
ComponentUtil.componentFromJSON(bot.config.core.coreName)
)
);
map.put(
DataComponentTypes.CUSTOM_NAME,
DataComponentTypes.CUSTOM_NAME
.getDataComponentFactory()
.create(
DataComponentTypes.CUSTOM_NAME,
ComponentUtil.componentFromJSON(bot.config.core.coreName)
)
);
final DataComponents dataComponents = new DataComponents(map);
bot.session.send(
new ServerboundSetCreativeModeSlotPacket(
(short) 36,
new ItemStack(
482,
64,
dataComponents
)
)
);
bot.session.send(
new ServerboundPlayerActionPacket(
PlayerAction.START_DIGGING,
itemPosition,
Direction.NORTH,
0
)
);
bot.session.send(
new ServerboundUseItemOnPacket(
itemPosition,
Direction.NORTH,
Hand.MAIN_HAND,
0.5f,
0.5f,
0.5f,
false,
false,
1
)
);
}
private String getCommand () {
Vector3i pos = position;
CommandCoreAreaData coreArea = area;
int startPosX = (int) Math.round(pos.getX() - coreArea.start().getX());
int startPosY = (int) Math.round(pos.getY() - coreArea.start().getY());
int startPosZ = (int) Math.round(pos.getZ() - coreArea.start().getZ());
int endPosX = (int) Math.round(pos.getX() - coreArea.end().getX());
int endPosY = (int) Math.round(pos.getY() - coreArea.end().getY());
int endPosZ = (int) Math.round(pos.getZ() - coreArea.end().getZ());
return String.format(
"minecraft:fill %s %s %s %s %s %s command_block{CustomName:%s} replace",
startPosX,
startPosY,
startPosZ,
endPosX,
endPosY,
endPosZ,
bot.config.core.coreName
);
}
public Vector3d currentBlockRelative = Vector3d.from(0, 0, 0);
public PositionData currentBlock () {
Vector3d relativePosition = currentBlockRelative;
Vector3i corePosition = position;
return new PositionData(
(float) (relativePosition.getX() + corePosition.getX()),
(float) (relativePosition.getY() + corePosition.getY()),
Vector3d.from(relativePosition.getZ(), relativePosition.getY(), relativePosition.getZ())
);
}
public void incrementCurrentBlock () {
Vector3d relativePosition = currentBlockRelative;
CommandCoreAreaData coreArea = area;
double posX = relativePosition.getX();
double posY = relativePosition.getY();
double posZ = relativePosition.getZ();
posX++;
if (posX > coreArea.end().getX()) {
posX = coreArea.start().getX();
posZ++;
}
if (posZ > coreArea.end().getZ()) {
posZ = coreArea.start().getZ();
posY++;
}
if (posY > coreArea.end().getY()) {
posX = coreArea.start().getX();
posY = coreArea.start().getY();
posZ = coreArea.start().getZ();
}
currentBlockRelative = Vector3d.from(posX, posY, posZ);
}
public void commandBlock (String command, boolean doesTrackOutput, boolean conditional, boolean automatic) {
if (command.length() > 32767 || position == null) return;
bot.session.send(
new ServerboundSetCommandBlockPacket(
position,
command,
CommandBlockMode.AUTO,
doesTrackOutput,
conditional,
automatic
)
);
}
public void run (String command) {
commandBlock(command, true, false, true);
incrementCurrentBlock();
}
public CommandCoreModule (Bot bot) {
this.bot = bot;
this.area = new CommandCoreAreaData(
Vector3d.from(
bot.config.core.area.start.x,
bot.config.core.area.start.y,
bot.config.core.area.start.z
),
Vector3d.from(
bot.config.core.area.end.x,
bot.config.core.area.end.y,
bot.config.core.area.end.z
)
);
bot.listenerManager.addListener(this);
}
}
@@ -1,6 +1,5 @@
package land.chipmunk.parker2991.nitoribot.modules;
import com.mojang.brigadier.CommandDispatcher;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.command.CommandContext;
import land.chipmunk.parker2991.nitoribot.command.CommandError;
@@ -19,71 +18,69 @@ import java.util.Arrays;
import java.util.List;
public class CommandManagerModule {
private Bot bot;
private final Bot bot;
public CommandDispatcher <CommandSource> dispatcher = new CommandDispatcher<>();
public final List<CommandInfo> commands = new ArrayList<>();
public List<CommandInfo> commands = new ArrayList<>();
public void registerCommand (CommandInfo command) {
commands.add(command);
}
public CommandInfo getCommand (String getCommand) {
for (CommandInfo command : commands) {
for (String aliases : command.aliases) {
if (getCommand.equals(aliases)) return command;
}
if (getCommand.equals(command.name)) return command;
public void registerCommand (CommandInfo command) {
commands.add(command);
}
return null;
}
public void execute (CommandSource source, String commandName, String[] args) {
try {
CommandInfo command = getCommand(commandName.toLowerCase());
if (command == null) throw new CommandError(
Component.translatable(
"%s%s%s %s",
Component.translatable("command.unknown.command"),
Component.text("\n"),
Component.text(commandName).color(NamedTextColor.GRAY),
Component.translatable("command.context.here")
).color(NamedTextColor.RED)
);
CommandContext context = new CommandContext(bot, args, source, command);
command.execute(context);
} catch (CommandError error) {
source.sendFeedback(error.message());
} catch (Exception error) {
source.sendFeedback(
Component.translatable("command.failed").color(NamedTextColor.DARK_RED)
);
String Error = ErrorToString.errorToString(error);
Logger.ERROR(bot, Error);
public CommandInfo getCommand (String getCommand) {
for (CommandInfo command : commands) {
for (String aliases : command.aliases) {
if (getCommand.equals(aliases)) return command;
}
if (getCommand.equals(command.name)) return command;
}
return null;
}
}
public void executeString (CommandSource source, String command) {
String[] splitArguments = command.split(" ");
String commandName = splitArguments[0];
final String[] args = Arrays.copyOfRange(splitArguments, 1, splitArguments.length);
this.execute(source, commandName, args);
}
public void execute (CommandSource source, String commandName, String[] args) {
try {
CommandInfo command = getCommand(commandName.toLowerCase());
public CommandManagerModule (Bot bot) throws IOException {
this.bot = bot;
if (command == null) throw new CommandError(
Component.translatable(
"%s%s%s %s",
Component.translatable("command.unknown.command"),
Component.text("\n"),
Component.text(commandName).color(NamedTextColor.GRAY),
Component.translatable("command.context.here")
).color(NamedTextColor.RED)
);
registerCommand(new EchoCommand());
registerCommand(new HelpCommand());
registerCommand(new ReconnectCommand());
registerCommand(new RCCommand());
registerCommand(new MCServerCommand());
registerCommand(new TestCommand());
registerCommand(new InfoCommand());
}
CommandContext context = new CommandContext(bot, args, source);
command.execute(context);
} catch (CommandError error) {
source.sendFeedback(error.message());
} catch (Exception error) {
source.sendFeedback(
Component.translatable("command.failed").color(NamedTextColor.DARK_RED)
);
String Error = ErrorToString.errorToString(error);
Logger.ERROR(bot, Error);
}
}
public void executeString (CommandSource source, String command) {
String[] splitArguments = command.split(" ");
String commandName = splitArguments[0];
final String[] args = Arrays.copyOfRange(splitArguments, 1, splitArguments.length);
this.execute(source, commandName, args);
}
public CommandManagerModule (Bot bot) throws IOException {
this.bot = bot;
registerCommand(new EchoCommand());
registerCommand(new HelpCommand());
registerCommand(new ReconnectCommand());
registerCommand(new RCCommand());
registerCommand(new MCServerCommand());
registerCommand(new TestCommand());
registerCommand(new InfoCommand());
}
}
@@ -10,50 +10,44 @@ import org.jetbrains.annotations.Unmodifiable;
import java.util.List;
public class CommandSpyModule extends Listener {
private Bot bot;
private final Bot bot;
private static final String COLON = ":";
private static final String SLASH = "/";
private static final String SLASH = "/";
@Override
public void systemChatReceived (Component data) {
@Unmodifiable List<Component> children = data.children();
@Override
public void systemChatReceived (Component data) {
@Unmodifiable List<Component> children = data.children();
if (!(children.get(1) instanceof final TextComponent commandComponent)) return;
TextComponent userComponent = null;
if (!(data instanceof final TextComponent userComponent)) return;
TextComponent commandComponent = null;
PlayerProfileData sender = null;
if (children.get(1) instanceof final TextComponent textComponent) commandComponent = textComponent;
for (PlayerProfileData player : bot.players.list) {
String username = player.profile().getName();
if (data instanceof final TextComponent textComponent) userComponent = textComponent;
if (username.equals(userComponent.content())) sender = player;
}
PlayerProfileData sender = null;
String command = commandComponent.content().substring(SLASH.length());
for (PlayerProfileData player : bot.players.list) {
String username = player.profile.getName();
if (username.equals(userComponent.content())) sender = player;
if (
(
commandComponent.content().contains(SLASH + command)
&&
sender != null
)
) {
for (Listener listener : bot.listenerManager.listeners) {
listener.commandSpyReceived(sender, command);
}
}
}
String command = commandComponent.content().substring(SLASH.length());
public CommandSpyModule (Bot bot) {
this.bot = bot;
if (
(
commandComponent.content().contains(SLASH + command)
&&
sender != null
)
) {
for (Listener listener : bot.listenerManager.listeners) {
listener.commandSpyReceived(sender, command);
}
bot.listenerManager.addListener(this);
}
}
public CommandSpyModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
}
@@ -1,46 +1,46 @@
package land.chipmunk.parker2991.nitoribot.modules;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.Config;
import land.chipmunk.parker2991.nitoribot.Main;
import org.jline.reader.*;
import java.util.List;
public class ConsoleModule implements Completer {
private static final List<Bot> servers = Main.Bots;
private static final List<Bot> servers = Main.Bots;
public LineReader reader;
public final LineReader reader;
public String server = "all";
public final String server = "all";
@Override
public void complete (LineReader reader, ParsedLine line, List<Candidate> candidates) {
@Override
public void complete (LineReader reader, ParsedLine line, List<Candidate> candidates) {
}
private void handleLine (String line) {
for (Bot bot : servers) {
if (line.equals("c.kill")) System.exit(0);
bot.chat.send(line);
}
}
public ConsoleModule (Config config) {
this.reader = LineReaderBuilder.builder()
.completer(this)
.build();
private void handleLine (String line) {
for (Bot bot : servers) {
if (line.equals(bot.config.console.prefix + "kill")) System.exit(0);
bot.chat.send(line);
}
}
Main.executorService.submit(() -> {
while (true) {
try {
String line = null;
public ConsoleModule () {
this.reader = LineReaderBuilder.builder()
.completer(this)
.build();
line = reader.readLine(String.format("[%s] > ", this.server));
Main.executorService.submit(() -> {
while (true) {
try {
String line;
handleLine(line);
} catch (Exception e) {}
}
}, "Console Thread");
}
line = reader.readLine(String.format("[%s] > ", this.server));
handleLine(line);
} catch (Exception _) {
}
}
}, "Console Thread");
}
}
@@ -1,79 +0,0 @@
package land.chipmunk.parker2991.nitoribot.modules;
/*
i will work on this module some other time,
i have been messing with it and trying to get it to work for 3 days straight
so this is currently stubbed
*/
import land.chipmunk.code.kaboomstandardsorganization.messaginglib.mcprotocollib.MCProtocolLibMessenger;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.listeners.*;
import org.geysermc.mcprotocollib.network.Session;
import org.geysermc.mcprotocollib.network.packet.Packet;
import java.util.ArrayList;
import java.util.List;
public class ExtrasMessagingModule extends Listener {
private Bot bot;
public final List<String> channels = new ArrayList<>();
public static final String TEST_CHANNEL = "test";
public void register (String channel) {
}
public void unregister (String channel) {
}
public void sendMessage (MCProtocolLibMessenger messenger, String channel, String message) {
}
@Override
public void extrasMessagingReceived (MCProtocolLibMessenger message) {
/*var findPlayer = bot.players.getPlayerUUID(player).profile.getName();
bot.chat.tellraw("@a[tag=nitoribot_debug]",
Component.text(
"Recieved: " + message + "\n" +
"From: " + findPlayer + "\n" +
"Channel: " + channel
)
);*/
}
@Override
public void packetSent(Session session, Packet packet) {
}
/*
messenger.receivePayloads(
TEST_CHANNEL,
(_, _, payload) -> {
Logger.info(
"Received {}",
payload.toString(StandardCharsets.UTF_8)
);
messenger.sendMessage(TEST_CHANNEL, payload);
}
);
messenger.sendMessage(
TEST_CHANNEL,
wrappedBuffer("echo".getBytes(StandardCharsets.UTF_8))
);
*/
public ExtrasMessagingModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
}
@@ -1,43 +1,39 @@
package land.chipmunk.parker2991.nitoribot.modules;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import land.chipmunk.parker2991.nitoribot.logger.Logger;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
import land.chipmunk.parker2991.nitoribot.listeners.*;
import net.kyori.adventure.text.Component;
public class LoggingModule extends Listener {
private Bot bot;
private final Bot bot;
@Override
public void playerChatReceived (Component message) {
handleMessages(message);
};
@Override
public void playerChatReceived (Component message) {
handleMessages(message);
}
@Override
public void disguisedChatReceived (Component message) {
handleMessages(message);
}
@Override
public void disguisedChatReceived (Component message) {
handleMessages(message);
}
@Override
public void systemChatReceived (Component message) {
handleMessages(message);
}
@Override
public void systemChatReceived (Component message) {
handleMessages(message);
}
public void handleMessages (Component _message) {
final String host = bot.options.host;
final int port = bot.options.port;
String message = ComponentUtil.componentToAnsi(_message);
//if (host.equals("kaboom.pw")) return;
Logger.LOG(bot, message);
}
public void handleMessages (Component _message) {
public LoggingModule (Bot bot) {
this.bot = bot;
String message = ComponentUtil.componentToAnsi(_message);
//if (host.equals("kaboom.pw")) return;
Logger.LOG(bot, message);
}
bot.listenerManager.addListener(this);
}
public LoggingModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
}
@@ -20,68 +20,66 @@ import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
public class MCServerModule {
private Bot bot;
private final Bot bot;
public ClientSession client;
public final SessionService sessionService = new SessionService();
public final MinecraftProtocol protocol = new MinecraftProtocol();
private final List<SkinPart> skinParts = new ArrayList<>();
public ClientSession client;
public PingServerData pingServer (String[] host) {
AtomicReference<PingServerData> serverData = new AtomicReference<>();
public final SessionService sessionService = new SessionService();
client = ClientNetworkSessionFactory.factory()
.setAddress("kaboom.pw", 25565)
//.setAddress(host[0], Integer.parseInt(host[1]))
.setProtocol(protocol)
.create();
client.send(
new ServerboundClientInformationPacket(
"en_us",
1,
ChatVisibility.FULL,
true,
skinParts,
HandPreference.RIGHT_HAND,
false,
true,
ParticleStatus.ALL
)
);
public final MinecraftProtocol protocol = new MinecraftProtocol();
client.setFlag(MinecraftConstants.SESSION_SERVICE_KEY, sessionService);
private final List<SkinPart> skinParts = new ArrayList<>();
client.setFlag(MinecraftConstants.SERVER_INFO_HANDLER_KEY, (Session session, ServerStatusInfo info) -> {
assert info.getVersionInfo() != null;
assert info.getPlayerInfo() != null;
public PingServerData pingServer (String[] host) {
AtomicReference<PingServerData> serverData = new AtomicReference<>();
serverData.set(new PingServerData(
info.getVersionInfo().getVersionName(),
info.getVersionInfo().getProtocolVersion(),
info.getPlayerInfo().getOnlinePlayers(),
info.getPlayerInfo().getMaxPlayers(),
info.getDescription()
));
});
client = ClientNetworkSessionFactory.factory()
.setAddress("kaboom.pw", 25565)
//.setAddress(host[0], Integer.parseInt(host[1]))
.setProtocol(protocol)
.create();
System.out.println(serverData);
client.send(
new ServerboundClientInformationPacket(
"en_us",
1,
ChatVisibility.FULL,
true,
skinParts,
HandPreference.RIGHT_HAND,
false,
true,
ParticleStatus.ALL
)
);
client.setFlag(MinecraftConstants.SERVER_PING_TIME_HANDLER_KEY, (session, pingTime) ->
serverData.get().latency(pingTime)
);
bot.executor.submit(() -> {
client.connect();
});
client.setFlag(MinecraftConstants.SESSION_SERVICE_KEY, sessionService);
return serverData.get();
}
public MCServerModule (Bot bot) {
this.bot = bot;
client.setFlag(MinecraftConstants.SERVER_INFO_HANDLER_KEY, (Session session, ServerStatusInfo info) -> {
assert info.getVersionInfo() != null;
assert info.getPlayerInfo() != null;
}
serverData.set(new PingServerData(
info.getVersionInfo().getVersionName(),
info.getVersionInfo().getProtocolVersion(),
info.getPlayerInfo().getOnlinePlayers(),
info.getPlayerInfo().getMaxPlayers(),
info.getDescription()
));
});
System.out.println(serverData);
client.setFlag(MinecraftConstants.SERVER_PING_TIME_HANDLER_KEY, (session, pingTime) ->
serverData.get().latency(pingTime)
);
bot.executor.submit(() -> client.connect());
return serverData.get();
}
public MCServerModule (Bot bot) {
this.bot = bot;
}
}
@@ -1,12 +1,11 @@
package land.chipmunk.parker2991.nitoribot.modules;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.data.PlayerPositionData;
import land.chipmunk.parker2991.nitoribot.data.PlayerProfileData;
import land.chipmunk.parker2991.nitoribot.data.PositionData;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import net.kyori.adventure.text.Component;
import org.cloudburstmc.math.vector.Vector3d;
import org.geysermc.mcprotocollib.network.Session;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.protocol.data.game.PlayerListEntry;
import org.geysermc.mcprotocollib.protocol.data.game.PlayerListEntryAction;
@@ -14,7 +13,6 @@ import org.geysermc.mcprotocollib.protocol.data.game.entity.type.EntityType;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.ClientboundPlayerInfoRemovePacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.ClientboundPlayerInfoUpdatePacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.ClientboundAddEntityPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.level.ClientboundTagQueryPacket;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
@@ -23,179 +21,160 @@ import java.util.List;
import java.util.UUID;
public class PlayerListModule extends Listener {
private Bot bot;
public final List<PlayerProfileData> list = new ArrayList<>();
public int transactionId = 0;
public final List<PlayerProfileData> list = new ArrayList<>();
@Override
public void packetReceived (Session session, Packet packet) {
if (packet instanceof ClientboundPlayerInfoUpdatePacket) playerInfo((ClientboundPlayerInfoUpdatePacket) packet);
else if (packet instanceof ClientboundPlayerInfoRemovePacket) playerRemove((ClientboundPlayerInfoRemovePacket) packet);
else if (packet instanceof ClientboundAddEntityPacket) getPlayerPosition((ClientboundAddEntityPacket) packet);
else if (packet instanceof ClientboundTagQueryPacket) queryPlayerData((ClientboundTagQueryPacket) packet);
}
public void playerInfo (ClientboundPlayerInfoUpdatePacket packet) {
EnumSet<PlayerListEntryAction> actions = packet.getActions();
for (PlayerListEntryAction action : actions) {
for (PlayerListEntry entry : packet.getEntries()) {
switch (action) {
case PlayerListEntryAction.UPDATE_LIST_ORDER,
PlayerListEntryAction.UPDATE_HAT,
PlayerListEntryAction.INITIALIZE_CHAT,
PlayerListEntryAction.ADD_PLAYER -> addPlayer(entry);
case PlayerListEntryAction.UPDATE_LISTED -> updateListed(entry);
case PlayerListEntryAction.UPDATE_GAME_MODE -> updateGamemode(entry);
case PlayerListEntryAction.UPDATE_LATENCY -> updateLatency(entry);
case PlayerListEntryAction.UPDATE_DISPLAY_NAME -> updateDisplayName(entry);
@Override
public void packetReceived (Packet packet) {
switch (packet) {
case ClientboundPlayerInfoUpdatePacket p -> playerInfo(p);
case ClientboundPlayerInfoRemovePacket p -> playerRemove(p);
case ClientboundAddEntityPacket p -> getPlayerPosition(p);
default -> {}
}
}
}
}
public void queryPlayerData (ClientboundTagQueryPacket packet) {
}
public void getPlayerPosition (ClientboundAddEntityPacket packet) {
if (packet.getType() == EntityType.PLAYER) {
UUID uuid = packet.getUuid();
int entityId = packet.getEntityId();
Vector3d playerPosition = Vector3d.from(packet.getX(), packet.getY(), packet.getZ());
float yaw = packet.getYaw();
float pitch = packet.getPitch();
PlayerProfileData player = getPlayerUUID(uuid);
player.entityId = entityId;
player.position = new PlayerPositionData(pitch, yaw, playerPosition);
// bot.session.send(
// new Server
//)
}
}
public final PlayerProfileData getPlayerByEntityID (int entityId) {
for (PlayerProfileData player : list) {
if (player.entityId == entityId) {
return player;
}
}
return null;
}
public void playerInfo (ClientboundPlayerInfoUpdatePacket packet) {
EnumSet<PlayerListEntryAction> actions = packet.getActions();
@Nullable
public final PlayerProfileData getPlayerUUID (UUID uuid) {
PlayerProfileData playerInfo = null;
try {
// lazy ass fix for the bot erroring when a player is null
for (PlayerProfileData player : list) {
//if (player.profile.getId() == null) {}
UUID playerUUID = player.profile.getId();
if (playerUUID == null) return playerInfo;
else if (player.profile.getId().equals(uuid)) {
playerInfo = player;
for (PlayerListEntryAction action : actions) {
for (PlayerListEntry entry : packet.getEntries()) {
switch (action) {
case PlayerListEntryAction.UPDATE_LIST_ORDER,
PlayerListEntryAction.UPDATE_HAT,
PlayerListEntryAction.INITIALIZE_CHAT,
PlayerListEntryAction.ADD_PLAYER -> addPlayer(entry);
case PlayerListEntryAction.UPDATE_LISTED -> updateListed(entry);
case PlayerListEntryAction.UPDATE_GAME_MODE -> updateGamemode(entry);
case PlayerListEntryAction.UPDATE_LATENCY -> updateLatency(entry);
case PlayerListEntryAction.UPDATE_DISPLAY_NAME -> updateDisplayName(entry);
}
}
}
}
} catch (Exception e) {
}
return playerInfo;
}
public final PlayerProfileData getDisplayName (Component displayName) {
for (PlayerProfileData candidate : list) {
if (candidate.displayName != null && candidate.displayName.equals(displayName)) {
return candidate;
}
}
return null;
}
public final PlayerProfileData getPlayerByUsername (String username) {
for (PlayerProfileData candidate : list) {
if (candidate.profile.getName().equals(username)) {
return candidate;
}
public void getPlayerPosition (ClientboundAddEntityPacket packet) {
if (packet.getType() == EntityType.PLAYER) {
UUID uuid = packet.getUuid();
int entityId = packet.getEntityId();
Vector3d playerPosition = Vector3d.from(packet.getX(), packet.getY(), packet.getZ());
float yaw = packet.getYaw();
float pitch = packet.getPitch();
PlayerProfileData player = getPlayerUUID(uuid);
assert player != null;
player.entityId(entityId);
player.position(new PositionData(pitch, yaw, playerPosition));
}
}
return null;
}
public void updateListed (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
@Nullable
public final PlayerProfileData getPlayerUUID (UUID uuid) {
PlayerProfileData playerInfo = null;
if (getPlayer == null) return;
try {
// lazy ass fix for the bot erroring when a player is null
for (PlayerProfileData player : list) {
UUID playerUUID = player.profile().getId();
getPlayer.listed = player.isListed();
}
public void updateGamemode (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) return;
else getPlayer.gameMode = player.getGameMode();
}
public void updateLatency (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) return;
else getPlayer.latency = player.getLatency();
}
public void updateDisplayName (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) return;
else getPlayer.displayName = player.getDisplayName();
}
public void addPlayer (PlayerListEntry player) {
PlayerProfileData findDuplicatePlayer = getPlayerUUID(player.getProfileId());
if (findDuplicatePlayer != null) list.remove(findDuplicatePlayer);
PlayerProfileData formatPlayerData = new PlayerProfileData(
player.getProfileId(),
player.getProfile(),
player.isListed(),
player.getLatency(),
player.getGameMode(),
player.getDisplayName()
);
list.add(formatPlayerData);
}
public void playerRemove (ClientboundPlayerInfoRemovePacket packet) {
for (UUID uuid : packet.getProfileIds()) {
PlayerProfileData getPlayer = getPlayerUUID(uuid);
if (getPlayer == null) return;
list.remove(getPlayer);
if (playerUUID == null) return playerInfo;
else if (player.profile().getId().equals(uuid)) {
playerInfo = player;
}
}
} catch (Exception _) {
}
return playerInfo;
}
}
public PlayerListModule (Bot bot) {
bot.listenerManager.addListener(this);
}
public final PlayerProfileData getDisplayName (Component displayName) {
for (PlayerProfileData candidate : list) {
if (candidate.displayName() != null && candidate.displayName().equals(displayName)) {
return candidate;
}
}
return null;
}
public final PlayerProfileData getPlayerByUsername (String username) {
for (PlayerProfileData candidate : list) {
if (candidate.profile().getName().equals(username)) {
return candidate;
}
}
return null;
}
public void updateListed (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) return;
getPlayer.listed(player.isListed());
}
public void updateGamemode (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) {
}
else getPlayer.gameMode(player.getGameMode());
}
public void updateLatency (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) {
}
else getPlayer.latency(player.getLatency());
}
public void updateDisplayName (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) {
}
else getPlayer.displayName(player.getDisplayName());
}
public void addPlayer (PlayerListEntry player) {
PlayerProfileData findDuplicatePlayer = getPlayerUUID(player.getProfileId());
if (findDuplicatePlayer != null) list.remove(findDuplicatePlayer);
PlayerProfileData formatPlayerData = new PlayerProfileData(
player.getProfileId(),
null,
player.getProfile(),
player.isListed(),
player.getLatency(),
player.getGameMode(),
player.getDisplayName(),
player.isShowHat(),
player.getListOrder(),
null,
null,
null
);
list.add(formatPlayerData);
}
public void playerRemove (ClientboundPlayerInfoRemovePacket packet) {
for (UUID uuid : packet.getProfileIds()) {
PlayerProfileData getPlayer = getPlayerUUID(uuid);
if (getPlayer == null) return;
list.remove(getPlayer);
}
}
public PlayerListModule (Bot bot) {
bot.listenerManager.addListener(this);
}
}
@@ -4,7 +4,6 @@ import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.data.PositionData;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import org.cloudburstmc.math.vector.Vector3d;
import org.geysermc.mcprotocollib.network.Session;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.player.ClientboundPlayerPositionPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.level.ServerboundAcceptTeleportationPacket;
@@ -15,71 +14,72 @@ import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class PositionModule extends Listener {
private Bot bot;
private final Bot bot;
public ScheduledFuture<?> timer;
public ScheduledFuture<?> timer;
private int i = 0;
private int i = 0;
public Vector3d positionAsVector = null;
public PositionData positionData;
public PositionData positionAsInteger;
private int x;
private int z;
private int x;
private int z;
@Override
public void packetReceived (Packet packet) {
if (packet instanceof ClientboundPlayerPositionPacket) packetReceived((ClientboundPlayerPositionPacket) packet);
}
@Override
public void packetReceived (Session session, Packet packet) {
if (packet instanceof ClientboundPlayerPositionPacket) packetReceived((ClientboundPlayerPositionPacket) packet);
}
public void packetReceived (ClientboundPlayerPositionPacket packet) {
Vector3d getPosition = packet.getPosition();
public void packetReceived (ClientboundPlayerPositionPacket packet) {
Vector3d getPosition = packet.getPosition();
x = (int) Math.round(getPosition.getX());
int y = (int) Math.round(getPosition.getY());
z = (int) Math.round(getPosition.getZ());
x = (int) Math.round(getPosition.getX());
int y = (int) Math.round(getPosition.getY());
z = (int) Math.round(getPosition.getZ());
positionData = new PositionData(
packet.getXRot(),
packet.getYRot(),
packet.getPosition()
);
positionAsInteger = new PositionData(x, y, z);
positionAsVector = getPosition;
if (bot.options.mode.equals("totalfreedom")) {
if (i < 5) timer = bot.executor.scheduleAtFixedRate(() -> {
System.out.println(i);
x += 1;
z += 1;
if (bot.options.mode.equals("totalfreedom")) {
if (i < 5) timer = bot.executor.scheduleAtFixedRate(() -> {
System.out.println(i);
x += 1;
z += 1;
bot.session.send(
new ServerboundMovePlayerPosPacket(
false,
false,
x,
y,
z
)
);
System.out.println("moved");
System.out.println(x);
i++;
if (i > 5) timer.cancel(true);
}, 5000, 5000, TimeUnit.MILLISECONDS);
}
bot.session.send(
new ServerboundMovePlayerPosPacket(
false,
false,
x,
y,
z
)
new ServerboundAcceptTeleportationPacket(
packet.getId()
)
);
System.out.println("moved");
System.out.println(x);
i++;
if (i > 5) timer.cancel(true);
}, 5000, 5000, TimeUnit.MILLISECONDS);
for (Listener listener : bot.listenerManager.listeners) {
if (! Objects.equals(bot.options.mode, "kaboom")) return;
listener.botMoved();
}
}
bot.session.send(
new ServerboundAcceptTeleportationPacket(
packet.getId()
)
);
public PositionModule (Bot bot) {
this.bot = bot;
for (Listener listener : bot.listenerManager.listeners) {
if (! Objects.equals(bot.options.mode, "kaboom")) return;
listener.botMoved();
bot.listenerManager.addListener(this);
}
}
public PositionModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
}
@@ -1,34 +1,34 @@
package land.chipmunk.parker2991.nitoribot.modules;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.listeners.*;
import org.geysermc.mcprotocollib.network.Session;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.protocol.packet.configuration.clientbound.ClientboundRegistryDataPacket;
import org.geysermc.mcprotocollib.protocol.data.game.RegistryEntry;
import org.geysermc.mcprotocollib.protocol.packet.configuration.clientbound.ClientboundRegistryDataPacket;
import java.util.List;
import java.util.ArrayList;
import java.util.List;
public class RegistryModule extends Listener {
public final List<String> chatTypes = new ArrayList<>();
public final List<String> chatTypes = new ArrayList<>();
@Override
public void packetReceived (Session session, Packet packet) {
if (packet instanceof ClientboundRegistryDataPacket) packetReceived((ClientboundRegistryDataPacket) packet);
}
public void packetReceived (ClientboundRegistryDataPacket packet) {
String getRegistry = packet.getRegistry().asString();
for (RegistryEntry entry : packet.getEntries()) {
if (getRegistry.equals("minecraft:chat_type"))
chatTypes.add(entry.getData().getCompound("chat").getString("translation_key"));
@Override
public void packetReceived (Packet packet) {
if (packet instanceof ClientboundRegistryDataPacket) packetReceived((ClientboundRegistryDataPacket) packet);
}
public void packetReceived (ClientboundRegistryDataPacket packet) {
String getRegistry = packet.getRegistry().asString();
for (RegistryEntry entry : packet.getEntries()) {
if (getRegistry.equals("minecraft:chat_type"))
if (entry.getData() != null) {
chatTypes.add(entry.getData().getCompound("chat").getString("translation_key"));
}
}
}
}
public RegistryModule (Bot bot) {
bot.listenerManager.addListener(this);
}
public RegistryModule (Bot bot) {
bot.listenerManager.addListener(this);
}
}
@@ -1,59 +1,63 @@
package land.chipmunk.parker2991.nitoribot.modules;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.selfcare.entity.*;
import land.chipmunk.parker2991.nitoribot.listeners.*;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import land.chipmunk.parker2991.nitoribot.selfcare.entity.GamemodeSelfcare;
import land.chipmunk.parker2991.nitoribot.selfcare.entity.PermissionSelfcare;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.network.Session;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.player.ServerboundChangeGameModePacket;
import org.geysermc.mcprotocollib.protocol.data.game.entity.player.GameMode;
import org.geysermc.mcprotocollib.protocol.packet.common.clientbound.ClientboundDisconnectPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.player.ServerboundChangeGameModePacket;
import org.geysermc.mcprotocollib.protocol.packet.login.clientbound.ClientboundLoginFinishedPacket;
import org.geysermc.mcprotocollib.network.event.session.DisconnectedEvent;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class SelfcareModule extends Listener {
public ScheduledFuture<?> timer;
public ScheduledFuture<?> timer;
private Bot bot;
private final Bot bot;
public PermissionSelfcare permission;
public PermissionSelfcare permission;
public GamemodeSelfcare gamemode;
public GamemodeSelfcare gamemode;
public int entityId;
public int entityId;
public void loadSelfcare () {
this.permission = new PermissionSelfcare(bot);
this.gamemode = new GamemodeSelfcare(bot);
}
public void loadSelfcare () {
this.permission = new PermissionSelfcare(bot);
this.gamemode = new GamemodeSelfcare(bot);
}
@Override
public void packetReceived (Session session, Packet packet) {
if (packet instanceof ClientboundLoginFinishedPacket) login((ClientboundLoginFinishedPacket) packet);
}
@Override
public void packetReceived (Packet packet) {
switch (packet) {
case ClientboundLoginFinishedPacket p -> login(p);
case ClientboundDisconnectPacket p -> disconnect(p);
default -> {}
}
}
public void login (ClientboundLoginFinishedPacket packet) {
if (bot.options.mode.equals("totalfreedom")) return;
timer = bot.executor.scheduleAtFixedRate(() -> {
if (permission.level < 2 && bot.loggedIn == true) bot.chat.command("minecraft:op @s[type=player]");
else if (gamemode.gamemode != 1) bot.session.send(
new ServerboundChangeGameModePacket(
GameMode.CREATIVE
)
);
}, 0, bot.options.selfcareInterval, TimeUnit.MILLISECONDS);
}
public void login (ClientboundLoginFinishedPacket packet) {
if (bot.options.mode.equals("totalfreedom")) return;
timer = bot.executor.scheduleAtFixedRate(() -> {
if (permission.level < 2 && bot.loggedIn) bot.chat.command("minecraft:op @s[type=player]");
else if (gamemode.gamemode != 1) bot.session.send(
new ServerboundChangeGameModePacket(
GameMode.CREATIVE
)
);
}, 0, bot.options.selfcareInterval, TimeUnit.MILLISECONDS);
}
public void disconnect (DisconnectedEvent event) {
timer.cancel(true);
}
public SelfcareModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
loadSelfcare();
}
public void disconnect (ClientboundDisconnectPacket event) {
timer.cancel(true);
}
public SelfcareModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
loadSelfcare();
}
}
@@ -4,34 +4,29 @@ import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
import net.kyori.adventure.text.Component;
import org.geysermc.mcprotocollib.network.Session;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.protocol.data.game.entity.metadata.EntityMetadata;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.ClientboundSetEntityDataPacket;
public class TextDisplayModule extends Listener {
private Bot bot;
private static final int TEXT_DISPLAY_ENTITY_ID = 32;
private static final int TEXT_DISPLAY_ENTITY_ID = 32;
private int entityId;
@Override
public void packetReceived (Session session, Packet packet) {
if (packet instanceof ClientboundSetEntityDataPacket) getTextDisplay((ClientboundSetEntityDataPacket) packet);
}
private void getTextDisplay (ClientboundSetEntityDataPacket packet) {
for (EntityMetadata<?, ?> metaData : packet.getMetadata()) {
if (metaData.getId() == TEXT_DISPLAY_ENTITY_ID) {
Component value = (Component) metaData.getValue();
System.out.println(ComponentUtil.componentToAnsi(value));
}
@Override
public void packetReceived (Packet packet) {
if (packet instanceof ClientboundSetEntityDataPacket) getTextDisplay((ClientboundSetEntityDataPacket) packet);
}
}
public TextDisplayModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
private void getTextDisplay (ClientboundSetEntityDataPacket packet) {
for (EntityMetadata<?, ?> metaData : packet.getMetadata()) {
if (metaData.getId() == TEXT_DISPLAY_ENTITY_ID) {
Component value = (Component) metaData.getValue();
System.out.println(ComponentUtil.componentToAnsi(value));
}
}
}
public TextDisplayModule (Bot bot) {
bot.listenerManager.addListener(this);
}
}
@@ -1,50 +1,45 @@
package land.chipmunk.parker2991.nitoribot.selfcare.entity;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.listeners.*;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.level.ClientboundGameEventPacket;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.protocol.data.game.entity.player.GameMode;
import org.geysermc.mcprotocollib.protocol.data.game.level.notify.GameEvent;
import org.geysermc.mcprotocollib.protocol.data.game.level.notify.GameEventValue;
import org.geysermc.mcprotocollib.protocol.data.game.entity.player.GameMode;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.network.Session;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.level.ClientboundGameEventPacket;
public class GamemodeSelfcare extends Listener {
@org.jetbrains.annotations.NotNull
private final Bot bot;
public int gamemode = 1;
@Override
public void packetReceived (Session session, Packet packet) {
if (packet instanceof ClientboundGameEventPacket) checkGamemode((ClientboundGameEventPacket) packet);
}
private void checkGamemode (ClientboundGameEventPacket packet) {
GameEvent notification = packet.getNotification();
GameEventValue value = packet.getValue();
if (notification == GameEvent.CHANGE_GAME_MODE) {
switch (value) {
case GameMode.SURVIVAL:
gamemode = 0;
break;
case GameMode.CREATIVE:
gamemode = 1;
break;
case GameMode.ADVENTURE:
gamemode = 2;
break;
case GameMode.SPECTATOR:
gamemode = 3;
break;
default:
}
@Override
public void packetReceived (Packet packet) {
if (packet instanceof ClientboundGameEventPacket) checkGamemode((ClientboundGameEventPacket) packet);
}
}
public GamemodeSelfcare (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
private void checkGamemode (ClientboundGameEventPacket packet) {
GameEvent notification = packet.getNotification();
GameEventValue value = packet.getValue();
if (notification == GameEvent.CHANGE_GAME_MODE) {
switch (value) {
case GameMode.SURVIVAL:
gamemode = 0;
break;
case GameMode.CREATIVE:
gamemode = 1;
break;
case GameMode.ADVENTURE:
gamemode = 2;
break;
case GameMode.SPECTATOR:
gamemode = 3;
break;
default:
}
}
}
public GamemodeSelfcare (Bot bot) {
bot.listenerManager.addListener(this);
}
}
@@ -1,45 +1,40 @@
package land.chipmunk.parker2991.nitoribot.selfcare.entity;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.listeners.*;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.ClientboundEntityEventPacket;
import org.geysermc.mcprotocollib.protocol.data.game.entity.EntityEvent;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.network.Session;
import static org.geysermc.mcprotocollib.protocol.data.game.entity.EntityEvent.*;
import org.geysermc.mcprotocollib.protocol.data.game.entity.EntityEvent;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.ClientboundEntityEventPacket;
public class PermissionSelfcare extends Listener {
public int level;
public int level;
private Bot bot;
private final Bot bot;
@Override
public void packetReceived (Session session, Packet packet) {
if (packet instanceof ClientboundEntityEventPacket) getPermissionLevel((ClientboundEntityEventPacket) packet);
}
private void getPermissionLevel (ClientboundEntityEventPacket packet) {
int permEntityId = packet.getEntityId();
final int botEntityId = bot.entityId;
EntityEvent event = packet.getEvent();
if (permEntityId == botEntityId) {
switch (event) {
case EntityEvent.PLAYER_SET_NO_PERMISSIONS -> level = 0;
case EntityEvent.PLAYER_SET_MODERATOR -> level = 1;
case EntityEvent.PLAYER_SET_GAMEMASTER -> level = 2;
case EntityEvent.PLAYER_SET_ADMIN -> level = 3;
case EntityEvent.PLAYER_SET_OWNER -> level = 4;
}
@Override
public void packetReceived (Packet packet) {
if (packet instanceof ClientboundEntityEventPacket) getPermissionLevel((ClientboundEntityEventPacket) packet);
}
};
public PermissionSelfcare (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
private void getPermissionLevel (ClientboundEntityEventPacket packet) {
int permEntityId = packet.getEntityId();
final int botEntityId = bot.entityId;
EntityEvent event = packet.getEvent();
if (permEntityId == botEntityId) {
switch (event) {
case EntityEvent.PLAYER_SET_NO_PERMISSIONS -> level = 0;
case EntityEvent.PLAYER_SET_MODERATOR -> level = 1;
case EntityEvent.PLAYER_SET_GAMEMASTER -> level = 2;
case EntityEvent.PLAYER_SET_ADMIN -> level = 3;
case EntityEvent.PLAYER_SET_OWNER -> level = 4;
}
}
}
public PermissionSelfcare (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
}
@@ -22,7 +22,6 @@ import java.util.regex.Pattern;
// credits to Werkku for letting me use this
public final class ComponentUtil {
private static final Map<String, String> LANGUAGE = loadJsonStringMap("language.json");
private static final Map<String, String> KEYBINDINGS = loadJsonStringMap("keybinds.json");
@@ -32,7 +31,7 @@ public final class ComponentUtil {
private static final int MAX_DEPTH = 512; //translate depth limit
public static Map<String, String> loadJsonStringMap(String name) {
public static Map<String, String> loadJsonStringMap (String name) {
Map<String, String> map = new HashMap<>();
var is = ClassLoader.getSystemClassLoader().getResourceAsStream(name);
@@ -48,50 +47,50 @@ public final class ComponentUtil {
}
private static final GsonComponentSerializer GSON_COMPONENT_SERIALIZER = GsonComponentSerializer.builder() // 1.21.5+ gson serializer
.build();
.build();
private static final ANSIComponentSerializer ANSI_COMPONENT_SERIALIZER = ANSIComponentSerializer.builder()
.flattener(getFlattener(true))
.colorLevel(ColorLevel.TRUE_COLOR)
.build();
.flattener(getFlattener(true))
.colorLevel(ColorLevel.TRUE_COLOR)
.build();
private static final PlainTextComponentSerializer PLAIN_TEXT_COMPONENT_SERIALIZER = PlainTextComponentSerializer.builder()
.flattener(getFlattener(false))
.build();
.flattener(getFlattener(false))
.build();
private static ComponentFlattener getFlattener(boolean parseSectionSigns) {
private static ComponentFlattener getFlattener (boolean parseSectionSigns) {
return ComponentFlattener.builder()
.mapper(TextComponent.class, component -> mapText(
component, parseSectionSigns
))
.mapper(ObjectComponent.class, ComponentUtil::mapObject)
.complexMapper(KeybindComponent.class, ComponentUtil::mapKeybind)
.mapper(SelectorComponent.class, SelectorComponent::pattern)
.complexMapper(TranslatableComponent.class, ComponentUtil::mapTranslatable)
.unknownMapper(_ -> "")
.nestingLimit(MAX_DEPTH) //max depth for nested mapper calls
.build();
.mapper(TextComponent.class, component -> mapText(
component, parseSectionSigns
))
.mapper(ObjectComponent.class, ComponentUtil::mapObject)
.complexMapper(KeybindComponent.class, ComponentUtil::mapKeybind)
.mapper(SelectorComponent.class, SelectorComponent::pattern)
.complexMapper(TranslatableComponent.class, ComponentUtil::mapTranslatable)
.unknownMapper(_ -> "")
.nestingLimit(MAX_DEPTH) //max depth for nested mapper calls
.build();
}
private static String getOrReturnFallback(TranslatableComponent component) {
private static String getOrReturnFallback (TranslatableComponent component) {
var key = component.key();
var fallback = component.fallback();
return LANGUAGE.getOrDefault(
key,
fallback == null ? key : fallback
key,
fallback == null ? key : fallback
);
}
private static String guardedStringify(ComponentEncoder<Component, String> serializer, Component message) {
private static String guardedStringify (ComponentEncoder<Component, String> serializer, Component message) {
try {
return serializer.serialize(message);
} catch (Exception e) {
return serializer.serialize(Component.translatable(
"<Failed to parse component: %s>",
NamedTextColor.RED,
Component.text(e.toString())));
"<Failed to parse component: %s>",
NamedTextColor.RED,
Component.text(e.toString())));
} finally {
TOTAL_DEPTH.set(0); //set translate depth to 0 after component is parsed
}
@@ -100,58 +99,52 @@ public final class ComponentUtil {
/**
* Convert Component to a JSON string
*/
public static String componentToJSON(Component component) {
public static String componentToJSON (Component component) {
return GSON_COMPONENT_SERIALIZER.serialize(component);
}
/**
* Convert JSON string to a Component
*/
public static Component componentFromJSON(String json) {
public static Component componentFromJSON (String json) {
return GSON_COMPONENT_SERIALIZER.deserialize(json);
}
/**
* Convert Component to a string
*/
public static String componentToString(Component component) {
public static String componentToString (Component component) {
return guardedStringify(PLAIN_TEXT_COMPONENT_SERIALIZER, component);
}
/**
* Convert Component to an ANSI string
*/
public static String componentToAnsi(Component component) {
public static String componentToAnsi (Component component) {
return guardedStringify(ANSI_COMPONENT_SERIALIZER, component);
}
private static String mapObject(ObjectComponent objectComponent) {
private static String mapObject (ObjectComponent objectComponent) {
var content = objectComponent.contents();
return switch (content) {
case SpriteObjectContents c -> "<Sprite:" + c.sprite() + ">";
case PlayerHeadObjectContents c ->
"<PlayerHead:" + componentToString(Component.translatable("block.minecraft.player_head.named").arguments(Component.text((c.name() != null) ? c.name() : "Unknown"))) + ">";
default -> "<Unknown Sprite>";
"<PlayerHead:" + componentToString(Component.translatable("block.minecraft.player_head.named").arguments(Component.text((c.name() != null) ? Objects.requireNonNull(c.name()) : "Unknown"))) + ">";
};
}
private static String mapText(TextComponent component, boolean parseSectionSigns) {
private static String mapText (TextComponent component, boolean parseSectionSigns) {
var content = component.content();
//if no section sign is found, return the original content
if (!parseSectionSigns || !content.contains("§")) {
return component.content();
} else {
//TODO: make it parse section signs properly
return component.content();
}
return component.content();
}
private static void mapKeybind(KeybindComponent component, Consumer<Component> consumer) {
private static void mapKeybind (KeybindComponent component, Consumer<Component> consumer) {
consumer.accept(Component.translatable(KEYBINDINGS.getOrDefault(component.keybind(), component.keybind())));
}
private static void mapTranslatable(TranslatableComponent component, Consumer<Component> consumer) {
private static void mapTranslatable (TranslatableComponent component, Consumer<Component> consumer) {
var format = getOrReturnFallback(component);
var matcher = ARG_PATTERN.matcher(format);
List<Component> result = new ArrayList<>();
@@ -168,7 +161,7 @@ public final class ComponentUtil {
if (start > lastIndex) {
var formatSegment = format.substring(lastIndex, start);
//ensure that theres no % in the formatSegment (if there is, we have a problem with escaping)
if (formatSegment.indexOf('%') != -1) throw new IllegalArgumentException();
if (formatSegment.indexOf('%') != - 1) throw new IllegalArgumentException();
result.add(Component.text(formatSegment));
}
@@ -205,7 +198,7 @@ public final class ComponentUtil {
//handle any remaining part of the string after the last match
if (lastIndex < format.length()) {
var remaining = format.substring(lastIndex);
if (remaining.indexOf('%') != -1)
if (remaining.indexOf('%') != - 1)
throw new IllegalArgumentException(); // Make sure no unescaped '%' remains
result.add(Component.text(remaining));
}
@@ -6,12 +6,12 @@ import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
public class ErrorToString {
public static String errorToString (Throwable error) {
final var byteArrayOut = new ByteArrayOutputStream();
final var outWriter = new OutputStreamWriter(byteArrayOut);
final var printWriter = new PrintWriter(outWriter);
error.printStackTrace(printWriter);
printWriter.flush();
return byteArrayOut.toString(StandardCharsets.UTF_8);
}
public static String errorToString (Throwable error) {
final var byteArrayOut = new ByteArrayOutputStream();
final var outWriter = new OutputStreamWriter(byteArrayOut);
final var printWriter = new PrintWriter(outWriter);
error.printStackTrace(printWriter);
printWriter.flush();
return byteArrayOut.toString(StandardCharsets.UTF_8);
}
}
@@ -2,14 +2,13 @@ package land.chipmunk.parker2991.nitoribot.util;
import net.kyori.adventure.text.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class TranslationsUtil {
private static final String TAG = "nitoribot";
private static final String TAG = "nitoribot";
private static final Map<String, String> TRANSLATIONS = ComponentUtil.loadJsonStringMap("translations.json");
private static final Map<String, String> TRANSLATIONS = ComponentUtil.loadJsonStringMap("translations.json");
/*public static void customTranslations (String translation, Component component) {
List<Component> list = new ArrayList<>();
@@ -22,18 +21,20 @@ public class TranslationsUtil {
customTranslations(translation, list);
}*/
public static Component customTranslations (String translation, List<Component> component) {
Component fallback;
if (component == null) fallback = Component.translatable(TAG + "." + translation).fallback(getTranslation(translation));
else fallback = Component.translatable(TAG + "." + translation, component).fallback(getTranslation(translation));
public static Component customTranslations (String translation, List<Component> component) {
Component fallback;
if (component == null)
fallback = Component.translatable(TAG + "." + translation).fallback(getTranslation(translation));
else
fallback = Component.translatable(TAG + "." + translation, component).fallback(getTranslation(translation));
return fallback;
}
private static String getTranslation (String translation) {
for (Map.Entry<String, String> translations : TRANSLATIONS.entrySet()) {
if (translation.equals(translations.getKey())) return translations.getValue();
return fallback;
}
private static String getTranslation (String translation) {
for (Map.Entry<String, String> translations : TRANSLATIONS.entrySet()) {
if (translation.equals(translations.getKey())) return translations.getValue();
}
return null;
}
return null;
}
}
@@ -2,37 +2,39 @@ package land.chipmunk.parker2991.nitoribot.util;
import org.cloudburstmc.nbt.NbtMap;
import org.cloudburstmc.nbt.NbtMapBuilder;
import java.util.UUID;
import java.nio.ByteBuffer;
import java.util.UUID;
public class UUIDUtil {
private UUIDUtil () {
}
private UUIDUtil () {
}
public static int[] intArray (UUID uuid) {
final ByteBuffer buffer = ByteBuffer.wrap(new byte[16]);
buffer.putLong(0, uuid.getMostSignificantBits());
buffer.putLong(8, uuid.getLeastSignificantBits());
public static int[] intArray (UUID uuid) {
final ByteBuffer buffer = ByteBuffer.wrap(new byte[16]);
buffer.putLong(0, uuid.getMostSignificantBits());
buffer.putLong(8, uuid.getLeastSignificantBits());
final int[] intArray = new int[4];
for (int i = 0; i < intArray.length; i++) intArray[i] = buffer.getInt();
final int[] intArray = new int[4];
for (int i = 0; i < intArray.length; i++) intArray[i] = buffer.getInt();
return intArray;
}
return intArray;
}
public static NbtMap tag (UUID uuid) {
final NbtMapBuilder builder = NbtMap.builder();
public static NbtMap tag (UUID uuid) {
final NbtMapBuilder builder = NbtMap.builder();
builder.putIntArray("", intArray(uuid));
builder.putIntArray("", intArray(uuid));
return builder.build();
}
return builder.build();
}
public static String snbt (UUID uuid) {
int[] array = intArray(uuid);
return "[I;" + array[0] + "," + array[1] + "," + array[2] + "," + array[3] + "]";
}
public static String snbt (UUID uuid) {
int[] array = intArray(uuid);
return "[I;" + array[0] + "," + array[1] + "," + array[2] + "," + array[3] + "]";
}
public static String selector (UUID uuid) { return "@p[nbt={UUID:" + snbt(uuid) + "}]"; }
public static String exclusiveSelector (UUID uuid) { return "@a[nbt=!{UUID:" + snbt(uuid) + "}]"; }
public static String selector (UUID uuid) {return "@p[nbt={UUID:" + snbt(uuid) + "}]";}
public static String exclusiveSelector (UUID uuid) {return "@a[nbt=!{UUID:" + snbt(uuid) + "}]";}
}
+1 -1
View File
@@ -25,7 +25,7 @@
"color": "blue"
}
],
"build": "5300",
"build": "5310",
"versionReleaseDate": "N\\A",
"initialBotRelease": "11/22/22"
},