Compare commits

...
7 Commits
Author SHA1 Message Date
Parker2991 a331466d9e fucking intellij formatting 2026-10-08 10:28:41 -05:00
Parker2991 4fb7099c0f refactored the command system
made the bot store the config in <home directory root>/.config
fuck you custom translations
semi-parsed the world
2026-10-08 10:01:10 -05:00
Parker2991 89dbac9974 refracture pretty much everything 2026-10-06 15:00:05 -05:00
Parker2991 dc03b5157f move functions that i call at boot to their own classes 2026-09-17 12:34:39 -05:00
Parker2991 4e2d737f9d fix the time in the jar not being in my timezone 2026-09-17 12:15:17 -05:00
Parker2991 16c92b075d EMERGENCY THREAD FIX!?!!11!! 2026-09-17 12:07:23 -05:00
Parker2991 6a26617c83 v9.0.0-alpha build: 5300 2026-09-17 09:30:17 -05:00
81 changed files with 10093 additions and 9869 deletions
+1 -1
View File
@@ -11,4 +11,4 @@ build
bin
# Ignore the config
config.yaml
config.yml
+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 -1
View File
@@ -5,7 +5,7 @@
<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$" />
+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>
+7
View File
@@ -1,5 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="PrintToLogpointModuleInspectionState">
<option name="disabledModuleNames">
<set>
<option value="NitoriBot.main" />
</set>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_25" default="true" project-jdk-name="25 (4)" project-jdk-type="JavaSDK" />
</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>
+53 -35
View File
@@ -1,11 +1,14 @@
version = "v9.0.0"
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.ZoneId
import java.time.ZonedDateTime
version = "v9.0.0-alpha"
group = "nitoribot"
description = "NitoriBot"
plugins {
id("com.gradleup.shadow") version "9.2.2"
kotlin("jvm") version "2.3.10"
id("maven-publish")
application
}
kotlin {
@@ -13,50 +16,65 @@ kotlin {
}
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.optmstc.dev/api/packages/kso/maven") {
content {
includeGroupAndSubgroups("land.chipmunk.code")
}
}*/
//maven("https://libraries.minecraft.net")
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:4.26.1")
implementation("net.kyori:adventure-text-serializer-plain:4.26.1")
implementation("net.kyori:adventure-text-serializer-legacy:4.26.1")
implementation("net.kyori:adventure-text-serializer-gson:4.26.1")
implementation("net.dv8tion:JDA:6.4.1")
implementation("de.connect2x.trixnity:trixnity-client:5.0.0")
implementation("org.pircbotx:pircbotx:2.1")
implementation("org.jline:jline:4.1.0")
implementation("land.chipmunk.code.kaboomstandardsorganization.messaginglib:mcprotocollib:3.1.2")
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")
}
application {
mainClass.set("land.chipmunk.parker2991.nitoribot.Main")
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();
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,173 +1,111 @@
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.modules.*;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
import land.chipmunk.parker2991.nitoribot.listeners.*;
import net.kyori.adventure.text.Component;
import org.geysermc.mcprotocollib.network.ProxyInfo;
import org.geysermc.mcprotocollib.protocol.MinecraftProtocol;
import org.geysermc.mcprotocollib.auth.GameProfile;
import org.geysermc.mcprotocollib.network.Session;
import org.geysermc.mcprotocollib.network.event.session.DisconnectingEvent;
import org.geysermc.mcprotocollib.network.event.session.DisconnectedEvent;
import org.geysermc.mcprotocollib.network.event.session.DisconnectingEvent;
import org.geysermc.mcprotocollib.network.event.session.PacketErrorEvent;
import org.geysermc.mcprotocollib.network.event.session.SessionAdapter;
import org.geysermc.mcprotocollib.network.session.ClientNetworkSession;
import org.geysermc.mcprotocollib.network.factory.ClientNetworkSessionFactory;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.auth.GameProfile;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.ServerboundPlayerLoadedPacket;
import org.geysermc.mcprotocollib.protocol.packet.login.clientbound.ClientboundLoginFinishedPacket;
import org.geysermc.mcprotocollib.network.session.ClientNetworkSession;
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.*;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.Scanner;
import java.nio.file.Paths;
import java.util.Map;
import java.util.concurrent.*;
public class Bot extends SessionAdapter {
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 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 boolean loggedIn = false;
public int entityId;
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 WorldModule world;
public List<?> modules;
public ProxyInfo randomProxyIp () throws IOException {
String result = null; // stub
Path proxiesPath = Paths.get("proxies.txt");
int countLines = Math.round(
Files.lines(proxiesPath).count()
);
Random random = new Random();
int randomIndex = random.nextInt(countLines);
String[] getIp = Files.lines(proxiesPath)
.skip(randomIndex)
.findAny()
.get()
.split(":");
String ip = getIp[0];
int port = new Integer(getIp[1]);
return new ProxyInfo(
ProxyInfo.Type.SOCKS5,
new InetSocketAddress(ip, port)
);
}
public void loadModules () {
try {
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);
} catch (Exception e) {}
}
public Bot (Config.Options options, List<Bot> bots, Config config) {
public Bot (Config.Options options, List<Bot> bots, @NotNull Config config) throws IOException {
this.options = options;
this.bots = bots;
this.config = config;
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),
this.world = new WorldModule(this)
);
try {
connect();
} catch (Exception e) {}
};
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public void connect () throws IOException {
final MinecraftProtocol protocol = new MinecraftProtocol(options.username);
if (options.useProxy) session = ClientNetworkSessionFactory.factory()
.setAddress(
if (options.useProxy) session = ClientNetworkSessionFactory.factory().setAddress(
options.host,
options.port
)
.setProxy(randomProxyIp())
.setProtocol(protocol)
.create();
).setProxy(new GetProxiesList().randomProxyIp()).setProtocol(protocol).create();
else session = ClientNetworkSessionFactory.factory()
.setAddress(
else session = ClientNetworkSessionFactory.factory().setAddress(
options.host,
options.port
)
.setProtocol(protocol)
.create();
).setProtocol(protocol).create();
session.addListener(this);
loadModules();
session.connect(false);
}
@Override
public void disconnecting (DisconnectingEvent event) {
String reason = event + "";
session.disconnect(reason);
Component component = event.getReason();
session.disconnect(component);
}
// ServerboundPlayerLoadedPacket
@Override
public void packetSent (Session session, Packet packet) {
for (Listener listener : listenerManager.listeners) {
listener.packetSent(session, packet);
listener.packetSent();
}
}
@@ -179,21 +117,20 @@ public class Bot extends SessionAdapter {
@Override
public void packetReceived (Session session, Packet packet) {
try {
if (packet instanceof ClientboundLoginPacket) this.session.send(
ServerboundPlayerLoadedPacket.INSTANCE
);
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);
listener.packetReceived(packet);
}
if (packet instanceof ClientboundLoginFinishedPacket) getProfile((ClientboundLoginFinishedPacket) packet);
else if (packet instanceof ClientboundLoginPacket) getEntityId((ClientboundLoginPacket) packet);
} catch (Exception e) { }
} catch (Exception _) {
}
}
@@ -209,24 +146,24 @@ public class Bot extends SessionAdapter {
@Override
public void disconnected (DisconnectedEvent event) {
listenerManager.clearListener();
loggedIn = false;
Component component = event.getReason();
String reason = ComponentUtil.componentToAnsi(component);
int reconnectDelay = options.reconnectDelay;
Logger.RECONNECT(this, reason);
executor.schedule(() -> {
if (services.get("reconnect") != null) services.get("reconnect").cancel(true);
services.put(
"reconnect", executor.schedule(
() -> {
try {
connect();
} catch (IOException e) {
throw new RuntimeException(e);
}
}, reconnectDelay, TimeUnit.MILLISECONDS);
}, options.reconnectDelay, TimeUnit.MILLISECONDS
)
);
}
}
@@ -3,56 +3,52 @@ package land.chipmunk.parker2991.nitoribot;
import java.util.List;
public class Config {
public final Colors colors = new Colors();
public final Core core = new Core();
public final Console console = new Console();
public final Options[] bots = new Options[]{};
public List<String> prefixes;
public static class Core {
public Area area = new Area();
public final Area area = new Area();
public String coreName;
}
public static class Area {
public Position start = new Position();
public Position end = new Position();
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 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 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 String Public;
public String trusted;
public String admin;
public String owner;
public String console;
}
public static class Console {
public String prefix = "c.";
public String prefix;
}
public static class Colors {
public String integer = "gold";
public CommandColors commands = new CommandColors();
public HelpCommandColors help = new HelpCommandColors();
public final CommandColors commands = new CommandColors();
public final HelpCommandColors help = new HelpCommandColors();
public String integer;
}
public Colors colors = new Colors();
public Core core = new Core();
public Console console = new Console();
public Options[] bots = new Options[]{};
public static class Options {
public String host;
public int port;
@@ -61,5 +57,6 @@ public class Config {
public String username;
public int reconnectDelay;
public int selfcareInterval;
};
public String mode;
}
}
@@ -1,73 +1,42 @@
package land.chipmunk.parker2991.nitoribot;
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;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.constructor.Constructor;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.*;
public class Main {
public final Object obj = new Object();
public static final ExecutorService executorService = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors()
);
public static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(
Runtime.getRuntime().availableProcessors()
);
public static Config config;
public static final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
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 final List<Bot> Bots = new ArrayList<>();
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)) {
//LoggerManager.INFO(null, "config not found making config now");
InputStream defaultConfig = Main.class.getClassLoader().getResourceAsStream("default_config.yaml");
Files.copy(defaultConfig, Paths.get("config.yaml"));
}
InputStream configFile = Files.newInputStream(configPath);
config = yaml.load(configFile);
return config;
}
public static RepoCommitInfo repoCommitInfo = null;
public static BotBuildInfo botBuildInfo = null;
public static ConsoleModule console;
public Config config;
public void main(String[] args) {
void main () {
try {
config = loadConfig();
config = new LoadConfig().loadConfig();
Config.Options[] bots = config.bots;
console = new ConsoleModule();
repoCommitInfo = new GetRepoInfo().getRepoInfo();
botBuildInfo = new GetBotBuildInfo().getBuildInfo();
console = new ConsoleModule(config);
for (Config.Options options : bots) {
final Bot bot = new Bot(options, Bots, config);
Bots.add(bot);
}
synchronized(obj) {
obj.wait();
};
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
};
}
@@ -0,0 +1,19 @@
package land.chipmunk.parker2991.nitoribot.boot;
import com.google.gson.Gson;
import land.chipmunk.parker2991.nitoribot.Main;
import land.chipmunk.parker2991.nitoribot.data.buildstring.BotBuildInfo;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Objects;
public class GetBotBuildInfo {
private static final Gson GSON = new Gson();
public BotBuildInfo getBuildInfo () {
Reader reader = new InputStreamReader(Objects.requireNonNull(Main.class.getResourceAsStream("/info.json")));
return GSON.fromJson(reader, BotBuildInfo.class);
}
}
@@ -0,0 +1,31 @@
package land.chipmunk.parker2991.nitoribot.boot;
import org.geysermc.mcprotocollib.network.ProxyInfo;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Random;
public class GetProxiesList {
public ProxyInfo randomProxyIp () throws IOException {
Path proxiesPath = Paths.get("proxies.txt");
int countLines = Math.round(Files.lines(proxiesPath).count());
Random random = new Random();
int randomIndex = random.nextInt(countLines);
List<String> lines = Files.lines(proxiesPath).toList();
String[] ip = lines.stream().skip(randomIndex).findAny().get().split(":");
InetSocketAddress address = new InetSocketAddress(ip[0], Integer.parseInt(ip[1]));
return new ProxyInfo(ProxyInfo.Type.SOCKS5, address);
}
}
@@ -0,0 +1,42 @@
package land.chipmunk.parker2991.nitoribot.boot;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import land.chipmunk.parker2991.nitoribot.data.buildstring.RepoCommitInfo;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class GetRepoInfo {
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(
10)).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());
info = GSON.fromJson(e.getAsJsonArray().get(0), RepoCommitInfo.class);
} catch (Exception e) {
e.printStackTrace(System.err);
}
return info;
}
}
@@ -0,0 +1,43 @@
package land.chipmunk.parker2991.nitoribot.boot;
import land.chipmunk.parker2991.nitoribot.Config;
import land.chipmunk.parker2991.nitoribot.Main;
import land.chipmunk.parker2991.nitoribot.logger.Logger;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
public class LoadConfig {
private static final String XDG_CONFIG_HOME = System.getenv("XDG_CONFIG_HOME");
private final Constructor yamlConfig = new Constructor(Config.class, new LoaderOptions());
private final Yaml yaml = new Yaml(yamlConfig);
private final String homeDirectory = System.getProperty("user.home");
public Config loadConfig () throws IOException {
Path configDirectory;
if (XDG_CONFIG_HOME == null) configDirectory = Path.of(homeDirectory, ".config/NitoriBot");
else configDirectory = Path.of(XDG_CONFIG_HOME, "NitoriBot");
final Path configPath = Path.of(String.valueOf(configDirectory), "config.yml");
if (!Files.exists(configPath)) {
Logger.INFO(null, "config not found, creating config in " + configPath);
if (!Files.exists(configDirectory)) Files.createDirectory(configDirectory);
InputStream defaultConfig = Main.class.getClassLoader().getResourceAsStream("default_config.yml");
if (defaultConfig != null) {
Files.copy(defaultConfig, configPath);
}
}
InputStream configFile = Files.newInputStream(configPath);
return yaml.load(configFile);
}
}
@@ -1,19 +1,19 @@
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 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();
private final Bot bot;
public KaboomChatParser (Bot bot) {
this.bot = bot;
@@ -28,9 +28,9 @@ public class KaboomChatParser implements ParseChatData {
public PlayerMessageData parse (TextComponent message) {
List<Component> children = message.children();
if (!message.content().equals("") || !message.style().isEmpty() || children == null || children.size() < 3) return null;
if (!message.content().isEmpty() || !message.style().isEmpty() || children.size() < 3) return null;
final Component prefix = children.get(0);
final Component prefix = children.getFirst();
Component displayName = Component.empty();
Component contents = Component.empty();
@@ -43,11 +43,12 @@ public class KaboomChatParser implements ParseChatData {
return null;
}
PlayerProfileData sender = bot.players.getDisplayName(Component.empty().append(prefix).append(displayName));//getSender());
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);
return (children.get(start).equals(SEPERATOR_COLON) || children.get(start).equals(SEPERATOR_COLON_RACCOON)) && children.get(
start + 1).equals(SEPERATOR_SPACE);
}
}
@@ -2,19 +2,5 @@ package land.chipmunk.parker2991.nitoribot.command;
import land.chipmunk.parker2991.nitoribot.Bot;
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,8 +3,7 @@ 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;
@@ -1,19 +1,15 @@
package land.chipmunk.parker2991.nitoribot.command;
public abstract class CommandInfo {
public String name;
public CommandTrustLevels trustlevel;
public String[] aliases;
public 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 abstract void execute (CommandContext context);
import java.util.List;
public interface CommandInfo {
//String getCommandName ();
CommandTrustLevels getTrustLevel ();
List<String> getAliases ();
String getDescription ();
void execute (CommandContext context);
}
@@ -1,45 +1,16 @@
package land.chipmunk.parker2991.nitoribot.command;
import land.chipmunk.parker2991.nitoribot.data.PlayerProfileData;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.data.ParsedChatType;
import land.chipmunk.parker2991.nitoribot.data.PlayerProfileData;
import net.kyori.adventure.text.Component;
import org.cloudburstmc.math.vector.Vector3d;
public record CommandSource(PlayerProfileData sender, boolean inGame, ParsedChatType chatType) {
public void sendFeedback (Bot bot, Component message) {
final String selector = String.format("@p[nbt={UUID:%s}]", sender().entityUUID());
public class CommandSource {
private Bot bot;
public PlayerProfileData sender;
public boolean inGame;
public CommandSource (Bot bot, PlayerProfileData sender) {
this.bot = bot;
this.sender = sender;
if (chatType() == ParsedChatType.NORMAL) bot.chat.tellraw("@a", message);
else bot.chat.tellraw(selector, message);
}
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}",
playerPos.getX(),
playerPos.getY(),
playerPos.getZ(),
"NitoriBot",
convertToJson
);
String selector = String.format(
"@p[nbt={UUID:%s}]",
sender.entityUUID
);
bot.chat.tellraw(selector, message);
}
}
@@ -1,10 +1,5 @@
package land.chipmunk.parker2991.nitoribot.command;
public enum CommandTrustLevels {
PUBLIC,
TRUSTED,
ADMIN,
OWNER,
CONSOLE,
DISABLED
PUBLIC, TRUSTED, ADMIN, OWNER, CONSOLE, DISABLED
}
@@ -5,20 +5,32 @@ import land.chipmunk.parker2991.nitoribot.command.CommandContext;
import land.chipmunk.parker2991.nitoribot.command.CommandInfo;
import land.chipmunk.parker2991.nitoribot.command.CommandTrustLevels;
public class EchoCommand extends CommandInfo {
import java.util.List;
public class EchoCommand implements CommandInfo {
public EchoCommand () {
super(
"echo",
CommandTrustLevels.PUBLIC,
new String[] { "say" },
"make the bot say a message"
);
}
@Override
public CommandTrustLevels getTrustLevel () {
return CommandTrustLevels.PUBLIC;
}
@Override
public List<String> getAliases () {
return List.of("echo", "say");
}
@Override
public String getDescription () {
return "make the bot say something";
}
@Override
public void execute (CommandContext context) {
Bot bot = context.bot;
String args = String.join(" ", context.args);
Bot bot = context.bot();
String args = String.join(" ", context.args());
if (args.startsWith("/")) {
bot.chat.command(args.substring("/".length()));
} else {
@@ -1,153 +1,107 @@
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.util.TranslationsUtil;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
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 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 java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class HelpCommand extends CommandInfo {
import static land.chipmunk.parker2991.nitoribot.util.ComponentUtil.convertColorString;
public class HelpCommand implements CommandInfo {
public HelpCommand () {
super(
"help",
CommandTrustLevels.PUBLIC,
new String[] { "heko", "hell", "?", "cmds"},
"see the list of commands"
);
}
@Override
public CommandTrustLevels getTrustLevel () {
return CommandTrustLevels.PUBLIC;
}
@Override
public List<String> getAliases () {
return List.of("help", "hell", "?", "heko", "cmds", "commands");
}
@Override
public String getDescription () {
return "see the list of commands the bot has";
}
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;
switch (commands.getTrustLevel()) {
case CommandTrustLevels.PUBLIC -> {
Public.add(Component.text(commands.getAliases().getFirst() + " ").color(convertColorString(bot.config.colors.help.Public)));
}
case CommandTrustLevels.TRUSTED -> {
Trusted.add(Component.text(commands.getAliases().getFirst() + " ").color(convertColorString(bot.config.colors.help.trusted)));
}
default -> {
}
}
}
Component component = Component.empty()
.append(Public)
.append(Component.text("\n"))
.append(Trusted);
// .append(Component.text("\n"));
return component;
return Component.empty().append(Public).append(Component.text("\n")).append(Trusted);
}
private Component getCommand (Bot bot, String[] command) {
List<Component> list = new ArrayList<>();
Component component = null;
for (CommandInfo commands : bot.commandManager.commands) {
if (commands.name.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)
)
)
);
for (String aliases : commands.getAliases()) {
if (aliases.equals(command[0])) component = Component.translatable(
"%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s",
Component.text("Command").color(convertColorString(bot.config.colors.commands.primary)),
Component.text(commands.getAliases().getFirst()).color(convertColorString(bot.config.colors.commands.secondary)),
Component.text("Aliases").color(convertColorString(bot.config.colors.commands.primary)),
Component.text(commands.getAliases().toString()).color(convertColorString(bot.config.colors.commands.secondary)),
Component.text("Description").color(convertColorString(bot.config.colors.commands.primary)),
Component.text(commands.getDescription()).color(convertColorString(bot.config.colors.commands.secondary)),
Component.text("Trust Level").color(convertColorString(bot.config.colors.commands.primary)),
Component.text(commands.getTrustLevel().toString()).color(convertColorString(bot.config.colors.commands.secondary)),
Component.text("Usages").color(convertColorString(bot.config.colors.commands.primary)),
Component.text("DUMMY STRING").color(convertColorString(bot.config.colors.commands.secondary))
).color(convertColorString(bot.config.colors.commands.tertiary));
}
}
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<>();
Bot bot = context.bot();
String[] args = context.args();
CommandSource source = context.source();
if (args.length != 0) {
source.sendFeedback(getCommand(bot, args));
//return null;
source.sendFeedback(bot, 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 = Component.translatable(
"%s: (%s) (%s | %s | %s | %s) ›\n",
Component.text("Commands").color(convertColorString(bot.config.colors.commands.primary)),
Component.text(String.valueOf(bot.commandManager.commands.size())).color(convertColorString(bot.config.colors.integer)),
Component.text("Public").color(convertColorString(bot.config.colors.help.Public)),
Component.text("Trusted").color(convertColorString(bot.config.colors.help.trusted)),
Component.text("Admin").color(convertColorString(bot.config.colors.help.admin)),
Component.text("Owner").color(convertColorString(bot.config.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)
)).color(convertColorString(bot.config.colors.commands.tertiary));
Component component = Component.empty()
.append(helpLayout)
.append(Component.join(JoinConfiguration.separator(Component.space()), getCommands(bot)));
source.sendFeedback(component);
source.sendFeedback(bot, component);
}
}
@@ -0,0 +1,103 @@
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 land.chipmunk.parker2991.nitoribot.data.buildstring.BotBuildInfo;
import land.chipmunk.parker2991.nitoribot.data.buildstring.RepoCommitInfo;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import java.io.IOException;
import java.net.URL;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import static land.chipmunk.parker2991.nitoribot.util.ComponentUtil.convertColorString;
public class InfoCommand implements CommandInfo {
private final Enumeration<URL> resources = InfoCommand.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
private final Manifest manifest = new Manifest(resources.nextElement().openStream());
private final Attributes attributes = manifest.getMainAttributes();
private final String buildTime = attributes.getValue("Build-Time");
public InfoCommand () throws IOException {
}
@Override
public CommandTrustLevels getTrustLevel () {
return CommandTrustLevels.PUBLIC;
}
@Override
public List<String> getAliases () {
return List.of("information", "info");
}
@Override
public String getDescription () {
return "see the bots info";
}
@Override
public void execute (CommandContext context) {
var bot = context.bot();
var source = context.source();
var args = context.args();
Component component = null;
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(convertColorString(bot.config.colors.commands.primary)),
Component.text(bot.modules.size()).color(convertColorString(bot.config.colors.integer)),
Component.text("Commands").color(convertColorString(bot.config.colors.commands.primary)),
Component.text(bot.commandManager.commands.size()).color(convertColorString(bot.config.colors.integer)),
Component.text("Chat Parsers").color(convertColorString(bot.config.colors.commands.primary)),
Component.text(bot.chat.chatParsers.size()).color(convertColorString(bot.config.colors.integer))
);
case "version" -> {
BotBuildInfo info = bot.botBuildInfo;
RepoCommitInfo repoCommitInfo = bot.repoCommitInfo;
ZonedDateTime dateTime = ZonedDateTime.parse(repoCommitInfo.created);
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(convertColorString(bot.config.colors.commands.secondary)),
gson.deserialize(info.buildstring.codename.toString()),
Component.text("Build").color(convertColorString(bot.config.colors.commands.primary)),
Component.text(info.buildstring.build).color(convertColorString(bot.config.colors.integer)),
Component.text("Commit").color(convertColorString(bot.config.colors.commands.primary)),
Component.text(repoCommitInfo.sha.substring(
0,
8
)).color(convertColorString(bot.config.colors.commands.secondary)),
Component.text("Version release Date").color(convertColorString(bot.config.colors.commands.primary)),
Component.text(dateTime.format(dateTimeFormatter)).color(convertColorString(bot.config.colors.commands.secondary)),
Component.text("Initial Bot Release").color(convertColorString(bot.config.colors.commands.primary)),
Component.text(info.buildstring.initialBotRelease).color(convertColorString(bot.config.colors.commands.secondary)),
Component.text("Jar Compile Date").color(convertColorString(bot.config.colors.commands.primary)),
Component.text(buildTime).color(convertColorString(bot.config.colors.commands.secondary))
).color(convertColorString(bot.config.colors.commands.tertiary));
}
}
source.sendFeedback(bot, component);
}
}
@@ -3,24 +3,34 @@ 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 {
import java.util.List;
public class MCServerCommand implements CommandInfo {
public MCServerCommand () {
super(
"mcserver",
CommandTrustLevels.PUBLIC,
new String[] { "minecraftserver" },
"ping a minecraft server"
);
}
@Override
public CommandTrustLevels getTrustLevel () {
return CommandTrustLevels.PUBLIC;
}
@Override
public List<String> getAliases () {
return List.of("mcserver");
}
@Override
public String getDescription () {
return "ping minecraft servers";
}
@Override
public void execute (CommandContext context) {
var bot = context.bot;
var source = context.source;
String args = String.join(" ", context.args);
var bot = context.bot();
var source = context.source();
String args = String.join(" ", context.args());
var ip = args.split(":");
@@ -28,25 +38,6 @@ public class MCServerCommand extends CommandInfo {
System.out.println(info);
/*source.sendFeedback(
Component.translatable(
"%s: (%s / %s)",
Component.text("Players").color(NamedTextColor.BLUE),
Component.text(info.playersOnline()).color(NamedTextColor.GOLD),
Component.text(info.maxPlayers()).color(NamedTextColor.GOLD)
)
);*/
/*source.sendFeedback(
Component.translatable(
"Server Version %s %s %s",
Component.text(":").color(NamedTextColor.GRAY),
Component.text(info.versionName()),
Component.text(info.protocolVersion())
)
);*/
//source.sendFeedback(info.description());
}
}
/*
@@ -6,25 +6,40 @@ import land.chipmunk.parker2991.nitoribot.command.CommandInfo;
import land.chipmunk.parker2991.nitoribot.command.CommandSource;
import land.chipmunk.parker2991.nitoribot.command.CommandTrustLevels;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
public class RCCommand extends CommandInfo {
import java.util.List;
import static land.chipmunk.parker2991.nitoribot.util.ComponentUtil.convertColorString;
public class RCCommand implements CommandInfo {
public RCCommand () {
super(
"rc",
CommandTrustLevels.PUBLIC,
new String[] { "refill", "refillcore" },
"refill the bot's core"
);
}
@Override
public CommandTrustLevels getTrustLevel () {
return CommandTrustLevels.PUBLIC;
}
@Override
public List<String> getAliases () {
return List.of("rc", "refillcore");
}
@Override
public String getDescription () {
return "refill the bots core";
}
@Override
public void execute (CommandContext context) {
Bot bot = context.bot;
CommandSource source = context.source;
Bot bot = context.bot();
CommandSource source = context.source();
bot.core.move();
source.sendFeedback(Component.text("Refilling core").color(NamedTextColor.BLUE));
source.sendFeedback(
bot,
Component.text("Refilling core").color(convertColorString(bot.config.colors.commands.primary))
);
}
}
@@ -0,0 +1,62 @@
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.minimessage.MiniMessage;
import java.util.List;
/*
Adventure Minimessage is very fucking weird.....
the fact it uses an HTML style with strings instead of components is very weird
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 implements CommandInfo {
private static final MiniMessage MINI_MESSAGE = MiniMessage.miniMessage();
public TestCommand () {
}
@Override
public CommandTrustLevels getTrustLevel () {
return CommandTrustLevels.PUBLIC;
}
@Override
public List<String> getAliases () {
return List.of("test");
}
@Override
public String getDescription () {
return "test cmd";
}
@Override
public void execute (CommandContext context) {
var bot = context.bot();
var args = String.join(" ", context.args());
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>"
));
source.sendFeedback(bot, component);
}
}
@@ -1,20 +1,35 @@
package land.chipmunk.parker2991.nitoribot.commands.trusted;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.command.*;
public class ReconnectCommand extends CommandInfo {
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.command.CommandContext;
import land.chipmunk.parker2991.nitoribot.command.CommandInfo;
import land.chipmunk.parker2991.nitoribot.command.CommandTrustLevels;
import java.util.List;
public class ReconnectCommand implements CommandInfo {
public ReconnectCommand () {
super(
"reconnect",
CommandTrustLevels.TRUSTED,
new String[] { },
"reconnect the bot"
);
}
@Override
public CommandTrustLevels getTrustLevel () {
return CommandTrustLevels.TRUSTED;
}
@Override
public List<String> getAliases () {
return List.of("end");
}
@Override
public String getDescription () {
return "reconnect the bot";
}
@Override
public void execute (CommandContext context) {
Bot bot = context.bot;
Bot bot = context.bot();
bot.session.disconnect("Reconnect Command");
}
@@ -0,0 +1,5 @@
package land.chipmunk.parker2991.nitoribot.data;
public enum ChatType {
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) {
}
@@ -0,0 +1,4 @@
package land.chipmunk.parker2991.nitoribot.data;
public record DimensionData(String dimension, int maxHeight, int minHeight) {
}
@@ -0,0 +1,5 @@
package land.chipmunk.parker2991.nitoribot.data;
public enum ParsedChatType {
COMMANDSPY, NORMAL
}
@@ -5,12 +5,10 @@ import net.kyori.adventure.text.Component;
public record PingServerData(
//String ip,
//int port,
String versionName,
long protocolVersion,
int playersOnline,
int maxPlayers,
Component description
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,44 +1,31 @@
package land.chipmunk.parker2991.nitoribot.data;
import land.chipmunk.parker2991.nitoribot.util.UUIDUtil;
import org.geysermc.mcprotocollib.protocol.data.game.entity.player.GameMode;
import org.geysermc.mcprotocollib.auth.GameProfile;
import net.kyori.adventure.text.Component;
import org.cloudburstmc.math.vector.Vector3d;
import org.geysermc.mcprotocollib.auth.GameProfile;
import org.geysermc.mcprotocollib.protocol.data.game.entity.player.GameMode;
import org.jetbrains.annotations.Nullable;
import java.util.UUID;
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 record PlayerProfileData(UUID uuid, String entityUUID, GameProfile profile, boolean listed, int latency,
GameMode gameMode, 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) {
public PlayerProfileData (
UUID uuid,
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;
}
}
@@ -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) {
}
@@ -0,0 +1,25 @@
package land.chipmunk.parker2991.nitoribot.data.buildstring;
import com.google.gson.JsonObject;
import java.util.List;
public class BotBuildInfo {
public final BuildInfo buildstring = new BuildInfo();
public String owner;
public Contributors[] contributors = new Contributors[]{};
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 Contributors {
public String name;
public String reason;
}
}
@@ -0,0 +1,9 @@
package land.chipmunk.parker2991.nitoribot.data.buildstring;
public class RepoCommitInfo {
public String sha;
public String created;
public int commits;
}
@@ -1,13 +1,7 @@
package land.chipmunk.parker2991.nitoribot.data.chat;
//import land.chipmunk.parker2991.nitoribot.data.PlayerProfileData;
import net.kyori.adventure.text.Component;
//import org.geysermc.mcprotocollib.protocol.data.game.PlayerListEntry;
public interface ParseChatData {
PlayerMessageData parse (Component message);
// PlayerProfileData parse (PlayerMessageData data);
}
@@ -1,20 +1,7 @@
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,31 +1,32 @@
package land.chipmunk.parker2991.nitoribot.listeners;
import io.netty.buffer.ByteBuf;
import land.chipmunk.code.kaboomstandardsorganization.messaginglib.mcprotocollib.MCProtocolLibMessenger;
import org.geysermc.mcprotocollib.network.Session;
import org.geysermc.mcprotocollib.network.packet.Packet;
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.packet.Packet;
import java.util.UUID;
public class Listener {
public void packetSent (Session session, Packet packet) {}
public void packetReceived (Session session, Packet packet) {}
public void extrasMessagingReceived (MCProtocolLibMessenger messenger) {}
public void chatAttestationMessageReceived () {}
public void playerChatReceived (Component message) {}
public void disguisedChatReceived (Component message) {}
public void systemChatReceived (Component message) {}
public void parsedMessage (Component message, PlayerMessageData data) {}
public void botMoved () {}
public interface Listener {
default void packetSent () {
}
default void packetReceived (Packet packet) {
}
default void playerChatReceived (Component message) {
}
default void disguisedChatReceived (Component message) {
}
default void systemChatReceived (Component message) {
}
default void parsedMessage (PlayerMessageData data) {
}
default void botMoved () {
}
default void commandSpyReceived (PlayerProfileData player, String command) {
}
}
@@ -3,14 +3,14 @@ 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 {
@@ -18,6 +18,38 @@ public class Logger {
private final DateTimeFormatter formatDate = DateTimeFormatter.ofPattern("MM/dd/yyyy");
public Logger () {
}
public static void LOG (Bot bot, String message) {
new Logger().prefix(LoggerType.LOG, bot, message);
}
public static void DEBUG (Bot bot, String message) {
new Logger().prefix(LoggerType.DEBUG, bot, message);
}
public static void ERROR (Bot bot, String message) {
new Logger().prefix(LoggerType.ERROR, bot, message);
}
public static void WARN (Bot bot, String message) {
new Logger().prefix(LoggerType.WARN, bot, message);
}
public static void COMMAND (Bot bot, String message) {
new Logger().prefix(LoggerType.COMMAND, bot, message);
}
public static void RECONNECT (Bot bot, String message) {
new Logger().prefix(LoggerType.RECONNECT, bot, message);
}
public static void INFO (Bot bot, String message) {
new Logger().prefix(LoggerType.INFO, bot, message);
}
public Component getLoggerType (LoggerType type) {
Component logType = null;
switch (type) {
@@ -29,14 +61,12 @@ public class Logger {
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, Bot bot, String message) {
Component component = null;
Component host = null;
private void prefix (LoggerType loggerType, @Nullable Bot bot, String message) {
Component component;
Component host;
ZoneId timezone = ZoneId.of("America/Chicago");
ZonedDateTime zoneDate = ZonedDateTime.now(timezone);
@@ -46,7 +76,7 @@ public class Logger {
Component type = getLoggerType(loggerType);
if (bot == null) host = Component.text("NitoriBot Jar").color(NamedTextColor.BLUE);
host = Component.text(bot.options.host + ":" + bot.options.port).color(NamedTextColor.BLUE);
else host = Component.text(bot.options.host + ":" + bot.options.port).color(NamedTextColor.BLUE);
component = Component.translatable(
"[%s %s %s] [%s] [%s] %s",
@@ -63,64 +93,4 @@ public class Logger {
if (bot == null) System.out.println(log);
else Main.console.reader.printAbove(log);
}
public static void LOG (Bot bot, String message) {
new Logger().prefix(
LoggerType.LOG,
bot,
message
);
}
public static void DEBUG (Bot bot, String message) {
new Logger().prefix(
LoggerType.DEBUG,
bot,
message
);
}
public static void ERROR (Bot bot, String message) {
new Logger().prefix(
LoggerType.ERROR,
bot,
message
);
}
public static void WARN (Bot bot, String message) {
new Logger().prefix(
LoggerType.WARN,
bot,
message
);
}
public static void COMMAND (Bot bot, String message) {
new Logger().prefix(
LoggerType.COMMAND,
bot,
message
);
}
public static void RECONNECT (Bot bot, String message) {
new Logger().prefix(
LoggerType.RECONNECT,
bot,
message
);
}
public static void INFO (Bot bot, String message) {
new Logger().prefix(
LoggerType.INFO,
bot,
message
);
}
public Logger () {
}
}
@@ -1,11 +1,5 @@
package land.chipmunk.parker2991.nitoribot.logger;
public enum LoggerType {
LOG,
DEBUG,
INFO,
COMMAND,
WARN,
ERROR,
RECONNECT,
LOG, DEBUG, INFO, COMMAND, WARN, ERROR, RECONNECT,
}
@@ -3,40 +3,58 @@ package land.chipmunk.parker2991.nitoribot.modules;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.Config;
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;
public class ChatCommandHandlerModule implements Listener {
private @NotNull final Bot bot;
private @NotNull final Config config;
public ChatCommandHandlerModule (Bot bot) {
this.bot = bot;
this.config = bot.config;
bot.listenerManager.addListener(this);
}
@Override
public void parsedMessage (Component message, PlayerMessageData data) {
if (data.chatType != "minecraft:chat") return;
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);
String plainMessage = ComponentUtil.componentToString(data.contents());
if (!plainMessage.startsWith(prefix)) return;
String command = plainMessage.substring(prefix.length());
CommandSource source = new CommandSource(bot, data.sender);
CommandSource source = new CommandSource(data.sender(), true, ParsedChatType.NORMAL);
bot.commandManager.executeString(source, command);
}
}
public ChatCommandHandlerModule (Bot bot) {
this.bot = bot;
@Override
public void commandSpyReceived (PlayerProfileData player, String message) {
List<String> prefixes = config.prefixes;
bot.listenerManager.addListener(this);
for (String prefix : prefixes) {
if (!message.startsWith(prefix)) return;
String command = message.substring(prefix.length());
CommandSource source = new CommandSource(player, true, ParsedChatType.COMMANDSPY);
bot.commandManager.executeString(source, command);
}
}
}
@@ -1,12 +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 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;
@@ -14,31 +15,37 @@ 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;
public class ChatModule implements Listener {
public final List<ParseChatData> chatParsers;
private final Bot bot;
public final List<ParseChatData> chatParsers = new ArrayList<>();
public ChatModule (Bot bot) {
this.bot = bot;
this.chatParsers = List.of(new KaboomChatParser(bot));
bot.listenerManager.addListener(this);
}
@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 void packetReceived (Packet packet) {
switch (packet) {
case ClientboundSystemChatPacket p -> systemChat(p);
case ClientboundPlayerChatPacket p -> playerChat(p);
case ClientboundDisguisedChatPacket p -> disguisedChat(p);
default -> {
}
}
}
public String parseChatTypes (int chatType) {
String getTranslation = bot.registry.chatTypes.get(chatType);
return getTranslation;
return bot.registry.chatTypes.get(chatType);
}
public void systemChat (ClientboundSystemChatPacket packet) {
@@ -49,9 +56,10 @@ public class ChatModule extends Listener {
}
}
public void diguisedChat (ClientboundDisguisedChatPacket packet) {
public void disguisedChat (ClientboundDisguisedChatPacket packet) {
Component getMessage = packet.getMessage();
Component targetUsername = packet.getName();
Component message;
final String parseChatTypes = parseChatTypes(packet.getChatType().id());
@@ -59,23 +67,30 @@ public class ChatModule extends Listener {
if (packet.getChatType().id() == 4) {
message = getMessage;
} else {
message = Component.translatable(
parseChatTypes,
targetUsername,
getMessage
);
message = Component.translatable(parseChatTypes, targetUsername, getMessage);
}
for (Listener listener : bot.listenerManager.listeners) {
listener.disguisedChatReceived(message);
}
TextComponent textComponent = (TextComponent) targetUsername;
parseMessage(
message,
new PlayerMessageData(
bot.players.getPlayerByUsername(textComponent.content()),
packet.getMessage(),
"minecraft:chat",
Objects.requireNonNull(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);
}
@@ -86,7 +101,7 @@ public class ChatModule extends Listener {
bot.players.getPlayerUUID(packet.getSender()),
content,
"minecraft:chat",
bot.players.getPlayerUUID(packet.getSender()).displayName
Objects.requireNonNull(bot.players.getPlayerUUID(packet.getSender())).displayName()
)
);
}
@@ -98,37 +113,24 @@ public class ChatModule extends Listener {
for (ParseChatData parser : chatParsers) {
parsed = parser.parse(message);
if (parsed != null) break;
};
}
if (parsed == null) return;
for (Listener listener : bot.listenerManager.listeners) {
listener.parsedMessage(message, data);
listener.parsedMessage(data);
}
} catch (Exception ignore) {}
} catch (Exception ignore) {
}
}
public void message (String message) {
bot.session.send(
new ServerboundChatPacket(
message,
Instant.now().toEpochMilli(),
0,
null,
0,
new BitSet(),
0
)
);
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
)
);
bot.session.send(new ServerboundChatCommandPacket(command));
}
public void send (String message) {
@@ -138,14 +140,12 @@ public class ChatModule extends Listener {
}
public void tellraw (String selector, Component message) {
bot.core.run("minecraft:tellraw " + selector + " " + GsonComponentSerializer.gson().serialize(message));
bot.core.run(String.format(
"%s %s %s",
"minecraft:tellraw",
selector,
GsonComponentSerializer.gson().serialize(message).trim()
));
}
public ChatModule (Bot bot) {
this.bot = bot;
chatParsers.add(new KaboomChatParser(bot));
bot.listenerManager.addListener(this);
};
}
@@ -1,85 +1,77 @@
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;
public class CommandCoreModule extends Listener {
private Bot bot;
import java.util.HashMap;
import java.util.Map;
public CommandCoreAreaData area;
public class CommandCoreModule implements Listener {
public final CommandCoreAreaData area;
private @NotNull final Bot bot;
public Vector3i position;
public Vector3i itemPosition;
public Vector3d currentBlockRelative = Vector3d.from(0, 0, 0);
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);
}
@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
);
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()
);
itemPosition = Vector3i.from(botPos.getX(), botPos.getY() - 1, botPos.getZ());
itemRefill();
};
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();
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}",
"minecraft:fill %s %s %s %s %s %s command_block{CustomName:%s} destroy",
startPosX,
startPosY,
startPosZ,
@@ -95,30 +87,9 @@ public class CommandCoreModule extends Listener {
public void itemRefill () {
final NbtMapBuilder blockEntityTagBuilder = NbtMap.builder();
Vector3i pos = position;
CommandCoreAreaData coreArea = area;
String command = getCommand();
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);
blockEntityTagBuilder.putString("Command", command).putByte("auto", (byte) 1).putByte("TrackOutput", (byte) 1);
final NbtMap blockEntityTag = blockEntityTagBuilder.build();
@@ -126,22 +97,15 @@ public class CommandCoreModule extends Listener {
map.put(
DataComponentTypes.BLOCK_ENTITY_DATA,
DataComponentTypes.BLOCK_ENTITY_DATA
.getDataComponentFactory()
.create(
DataComponentTypes.BLOCK_ENTITY_DATA.getDataComponentFactory().create(
DataComponentTypes.BLOCK_ENTITY_DATA,
TypedEntityData.<BlockEntityType>builder()
.type(BlockEntityType.COMMAND_BLOCK)
.tag(blockEntityTag)
.build()
TypedEntityData.<BlockEntityType>builder().type(BlockEntityType.COMMAND_BLOCK).tag(blockEntityTag).build()
)
);
map.put(
DataComponentTypes.ITEM_NAME,
DataComponentTypes.ITEM_NAME
.getDataComponentFactory()
.create(
DataComponentTypes.ITEM_NAME.getDataComponentFactory().create(
DataComponentTypes.ITEM_NAME,
ComponentUtil.componentFromJSON(bot.config.core.coreName)
)
@@ -149,9 +113,7 @@ public class CommandCoreModule extends Listener {
map.put(
DataComponentTypes.CUSTOM_NAME,
DataComponentTypes.CUSTOM_NAME
.getDataComponentFactory()
.create(
DataComponentTypes.CUSTOM_NAME.getDataComponentFactory().create(
DataComponentTypes.CUSTOM_NAME,
ComponentUtil.componentFromJSON(bot.config.core.coreName)
)
@@ -159,28 +121,16 @@ public class CommandCoreModule extends Listener {
final DataComponents dataComponents = new DataComponents(map);
bot.session.send(
new ServerboundSetCreativeModeSlotPacket(
(short) 36,
new ItemStack(
482,
64,
dataComponents
)
)
);
bot.session.send(new ServerboundSetCreativeModeSlotPacket((short) 36, new ItemStack(482, 64, dataComponents)));
bot.session.send(
new ServerboundPlayerActionPacket(
bot.session.send(new ServerboundPlayerActionPacket(
PlayerAction.START_DIGGING,
itemPosition,
Direction.NORTH,
0
)
);
));
bot.session.send(
new ServerboundUseItemOnPacket(
bot.session.send(new ServerboundUseItemOnPacket(
itemPosition,
Direction.NORTH,
Hand.MAIN_HAND,
@@ -190,86 +140,88 @@ public class CommandCoreModule extends Listener {
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 Vector3i currentBlockRelative = Vector3i.from(0, 0, 0);
public PositionData currentBlock () {
Vector3i relativePosition = currentBlockRelative;
Vector3d relativePosition = currentBlockRelative;
Vector3i corePosition = position;
return new PositionData(
relativePosition.getX() + corePosition.getX(),
relativePosition.getY() + corePosition.getY(),
relativePosition.getZ() + corePosition.getZ()
(float) (relativePosition.getX() + corePosition.getX()),
(float) (relativePosition.getY() + corePosition.getY()),
Vector3d.from(relativePosition.getZ(), relativePosition.getY(), relativePosition.getZ())
);
}
public void incrementCurrentBlock () {
Vector3i relativePosition = currentBlockRelative;
Vector3d relativePosition = currentBlockRelative;
CommandCoreAreaData coreArea = area;
int posX = relativePosition.getX();
int posY = relativePosition.getY();
int posZ = relativePosition.getZ();
double posX = relativePosition.getX();
double posY = relativePosition.getY();
double posZ = relativePosition.getZ();
posX++;
if (posX > coreArea.end.getX()) {
posX = coreArea.start.getX();
if (posX > coreArea.end().getX()) {
posX = coreArea.start().getX();
posZ++;
}
if (posZ > coreArea.end.getZ()) {
posZ = coreArea.start.getZ();
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();
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) return;
bot.session.send(
new ServerboundSetCommandBlockPacket(
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(
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
)
);
bot.listenerManager.addListener(this);
}
}
@@ -1,27 +1,37 @@
package land.chipmunk.parker2991.nitoribot.modules;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.command.CommandError;
import land.chipmunk.parker2991.nitoribot.command.CommandContext;
import land.chipmunk.parker2991.nitoribot.command.CommandError;
import land.chipmunk.parker2991.nitoribot.command.CommandInfo;
import land.chipmunk.parker2991.nitoribot.command.CommandSource;
import land.chipmunk.parker2991.nitoribot.commands.Public.*;
import land.chipmunk.parker2991.nitoribot.commands.trusted.ReconnectCommand;
import land.chipmunk.parker2991.nitoribot.logger.Logger;
import land.chipmunk.parker2991.nitoribot.util.ErrorToString;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import java.util.List;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import java.util.List;
public class CommandManagerModule {
private Bot bot;
public final List<CommandInfo> commands = new ArrayList<>();
private final Bot bot;
public List<CommandInfo> commands = new ArrayList<>();
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());
}
public void registerCommand (CommandInfo command) {
commands.add(command);
@@ -29,10 +39,9 @@ public class CommandManagerModule {
public CommandInfo getCommand (String getCommand) {
for (CommandInfo command : commands) {
for (String aliases : command.aliases) {
for (String aliases : command.getAliases()) {
if (getCommand.equals(aliases)) return command;
}
if (getCommand.equals(command.name)) return command;
}
return null;
}
@@ -41,26 +50,21 @@ public class CommandManagerModule {
try {
CommandInfo command = getCommand(commandName.toLowerCase());
if (command == null) throw new CommandError(
Component.translatable(
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)
);
).color(NamedTextColor.RED));
CommandContext context = new CommandContext(bot, args, source, command);
CommandContext context = new CommandContext(bot, args, source);
command.execute(context);
} catch (CommandError error) {
source.sendFeedback(error.message());
source.sendFeedback(bot, error.message());
} catch (Exception error) {
source.sendFeedback(
Component.translatable("command.failed").color(NamedTextColor.DARK_RED)
);
source.sendFeedback(bot, Component.translatable("command.failed").color(NamedTextColor.DARK_RED));
String Error = ErrorToString.errorToString(error);
Logger.ERROR(bot, Error);
}
@@ -73,14 +77,4 @@ public class CommandManagerModule {
this.execute(source, commandName, args);
}
public CommandManagerModule (Bot bot) {
this.bot = bot;
registerCommand(new EchoCommand());
registerCommand(new HelpCommand());
registerCommand(new ReconnectCommand());
registerCommand(new RCCommand());
registerCommand(new MCServerCommand());
}
}
@@ -0,0 +1,46 @@
package land.chipmunk.parker2991.nitoribot.modules;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.data.PlayerProfileData;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import org.jetbrains.annotations.Unmodifiable;
import java.util.List;
public class CommandSpyModule implements Listener {
private static final String SLASH = "/";
private final Bot bot;
public CommandSpyModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
@Override
public void systemChatReceived (Component data) {
@Unmodifiable List<Component> children = data.children();
if (!(children.get(1) instanceof final TextComponent commandComponent)) return;
if (!(data instanceof final TextComponent userComponent)) return;
PlayerProfileData sender = null;
for (PlayerProfileData player : bot.players.list) {
String username = player.profile().getName();
if (username.equals(userComponent.content())) sender = player;
}
String command = commandComponent.content().substring(SLASH.length());
if ((commandComponent.content().contains(SLASH + command) && sender != null)) {
for (Listener listener : bot.listenerManager.listeners) {
listener.commandSpyReceived(sender, command);
}
}
}
}
@@ -1,23 +1,36 @@
package land.chipmunk.parker2991.nitoribot.modules;
import land.chipmunk.parker2991.nitoribot.Bot;
//import org.jline
import land.chipmunk.parker2991.nitoribot.Config;
import land.chipmunk.parker2991.nitoribot.Main;
import org.jline.reader.*;
import org.jline.terminal.*;
import javax.sound.sampled.Line;
import java.io.IOException;
import java.util.List;
public class ConsoleModule implements Completer {
private static final List<Bot> servers = Main.Bots;
public LineReader reader;
public final LineReader reader;
public String server = "all";
public final String server = "all";
public ConsoleModule () {
this.reader = LineReaderBuilder.builder().completer(this).build();
Main.executorService.submit(
() -> {
while (true) {
try {
String line;
line = reader.readLine(String.format("[%s] > ", this.server));
handleLine(line);
} catch (Exception _) {
}
}
}, "Console Thread"
);
}
@Override
public void complete (LineReader reader, ParsedLine line, List<Candidate> candidates) {
@@ -26,26 +39,8 @@ public class ConsoleModule implements Completer {
private void handleLine (String line) {
for (Bot bot : servers) {
if (line.equals("c.kill")) System.exit(0);
if (line.equals(bot.config.console.prefix + "kill")) System.exit(0);
bot.chat.send(line);
}
}
public ConsoleModule (Config config) {
this.reader = LineReaderBuilder.builder()
.completer(this)
.build();
Main.executorService.submit(() -> {
while (true) {
try {
String line = null;
line = reader.readLine(String.format("[%s] > ", this.server));
handleLine(line);
} catch (Exception e) {}
}
}, "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,19 +1,24 @@
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;
public class LoggingModule implements Listener {
private final Bot bot;
public LoggingModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
@Override
public void playerChatReceived (Component message) {
handleMessages(message);
};
}
@Override
public void disguisedChatReceived (Component message) {
@@ -26,18 +31,9 @@ public class LoggingModule extends Listener {
}
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 LoggingModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
Logger.LOG(bot, message);
}
}
@@ -20,27 +20,25 @@ import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
public class MCServerModule {
private Bot bot;
public final SessionService sessionService = new SessionService();
public final MinecraftProtocol protocol = new MinecraftProtocol();
private final Bot bot;
private final List<SkinPart> skinParts = new ArrayList<>();
public ClientSession client;
public final SessionService sessionService = new SessionService();
public MCServerModule (Bot bot) {
this.bot = bot;
public final MinecraftProtocol protocol = new MinecraftProtocol();
private final List<SkinPart> skinParts = new ArrayList<>();
}
public PingServerData pingServer (String[] host) {
AtomicReference<PingServerData> serverData = new AtomicReference<>();
client = ClientNetworkSessionFactory.factory()
.setAddress("kaboom.pw", 25565)
client = ClientNetworkSessionFactory.factory().setAddress("kaboom.pw", 25565)
//.setAddress(host[0], Integer.parseInt(host[1]))
.setProtocol(protocol)
.create();
.setProtocol(protocol).create();
client.send(
new ServerboundClientInformationPacket(
client.send(new ServerboundClientInformationPacket(
"en_us",
1,
ChatVisibility.FULL,
@@ -50,23 +48,12 @@ public class MCServerModule {
false,
true,
ParticleStatus.ALL
)
);
));
client.setFlag(MinecraftConstants.SESSION_SERVICE_KEY, sessionService);
client.setFlag(MinecraftConstants.SERVER_INFO_HANDLER_KEY, (Session session, ServerStatusInfo info) -> {
//System.out.println(info.getVersionInfo().getVersionName());
//System.out.println(info.getPlayerInfo().getOnlinePlayers());
//assert info.getVersionInfo() != null;
//assert info.getPlayerInfo() != null;
/*
String versionName,
long protocolVersion,
int playersOnline,
int maxPlayers,
Component description
*/
client.setFlag(
MinecraftConstants.SERVER_INFO_HANDLER_KEY, (Session session, ServerStatusInfo info) -> {
assert info.getVersionInfo() != null;
assert info.getPlayerInfo() != null;
@@ -77,22 +64,17 @@ public class MCServerModule {
info.getPlayerInfo().getMaxPlayers(),
info.getDescription()
));
});
}
);
System.out.println(serverData);
client.setFlag(MinecraftConstants.SERVER_PING_TIME_HANDLER_KEY, (session, pingTime) ->
serverData.get().latency(pingTime)
client.setFlag(
MinecraftConstants.SERVER_PING_TIME_HANDLER_KEY,
(session, pingTime) -> serverData.get().latency(pingTime)
);
bot.executor.submit(() -> {
client.connect();
});
bot.executor.submit(() -> client.connect());
return serverData.get();
}
public MCServerModule (Bot bot) {
this.bot = bot;
}
}
@@ -1,47 +1,42 @@
package land.chipmunk.parker2991.nitoribot.modules;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.UUID;
import land.chipmunk.parker2991.nitoribot.Bot;
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;
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.ClientboundMoveEntityPosPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.ClientboundMoveEntityPosRotPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.ClientboundAddEntityPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.ClientboundRemoveEntitiesPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.ClientboundTeleportEntityPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.ClientboundRotateHeadPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.ClientboundEntityPositionSyncPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.level.ServerboundEntityTagQuery;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.level.ClientboundTagQueryPacket;
import org.jetbrains.annotations.Nullable;
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.listeners.Listener;
import net.kyori.adventure.text.Component;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.UUID;
public class PlayerListModule extends Listener {
private Bot bot;
public class PlayerListModule implements Listener {
public final List<PlayerProfileData> list = new ArrayList<>();
public int transactionId = 0;
public PlayerListModule (Bot bot) {
bot.listenerManager.addListener(this);
}
@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 packetReceived (Packet packet) {
switch (packet) {
case ClientboundPlayerInfoUpdatePacket p -> playerInfo(p);
case ClientboundPlayerInfoRemovePacket p -> playerRemove(p);
case ClientboundAddEntityPacket p -> getPlayerPosition(p);
default -> {
}
}
}
public void playerInfo (ClientboundPlayerInfoUpdatePacket packet) {
@@ -50,10 +45,8 @@ public class PlayerListModule extends Listener {
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_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);
@@ -63,61 +56,52 @@ public class PlayerListModule extends Listener {
}
}
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
//)
assert player != null;
player.entityId(entityId);
player.position(new PositionData(pitch, yaw, playerPosition));
}
}
public final PlayerProfileData getPlayerByEntityID (int entityId) {
@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.entityId == entityId) {
return player;
UUID playerUUID = player.profile().getId();
if (playerUUID == null) return playerInfo;
else if (player.profile().getId().equals(uuid)) {
playerInfo = player;
}
}
} catch (Exception _) {
}
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 getPlayerUUID (UUID uuid) {
PlayerProfileData playerInfo = null;
for (PlayerProfileData player : list) {
if (player.profile.getId().equals(uuid)) {
playerInfo = player;
}
};
if (playerInfo == null) {};
return playerInfo;
}
public final PlayerProfileData getDisplayName (Component displayName) {
public final PlayerProfileData getPlayerByUsername (String username) {
for (PlayerProfileData candidate : list) {
if (candidate.displayName != null && candidate.displayName.equals(displayName)) {
if (candidate.profile().getName().equals(username)) {
return candidate;
}
}
@@ -130,31 +114,28 @@ public class PlayerListModule extends Listener {
if (getPlayer == null) return;
getPlayer.listed = player.isListed();
getPlayer.listed(player.isListed());
}
public void updateGamemode (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) return;
getPlayer.gameMode = player.getGameMode();
if (getPlayer == null) {
} else getPlayer.gameMode(player.getGameMode());
}
public void updateLatency (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) return;
getPlayer.latency = player.getLatency();
if (getPlayer == null) {
} else getPlayer.latency(player.getLatency());
}
public void updateDisplayName (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) return;
getPlayer.displayName = player.getDisplayName();
if (getPlayer == null) {
} else getPlayer.displayName(player.getDisplayName());
}
public void addPlayer (PlayerListEntry player) {
@@ -164,11 +145,17 @@ public class PlayerListModule extends Listener {
PlayerProfileData formatPlayerData = new PlayerProfileData(
player.getProfileId(),
null,
player.getProfile(),
player.isListed(),
player.getLatency(),
player.getGameMode(),
player.getDisplayName()
player.getDisplayName(),
player.isShowHat(),
player.getListOrder(),
null,
null,
null
);
list.add(formatPlayerData);
@@ -177,11 +164,9 @@ public class PlayerListModule extends Listener {
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);
}
}
@@ -2,51 +2,67 @@ package land.chipmunk.parker2991.nitoribot.modules;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.data.PositionData;
import land.chipmunk.parker2991.nitoribot.listeners.*;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.player.ClientboundPlayerPositionPacket;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.network.Session;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.level.ServerboundAcceptTeleportationPacket;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import org.cloudburstmc.math.vector.Vector3d;
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;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.player.ServerboundMovePlayerPosPacket;
public class PositionModule extends Listener {
private Bot bot;
import java.util.Objects;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public Vector3d positionAsVector = null;
public class PositionModule implements Listener {
private final Bot bot;
public PositionData positionAsInteger;
@Override
public void packetReceived (Session session, Packet packet) {
if (packet instanceof ClientboundPlayerPositionPacket) packetReceived((ClientboundPlayerPositionPacket) packet);
}
public void packetReceived (ClientboundPlayerPositionPacket packet) {
Vector3d getPosition = packet.getPosition();
int x = (int) Math.round(getPosition.getX());
int y = (int) Math.round(getPosition.getY());
int z = (int) Math.round(getPosition.getZ());
positionAsInteger = new PositionData(x, y, z);
positionAsVector = getPosition;
bot.session.send(
new ServerboundAcceptTeleportationPacket(
packet.getId()
)
);
for (Listener listener : bot.listenerManager.listeners) {
listener.botMoved();
}
}
public ScheduledFuture<?> timer;
public PositionData positionData;
private int i = 0;
private int x;
private int z;
public PositionModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
@Override
public void packetReceived (Packet packet) {
if (packet instanceof ClientboundPlayerPositionPacket) packetReceived((ClientboundPlayerPositionPacket) packet);
}
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());
positionData = new PositionData(packet.getXRot(), packet.getYRot(), packet.getPosition());
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 ServerboundAcceptTeleportationPacket(packet.getId()));
for (Listener listener : bot.listenerManager.listeners) {
if (!Objects.equals(bot.options.mode, "kaboom")) return;
listener.botMoved();
}
}
}
@@ -1,34 +1,53 @@
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.data.DimensionData;
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 class RegistryModule implements Listener {
public final List<String> chatTypes = new ArrayList<>();
public final List<DimensionData> dimensions = new ArrayList<>();
private Bot bot;
public RegistryModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
@Override
public void packetReceived (Session session, Packet packet) {
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 (getRegistry.equals("minecraft:chat_type")) if (entry.getData() != null) {
chatTypes.add(entry.getData().getCompound("chat").getString("translation_key"));
}
if (getRegistry.equals("minecraft:worldgen/biome")) {
System.out.println(entry);
}
if (getRegistry.equals("minecraft:dimension_type")) {
if (entry.getData() != null) {
String dimension = null;
if (entry.getId().toString().equals("minecraft:overworld_caves"))
dimension = "minecraft:world_flatlands";
else dimension = String.valueOf(entry.getId());
this.dimensions.add(new DimensionData(
dimension,
Integer.parseInt(entry.getData().get("height").toString().replace("i", "")),
Integer.parseInt(entry.getData().get("min_y").toString().replace("i", ""))
));
}
}
}
public RegistryModule (Bot bot) {
bot.listenerManager.addListener(this);
}
}
@@ -1,58 +1,60 @@
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 class SelfcareModule implements Listener {
private final Bot bot;
public ScheduledFuture<?> timer;
private Bot bot;
public PermissionSelfcare permission;
public GamemodeSelfcare gamemode;
public int entityId;
public SelfcareModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
loadSelfcare();
}
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);
public void packetReceived (Packet packet) {
switch (packet) {
case ClientboundLoginFinishedPacket p -> login(p);
case ClientboundDisconnectPacket p -> disconnect(p);
default -> {
}
}
}
public void login (ClientboundLoginFinishedPacket packet) {
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
)
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
);
}, 0, bot.options.selfcareInterval, TimeUnit.MILLISECONDS);
}
public void disconnect (DisconnectedEvent event) {
public void disconnect (ClientboundDisconnectPacket event) {
timer.cancel(true);
}
public SelfcareModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
loadSelfcare();
}
}
@@ -1,33 +1,22 @@
package land.chipmunk.parker2991.nitoribot.modules;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.listeners.*;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
import org.geysermc.mcprotocollib.protocol.data.game.entity.metadata.MetadataType;
import org.geysermc.mcprotocollib.protocol.data.game.entity.metadata.MetadataTypes;
import org.geysermc.mcprotocollib.protocol.data.game.entity.metadata.ByteMetadataType;
import org.geysermc.mcprotocollib.protocol.data.game.entity.metadata.EntityMetadata;
import org.geysermc.mcprotocollib.protocol.data.game.entity.type.EntityType;
import org.geysermc.mcprotocollib.network.Session;
import net.kyori.adventure.text.Component;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.ClientboundAddEntityPacket;
import org.geysermc.mcprotocollib.protocol.data.game.entity.metadata.EntityMetadata;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.ClientboundSetEntityDataPacket;
import net.kyori.adventure.text.Component;
import java.util.ArrayList;
import java.util.List;
public class TextDisplayModule extends Listener {
private Bot bot;
public class TextDisplayModule implements Listener {
private static final int TEXT_DISPLAY_ENTITY_ID = 32;
private int entityId;
public TextDisplayModule (Bot bot) {
bot.listenerManager.addListener(this);
}
@Override
public void packetReceived (Session session, Packet packet) {
public void packetReceived (Packet packet) {
if (packet instanceof ClientboundSetEntityDataPacket) getTextDisplay((ClientboundSetEntityDataPacket) packet);
}
@@ -39,9 +28,4 @@ public class TextDisplayModule extends Listener {
}
}
}
public TextDisplayModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
}
@@ -0,0 +1,30 @@
package land.chipmunk.parker2991.nitoribot.modules;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.level.ClientboundLevelChunkWithLightPacket;
import org.jetbrains.annotations.NotNull;
public class WorldModule implements Listener {
private @NotNull Bot bot;
public WorldModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
@Override
public void packetReceived (Packet packet) {
switch (packet) {
case ClientboundLevelChunkWithLightPacket p -> chunks(p);
default -> {
}
}
}
private void chunks (ClientboundLevelChunkWithLightPacket packet) {
//System.out.println(Arrays.toString(packet.getChunkData()));
}
}
@@ -1,22 +1,22 @@
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 class GamemodeSelfcare implements Listener {
public int gamemode = 1;
public GamemodeSelfcare (Bot bot) {
bot.listenerManager.addListener(this);
}
@Override
public void packetReceived (Session session, Packet packet) {
public void packetReceived (Packet packet) {
if (packet instanceof ClientboundGameEventPacket) checkGamemode((ClientboundGameEventPacket) packet);
}
@@ -42,9 +42,4 @@ public class GamemodeSelfcare extends Listener {
}
}
}
public GamemodeSelfcare (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
}
@@ -1,24 +1,23 @@
package land.chipmunk.parker2991.nitoribot.selfcare.entity;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.listeners.*;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.protocol.data.game.entity.EntityEvent;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.ClientboundEntityEventPacket;
import org.geysermc.mcprotocollib.protocol.data.game.entity.EntityEvent;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.network.Session;
import static org.geysermc.mcprotocollib.protocol.data.game.entity.EntityEvent.*;
public class PermissionSelfcare extends Listener {
public class PermissionSelfcare implements Listener {
private final Bot bot;
public int level;
private Bot bot;
public PermissionSelfcare (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
@Override
public void packetReceived (Session session, Packet packet) {
public void packetReceived (Packet packet) {
if (packet instanceof ClientboundEntityEventPacket) getPermissionLevel((ClientboundEntityEventPacket) packet);
}
@@ -36,10 +35,5 @@ public class PermissionSelfcare extends Listener {
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");
@@ -31,6 +30,16 @@ public final class ComponentUtil {
private static final ThreadLocal<Integer> TOTAL_DEPTH = ThreadLocal.withInitial(() -> 0); //used to track the depth of translate components
private static final int MAX_DEPTH = 512; //translate depth limit
private static final GsonComponentSerializer GSON_COMPONENT_SERIALIZER = GsonComponentSerializer.builder() // 1.21.5+ gson serializer
.build();
private static final ANSIComponentSerializer ANSI_COMPONENT_SERIALIZER = ANSIComponentSerializer.builder().flattener(
getFlattener(true)).colorLevel(ColorLevel.TRUE_COLOR).build();
private static final PlainTextComponentSerializer PLAIN_TEXT_COMPONENT_SERIALIZER = PlainTextComponentSerializer.builder().flattener(
getFlattener(false)).build();
public static NamedTextColor convertColorString (String color) {
return NamedTextColor.NAMES.value(color);
}
public static Map<String, String> loadJsonStringMap (String name) {
Map<String, String> map = new HashMap<>();
@@ -47,29 +56,17 @@ public final class ComponentUtil {
return map;
}
private static final GsonComponentSerializer GSON_COMPONENT_SERIALIZER = GsonComponentSerializer.builder() // 1.21.5+ gson serializer
.build();
private static final ANSIComponentSerializer ANSI_COMPONENT_SERIALIZER = ANSIComponentSerializer.builder()
.flattener(getFlattener(true))
.colorLevel(ColorLevel.TRUE_COLOR)
.build();
private static final PlainTextComponentSerializer PLAIN_TEXT_COMPONENT_SERIALIZER = PlainTextComponentSerializer.builder()
.flattener(getFlattener(false))
.build();
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
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();
}
@@ -78,10 +75,7 @@ public final class ComponentUtil {
var key = component.key();
var fallback = component.fallback();
return LANGUAGE.getOrDefault(
key,
fallback == null ? key : fallback
);
return LANGUAGE.getOrDefault(key, fallback == null ? key : fallback);
}
private static String guardedStringify (ComponentEncoder<Component, String> serializer, Component message) {
@@ -91,7 +85,8 @@ public final class ComponentUtil {
return serializer.serialize(Component.translatable(
"<Failed to parse component: %s>",
NamedTextColor.RED,
Component.text(e.toString())));
Component.text(e.toString())
));
} finally {
TOTAL_DEPTH.set(0); //set translate depth to 0 after component is parsed
}
@@ -130,8 +125,8 @@ public final class ComponentUtil {
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"))) + ">";
};
}
@@ -139,12 +134,7 @@ public final class ComponentUtil {
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();
}
}
private static void mapKeybind (KeybindComponent component, Consumer<Component> consumer) {
@@ -1,39 +0,0 @@
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 Map<String, String> TRANSLATIONS = ComponentUtil.loadJsonStringMap("translations.json");
/*public static void customTranslations (String translation, Component component) {
List<Component> list = new ArrayList<>();
if (component != null) list = List.of(
component
);
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));
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;
}
}
@@ -2,8 +2,9 @@ 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 () {
@@ -33,6 +34,11 @@ public class UUIDUtil {
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) + "}]";
}
}
@@ -17,8 +17,8 @@ colors:
integer: "gold"
commands:
primary: "blue"
secondary: "aqua"
tertiary: "dark_aqua"
secondary: "dark_aqua"
tertiary: "aqua"
help:
Public: "blue"
trusted: "dark_aqua"
@@ -29,9 +29,6 @@ colors:
console:
prefix: "c."
chatAttestation:
url: "https://optmstc.dev/key-manifest-v1.json"
bots:
- host: "localhost"
port: 25565
+68 -16
View File
@@ -1,23 +1,75 @@
{
"buildstring": {
"bot": {
"version": "v9.0.0-alpha",
"codename": "Night of Nights",
"build": "5250"
"botName": [
{
"text": "Nitori",
"color": "blue"
},
{
"text": "Bot",
"color": "green"
}
],
"version": "v9.0.0-alpha",
"codename": [
{
"text": "Night",
"color": "blue"
},
{
"text": " of ",
"color": "dark_blue"
},
{
"text": "Nights",
"color": "blue"
}
],
"build": "5311",
"versionReleaseDate": "N\\A",
"initialBotRelease": "11/22/22"
},
"owner": "Parker2991",
"credits": [
{ "name": "_ChipMC_", "reason": "v4.0.0 rewrite / v9.0.0 entity uuid / v9.0.0 chat command parsing" },
{ "name": "chayapak", "reason": "v4.0.0-rewrite / listeners for v9.0.0 / v9.0.0 threads / v9.0.0 entity uuid / v9.0.0 command" },
{ "name": "_yfd", "reason": "rewriting the discord logging for v4.x and giving tht version a username gen" },
{ "name": "aaa/ImFloriz", "reason": "v6.0.3 vanish support" },
{ "name": "Ploat/ImGloriz/NamespaceDev", "reason": "v7.0.3 command core runTracked function" },
{ "name": "TurtleKid", "reason": "v5.0.7b file logger rewrite" },
{ "name": "Blackilykat", "reason": "v9.0.0 client creation / v9.0.0 config creation" },
{ "name": "OptimisticDev", "reason": "v9.0.0 client creation / v9.0.0 ErrorToString function / v9.0.0 multi-server connecting / v9.0.0 jar creation" },
{ "name": "PthePro777", "reason": "v9.0.0 client creation / v9.0.0 config yaml parsing" },
{ "name": "Werkku", "reason": "v9.0.0 ComponentUtil functions / v9.0.0 command sending" }
"contributors": [
{
"name": "_ChipMC_",
"reason": "v4.0.0 rewrite / v9.0.0 entity uuid / v9.0.0 chat command parsing"
},
{
"name": "chayapak",
"reason": "v4.0.0-rewrite / listeners for v9.0.0 / v9.0.0 threads / v9.0.0 entity uuid / v9.0.0 command"
},
{
"name": "_yfd",
"reason": "rewriting the discord logging for v4.x and giving tht version a username gen"
},
{
"name": "aaa/ImFloriz",
"reason": "v6.0.3 vanish support"
},
{
"name": "Ploat/ImGloriz/NamespaceDev",
"reason": "v7.0.3 command core runTracked function"
},
{
"name": "TurtleKid",
"reason": "v5.0.7b file logger rewrite"
},
{
"name": "Blackilykat",
"reason": "v9.0.0 client creation / v9.0.0 config creation"
},
{
"name": "OptimisticDev",
"reason": "v9.0.0 client creation / v9.0.0 ErrorToString function / v9.0.0 multi-server connecting / v9.0.0 jar creation"
},
{
"name": "PthePro777",
"reason": "v9.0.0 client creation / v9.0.0 config yaml parsing"
},
{
"name": "Werkku",
"reason": "v9.0.0 ComponentUtil functions / v9.0.0 command sending"
}
]
}
-15
View File
@@ -1,15 +0,0 @@
{
"command.help.info.aliases":"Aliases",
"command.help.info.command": "Command",
"command.help.info.description": "Description",
"command.help.info.layout": "%s: %s\n",
"command.help.info.trust_level": "Trust Level",
"command.help.info.usages": "Usages",
"command.help.layout": "%s: (%s) (%s | %s | %s | %s) \u203a\n",
"command.help.trust_level.admin": "Admin",
"command.help.trust_level.owner": "Owner",
"command.help.trust_level.public": "Public",
"command.help.trust_level.trusted": "Trusted",
"command.string.placeholder": "DUMMY STRING"
}
@@ -0,0 +1,6 @@
package land.chipmunk.parker2991.nitoribot.command;
import land.chipmunk.parker2991.nitoribot.Bot;
public record CommandContext(Bot bot, String[] args, CommandSource source) {
}
@@ -0,0 +1,15 @@
package land.chipmunk.parker2991.nitoribot.command;
import net.kyori.adventure.text.Component;
public class CommandError extends Exception {
public final Component message;
public CommandError (Component message) {
this.message = message;
}
public Component message () {
return message;
}
}
@@ -0,0 +1,20 @@
package land.chipmunk.parker2991.nitoribot.command;
public abstract class CommandInfo {
// 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 abstract void execute (CommandContext context);
}
@@ -0,0 +1,42 @@
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.util.ComponentUtil;
import net.kyori.adventure.text.Component;
public class CommandSource {
public final PlayerProfileData sender;
public final ParsedChatType parsedChatType;
private final Bot bot;
public boolean inGame;
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();
/* String formatCommand = String.format(
"minecraft:summon text_display %s %s %s {tag:[%s], text:%s}",
playerPos.getX(),
playerPos.getY(),
playerPos.getZ(),
"NitoriBot",
convertToJson
);*/
String selector = String.format("@p[nbt={UUID:%s}]", sender.entityUUID());
//System.out.println(sender.profile.getName());
if (this.parsedChatType == ParsedChatType.NORMAL) bot.chat.tellraw("@a", message);
else bot.chat.tellraw(selector, message);
}
}
@@ -0,0 +1,5 @@
package land.chipmunk.parker2991.nitoribot.command;
public enum CommandTrustLevels {
PUBLIC, TRUSTED, ADMIN, OWNER, CONSOLE, DISABLED
}