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>
+66 -48
View File
@@ -1,62 +1,80 @@
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("jvm") version "2.3.10"
id("maven-publish")
}
kotlin {
jvmToolchain(25)
jvmToolchain(25)
}
repositories {
mavenCentral()
maven("https://repo.opencollab.dev/maven-releases/")
maven("https://repo.opencollab.dev/maven-snapshots/")
maven("https://jitpack.io/")
maven("https://repo.opencollab.dev/main/")
maven("https://maven.maxhenkel.de/repository/public/")
// maven("https://libraries.minecraft.net")
/* maven("https://code.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/")
repositories {
mavenCentral()
maven("https://repo.opencollab.dev/maven-releases/")
maven("https://repo.opencollab.dev/maven-snapshots/")
maven("https://jitpack.io/")
maven("https://repo.opencollab.dev/main/")
maven("https://maven.maxhenkel.de/repository/public/")
maven("https://code.chipmunk.land/api/packages/kaboomstandardsorganization/maven/")
}
dependencies {
implementation("org.geysermc.mcprotocollib:protocol:26.2-SNAPSHOT")
implementation("org.slf4j:slf4j-api:2.0.13")
implementation("org.tinylog:slf4j-tinylog:2.7.0")
implementation("org.tinylog:tinylog-impl:2.7.0")
implementation("org.yaml:snakeyaml:2.2")
implementation("net.kyori:adventure-text-serializer-ansi: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")
implementation("org.geysermc.mcprotocollib:protocol:26.2-SNAPSHOT")
constraints {
implementation("io.netty:netty-codec-dns:4.2.16.Final") {
because("dos vulnerability!")
}
implementation("io.netty:netty-all:4.2.18.Final") {
because("vulnerability")
}
}
implementation("org.slf4j:slf4j-api:2.0.20")
implementation("org.tinylog:slf4j-tinylog:2.8.1")
implementation("org.tinylog:tinylog-impl:2.8.1")
implementation("org.yaml:snakeyaml:2.7")
implementation("net.kyori:adventure-text-serializer-ansi:5.2.0")
implementation("net.kyori:adventure-text-serializer-plain:5.2.0")
implementation("net.kyori:adventure-text-serializer-legacy:5.2.0")
implementation("net.kyori:adventure-text-serializer-gson:5.2.0")
implementation("net.kyori:adventure-text-minimessage:5.2.0")
implementation("net.dv8tion:JDA:6.7.0")
implementation("org.jline:jline:4.4.7")
}
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,232 +1,169 @@
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 final ListenerManager listenerManager = new ListenerManager();
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 CommandManagerModule commandManager;
public MCServerModule mcServer;
public WorldModule world;
public List<?> modules;
public boolean loggedIn = false;
public Bot (Config.Options options, List<Bot> bots, @NotNull Config config) throws IOException {
this.options = options;
this.bots = bots;
this.config = config;
public int entityId;
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)
);
public final ScheduledExecutorService executor = Main.executor;
public final ExecutorService executorService = Main.executorService;
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 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) {
this.options = options;
this.bots = bots;
this.config = config;
try {
connect();
} catch (Exception e) {}
};
public void connect () throws IOException {
final MinecraftProtocol protocol = new MinecraftProtocol(options.username);
if (options.useProxy) session = ClientNetworkSessionFactory.factory()
.setAddress(
options.host,
options.port
)
.setProxy(randomProxyIp())
.setProtocol(protocol)
.create();
else session = ClientNetworkSessionFactory.factory()
.setAddress(
options.host,
options.port
)
.setProtocol(protocol)
.create();
session.addListener(this);
loadModules();
session.connect(false);
}
@Override
public void disconnecting (DisconnectingEvent event) {
String reason = event + "";
session.disconnect(reason);
}
// ServerboundPlayerLoadedPacket
@Override
public void packetSent (Session session, Packet packet) {
for (Listener listener : listenerManager.listeners) {
listener.packetSent(session, packet);
try {
connect();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
@Override
public void packetError (PacketErrorEvent error) {
error.setSuppress(true);
}
public void connect () throws IOException {
final MinecraftProtocol protocol = new MinecraftProtocol(options.username);
@Override
public void packetReceived (Session session, Packet packet) {
try {
if (packet instanceof ClientboundLoginPacket) this.session.send(
ServerboundPlayerLoadedPacket.INSTANCE
);
if (options.useProxy) session = ClientNetworkSessionFactory.factory().setAddress(
options.host,
options.port
).setProxy(new GetProxiesList().randomProxyIp()).setProtocol(protocol).create();
if (packet instanceof ServerboundPlayerLoadedPacket) {
System.out.println(packet);
}
else session = ClientNetworkSessionFactory.factory().setAddress(
options.host,
options.port
).setProtocol(protocol).create();
session.addListener(this);
session.connect(false);
}
for (Listener listener : listenerManager.listeners) {
listener.packetReceived(session, packet);
}
@Override
public void disconnecting (DisconnectingEvent event) {
Component component = event.getReason();
session.disconnect(component);
}
if (packet instanceof ClientboundLoginFinishedPacket) getProfile((ClientboundLoginFinishedPacket) packet);
else if (packet instanceof ClientboundLoginPacket) getEntityId((ClientboundLoginPacket) packet);
} catch (Exception e) { }
}
@Override
public void packetSent (Session session, Packet packet) {
for (Listener listener : listenerManager.listeners) {
listener.packetSent();
}
}
@Override
public void packetError (PacketErrorEvent error) {
error.setSuppress(true);
}
@Override
public void packetReceived (Session session, Packet packet) {
try {
if (packet instanceof ClientboundLoginPacket) this.session.send(ServerboundPlayerLoadedPacket.INSTANCE);
if (packet instanceof ServerboundPlayerLoadedPacket) {
System.out.println(packet);
}
for (Listener listener : listenerManager.listeners) {
listener.packetReceived(packet);
}
if (packet instanceof ClientboundLoginFinishedPacket) getProfile((ClientboundLoginFinishedPacket) packet);
else if (packet instanceof ClientboundLoginPacket) getEntityId((ClientboundLoginPacket) packet);
} catch (Exception _) {
}
}
public void getProfile (ClientboundLoginFinishedPacket packet) {
profile = packet.getProfile();
public void getProfile (ClientboundLoginFinishedPacket packet) {
profile = packet.getProfile();
loggedIn = true;
}
loggedIn = true;
}
public void getEntityId (ClientboundLoginPacket packet) {
entityId = packet.getEntityId();
}
public void getEntityId (ClientboundLoginPacket packet) {
entityId = packet.getEntityId();
}
@Override
public void disconnected (DisconnectedEvent event) {
listenerManager.clearListener();
@Override
public void disconnected (DisconnectedEvent event) {
loggedIn = false;
Component component = event.getReason();
String reason = ComponentUtil.componentToAnsi(component);
loggedIn = false;
Logger.RECONNECT(this, reason);
Component component = event.getReason();
if (services.get("reconnect") != null) services.get("reconnect").cancel(true);
String reason = ComponentUtil.componentToAnsi(component);
int reconnectDelay = options.reconnectDelay;
Logger.RECONNECT(this, reason);
executor.schedule(() -> {
try {
connect();
} catch (IOException e) {
throw new RuntimeException(e);
}
}, reconnectDelay, TimeUnit.MILLISECONDS);
}
}
services.put(
"reconnect", executor.schedule(
() -> {
try {
connect();
} catch (IOException e) {
throw new RuntimeException(e);
}
}, options.reconnectDelay, TimeUnit.MILLISECONDS
)
);
}
}
@@ -3,63 +3,60 @@ package land.chipmunk.parker2991.nitoribot;
import java.util.List;
public class Config {
public List<String> prefixes;
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 String coreName;
}
public static class Core {
public final Area area = new Area();
public String coreName;
}
public static class Area {
public Position start = new Position();
public Position end = new Position();
}
public static class Area {
public final Position start = new Position();
public final Position end = new Position();
}
public static class Position {
public int x = 0;
public int y = 0;
public int z = 0;
}
public static class Position {
public int x;
public int y;
public int z;
}
public static class CommandColors {
public String primary = "blue";
public String secondary = "aqua";
public String tertiary = "dark_aqua";
}
public static class CommandColors {
public String primary;
public String secondary;
public String tertiary;
}
public static class HelpCommandColors {
public String Public = "blue";
public String trusted = "dark_aqua";
public String admin = "aqua";
public String owner = "light_purple";
public String console = "dark_purple";
}
public static class HelpCommandColors {
public String Public;
public String trusted;
public String admin;
public String owner;
public String console;
}
public static class Console {
public String prefix = "c.";
}
public static class Console {
public String prefix;
}
public static class Colors {
public String integer = "gold";
public CommandColors commands = new CommandColors();
public HelpCommandColors help = new HelpCommandColors();
}
public static class Colors {
public 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;
public boolean useProxy;
public String serverName;
public String username;
public int reconnectDelay;
public int selfcareInterval;
};
public static class Options {
public String host;
public int port;
public boolean useProxy;
public String serverName;
public String username;
public int reconnectDelay;
public int selfcareInterval;
public String mode;
}
}
@@ -1,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 ExecutorService virtualThreads = Executors.newVirtualThreadPerTaskExecutor();
public static final ExecutorService executorService = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors()
);
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 static RepoCommitInfo repoCommitInfo = null;
public static BotBuildInfo botBuildInfo = null;
public static ConsoleModule console;
public Config config;
public static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(
Runtime.getRuntime().availableProcessors()
);
void main () {
try {
config = new LoadConfig().loadConfig();
Config.Options[] bots = config.bots;
console = new ConsoleModule();
repoCommitInfo = new GetRepoInfo().getRepoInfo();
botBuildInfo = new GetBotBuildInfo().getBuildInfo();
public static Config config;
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"));
for (Config.Options options : bots) {
final Bot bot = new Bot(options, Bots, config);
Bots.add(bot);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
InputStream configFile = Files.newInputStream(configPath);
config = yaml.load(configFile);
return config;
}
public static ConsoleModule console;
public void main(String[] args) {
try {
config = loadConfig();
Config.Options[] bots = config.bots;
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) {
}
};
}
@@ -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,53 +1,54 @@
package land.chipmunk.parker2991.nitoribot.chatparsers;
import java.util.List;
import land.chipmunk.parker2991.nitoribot.data.chat.*;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.data.PlayerProfileData;
import land.chipmunk.parker2991.nitoribot.data.chat.ParseChatData;
import land.chipmunk.parker2991.nitoribot.data.chat.PlayerMessageData;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import java.util.List;
public class KaboomChatParser implements ParseChatData {
private Bot bot;
private static Component SEPERATOR_COLON = Component.text(":");
private static Component SEPERATOR_COLON_RACCOON = Component.text("\u00a7f:"); // https://github.com/raccoonserver/extras/commit/315f704075db2f00e3e1bfbf55f858469c22880f
private static Component SEPERATOR_SPACE = Component.space();
private 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;
}
@Override
public PlayerMessageData parse (Component message) {
if (message instanceof TextComponent) return parse((TextComponent) message);
return null;
}
public PlayerMessageData parse (TextComponent message) {
List<Component> children = message.children();
if (!message.content().equals("") || !message.style().isEmpty() || children == null || children.size() < 3) return null;
final Component prefix = children.get(0);
Component displayName = Component.empty();
Component contents = Component.empty();
if (isSeperatorAt(children, 1)) { // Missing/blank display name
if (children.size() > 3) contents = children.get(3);
} else if (isSeperatorAt(children, 2)) {
displayName = children.get(1);
if (children.size() > 4) contents = children.get(4);
} else {
return null;
public KaboomChatParser (Bot bot) {
this.bot = bot;
}
PlayerProfileData sender = bot.players.getDisplayName(Component.empty().append(prefix).append(displayName));//getSender());
return new PlayerMessageData(sender, contents, "minecraft:chat", displayName);
}
@Override
public PlayerMessageData parse (Component message) {
if (message instanceof TextComponent) return parse((TextComponent) message);
return null;
}
private boolean isSeperatorAt (List<Component> children, int start) {
return (children.get(start).equals(SEPERATOR_COLON) || children.get(start).equals(SEPERATOR_COLON_RACCOON)) && children.get(start + 1).equals(SEPERATOR_SPACE);
}
public PlayerMessageData parse (TextComponent message) {
List<Component> children = message.children();
if (!message.content().isEmpty() || !message.style().isEmpty() || children.size() < 3) return null;
final Component prefix = children.getFirst();
Component displayName = Component.empty();
Component contents = Component.empty();
if (isSeperatorAt(children, 1)) { // Missing/blank display name
if (children.size() > 3) contents = children.get(3);
} else if (isSeperatorAt(children, 2)) {
displayName = children.get(1);
if (children.size() > 4) contents = children.get(4);
} else {
return null;
}
PlayerProfileData sender = bot.players.getDisplayName(Component.empty().append(prefix).append(displayName));
return new PlayerMessageData(sender, contents, "minecraft:chat", displayName);
}
private boolean isSeperatorAt (List<Component> children, int start) {
return (children.get(start).equals(SEPERATOR_COLON) || children.get(start).equals(SEPERATOR_COLON_RACCOON)) && children.get(
start + 1).equals(SEPERATOR_SPACE);
}
}
@@ -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,14 +3,13 @@ package land.chipmunk.parker2991.nitoribot.command;
import net.kyori.adventure.text.Component;
public class CommandError extends Exception {
public String name = "CommandError";
public Component message;
public final Component message;
public CommandError (Component message) {
this.message = message;
}
public CommandError (Component message) {
this.message = message;
}
public Component message () {
return message;
}
public Component message () {
return message;
}
}
@@ -1,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;
import java.util.List;
public CommandInfo (String name, CommandTrustLevels trustlevel, String[] aliases, String description) {
this.name = name;
this.trustlevel = trustlevel;
this.aliases = aliases;
this.description = description;
}
public interface CommandInfo {
//String getCommandName ();
public abstract void execute (CommandContext context);
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 class CommandSource {
private Bot bot;
public PlayerProfileData sender;
public boolean inGame;
public CommandSource (Bot bot, PlayerProfileData sender) {
this.bot = bot;
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
);
bot.chat.tellraw(selector, message);
}
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());
if (chatType() == ParsedChatType.NORMAL) bot.chat.tellraw("@a", message);
else 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,24 +5,36 @@ 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 {
public EchoCommand () {
super(
"echo",
CommandTrustLevels.PUBLIC,
new String[] { "say" },
"make the bot say a message"
);
}
import java.util.List;
public class EchoCommand implements CommandInfo {
public EchoCommand () {
@Override
public void execute(CommandContext context) {
Bot bot = context.bot;
String args = String.join(" ", context.args);
if (args.startsWith("/")) {
bot.chat.command(args.substring("/".length()));
} else {
bot.chat.message(args);
}
}
}
@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());
if (args.startsWith("/")) {
bot.chat.command(args.substring("/".length()));
} else {
bot.chat.message(args);
}
}
}
@@ -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 {
public HelpCommand () {
super(
"help",
CommandTrustLevels.PUBLIC,
new String[] { "heko", "hell", "?", "cmds"},
"see the list of commands"
);
}
import static land.chipmunk.parker2991.nitoribot.util.ComponentUtil.convertColorString;
public class HelpCommand implements CommandInfo {
public HelpCommand () {
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;
}
}
Component component = Component.empty()
.append(Public)
.append(Component.text("\n"))
.append(Trusted);
// .append(Component.text("\n"));
return component;
}
@Override
public CommandTrustLevels getTrustLevel () {
return CommandTrustLevels.PUBLIC;
}
private Component getCommand (Bot bot, String[] command) {
List<Component> list = new ArrayList<>();
@Override
public List<String> getAliases () {
return List.of("help", "hell", "?", "heko", "cmds", "commands");
}
Component component = null;
@Override
public String getDescription () {
return "see the list of commands the bot has";
}
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)
)
)
public Component getCommands (Bot bot) {
List<Component> Public = new ArrayList<>();
List<Component> Trusted = new ArrayList<>();
for (CommandInfo commands : bot.commandManager.commands) {
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 -> {
}
}
}
return Component.empty().append(Public).append(Component.text("\n")).append(Trusted);
}
private Component getCommand (Bot bot, String[] command) {
Component component = null;
for (CommandInfo commands : bot.commandManager.commands) {
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();
if (args.length != 0) {
source.sendFeedback(bot, getCommand(bot, args));
return;
}
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 component = Component.empty().append(helpLayout).append(Component.join(
JoinConfiguration.separator(Component.space()),
getCommands(bot)
)).color(convertColorString(bot.config.colors.commands.tertiary));
source.sendFeedback(bot, component);
}
return component;
}
@Override
public void execute (CommandContext context) {
Bot bot = context.bot;
String[] args = context.args;
CommandSource source = context.source;
Config config = bot.config;
Config.Colors colors = config.colors;
List<Component> list = new ArrayList<>();
if (args.length != 0) {
source.sendFeedback(getCommand(bot, args));
//return null;
}
list = List.of(
Component.text("Commands").color(NamedTextColor.NAMES.value(colors.commands.primary)),
Component.text(bot.commandManager.commands.size()).color(NamedTextColor.NAMES.value(colors.integer)),
TranslationsUtil.customTranslations("command.help.trust_level.public", null).color(NamedTextColor.NAMES.value(colors.help.Public)),
TranslationsUtil.customTranslations("command.help.trust_level.trusted", null).color(NamedTextColor.NAMES.value(colors.help.trusted)),
TranslationsUtil.customTranslations("command.help.trust_level.admin", null).color(NamedTextColor.NAMES.value(colors.help.admin)),
TranslationsUtil.customTranslations("command.help.trust_level.owner", null).color(NamedTextColor.NAMES.value(colors.help.owner))
);
Component helpLayout = TranslationsUtil.customTranslations(
"command.help.layout",
list
);
Component component = Component.empty()
.append(helpLayout)
.append(Component.join(JoinConfiguration.separator(Component.space()), getCommands(bot)));
source.sendFeedback(component);
}
}
@@ -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,51 +3,42 @@ package land.chipmunk.parker2991.nitoribot.commands.Public;
import land.chipmunk.parker2991.nitoribot.command.CommandContext;
import land.chipmunk.parker2991.nitoribot.command.CommandInfo;
import land.chipmunk.parker2991.nitoribot.command.CommandTrustLevels;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
public class MCServerCommand extends CommandInfo {
public MCServerCommand () {
super(
"mcserver",
CommandTrustLevels.PUBLIC,
new String[] { "minecraftserver" },
"ping a minecraft server"
);
}
import java.util.List;
@Override
public void execute (CommandContext context) {
var bot = context.bot;
var source = context.source;
String args = String.join(" ", context.args);
public class MCServerCommand implements CommandInfo {
public MCServerCommand () {
var ip = args.split(":");
}
var info = bot.mcServer.pingServer(ip);
@Override
public CommandTrustLevels getTrustLevel () {
return CommandTrustLevels.PUBLIC;
}
System.out.println(info);
@Override
public List<String> getAliases () {
return List.of("mcserver");
}
/*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)
)
);*/
@Override
public String getDescription () {
return "ping minecraft servers";
}
/*source.sendFeedback(
Component.translatable(
"Server Version %s %s %s",
Component.text(":").color(NamedTextColor.GRAY),
Component.text(info.versionName()),
Component.text(info.protocolVersion())
)
);*/
@Override
public void execute (CommandContext context) {
var bot = context.bot();
var source = context.source();
String args = String.join(" ", context.args());
//source.sendFeedback(info.description());
}
var ip = args.split(":");
var info = bot.mcServer.pingServer(ip);
System.out.println(info);
}
}
/*
[logs] [System Chat] Ip: kaboom.pw:25565
@@ -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 {
public RCCommand () {
super(
"rc",
CommandTrustLevels.PUBLIC,
new String[] { "refill", "refillcore" },
"refill the bot's core"
);
}
import java.util.List;
@Override
public void execute (CommandContext context) {
Bot bot = context.bot;
CommandSource source = context.source;
import static land.chipmunk.parker2991.nitoribot.util.ComponentUtil.convertColorString;
bot.core.move();
public class RCCommand implements CommandInfo {
public RCCommand () {
}
source.sendFeedback(Component.text("Refilling core").color(NamedTextColor.BLUE));
}
@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.core.move();
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,21 +1,36 @@
package land.chipmunk.parker2991.nitoribot.commands.trusted;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.command.*;
import land.chipmunk.parker2991.nitoribot.command.CommandContext;
import land.chipmunk.parker2991.nitoribot.command.CommandInfo;
import land.chipmunk.parker2991.nitoribot.command.CommandTrustLevels;
public class ReconnectCommand extends CommandInfo {
public ReconnectCommand () {
super(
"reconnect",
CommandTrustLevels.TRUSTED,
new String[] { },
"reconnect the bot"
);
}
import java.util.List;
@Override
public void execute (CommandContext context) {
Bot bot = context.bot;
public class ReconnectCommand implements CommandInfo {
public ReconnectCommand () {
bot.session.disconnect("Reconnect Command");
}
}
@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.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
}
@@ -2,15 +2,13 @@ package land.chipmunk.parker2991.nitoribot.data;
import net.kyori.adventure.text.Component;
public record PingServerData (
//String ip,
//int port,
String versionName,
long protocolVersion,
int playersOnline,
int maxPlayers,
Component description
//long latency
public record PingServerData(
//String ip,
//int port,
String versionName, long protocolVersion, int playersOnline, int maxPlayers, Component description
//long latency
) {
public void latency (long pingTime) { System.out.println(versionName); }
public void latency (long pingTime) {
System.out.println(versionName);
}
}
@@ -1,5 +0,0 @@
package land.chipmunk.parker2991.nitoribot.data;
import org.cloudburstmc.math.vector.Vector3d;
public record PlayerPositionData (float pitch, float yaw, Vector3d position) {}
@@ -1,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 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;
}
public void gameMode (GameMode gameMode) {
}
public void latency (int latency) {
}
public void position (PositionData position) {
}
public void displayName (@Nullable Component displayName) {
}
public void entityId (int entityId) {
}
}
@@ -1,3 +1,6 @@
package land.chipmunk.parker2991.nitoribot.data;
public record PositionData (int x, int y, int z) {}
import org.cloudburstmc.math.vector.Vector3d;
public record PositionData(float pitch, float yaw, Vector3d position) {
}
@@ -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);
PlayerMessageData parse (Component message);
}
@@ -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 interface Listener {
default void packetSent () {
}
public class Listener {
public void packetSent (Session session, Packet packet) {}
default void packetReceived (Packet packet) {
}
public void packetReceived (Session session, Packet packet) {}
default void playerChatReceived (Component message) {
}
public void extrasMessagingReceived (MCProtocolLibMessenger messenger) {}
default void disguisedChatReceived (Component message) {
}
public void chatAttestationMessageReceived () {}
default void systemChatReceived (Component message) {
}
public void playerChatReceived (Component message) {}
default void parsedMessage (PlayerMessageData data) {
}
public void disguisedChatReceived (Component message) {}
default void botMoved () {
}
public void systemChatReceived (Component message) {}
public void parsedMessage (Component message, PlayerMessageData data) {}
public void botMoved () {}
default void commandSpyReceived (PlayerProfileData player, String command) {
}
}
@@ -4,17 +4,17 @@ import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class ListenerManager {
public final List<Listener> listeners = new CopyOnWriteArrayList<>();
public final List<Listener> listeners = new CopyOnWriteArrayList<>();
public void addListener (Listener listener) {
listeners.add(listener);
}
public void addListener (Listener listener) {
listeners.add(listener);
}
public void removeListener (Listener listener) {
listeners.remove(listener);
}
public void removeListener (Listener listener) {
listeners.remove(listener);
}
public void clearListener () {
listeners.clear();
}
public void clearListener () {
listeners.clear();
}
}
@@ -3,124 +3,94 @@ package land.chipmunk.parker2991.nitoribot.logger;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.Main;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Logger {
private final DateTimeFormatter formatTime = DateTimeFormatter.ofPattern("hh:mm:ss");
private final DateTimeFormatter formatTime = DateTimeFormatter.ofPattern("hh:mm:ss");
private final DateTimeFormatter formatDate = DateTimeFormatter.ofPattern("MM/dd/yyyy");
private final DateTimeFormatter formatDate = DateTimeFormatter.ofPattern("MM/dd/yyyy");
public Logger () {
public Component getLoggerType (LoggerType type) {
Component logType = null;
switch (type) {
case LoggerType.LOG -> logType = Component.text("LOG").color(NamedTextColor.GOLD);
case LoggerType.COMMAND -> logType = Component.text("COMMAND").color(NamedTextColor.GREEN);
case LoggerType.ERROR -> logType = Component.text("ERROR").color(NamedTextColor.DARK_RED);
case LoggerType.WARN -> logType = Component.text("WARN").color(NamedTextColor.YELLOW);
case LoggerType.INFO -> logType = Component.text("INFO").color(NamedTextColor.DARK_GREEN);
case LoggerType.RECONNECT -> logType = Component.text("RECONNECT").color(NamedTextColor.AQUA);
case LoggerType.DEBUG -> logType = Component.text("DEBUG").color(NamedTextColor.GOLD);
}
public static void LOG (Bot bot, String message) {
new Logger().prefix(LoggerType.LOG, bot, message);
}
return logType;
}
public static void DEBUG (Bot bot, String message) {
new Logger().prefix(LoggerType.DEBUG, bot, message);
}
private void prefix (LoggerType loggerType, Bot bot, String message) {
Component component = null;
Component host = null;
public static void ERROR (Bot bot, String message) {
new Logger().prefix(LoggerType.ERROR, bot, message);
}
ZoneId timezone = ZoneId.of("America/Chicago");
ZonedDateTime zoneDate = ZonedDateTime.now(timezone);
LocalDate date = zoneDate.toLocalDate();
LocalTime time = zoneDate.toLocalTime();
public static void WARN (Bot bot, String message) {
new Logger().prefix(LoggerType.WARN, bot, message);
}
Component type = getLoggerType(loggerType);
public static void COMMAND (Bot bot, String message) {
new Logger().prefix(LoggerType.COMMAND, bot, message);
}
if (bot == null) host = Component.text("NitoriBot Jar").color(NamedTextColor.BLUE);
host = Component.text(bot.options.host + ":" + bot.options.port).color(NamedTextColor.BLUE);
public static void RECONNECT (Bot bot, String message) {
new Logger().prefix(LoggerType.RECONNECT, bot, message);
}
component = Component.translatable(
"[%s %s %s] [%s] [%s] %s",
Component.translatable(formatTime.format(time)).color(NamedTextColor.BLUE),
Component.translatable(formatDate.format(date)).color(NamedTextColor.BLUE),
type,
Component.translatable(Thread.currentThread().getName()).color(NamedTextColor.BLUE),
host,
Component.translatable(message).color(NamedTextColor.WHITE)
).color(NamedTextColor.DARK_BLUE);
public static void INFO (Bot bot, String message) {
new Logger().prefix(LoggerType.INFO, bot, message);
}
String log = ComponentUtil.componentToAnsi(component);
public Component getLoggerType (LoggerType type) {
Component logType = null;
switch (type) {
case LoggerType.LOG -> logType = Component.text("LOG").color(NamedTextColor.GOLD);
case LoggerType.COMMAND -> logType = Component.text("COMMAND").color(NamedTextColor.GREEN);
case LoggerType.ERROR -> logType = Component.text("ERROR").color(NamedTextColor.DARK_RED);
case LoggerType.WARN -> logType = Component.text("WARN").color(NamedTextColor.YELLOW);
case LoggerType.INFO -> logType = Component.text("INFO").color(NamedTextColor.DARK_GREEN);
case LoggerType.RECONNECT -> logType = Component.text("RECONNECT").color(NamedTextColor.AQUA);
case LoggerType.DEBUG -> logType = Component.text("DEBUG").color(NamedTextColor.GOLD);
}
return logType;
}
if (bot == null) System.out.println(log);
else Main.console.reader.printAbove(log);
}
private void prefix (LoggerType loggerType, @Nullable Bot bot, String message) {
Component component;
Component host;
public static void LOG (Bot bot, String message) {
new Logger().prefix(
LoggerType.LOG,
bot,
message
);
}
ZoneId timezone = ZoneId.of("America/Chicago");
ZonedDateTime zoneDate = ZonedDateTime.now(timezone);
LocalDate date = zoneDate.toLocalDate();
LocalTime time = zoneDate.toLocalTime();
public static void DEBUG (Bot bot, String message) {
new Logger().prefix(
LoggerType.DEBUG,
bot,
message
);
}
Component type = getLoggerType(loggerType);
public static void ERROR (Bot bot, String message) {
new Logger().prefix(
LoggerType.ERROR,
bot,
message
);
}
if (bot == null) host = Component.text("NitoriBot Jar").color(NamedTextColor.BLUE);
else host = Component.text(bot.options.host + ":" + bot.options.port).color(NamedTextColor.BLUE);
public static void WARN (Bot bot, String message) {
new Logger().prefix(
LoggerType.WARN,
bot,
message
);
}
component = Component.translatable(
"[%s %s %s] [%s] [%s] %s",
Component.translatable(formatTime.format(time)).color(NamedTextColor.BLUE),
Component.translatable(formatDate.format(date)).color(NamedTextColor.BLUE),
type,
Component.translatable(Thread.currentThread().getName()).color(NamedTextColor.BLUE),
host,
Component.translatable(message).color(NamedTextColor.WHITE)
).color(NamedTextColor.DARK_BLUE);
public static void COMMAND (Bot bot, String message) {
new Logger().prefix(
LoggerType.COMMAND,
bot,
message
);
}
String log = ComponentUtil.componentToAnsi(component);
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 () {
}
if (bot == null) System.out.println(log);
else Main.console.reader.printAbove(log);
}
}
@@ -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;
@Override
public void parsedMessage (Component message, PlayerMessageData data) {
if (data.chatType != "minecraft:chat") return;
List<String> prefixes = bot.config.prefixes;
for (String prefix : prefixes) {
String plainMessage = ComponentUtil.componentToString(data.contents);
if (!plainMessage.startsWith(prefix)) return;
String command = plainMessage.substring(prefix.length());
CommandSource source = new CommandSource(bot, data.sender);
bot.commandManager.executeString(source, command);
public ChatCommandHandlerModule (Bot bot) {
this.bot = bot;
this.config = bot.config;
bot.listenerManager.addListener(this);
}
}
public ChatCommandHandlerModule (Bot bot) {
this.bot = bot;
@Override
public void parsedMessage (PlayerMessageData data) {
if (!data.chatType().equals("minecraft:chat")) return;
bot.listenerManager.addListener(this);
}
List<String> prefixes = config.prefixes;
for (String prefix : prefixes) {
String plainMessage = ComponentUtil.componentToString(data.contents());
if (!plainMessage.startsWith(prefix)) return;
String command = plainMessage.substring(prefix.length());
CommandSource source = new CommandSource(data.sender(), true, ParsedChatType.NORMAL);
bot.commandManager.executeString(source, command);
}
}
@Override
public void commandSpyReceived (PlayerProfileData player, String message) {
List<String> prefixes = config.prefixes;
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,138 +15,137 @@ 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;
@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);
}
this.chatParsers = List.of(new KaboomChatParser(bot));
public String parseChatTypes (int chatType) {
String getTranslation = bot.registry.chatTypes.get(chatType);
return getTranslation;
}
public void systemChat (ClientboundSystemChatPacket packet) {
final Component message = packet.getContent();
for (Listener listener : bot.listenerManager.listeners) {
listener.systemChatReceived(message);
}
}
public void diguisedChat (ClientboundDisguisedChatPacket packet) {
Component getMessage = packet.getMessage();
Component targetUsername = packet.getName();
Component message;
final String parseChatTypes = parseChatTypes(packet.getChatType().id());
if (packet.getChatType().id() == 4) {
message = getMessage;
} else {
message = Component.translatable(
parseChatTypes,
targetUsername,
getMessage
);
bot.listenerManager.addListener(this);
}
for (Listener listener : bot.listenerManager.listeners) {
listener.disguisedChatReceived(message);
}
}
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);
@Override
public void packetReceived (Packet packet) {
switch (packet) {
case ClientboundSystemChatPacket p -> systemChat(p);
case ClientboundPlayerChatPacket p -> playerChat(p);
case ClientboundDisguisedChatPacket p -> disguisedChat(p);
default -> {
}
}
}
parseMessage(
unsignedContent,
new PlayerMessageData(
bot.players.getPlayerUUID(packet.getSender()),
content,
"minecraft:chat",
bot.players.getPlayerUUID(packet.getSender()).displayName
)
);
}
public String parseChatTypes (int chatType) {
public void parseMessage (Component message, PlayerMessageData data) {
try {
PlayerMessageData parsed = null;
return bot.registry.chatTypes.get(chatType);
}
for (ParseChatData parser : chatParsers) {
parsed = parser.parse(message);
if (parsed != null) break;
};
public void systemChat (ClientboundSystemChatPacket packet) {
final Component message = packet.getContent();
if (parsed == null) return;
for (Listener listener : bot.listenerManager.listeners) {
listener.systemChatReceived(message);
}
}
for (Listener listener : bot.listenerManager.listeners) {
listener.parsedMessage(message, data);
}
public void disguisedChat (ClientboundDisguisedChatPacket packet) {
Component getMessage = packet.getMessage();
Component targetUsername = packet.getName();
} catch (Exception ignore) {}
}
Component message;
public void message (String message) {
bot.session.send(
new ServerboundChatPacket(
message,
Instant.now().toEpochMilli(),
0,
null,
0,
new BitSet(),
0
)
);
}
final String parseChatTypes = parseChatTypes(packet.getChatType().id());
public void command (String command) {
bot.session.send(
new ServerboundChatCommandPacket(
command
)
);
}
if (packet.getChatType().id() == 4) {
message = getMessage;
} else {
message = Component.translatable(parseChatTypes, targetUsername, getMessage);
}
public void send (String message) {
if (message.startsWith("/")) bot.chat.command(message.substring(1));
for (Listener listener : bot.listenerManager.listeners) {
listener.disguisedChatReceived(message);
}
else bot.chat.message(message);
}
TextComponent textComponent = (TextComponent) targetUsername;
public void tellraw (String selector, Component message) {
bot.core.run("minecraft:tellraw " + selector + " " + GsonComponentSerializer.gson().serialize(message));
}
parseMessage(
message,
new PlayerMessageData(
bot.players.getPlayerByUsername(textComponent.content()),
packet.getMessage(),
"minecraft:chat",
Objects.requireNonNull(bot.players.getPlayerByUsername(textComponent.content())).displayName()
)
);
}
public ChatModule (Bot bot) {
this.bot = bot;
chatParsers.add(new KaboomChatParser(bot));
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);
}
parseMessage(
unsignedContent,
new PlayerMessageData(
bot.players.getPlayerUUID(packet.getSender()),
content,
"minecraft:chat",
Objects.requireNonNull(bot.players.getPlayerUUID(packet.getSender())).displayName()
)
);
}
public void parseMessage (Component message, PlayerMessageData data) {
try {
PlayerMessageData parsed = null;
for (ParseChatData parser : chatParsers) {
parsed = parser.parse(message);
if (parsed != null) break;
}
if (parsed == null) return;
for (Listener listener : bot.listenerManager.listeners) {
listener.parsedMessage(data);
}
} catch (Exception ignore) {
}
}
public void message (String message) {
bot.session.send(new ServerboundChatPacket(message, Instant.now().toEpochMilli(), 0, null, 0, new BitSet(), 0));
}
public void command (String command) {
bot.session.send(new ServerboundChatCommandPacket(command));
}
public void send (String message) {
if (message.startsWith("/")) bot.chat.command(message.substring(1));
else bot.chat.message(message);
}
public void tellraw (String selector, Component message) {
bot.core.run(String.format(
"%s %s %s",
"minecraft:tellraw",
selector,
GsonComponentSerializer.gson().serialize(message).trim()
));
}
bot.listenerManager.addListener(this);
};
}
@@ -1,275 +1,227 @@
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);
@Override
public void botMoved () {
move();
}
public CommandCoreModule (Bot bot) {
this.bot = bot;
public Vector3i position;
public Vector3i itemPosition;
public void move () {
Vector3d botPos = bot.position.positionAsVector;
position = Vector3i.from(
Math.floor(botPos.getX() / 16) * 16,
0,
Math.floor(botPos.getZ() / 16) * 16
);
itemPosition = Vector3i.from(
botPos.getX(),
botPos.getY() - 1,
botPos.getZ()
);
itemRefill();
};
public void chatRefill () {
Vector3i pos = position;
CommandCoreAreaData coreArea = area;
int startPosX = pos.getX() - coreArea.start.getX();
int startPosY = pos.getY() - coreArea.start.getY();
int startPosZ = pos.getZ() - coreArea.start.getZ();
int endPosX = pos.getX() - coreArea.end.getX();
int endPosY = pos.getY() - coreArea.end.getY();
int endPosZ = pos.getZ() - coreArea.end.getZ();
String command = String.format(
"minecraft:fill %s %s %s %s %s %s command_block{CustomName:%s}",
startPosX,
startPosY,
startPosZ,
endPosX,
endPosY,
endPosZ,
bot.config.core.coreName
);
bot.chat.command(command);
}
public void itemRefill () {
final NbtMapBuilder blockEntityTagBuilder = NbtMap.builder();
Vector3i pos = position;
CommandCoreAreaData coreArea = area;
int startPosX = pos.getX() - coreArea.start.getX();
int startPosY = pos.getY() - coreArea.start.getY();
int startPosZ = pos.getZ() - coreArea.start.getZ();
int endPosX = pos.getX() - coreArea.end.getX();
int endPosY = pos.getY() - coreArea.end.getY();
int endPosZ = pos.getZ() - coreArea.end.getZ();
String command = String.format(
"minecraft:fill %s %s %s %s %s %s command_block{CustomName:%s} replace",
startPosX,
startPosY,
startPosZ,
endPosX,
endPosY,
endPosZ,
bot.config.core.coreName
);
blockEntityTagBuilder.putString("Command", command)
.putByte("auto", (byte) 1)
.putByte("TrackOutput", (byte) 1);
final NbtMap blockEntityTag = blockEntityTagBuilder.build();
final Map<DataComponentType<?>, DataComponent<?, ?>> map = new HashMap<>();
map.put(
DataComponentTypes.BLOCK_ENTITY_DATA,
DataComponentTypes.BLOCK_ENTITY_DATA
.getDataComponentFactory()
.create(
DataComponentTypes.BLOCK_ENTITY_DATA,
TypedEntityData.<BlockEntityType>builder()
.type(BlockEntityType.COMMAND_BLOCK)
.tag(blockEntityTag)
.build()
)
);
map.put(
DataComponentTypes.ITEM_NAME,
DataComponentTypes.ITEM_NAME
.getDataComponentFactory()
.create(
DataComponentTypes.ITEM_NAME,
ComponentUtil.componentFromJSON(bot.config.core.coreName)
)
);
map.put(
DataComponentTypes.CUSTOM_NAME,
DataComponentTypes.CUSTOM_NAME
.getDataComponentFactory()
.create(
DataComponentTypes.CUSTOM_NAME,
ComponentUtil.componentFromJSON(bot.config.core.coreName)
)
);
final DataComponents dataComponents = new DataComponents(map);
bot.session.send(
new ServerboundSetCreativeModeSlotPacket(
(short) 36,
new ItemStack(
482,
64,
dataComponents
)
)
);
bot.session.send(
new ServerboundPlayerActionPacket(
PlayerAction.START_DIGGING,
itemPosition,
Direction.NORTH,
0
)
);
bot.session.send(
new ServerboundUseItemOnPacket(
itemPosition,
Direction.NORTH,
Hand.MAIN_HAND,
0.5f,
0.5f,
0.5f,
false,
false,
1
)
);
}
public Vector3i currentBlockRelative = Vector3i.from(0, 0, 0);
public PositionData currentBlock () {
Vector3i relativePosition = currentBlockRelative;
Vector3i corePosition = position;
return new PositionData(
relativePosition.getX() + corePosition.getX(),
relativePosition.getY() + corePosition.getY(),
relativePosition.getZ() + corePosition.getZ()
);
}
public void incrementCurrentBlock () {
Vector3i relativePosition = currentBlockRelative;
CommandCoreAreaData coreArea = area;
int posX = relativePosition.getX();
int posY = relativePosition.getY();
int posZ = relativePosition.getZ();
posX++;
if (posX > coreArea.end.getX()) {
posX = coreArea.start.getX();
posZ++;
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);
}
if (posZ > coreArea.end.getZ()) {
posZ = coreArea.start.getZ();
posY++;
@Override
public void botMoved () {
move();
}
if (posY > coreArea.end.getY()) {
posX = coreArea.start.getX();
posY = coreArea.start.getY();
posZ = coreArea.start.getZ();
public void move () {
Vector3d botPos = bot.position.positionData.position();
position = Vector3i.from(Math.floor(botPos.getX() / 16) * 16, 0, Math.floor(botPos.getZ() / 16) * 16);
itemPosition = Vector3i.from(botPos.getX(), botPos.getY() - 1, botPos.getZ());
chatRefill();
}
}
public void commandBlock (String command, boolean doesTrackOutput, boolean conditional, boolean automatic) {
if (command.length() > 32767) return;
bot.session.send(
new ServerboundSetCommandBlockPacket(
position,
command,
CommandBlockMode.AUTO,
doesTrackOutput,
conditional,
automatic
)
);
}
public void chatRefill () {
Vector3i pos = position;
CommandCoreAreaData coreArea = area;
public void run (String command) {
commandBlock(command, true, false, true);
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());
incrementCurrentBlock();
}
String command = String.format(
"minecraft:fill %s %s %s %s %s %s command_block{CustomName:%s} destroy",
startPosX,
startPosY,
startPosZ,
endPosX,
endPosY,
endPosZ,
bot.config.core.coreName
);
public CommandCoreModule (Bot bot) {
this.bot = bot;
bot.chat.command(command);
}
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
)
);
public void itemRefill () {
final NbtMapBuilder blockEntityTagBuilder = NbtMap.builder();
bot.listenerManager.addListener(this);
}
String command = getCommand();
blockEntityTagBuilder.putString("Command", command).putByte("auto", (byte) 1).putByte("TrackOutput", (byte) 1);
final NbtMap blockEntityTag = blockEntityTagBuilder.build();
final Map<DataComponentType<?>, DataComponent<?, ?>> map = new HashMap<>();
map.put(
DataComponentTypes.BLOCK_ENTITY_DATA,
DataComponentTypes.BLOCK_ENTITY_DATA.getDataComponentFactory().create(
DataComponentTypes.BLOCK_ENTITY_DATA,
TypedEntityData.<BlockEntityType>builder().type(BlockEntityType.COMMAND_BLOCK).tag(blockEntityTag).build()
)
);
map.put(
DataComponentTypes.ITEM_NAME,
DataComponentTypes.ITEM_NAME.getDataComponentFactory().create(
DataComponentTypes.ITEM_NAME,
ComponentUtil.componentFromJSON(bot.config.core.coreName)
)
);
map.put(
DataComponentTypes.CUSTOM_NAME,
DataComponentTypes.CUSTOM_NAME.getDataComponentFactory().create(
DataComponentTypes.CUSTOM_NAME,
ComponentUtil.componentFromJSON(bot.config.core.coreName)
)
);
final DataComponents dataComponents = new DataComponents(map);
bot.session.send(new ServerboundSetCreativeModeSlotPacket((short) 36, new ItemStack(482, 64, dataComponents)));
bot.session.send(new ServerboundPlayerActionPacket(
PlayerAction.START_DIGGING,
itemPosition,
Direction.NORTH,
0
));
bot.session.send(new ServerboundUseItemOnPacket(
itemPosition,
Direction.NORTH,
Hand.MAIN_HAND,
0.5f,
0.5f,
0.5f,
false,
false,
1
));
}
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 PositionData currentBlock () {
Vector3d relativePosition = currentBlockRelative;
Vector3i corePosition = position;
return new PositionData(
(float) (relativePosition.getX() + corePosition.getX()),
(float) (relativePosition.getY() + corePosition.getY()),
Vector3d.from(relativePosition.getZ(), relativePosition.getY(), relativePosition.getZ())
);
}
public void incrementCurrentBlock () {
Vector3d relativePosition = currentBlockRelative;
CommandCoreAreaData coreArea = area;
double posX = relativePosition.getX();
double posY = relativePosition.getY();
double posZ = relativePosition.getZ();
posX++;
if (posX > coreArea.end().getX()) {
posX = coreArea.start().getX();
posZ++;
}
if (posZ > coreArea.end().getZ()) {
posZ = coreArea.start().getZ();
posY++;
}
if (posY > coreArea.end().getY()) {
posX = coreArea.start().getX();
posY = coreArea.start().getY();
posZ = coreArea.start().getZ();
}
currentBlockRelative = Vector3d.from(posX, posY, posZ);
}
public void commandBlock (String command, boolean doesTrackOutput, boolean conditional, boolean automatic) {
if (command.length() > 32767 || position == null) return;
bot.session.send(new ServerboundSetCommandBlockPacket(
position,
command,
CommandBlockMode.AUTO,
doesTrackOutput,
conditional,
automatic
));
}
public void run (String command) {
commandBlock(command, true, false, true);
incrementCurrentBlock();
}
}
@@ -1,86 +1,80 @@
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;
public void registerCommand (CommandInfo command) {
commands.add(command);
}
public CommandInfo getCommand (String getCommand) {
for (CommandInfo command : commands) {
for (String aliases : command.aliases) {
if (getCommand.equals(aliases)) return command;
}
if (getCommand.equals(command.name)) return command;
registerCommand(new EchoCommand());
registerCommand(new HelpCommand());
registerCommand(new ReconnectCommand());
registerCommand(new RCCommand());
registerCommand(new MCServerCommand());
registerCommand(new TestCommand());
registerCommand(new InfoCommand());
}
return null;
}
public void execute (CommandSource source, String commandName, String[] args) {
try {
CommandInfo command = getCommand(commandName.toLowerCase());
if (command == null) throw new CommandError(
Component.translatable(
"%s%s%s %s",
Component.translatable("command.unknown.command"),
Component.text("\n"),
Component.text(commandName).color(NamedTextColor.GRAY),
Component.translatable("command.context.here")
).color(NamedTextColor.RED)
);
CommandContext context = new CommandContext(bot, args, source, command);
command.execute(context);
} catch (CommandError error) {
source.sendFeedback(error.message());
} catch (Exception error) {
source.sendFeedback(
Component.translatable("command.failed").color(NamedTextColor.DARK_RED)
);
String Error = ErrorToString.errorToString(error);
Logger.ERROR(bot, Error);
public void registerCommand (CommandInfo command) {
commands.add(command);
}
}
public void executeString (CommandSource source, String command) {
String[] splitArguments = command.split(" ");
String commandName = splitArguments[0];
final String[] args = Arrays.copyOfRange(splitArguments, 1, splitArguments.length);
this.execute(source, commandName, args);
}
public CommandInfo getCommand (String getCommand) {
for (CommandInfo command : commands) {
for (String aliases : command.getAliases()) {
if (getCommand.equals(aliases)) return command;
}
}
return null;
}
public CommandManagerModule (Bot bot) {
this.bot = bot;
public void execute (CommandSource source, String commandName, String[] args) {
try {
CommandInfo command = getCommand(commandName.toLowerCase());
registerCommand(new EchoCommand());
registerCommand(new HelpCommand());
registerCommand(new ReconnectCommand());
registerCommand(new RCCommand());
registerCommand(new MCServerCommand());
}
if (command == null) throw new CommandError(Component.translatable(
"%s%s%s %s",
Component.translatable("command.unknown.command"),
Component.text("\n"),
Component.text(commandName).color(NamedTextColor.GRAY),
Component.translatable("command.context.here")
).color(NamedTextColor.RED));
CommandContext context = new CommandContext(bot, args, source);
command.execute(context);
} catch (CommandError error) {
source.sendFeedback(bot, error.message());
} catch (Exception error) {
source.sendFeedback(bot, Component.translatable("command.failed").color(NamedTextColor.DARK_RED));
String Error = ErrorToString.errorToString(error);
Logger.ERROR(bot, Error);
}
}
public void executeString (CommandSource source, String command) {
String[] splitArguments = command.split(" ");
String commandName = splitArguments[0];
final String[] args = Arrays.copyOfRange(splitArguments, 1, splitArguments.length);
this.execute(source, commandName, args);
}
}
@@ -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,51 +1,46 @@
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;
private static final List<Bot> servers = Main.Bots;
public LineReader reader;
public final LineReader reader;
public String server = "all";
public final String server = "all";
@Override
public void complete (LineReader reader, ParsedLine line, List<Candidate> candidates) {
public ConsoleModule () {
this.reader = LineReaderBuilder.builder().completer(this).build();
}
Main.executorService.submit(
() -> {
while (true) {
try {
String line;
private void handleLine (String line) {
for (Bot bot : servers) {
if (line.equals("c.kill")) System.exit(0);
bot.chat.send(line);
line = reader.readLine(String.format("[%s] > ", this.server));
handleLine(line);
} catch (Exception _) {
}
}
}, "Console Thread"
);
}
}
public ConsoleModule (Config config) {
this.reader = LineReaderBuilder.builder()
.completer(this)
.build();
@Override
public void complete (LineReader reader, ParsedLine line, List<Candidate> candidates) {
Main.executorService.submit(() -> {
while (true) {
try {
String line = null;
}
line = reader.readLine(String.format("[%s] > ", this.server));
handleLine(line);
} catch (Exception e) {}
}
}, "Console Thread");
}
private void handleLine (String line) {
for (Bot bot : servers) {
if (line.equals(bot.config.console.prefix + "kill")) System.exit(0);
bot.chat.send(line);
}
}
}
@@ -1,79 +0,0 @@
package land.chipmunk.parker2991.nitoribot.modules;
/*
i will work on this module some other time,
i have been messing with it and trying to get it to work for 3 days straight
so this is currently stubbed
*/
import land.chipmunk.code.kaboomstandardsorganization.messaginglib.mcprotocollib.MCProtocolLibMessenger;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.listeners.*;
import org.geysermc.mcprotocollib.network.Session;
import org.geysermc.mcprotocollib.network.packet.Packet;
import java.util.ArrayList;
import java.util.List;
public class ExtrasMessagingModule extends Listener {
private Bot bot;
public final List<String> channels = new ArrayList<>();
public static final String TEST_CHANNEL = "test";
public void register (String channel) {
}
public void unregister (String channel) {
}
public void sendMessage (MCProtocolLibMessenger messenger, String channel, String message) {
}
@Override
public void extrasMessagingReceived (MCProtocolLibMessenger message) {
/*var findPlayer = bot.players.getPlayerUUID(player).profile.getName();
bot.chat.tellraw("@a[tag=nitoribot_debug]",
Component.text(
"Recieved: " + message + "\n" +
"From: " + findPlayer + "\n" +
"Channel: " + channel
)
);*/
}
@Override
public void packetSent(Session session, Packet packet) {
}
/*
messenger.receivePayloads(
TEST_CHANNEL,
(_, _, payload) -> {
Logger.info(
"Received {}",
payload.toString(StandardCharsets.UTF_8)
);
messenger.sendMessage(TEST_CHANNEL, payload);
}
);
messenger.sendMessage(
TEST_CHANNEL,
wrappedBuffer("echo".getBytes(StandardCharsets.UTF_8))
);
*/
public ExtrasMessagingModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
}
@@ -1,43 +1,39 @@
package land.chipmunk.parker2991.nitoribot.modules;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import land.chipmunk.parker2991.nitoribot.logger.Logger;
import land.chipmunk.parker2991.nitoribot.util.ComponentUtil;
import land.chipmunk.parker2991.nitoribot.listeners.*;
import net.kyori.adventure.text.Component;
public class LoggingModule extends Listener {
private Bot bot;
public class LoggingModule implements Listener {
private final Bot bot;
@Override
public void playerChatReceived (Component message) {
handleMessages(message);
};
public LoggingModule (Bot bot) {
this.bot = bot;
@Override
public void disguisedChatReceived (Component message) {
handleMessages(message);
}
bot.listenerManager.addListener(this);
}
@Override
public void systemChatReceived (Component message) {
handleMessages(message);
}
@Override
public void playerChatReceived (Component message) {
handleMessages(message);
}
public void handleMessages (Component _message) {
final String host = bot.options.host;
final int port = bot.options.port;
String message = ComponentUtil.componentToAnsi(_message);
//if (host.equals("kaboom.pw")) return;
// Logger.LOG(bot, message);
}
@Override
public void disguisedChatReceived (Component message) {
handleMessages(message);
}
public LoggingModule (Bot bot) {
this.bot = bot;
@Override
public void systemChatReceived (Component message) {
handleMessages(message);
}
bot.listenerManager.addListener(this);
}
public void handleMessages (Component _message) {
String message = ComponentUtil.componentToAnsi(_message);
//if (host.equals("kaboom.pw")) return;
Logger.LOG(bot, message);
}
}
@@ -20,79 +20,61 @@ 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 ClientSession client;
public final SessionService sessionService = new SessionService();
public final MinecraftProtocol protocol = new MinecraftProtocol();
private final List<SkinPart> skinParts = new ArrayList<>();
public MCServerModule (Bot bot) {
this.bot = bot;
public PingServerData pingServer (String[] host) {
AtomicReference<PingServerData> serverData = new AtomicReference<>();
}
client = ClientNetworkSessionFactory.factory()
.setAddress("kaboom.pw", 25565)
//.setAddress(host[0], Integer.parseInt(host[1]))
.setProtocol(protocol)
.create();
client.send(
new ServerboundClientInformationPacket(
"en_us",
1,
ChatVisibility.FULL,
true,
skinParts,
HandPreference.RIGHT_HAND,
false,
true,
ParticleStatus.ALL
)
);
public PingServerData pingServer (String[] host) {
AtomicReference<PingServerData> serverData = new AtomicReference<>();
client.setFlag(MinecraftConstants.SESSION_SERVICE_KEY, sessionService);
client = ClientNetworkSessionFactory.factory().setAddress("kaboom.pw", 25565)
//.setAddress(host[0], Integer.parseInt(host[1]))
.setProtocol(protocol).create();
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
*/
assert info.getVersionInfo() != null;
assert info.getPlayerInfo() != null;
client.send(new ServerboundClientInformationPacket(
"en_us",
1,
ChatVisibility.FULL,
true,
skinParts,
HandPreference.RIGHT_HAND,
false,
true,
ParticleStatus.ALL
));
serverData.set(new PingServerData(
info.getVersionInfo().getVersionName(),
info.getVersionInfo().getProtocolVersion(),
info.getPlayerInfo().getOnlinePlayers(),
info.getPlayerInfo().getMaxPlayers(),
info.getDescription()
));
});
client.setFlag(MinecraftConstants.SESSION_SERVICE_KEY, sessionService);
System.out.println(serverData);
client.setFlag(
MinecraftConstants.SERVER_INFO_HANDLER_KEY, (Session session, ServerStatusInfo info) -> {
assert info.getVersionInfo() != null;
assert info.getPlayerInfo() != null;
client.setFlag(MinecraftConstants.SERVER_PING_TIME_HANDLER_KEY, (session, pingTime) ->
serverData.get().latency(pingTime)
);
bot.executor.submit(() -> {
client.connect();
});
serverData.set(new PingServerData(
info.getVersionInfo().getVersionName(),
info.getVersionInfo().getProtocolVersion(),
info.getPlayerInfo().getOnlinePlayers(),
info.getPlayerInfo().getMaxPlayers(),
info.getDescription()
));
}
);
return serverData.get();
}
public MCServerModule (Bot bot) {
this.bot = bot;
System.out.println(serverData);
}
client.setFlag(
MinecraftConstants.SERVER_PING_TIME_HANDLER_KEY,
(session, pingTime) -> serverData.get().latency(pingTime)
);
bot.executor.submit(() -> client.connect());
return serverData.get();
}
}
@@ -1,187 +1,172 @@
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 final List<PlayerProfileData> list = new ArrayList<>();
public class PlayerListModule implements Listener {
public int transactionId = 0;
public final List<PlayerProfileData> list = new ArrayList<>();
@Override
public void packetReceived (Session session, Packet packet) {
if (packet instanceof ClientboundPlayerInfoUpdatePacket) playerInfo((ClientboundPlayerInfoUpdatePacket) packet);
else if (packet instanceof ClientboundPlayerInfoRemovePacket) playerRemove((ClientboundPlayerInfoRemovePacket) packet);
else if (packet instanceof ClientboundAddEntityPacket) getPlayerPosition((ClientboundAddEntityPacket) packet);
else if (packet instanceof ClientboundTagQueryPacket) queryPlayerData((ClientboundTagQueryPacket) packet);
}
public PlayerListModule (Bot bot) {
bot.listenerManager.addListener(this);
}
public void playerInfo (ClientboundPlayerInfoUpdatePacket packet) {
EnumSet<PlayerListEntryAction> actions = packet.getActions();
for (PlayerListEntryAction action : actions) {
for (PlayerListEntry entry : packet.getEntries()) {
switch (action) {
case PlayerListEntryAction.UPDATE_LIST_ORDER,
PlayerListEntryAction.UPDATE_HAT,
PlayerListEntryAction.INITIALIZE_CHAT,
PlayerListEntryAction.ADD_PLAYER -> addPlayer(entry);
case PlayerListEntryAction.UPDATE_LISTED -> updateListed(entry);
case PlayerListEntryAction.UPDATE_GAME_MODE -> updateGamemode(entry);
case PlayerListEntryAction.UPDATE_LATENCY -> updateLatency(entry);
case PlayerListEntryAction.UPDATE_DISPLAY_NAME -> updateDisplayName(entry);
@Override
public void packetReceived (Packet packet) {
switch (packet) {
case ClientboundPlayerInfoUpdatePacket p -> playerInfo(p);
case ClientboundPlayerInfoRemovePacket p -> playerRemove(p);
case ClientboundAddEntityPacket p -> getPlayerPosition(p);
default -> {
}
}
}
}
}
public void queryPlayerData (ClientboundTagQueryPacket packet) {
}
public void getPlayerPosition (ClientboundAddEntityPacket packet) {
if (packet.getType() == EntityType.PLAYER) {
UUID uuid = packet.getUuid();
int entityId = packet.getEntityId();
Vector3d playerPosition = Vector3d.from(packet.getX(), packet.getY(), packet.getZ());
float yaw = packet.getYaw();
float pitch = packet.getPitch();
PlayerProfileData player = getPlayerUUID(uuid);
player.entityId = entityId;
player.position = new PlayerPositionData(pitch, yaw, playerPosition);
// bot.session.send(
// new Server
//)
}
}
public final PlayerProfileData getPlayerByEntityID (int entityId) {
for (PlayerProfileData player : list) {
if (player.entityId == entityId) {
return player;
}
}
return null;
}
public void playerInfo (ClientboundPlayerInfoUpdatePacket packet) {
EnumSet<PlayerListEntryAction> actions = packet.getActions();
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) {
for (PlayerProfileData candidate : list) {
if (candidate.displayName != null && candidate.displayName.equals(displayName)) {
return candidate;
}
for (PlayerListEntryAction action : actions) {
for (PlayerListEntry entry : packet.getEntries()) {
switch (action) {
case PlayerListEntryAction.UPDATE_LIST_ORDER, PlayerListEntryAction.UPDATE_HAT,
PlayerListEntryAction.INITIALIZE_CHAT, PlayerListEntryAction.ADD_PLAYER -> addPlayer(entry);
case PlayerListEntryAction.UPDATE_LISTED -> updateListed(entry);
case PlayerListEntryAction.UPDATE_GAME_MODE -> updateGamemode(entry);
case PlayerListEntryAction.UPDATE_LATENCY -> updateLatency(entry);
case PlayerListEntryAction.UPDATE_DISPLAY_NAME -> updateDisplayName(entry);
}
}
}
}
return null;
}
public void updateListed (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) return;
getPlayer.listed = player.isListed();
}
public void updateGamemode (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) return;
getPlayer.gameMode = player.getGameMode();
}
public void updateLatency (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) return;
getPlayer.latency = player.getLatency();
}
public void updateDisplayName (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) return;
getPlayer.displayName = player.getDisplayName();
}
public void addPlayer (PlayerListEntry player) {
PlayerProfileData findDuplicatePlayer = getPlayerUUID(player.getProfileId());
if (findDuplicatePlayer != null) list.remove(findDuplicatePlayer);
PlayerProfileData formatPlayerData = new PlayerProfileData(
player.getProfileId(),
player.getProfile(),
player.isListed(),
player.getLatency(),
player.getGameMode(),
player.getDisplayName()
);
list.add(formatPlayerData);
}
public void playerRemove (ClientboundPlayerInfoRemovePacket packet) {
for (UUID uuid : packet.getProfileIds()) {
PlayerProfileData getPlayer = getPlayerUUID(uuid);
list.remove(getPlayer);
public void getPlayerPosition (ClientboundAddEntityPacket packet) {
if (packet.getType() == EntityType.PLAYER) {
UUID uuid = packet.getUuid();
int entityId = packet.getEntityId();
Vector3d playerPosition = Vector3d.from(packet.getX(), packet.getY(), packet.getZ());
float yaw = packet.getYaw();
float pitch = packet.getPitch();
PlayerProfileData player = getPlayerUUID(uuid);
assert player != null;
player.entityId(entityId);
player.position(new PositionData(pitch, yaw, playerPosition));
}
}
}
public PlayerListModule (Bot bot) {
bot.listenerManager.addListener(this);
}
@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) {
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 getPlayerByUsername (String username) {
for (PlayerProfileData candidate : list) {
if (candidate.profile().getName().equals(username)) {
return candidate;
}
}
return null;
}
public void updateListed (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) return;
getPlayer.listed(player.isListed());
}
public void updateGamemode (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) {
} else getPlayer.gameMode(player.getGameMode());
}
public void updateLatency (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) {
} else getPlayer.latency(player.getLatency());
}
public void updateDisplayName (PlayerListEntry player) {
PlayerProfileData getPlayer = getPlayerUUID(player.getProfileId());
if (getPlayer == null) {
} else getPlayer.displayName(player.getDisplayName());
}
public void addPlayer (PlayerListEntry player) {
PlayerProfileData findDuplicatePlayer = getPlayerUUID(player.getProfileId());
if (findDuplicatePlayer != null) list.remove(findDuplicatePlayer);
PlayerProfileData formatPlayerData = new PlayerProfileData(
player.getProfileId(),
null,
player.getProfile(),
player.isListed(),
player.getLatency(),
player.getGameMode(),
player.getDisplayName(),
player.isShowHat(),
player.getListOrder(),
null,
null,
null
);
list.add(formatPlayerData);
}
public void playerRemove (ClientboundPlayerInfoRemovePacket packet) {
for (UUID uuid : packet.getProfileIds()) {
PlayerProfileData getPlayer = getPlayerUUID(uuid);
if (getPlayer == null) return;
list.remove(getPlayer);
}
}
}
@@ -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;
public ScheduledFuture<?> timer;
public PositionData positionData;
private int i = 0;
private int x;
private int z;
@Override
public void packetReceived (Session session, Packet packet) {
if (packet instanceof ClientboundPlayerPositionPacket) packetReceived((ClientboundPlayerPositionPacket) packet);
}
public PositionModule (Bot bot) {
this.bot = bot;
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();
bot.listenerManager.addListener(this);
}
}
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 final List<String> chatTypes = new ArrayList<>();
public class RegistryModule implements Listener {
public final List<String> chatTypes = new ArrayList<>();
public final List<DimensionData> dimensions = new ArrayList<>();
private Bot bot;
@Override
public void packetReceived (Session session, Packet packet) {
if (packet instanceof ClientboundRegistryDataPacket) packetReceived((ClientboundRegistryDataPacket) packet);
}
public void packetReceived (ClientboundRegistryDataPacket packet) {
String getRegistry = packet.getRegistry().asString();
for (RegistryEntry entry : packet.getEntries()) {
if (getRegistry.equals("minecraft:chat_type"))
chatTypes.add(entry.getData().getCompound("chat").getString("translation_key"));
public RegistryModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
}
@Override
public void packetReceived (Packet packet) {
if (packet instanceof ClientboundRegistryDataPacket) packetReceived((ClientboundRegistryDataPacket) packet);
}
public RegistryModule (Bot bot) {
bot.listenerManager.addListener(this);
}
public void packetReceived (ClientboundRegistryDataPacket packet) {
String getRegistry = packet.getRegistry().asString();
for (RegistryEntry entry : packet.getEntries()) {
if (getRegistry.equals("minecraft:chat_type")) if (entry.getData() != null) {
chatTypes.add(entry.getData().getCompound("chat").getString("translation_key"));
}
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", ""))
));
}
}
}
}
}
@@ -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 ScheduledFuture<?> timer;
public class SelfcareModule implements Listener {
private final Bot bot;
public ScheduledFuture<?> timer;
public PermissionSelfcare permission;
private Bot bot;
public GamemodeSelfcare gamemode;
public PermissionSelfcare permission;
public int entityId;
public GamemodeSelfcare gamemode;
public SelfcareModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
loadSelfcare();
}
public int entityId;
public void loadSelfcare () {
this.permission = new PermissionSelfcare(bot);
this.gamemode = new GamemodeSelfcare(bot);
}
public void loadSelfcare () {
this.permission = new PermissionSelfcare(bot);
this.gamemode = new GamemodeSelfcare(bot);
}
@Override
public void packetReceived (Packet packet) {
switch (packet) {
case ClientboundLoginFinishedPacket p -> login(p);
case ClientboundDisconnectPacket p -> disconnect(p);
default -> {
}
}
}
@Override
public void packetReceived (Session session, Packet packet) {
if (packet instanceof ClientboundLoginFinishedPacket) login((ClientboundLoginFinishedPacket) packet);
}
public void login (ClientboundLoginFinishedPacket packet) {
if (bot.options.mode.equals("totalfreedom")) return;
timer = bot.executor.scheduleAtFixedRate(
() -> {
if (permission.level < 2 && bot.loggedIn) bot.chat.command("minecraft:op @s[type=player]");
else if (gamemode.gamemode != 1)
bot.session.send(new ServerboundChangeGameModePacket(GameMode.CREATIVE));
}, 0, bot.options.selfcareInterval, TimeUnit.MILLISECONDS
);
}
public void 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
)
);
}, 0, bot.options.selfcareInterval, TimeUnit.MILLISECONDS);
}
public void disconnect (DisconnectedEvent event) {
timer.cancel(true);
}
public SelfcareModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
loadSelfcare();
}
public void disconnect (ClientboundDisconnectPacket event) {
timer.cancel(true);
}
}
@@ -1,47 +1,31 @@
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;
public class TextDisplayModule implements Listener {
private static final int TEXT_DISPLAY_ENTITY_ID = 32;
import java.util.ArrayList;
import java.util.List;
public class TextDisplayModule extends Listener {
private Bot bot;
private static final int TEXT_DISPLAY_ENTITY_ID = 32;
private int entityId;
@Override
public void packetReceived (Session session, Packet packet) {
if (packet instanceof ClientboundSetEntityDataPacket) getTextDisplay((ClientboundSetEntityDataPacket) packet);
}
private void getTextDisplay (ClientboundSetEntityDataPacket packet) {
for (EntityMetadata<?, ?> metaData : packet.getMetadata()) {
if (metaData.getId() == TEXT_DISPLAY_ENTITY_ID) {
Component value = (Component) metaData.getValue();
System.out.println(ComponentUtil.componentToAnsi(value));
}
public TextDisplayModule (Bot bot) {
bot.listenerManager.addListener(this);
}
}
public TextDisplayModule (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
@Override
public void packetReceived (Packet packet) {
if (packet instanceof ClientboundSetEntityDataPacket) getTextDisplay((ClientboundSetEntityDataPacket) packet);
}
private void getTextDisplay (ClientboundSetEntityDataPacket packet) {
for (EntityMetadata<?, ?> metaData : packet.getMetadata()) {
if (metaData.getId() == TEXT_DISPLAY_ENTITY_ID) {
Component value = (Component) metaData.getValue();
System.out.println(ComponentUtil.componentToAnsi(value));
}
}
}
}
@@ -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,50 +1,45 @@
package land.chipmunk.parker2991.nitoribot.selfcare.entity;
import land.chipmunk.parker2991.nitoribot.Bot;
import land.chipmunk.parker2991.nitoribot.listeners.*;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.level.ClientboundGameEventPacket;
import land.chipmunk.parker2991.nitoribot.listeners.Listener;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.protocol.data.game.entity.player.GameMode;
import org.geysermc.mcprotocollib.protocol.data.game.level.notify.GameEvent;
import org.geysermc.mcprotocollib.protocol.data.game.level.notify.GameEventValue;
import org.geysermc.mcprotocollib.protocol.data.game.entity.player.GameMode;
import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.network.Session;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.level.ClientboundGameEventPacket;
public class GamemodeSelfcare extends Listener {
@org.jetbrains.annotations.NotNull
private final Bot bot;
public class GamemodeSelfcare implements Listener {
public int gamemode = 1;
@Override
public void packetReceived (Session session, Packet packet) {
if (packet instanceof ClientboundGameEventPacket) checkGamemode((ClientboundGameEventPacket) packet);
}
private void checkGamemode (ClientboundGameEventPacket packet) {
GameEvent notification = packet.getNotification();
GameEventValue value = packet.getValue();
if (notification == GameEvent.CHANGE_GAME_MODE) {
switch (value) {
case GameMode.SURVIVAL:
gamemode = 0;
break;
case GameMode.CREATIVE:
gamemode = 1;
break;
case GameMode.ADVENTURE:
gamemode = 2;
break;
case GameMode.SPECTATOR:
gamemode = 3;
break;
default:
}
public GamemodeSelfcare (Bot bot) {
bot.listenerManager.addListener(this);
}
}
public GamemodeSelfcare (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
@Override
public void packetReceived (Packet packet) {
if (packet instanceof ClientboundGameEventPacket) checkGamemode((ClientboundGameEventPacket) packet);
}
private void checkGamemode (ClientboundGameEventPacket packet) {
GameEvent notification = packet.getNotification();
GameEventValue value = packet.getValue();
if (notification == GameEvent.CHANGE_GAME_MODE) {
switch (value) {
case GameMode.SURVIVAL:
gamemode = 0;
break;
case GameMode.CREATIVE:
gamemode = 1;
break;
case GameMode.ADVENTURE:
gamemode = 2;
break;
case GameMode.SPECTATOR:
gamemode = 3;
break;
default:
}
}
}
}
@@ -1,45 +1,39 @@
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 implements Listener {
private final Bot bot;
public int level;
public class PermissionSelfcare extends Listener {
public int level;
private Bot bot;
@Override
public void packetReceived (Session session, Packet packet) {
if (packet instanceof ClientboundEntityEventPacket) getPermissionLevel((ClientboundEntityEventPacket) packet);
}
private void getPermissionLevel (ClientboundEntityEventPacket packet) {
int permEntityId = packet.getEntityId();
final int botEntityId = bot.entityId;
EntityEvent event = packet.getEvent();
if (permEntityId == botEntityId) {
switch (event) {
case EntityEvent.PLAYER_SET_NO_PERMISSIONS -> level = 0;
case EntityEvent.PLAYER_SET_MODERATOR -> level = 1;
case EntityEvent.PLAYER_SET_GAMEMASTER -> level = 2;
case EntityEvent.PLAYER_SET_ADMIN -> level = 3;
case EntityEvent.PLAYER_SET_OWNER -> level = 4;
}
public PermissionSelfcare (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
};
public PermissionSelfcare (Bot bot) {
this.bot = bot;
bot.listenerManager.addListener(this);
}
@Override
public void packetReceived (Packet packet) {
if (packet instanceof ClientboundEntityEventPacket) getPermissionLevel((ClientboundEntityEventPacket) packet);
}
private void getPermissionLevel (ClientboundEntityEventPacket packet) {
int permEntityId = packet.getEntityId();
final int botEntityId = bot.entityId;
EntityEvent event = packet.getEvent();
if (permEntityId == botEntityId) {
switch (event) {
case EntityEvent.PLAYER_SET_NO_PERMISSIONS -> level = 0;
case EntityEvent.PLAYER_SET_MODERATOR -> level = 1;
case EntityEvent.PLAYER_SET_GAMEMASTER -> level = 2;
case EntityEvent.PLAYER_SET_ADMIN -> level = 3;
case EntityEvent.PLAYER_SET_OWNER -> level = 4;
}
}
}
}
@@ -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,8 +30,18 @@ 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 Map<String, String> loadJsonStringMap(String name) {
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<>();
var is = ClassLoader.getSystemClassLoader().getResourceAsStream(name);
@@ -47,51 +56,37 @@ public final class ComponentUtil {
return map;
}
private static final GsonComponentSerializer GSON_COMPONENT_SERIALIZER = GsonComponentSerializer.builder() // 1.21.5+ gson serializer
private static ComponentFlattener getFlattener (boolean parseSectionSigns) {
return ComponentFlattener.builder().mapper(
TextComponent.class,
component -> mapText(component, parseSectionSigns)
).mapper(ObjectComponent.class, ComponentUtil::mapObject).complexMapper(
KeybindComponent.class,
ComponentUtil::mapKeybind
).mapper(SelectorComponent.class, SelectorComponent::pattern).complexMapper(
TranslatableComponent.class,
ComponentUtil::mapTranslatable
).unknownMapper(_ -> "").nestingLimit(MAX_DEPTH) //max depth for nested mapper calls
.build();
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
.build();
}
private static String getOrReturnFallback(TranslatableComponent component) {
private static String getOrReturnFallback (TranslatableComponent component) {
var key = component.key();
var fallback = component.fallback();
return LANGUAGE.getOrDefault(
key,
fallback == null ? key : fallback
);
return LANGUAGE.getOrDefault(key, fallback == null ? key : fallback);
}
private static String guardedStringify(ComponentEncoder<Component, String> serializer, Component message) {
private static String guardedStringify (ComponentEncoder<Component, String> serializer, Component message) {
try {
return serializer.serialize(message);
} catch (Exception e) {
return serializer.serialize(Component.translatable(
"<Failed to parse component: %s>",
NamedTextColor.RED,
Component.text(e.toString())));
"<Failed to parse component: %s>",
NamedTextColor.RED,
Component.text(e.toString())
));
} finally {
TOTAL_DEPTH.set(0); //set translate depth to 0 after component is parsed
}
@@ -100,58 +95,53 @@ public final class ComponentUtil {
/**
* Convert Component to a JSON string
*/
public static String componentToJSON(Component component) {
public static String componentToJSON (Component component) {
return GSON_COMPONENT_SERIALIZER.serialize(component);
}
/**
* Convert JSON string to a Component
*/
public static Component componentFromJSON(String json) {
public static Component componentFromJSON (String json) {
return GSON_COMPONENT_SERIALIZER.deserialize(json);
}
/**
* Convert Component to a string
*/
public static String componentToString(Component component) {
public static String componentToString (Component component) {
return guardedStringify(PLAIN_TEXT_COMPONENT_SERIALIZER, component);
}
/**
* Convert Component to an ANSI string
*/
public static String componentToAnsi(Component component) {
public static String componentToAnsi (Component component) {
return guardedStringify(ANSI_COMPONENT_SERIALIZER, component);
}
private static String mapObject(ObjectComponent objectComponent) {
private static String mapObject (ObjectComponent objectComponent) {
var content = objectComponent.contents();
return switch (content) {
case SpriteObjectContents c -> "<Sprite:" + c.sprite() + ">";
case PlayerHeadObjectContents c ->
"<PlayerHead:" + componentToString(Component.translatable("block.minecraft.player_head.named").arguments(Component.text((c.name() != null) ? c.name() : "Unknown"))) + ">";
default -> "<Unknown Sprite>";
"<PlayerHead:" + componentToString(Component.translatable("block.minecraft.player_head.named").arguments(
Component.text((c.name() != null) ? Objects.requireNonNull(c.name()) : "Unknown"))) + ">";
};
}
private static String mapText(TextComponent component, boolean parseSectionSigns) {
private static String mapText (TextComponent component, boolean parseSectionSigns) {
var content = component.content();
//if no section sign is found, return the original content
if (!parseSectionSigns || !content.contains("§")) {
return component.content();
} else {
//TODO: make it parse section signs properly
return component.content();
}
return component.content();
}
private static void mapKeybind(KeybindComponent component, Consumer<Component> consumer) {
private static void mapKeybind (KeybindComponent component, Consumer<Component> consumer) {
consumer.accept(Component.translatable(KEYBINDINGS.getOrDefault(component.keybind(), component.keybind())));
}
private static void mapTranslatable(TranslatableComponent component, Consumer<Component> consumer) {
private static void mapTranslatable (TranslatableComponent component, Consumer<Component> consumer) {
var format = getOrReturnFallback(component);
var matcher = ARG_PATTERN.matcher(format);
List<Component> result = new ArrayList<>();
@@ -6,12 +6,12 @@ import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
public class ErrorToString {
public static String errorToString (Throwable error) {
final var byteArrayOut = new ByteArrayOutputStream();
final var outWriter = new OutputStreamWriter(byteArrayOut);
final var printWriter = new PrintWriter(outWriter);
error.printStackTrace(printWriter);
printWriter.flush();
return byteArrayOut.toString(StandardCharsets.UTF_8);
}
public static String errorToString (Throwable error) {
final var byteArrayOut = new ByteArrayOutputStream();
final var outWriter = new OutputStreamWriter(byteArrayOut);
final var printWriter = new PrintWriter(outWriter);
error.printStackTrace(printWriter);
printWriter.flush();
return byteArrayOut.toString(StandardCharsets.UTF_8);
}
}
@@ -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,37 +2,43 @@ package land.chipmunk.parker2991.nitoribot.util;
import org.cloudburstmc.nbt.NbtMap;
import org.cloudburstmc.nbt.NbtMapBuilder;
import java.util.UUID;
import java.nio.ByteBuffer;
import java.util.UUID;
public class UUIDUtil {
private UUIDUtil () {
}
private UUIDUtil () {
}
public static int[] intArray (UUID uuid) {
final ByteBuffer buffer = ByteBuffer.wrap(new byte[16]);
buffer.putLong(0, uuid.getMostSignificantBits());
buffer.putLong(8, uuid.getLeastSignificantBits());
public static int[] intArray (UUID uuid) {
final ByteBuffer buffer = ByteBuffer.wrap(new byte[16]);
buffer.putLong(0, uuid.getMostSignificantBits());
buffer.putLong(8, uuid.getLeastSignificantBits());
final int[] intArray = new int[4];
for (int i = 0; i < intArray.length; i++) intArray[i] = buffer.getInt();
final int[] intArray = new int[4];
for (int i = 0; i < intArray.length; i++) intArray[i] = buffer.getInt();
return intArray;
}
return intArray;
}
public static NbtMap tag (UUID uuid) {
final NbtMapBuilder builder = NbtMap.builder();
public static NbtMap tag (UUID uuid) {
final NbtMapBuilder builder = NbtMap.builder();
builder.putIntArray("", intArray(uuid));
builder.putIntArray("", intArray(uuid));
return builder.build();
}
return builder.build();
}
public static String snbt (UUID uuid) {
int[] array = intArray(uuid);
return "[I;" + array[0] + "," + array[1] + "," + array[2] + "," + array[3] + "]";
}
public static String snbt (UUID uuid) {
int[] array = intArray(uuid);
return "[I;" + array[0] + "," + array[1] + "," + array[2] + "," + array[3] + "]";
}
public static String selector (UUID uuid) { return "@p[nbt={UUID:" + snbt(uuid) + "}]"; }
public static String exclusiveSelector (UUID uuid) { return "@a[nbt=!{UUID:" + snbt(uuid) + "}]"; }
public static String selector (UUID uuid) {
return "@p[nbt={UUID:" + snbt(uuid) + "}]";
}
public static String exclusiveSelector (UUID uuid) {
return "@a[nbt=!{UUID:" + snbt(uuid) + "}]";
}
}
@@ -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
+70 -18
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"
}
]
}
}
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1 +1 @@
writer.level = error
writer.level=error
-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
}