From 0ee70b93b9579983c2e58732f61f22c5de48c20d Mon Sep 17 00:00:00 2001 From: ChomeNS <95471003+ChomeNS@users.noreply.github.com> Date: Wed, 5 Apr 2023 15:41:34 +0700 Subject: [PATCH] fix all problems about console and discord and logger and shits yes i fixed EVERY single problem (mabe) --- .../chipmunk/chayapak/chomens_bot/Bot.java | 57 +++++++++------- .../chipmunk/chayapak/chomens_bot/Main.java | 36 +++++----- .../chomens_bot/plugins/ConsolePlugin.java | 18 ++++- .../chomens_bot/plugins/DiscordPlugin.java | 67 +++++++------------ .../chomens_bot/plugins/LoggerPlugin.java | 9 ++- .../chomens_bot/plugins/TrustedPlugin.java | 2 + 6 files changed, 101 insertions(+), 88 deletions(-) diff --git a/src/main/java/land/chipmunk/chayapak/chomens_bot/Bot.java b/src/main/java/land/chipmunk/chayapak/chomens_bot/Bot.java index 4a5ff80f..5d99550c 100644 --- a/src/main/java/land/chipmunk/chayapak/chomens_bot/Bot.java +++ b/src/main/java/land/chipmunk/chayapak/chomens_bot/Bot.java @@ -32,29 +32,32 @@ public class Bot { @Getter public Session session; + @Getter private boolean loggedIn = false; + @Getter private ScheduledExecutorService executor = Executors.newScheduledThreadPool(100); @Getter @Setter private ConsolePlugin console; @Getter @Setter private LoggerPlugin logger; // in ConsolePlugin - @Getter @Setter private DiscordPlugin discord; - @Getter private final ChatPlugin chat; - @Getter private final SelfCarePlugin selfCare; - @Getter private final PositionPlugin position; - @Getter private final CorePlugin core; - @Getter private final PlayersPlugin players; - @Getter private final TabCompletePlugin tabComplete; - @Getter private final CommandHandlerPlugin commandHandler; - @Getter private final ChatCommandHandlerPlugin chatCommandHandler; - @Getter private final HashingPlugin hashing; - @Getter private final BossbarManagerPlugin bossbar; - @Getter private final MusicPlayerPlugin music; - @Getter private final TPSPlugin tps; - @Getter private final EvalRunnerPlugin eval; - @Getter private final ClearChatUsernamePlugin clearChatUsername; - @Getter private final TrustedPlugin trusted; - @Getter private final BruhifyPlugin bruhify; - @Getter private final GrepLogPlugin grepLog; - @Getter private final CloopPlugin cloop; + @Getter @Setter private DiscordPlugin discord; // same for this one too + + @Getter private ChatPlugin chat; + @Getter private SelfCarePlugin selfCare; + @Getter private PositionPlugin position; + @Getter private CorePlugin core; + @Getter private PlayersPlugin players; + @Getter private TabCompletePlugin tabComplete; + @Getter private CommandHandlerPlugin commandHandler; + @Getter private ChatCommandHandlerPlugin chatCommandHandler; + @Getter private HashingPlugin hashing; + @Getter private BossbarManagerPlugin bossbar; + @Getter private MusicPlayerPlugin music; + @Getter private TPSPlugin tps; + @Getter private EvalRunnerPlugin eval; + @Getter private ClearChatUsernamePlugin clearChatUsername; + @Getter private TrustedPlugin trusted; + @Getter private BruhifyPlugin bruhify; + @Getter private GrepLogPlugin grepLog; + @Getter private CloopPlugin cloop; public Bot (String host, int port, String _username, boolean kaboom, String serverName, List allBots, Configuration config) { this.host = host; @@ -65,12 +68,15 @@ public class Bot { this.allBots = allBots; this.config = config; - try { - DiscordPlugin.readyLatch().await(); - - // Thread.sleep(2000); // prob the worst way to fix this thing - } catch (InterruptedException ignored) { System.exit(1); } + ConsolePlugin.addListener(new ConsolePlugin.Listener() { + @Override + public void ready() { + Bot.this.ready(); + } + }); + } + public void ready () { this.chat = new ChatPlugin(this); this.selfCare = new SelfCarePlugin(this); this.position = new PositionPlugin(this); @@ -112,6 +118,7 @@ public class Bot { if (packet instanceof ClientboundLoginPacket) { for (SessionListener listener : listeners) { + loggedIn = true; listener.connected(new ConnectedEvent(session)); } } @@ -148,6 +155,8 @@ public class Bot { @Override public void disconnected(DisconnectedEvent disconnectedEvent) { + loggedIn = false; + final int reconnectDelay = config.reconnectDelay(); executor.schedule(() -> reconnect(), reconnectDelay, TimeUnit.MILLISECONDS); diff --git a/src/main/java/land/chipmunk/chayapak/chomens_bot/Main.java b/src/main/java/land/chipmunk/chayapak/chomens_bot/Main.java index c86dbe7a..e4af31b2 100644 --- a/src/main/java/land/chipmunk/chayapak/chomens_bot/Main.java +++ b/src/main/java/land/chipmunk/chayapak/chomens_bot/Main.java @@ -1,21 +1,20 @@ package land.chipmunk.chayapak.chomens_bot; import land.chipmunk.chayapak.chomens_bot.plugins.ConsolePlugin; -import land.chipmunk.chayapak.chomens_bot.plugins.DiscordPlugin; +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.JDABuilder; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; +import javax.security.auth.login.LoginException; import java.io.*; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.CountDownLatch; public class Main { public static final List allBots = new ArrayList<>(); - public static CountDownLatch latch = null; - - public static void main(String[] args) throws IOException, InterruptedException { + public static void main(String[] args) throws IOException { final File file = new File("config.yml"); final Constructor constructor = new Constructor(Configuration.class); final Yaml yaml = new Yaml(constructor); @@ -51,7 +50,19 @@ public class Main { Configuration.Bots[] botsOptions = config.bots(); - latch = new CountDownLatch(botsOptions.length); + // idk if these should be here lol, but it is just the discord stuff + JDA jda = null; + JDABuilder builder = JDABuilder.createDefault(config.discord().token()); + try { + jda = builder.build(); + jda.awaitReady(); + } catch (LoginException e) { + System.err.println("Failed to login to Discord, stacktrace:"); + e.printStackTrace(); + System.exit(1); + } catch (InterruptedException ignored) { + System.exit(1); + } for (Configuration.Bots botOption : botsOptions) { final String host = botOption.host(); @@ -60,17 +71,10 @@ public class Main { final boolean kaboom = botOption.kaboom(); final String serverName = botOption.serverName(); - new Thread(() -> { - final Bot bot = new Bot(host, port, username, kaboom, serverName, allBots, config); - allBots.add(bot); - - latch.countDown(); - }).start(); + final Bot bot = new Bot(host, port, username, kaboom, serverName, allBots, config); + allBots.add(bot); } - new DiscordPlugin(config); - - latch.await(); - new ConsolePlugin(allBots); + new ConsolePlugin(allBots, config, jda); } } \ No newline at end of file diff --git a/src/main/java/land/chipmunk/chayapak/chomens_bot/plugins/ConsolePlugin.java b/src/main/java/land/chipmunk/chayapak/chomens_bot/plugins/ConsolePlugin.java index 7c832c82..cd0c22a0 100644 --- a/src/main/java/land/chipmunk/chayapak/chomens_bot/plugins/ConsolePlugin.java +++ b/src/main/java/land/chipmunk/chayapak/chomens_bot/plugins/ConsolePlugin.java @@ -1,8 +1,10 @@ package land.chipmunk.chayapak.chomens_bot.plugins; +import land.chipmunk.chayapak.chomens_bot.Configuration; import lombok.Getter; import land.chipmunk.chayapak.chomens_bot.Bot; import land.chipmunk.chayapak.chomens_bot.command.ConsoleCommandContext; +import net.dv8tion.jda.api.JDA; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.format.NamedTextColor; @@ -10,6 +12,7 @@ import org.jline.reader.EndOfFileException; import org.jline.reader.LineReader; import org.jline.reader.LineReaderBuilder; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -23,7 +26,9 @@ public class ConsolePlugin { @Getter private String prefix; @Getter private String consoleServerPrefix; - public ConsolePlugin (List allBots) { + private static final List listeners = new ArrayList<>(); + + public ConsolePlugin (List allBots, Configuration discordConfig, JDA jda) { this.allBots = allBots; this.reader = LineReaderBuilder.builder().build(); @@ -32,9 +37,12 @@ public class ConsolePlugin { consoleServerPrefix = bot.config().consolePrefixes().get("consoleServerPrefix"); bot.console(this); + bot.logger(new LoggerPlugin(bot)); } + new DiscordPlugin(discordConfig, jda); + String prompt = "> "; new Thread(() -> { @@ -53,6 +61,8 @@ public class ConsolePlugin { handleLine(line); } }).start(); + + for (Listener listener : listeners) { listener.ready(); } } public void handleLine (String line) { @@ -104,4 +114,10 @@ public class ConsolePlugin { ); } } + + public static void addListener (Listener listener) { listeners.add(listener); } + + public static class Listener { + public void ready () {} + } } diff --git a/src/main/java/land/chipmunk/chayapak/chomens_bot/plugins/DiscordPlugin.java b/src/main/java/land/chipmunk/chayapak/chomens_bot/plugins/DiscordPlugin.java index 602948be..9ee877ed 100644 --- a/src/main/java/land/chipmunk/chayapak/chomens_bot/plugins/DiscordPlugin.java +++ b/src/main/java/land/chipmunk/chayapak/chomens_bot/plugins/DiscordPlugin.java @@ -1,10 +1,8 @@ package land.chipmunk.chayapak.chomens_bot.plugins; -import com.github.steveice10.mc.protocol.packet.ingame.clientbound.ClientboundLoginPacket; -import com.github.steveice10.packetlib.Session; +import com.github.steveice10.packetlib.event.session.ConnectedEvent; import com.github.steveice10.packetlib.event.session.DisconnectedEvent; import com.github.steveice10.packetlib.event.session.SessionAdapter; -import com.github.steveice10.packetlib.packet.Packet; import land.chipmunk.chayapak.chomens_bot.Bot; import land.chipmunk.chayapak.chomens_bot.Configuration; import land.chipmunk.chayapak.chomens_bot.Main; @@ -13,7 +11,6 @@ import land.chipmunk.chayapak.chomens_bot.util.ComponentUtilities; import land.chipmunk.chayapak.chomens_bot.util.EscapeCodeBlock; import lombok.Getter; import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; @@ -25,12 +22,11 @@ import net.kyori.adventure.text.event.HoverEvent; import net.kyori.adventure.text.format.NamedTextColor; import org.jetbrains.annotations.NotNull; -import javax.security.auth.login.LoginException; import java.util.HashMap; import java.util.Map; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +// please ignore my shitcode public class DiscordPlugin { @Getter private JDA jda; @@ -38,50 +34,43 @@ public class DiscordPlugin { public final String prefix; - @Getter private static CountDownLatch readyLatch = new CountDownLatch(1); - private final Map alreadyAddedListeners = new HashMap<>(); - public DiscordPlugin (Configuration config) { + public DiscordPlugin (Configuration config, JDA jda) { final Configuration.Discord options = config.discord(); this.prefix = options.prefix(); this.servers = options.servers(); - - JDABuilder builder = JDABuilder.createDefault(options.token()); - - new Thread(() -> { - try { - jda = builder.build(); - jda.awaitReady(); - } catch (LoginException e) { - System.err.println("Failed to login to Discord, stacktrace:"); - e.printStackTrace(); - System.exit(1); - } catch (InterruptedException ignored) { - System.exit(1); - } - - readyLatch.countDown(); - }).start(); - - try { - Main.latch.await(); - } catch (InterruptedException ignored) { System.exit(1); } + this.jda = jda; for (Bot bot : Main.allBots) { String channelId = servers.get(bot.host() + ":" + bot.port()); + System.out.println("bot for server " + bot.host() + ":" + bot.port()); + System.out.println("adding listeners..."); + bot.addListener(new SessionAdapter() { @Override - public void packetReceived (Session session, Packet packet) { - if (!(packet instanceof ClientboundLoginPacket)) return; - + public void connected (ConnectedEvent event) { boolean channelAlreadyAddedListeners = alreadyAddedListeners.getOrDefault(channelId, false); + System.out.println("connected, added listeners is " + channelAlreadyAddedListeners); + sendMessageInstantly("Successfully connected to: " + "`" + bot.host() + ":" + bot.port() + "`", channelId); + System.out.println("sent message..."); + if (channelAlreadyAddedListeners) return; + bot.executor().scheduleAtFixedRate(() -> onDiscordTick(channelId), 0, 50, TimeUnit.MILLISECONDS); + + bot.chat().addListener(new ChatPlugin.ChatListener() { + @Override + public void systemMessageReceived (String ignoredMessage, Component component) { + final String content = ComponentUtilities.stringifyAnsi(component); + sendMessage(EscapeCodeBlock.escape(content.replace("\u001b[9", "\u001b[3")), channelId); + } + }); + jda.addEventListener(new ListenerAdapter() { @Override public void onMessageReceived(@NotNull MessageReceivedEvent event) { @@ -141,7 +130,7 @@ public class DiscordPlugin { ) .color(NamedTextColor.RED); - final String discordUrl = "https://discord.gg/xdgCkUyaA4"; + final String discordUrl = "https://discord.gg/xdgCkUyaA4"; // too lazy to make a config final Component discordComponent = Component.empty() .append(Component.text("ChomeNS ").color(NamedTextColor.YELLOW)) @@ -168,17 +157,7 @@ public class DiscordPlugin { } }); - bot.chat().addListener(new ChatPlugin.ChatListener() { - @Override - public void systemMessageReceived (String ignoredMessage, Component component) { - final String content = ComponentUtilities.stringifyAnsi(component); - sendMessage(EscapeCodeBlock.escape(content.replace("\u001b[9", "\u001b[3")), channelId); - } - }); - alreadyAddedListeners.put(channelId, true); - - bot.executor().scheduleAtFixedRate(() -> onDiscordTick(channelId), 0, 50, TimeUnit.MILLISECONDS); } @Override diff --git a/src/main/java/land/chipmunk/chayapak/chomens_bot/plugins/LoggerPlugin.java b/src/main/java/land/chipmunk/chayapak/chomens_bot/plugins/LoggerPlugin.java index b3b1f947..25ee2220 100644 --- a/src/main/java/land/chipmunk/chayapak/chomens_bot/plugins/LoggerPlugin.java +++ b/src/main/java/land/chipmunk/chayapak/chomens_bot/plugins/LoggerPlugin.java @@ -11,6 +11,8 @@ import net.kyori.adventure.text.Component; public class LoggerPlugin extends ChatPlugin.ChatListener { private final Bot bot; + private boolean addedListener = false; + public LoggerPlugin(Bot bot) { this.bot = bot; @@ -18,16 +20,17 @@ public class LoggerPlugin extends ChatPlugin.ChatListener { @Override public void connected (ConnectedEvent event) { log("Successfully connected to: " + bot.host() + ":" + bot.port()); + + if (addedListener) return; + bot.chat().addListener(LoggerPlugin.this); + addedListener = true; } @Override public void disconnected (DisconnectedEvent event) { log("Disconnected from " + bot.host() + ":" + bot.port() + ", reason: " + event.getReason()); - event.getCause().printStackTrace(); } }); - - bot.chat().addListener(this); } public void log (String message) { diff --git a/src/main/java/land/chipmunk/chayapak/chomens_bot/plugins/TrustedPlugin.java b/src/main/java/land/chipmunk/chayapak/chomens_bot/plugins/TrustedPlugin.java index ecc80a3c..43b9b4e1 100644 --- a/src/main/java/land/chipmunk/chayapak/chomens_bot/plugins/TrustedPlugin.java +++ b/src/main/java/land/chipmunk/chayapak/chomens_bot/plugins/TrustedPlugin.java @@ -23,6 +23,8 @@ public class TrustedPlugin extends PlayersPlugin.PlayerListener { public void broadcast (Component message) { for (Bot allBot : bot.allBots()) { + if (!allBot.loggedIn()) continue; + for (String player : trusted) { final Component component = Component.translatable( "[%s] [%s] %s",