From 6e9e344987ae29d0e998269b8e4e7063de54508c Mon Sep 17 00:00:00 2001 From: HypherionMC Date: Sun, 11 Jun 2023 18:03:54 +0200 Subject: [PATCH] CraterLib integration and final code to reach feature parity with V2 --- build.gradle | 9 +- gradle.properties | 3 +- .../sdlink/core/accounts/DiscordAuthor.java | 7 +- .../core/accounts/MinecraftAccount.java | 14 +-- .../sdlink/core/config/ConfigController.java | 59 +++++------- .../sdlink/core/config/SDLinkConfig.java | 95 ++++++++++++++++++- .../core/config/impl/ChatSettingsConfig.java | 2 +- .../config/impl/GeneralConfigSettings.java | 4 +- .../config/impl/LinkedCommandsConfig.java | 4 +- .../config/impl/MessageChannelConfig.java | 2 +- .../sdlink/core/discord/BotController.java | 20 ++-- .../core/discord/commands/CommandManager.java | 18 ++-- .../commands/slash/LINKEDSLASHCOMMANDS | 1 - .../slash/linking/LinkAccountCommand.java | 2 +- .../commands/slash/mc/MCSlashCommand.java | 90 ++++++++++++++++++ .../UnWhitelistAccountSlashCommand.java | 2 +- .../whitelist/WhitelistAccountCommand.java | 6 +- .../discord/events/DiscordEventHandler.java | 3 + .../core/discord/hooks/BotReadyHooks.java | 23 +++-- .../discord/hooks/DiscordMessageHooks.java | 9 +- .../sdlink/core/events/SDLinkReadyEvent.java | 14 +++ .../sdlink/core/managers/ChannelManager.java | 9 +- .../core/managers/PermissionChecker.java | 11 +-- .../sdlink/core/managers/RoleManager.java | 19 ++-- .../sdlink/core/managers/WebhookManager.java | 19 ++-- .../messaging/discord/DiscordMessage.java | 43 +++++---- .../sdlink/core/util/LogReader.java | 7 +- 27 files changed, 340 insertions(+), 155 deletions(-) delete mode 100644 src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/LINKEDSLASHCOMMANDS create mode 100644 src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/mc/MCSlashCommand.java create mode 100644 src/main/java/com/hypherionmc/sdlink/core/events/SDLinkReadyEvent.java diff --git a/build.gradle b/build.gradle index f0971e5..32f661d 100644 --- a/build.gradle +++ b/build.gradle @@ -44,9 +44,10 @@ dependencies { shaded("io.jsondb:jsondb-core:${json_db}") // Config - shaded("me.hypherionmc.moon-config:core:${moonconfig}") - shaded("me.hypherionmc.moon-config:toml:${moonconfig}") - + implementation("me.hypherionmc.moon-config:core:${moonconfig}") + implementation("me.hypherionmc.moon-config:toml:${moonconfig}") + implementation "me.hypherionmc.craterlib:CraterLib-modules:${craterlib}:config" + implementation "me.hypherionmc.craterlib:CraterLib-modules:${craterlib}:events" // Compile Only, Not Shaded @@ -88,7 +89,7 @@ shadowJar { relocate 'com.iwebpp', shade_group + 'iwebpp' relocate 'com.jagrosh', shade_group + 'jagrosh' relocate 'com.neovisionaries', shade_group + 'neovisionaries' - relocate 'me.hypherionmc.moonconfig', shade_group + 'moonconfig' + relocate 'me.hypherionmc.moonconfig', 'shadow.hypherionmc.moonconfig' relocate 'me.hypherionmc.jqlite', shade_group + 'jqlite' relocate 'net.dv8tion', shade_group + 'dv8tion' relocate 'okhttp3', shade_group + 'okhttp3' diff --git a/gradle.properties b/gradle.properties index d4555da..45b62f0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,6 +1,6 @@ version_major=0 version_minor=0 -version_patch=2 +version_patch=1 shade_group=com.hypherionmc.sdlink.shaded. @@ -19,3 +19,4 @@ log4j=2.17.2 commons=3.12.0 commonsio=2.11.0 gson=2.10.1 +craterlib=1.0.0 \ No newline at end of file diff --git a/src/main/java/com/hypherionmc/sdlink/core/accounts/DiscordAuthor.java b/src/main/java/com/hypherionmc/sdlink/core/accounts/DiscordAuthor.java index 23acaa9..c25fba9 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/accounts/DiscordAuthor.java +++ b/src/main/java/com/hypherionmc/sdlink/core/accounts/DiscordAuthor.java @@ -4,10 +4,9 @@ */ package com.hypherionmc.sdlink.core.accounts; +import com.hypherionmc.sdlink.core.config.SDLinkConfig; import com.hypherionmc.sdlink.core.services.SDLinkPlatform; -import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig; - /** * @author HypherionSA * Represents a Message Author for messages sent from Minecraft to Discord @@ -15,7 +14,7 @@ import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig; public class DiscordAuthor { // User used for Server Messages - public static final DiscordAuthor SERVER = new DiscordAuthor(sdLinkConfig.channelsAndWebhooks.serverName, sdLinkConfig.channelsAndWebhooks.serverAvatar, true); + public static final DiscordAuthor SERVER = new DiscordAuthor(SDLinkConfig.INSTANCE.channelsAndWebhooks.serverName, SDLinkConfig.INSTANCE.channelsAndWebhooks.serverAvatar, true); private final String username; private final String avatar; @@ -42,7 +41,7 @@ public class DiscordAuthor { public static DiscordAuthor of(String username, String uuid) { return new DiscordAuthor( username, - SDLinkPlatform.minecraftHelper.isOnlineMode() ? sdLinkConfig.chatConfig.playerAvatarType.resolve(uuid) : username, + SDLinkConfig.INSTANCE.chatConfig.playerAvatarType.resolve(SDLinkPlatform.minecraftHelper.isOnlineMode() ? uuid : username), false ); } diff --git a/src/main/java/com/hypherionmc/sdlink/core/accounts/MinecraftAccount.java b/src/main/java/com/hypherionmc/sdlink/core/accounts/MinecraftAccount.java index 205f9cc..4f2484e 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/accounts/MinecraftAccount.java +++ b/src/main/java/com/hypherionmc/sdlink/core/accounts/MinecraftAccount.java @@ -4,6 +4,7 @@ */ package com.hypherionmc.sdlink.core.accounts; +import com.hypherionmc.sdlink.core.config.SDLinkConfig; import com.hypherionmc.sdlink.core.database.SDLinkAccount; import com.hypherionmc.sdlink.core.discord.BotController; import com.hypherionmc.sdlink.core.managers.RoleManager; @@ -27,7 +28,6 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; -import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig; import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase; /** @@ -116,6 +116,7 @@ public class MinecraftAccount { SDLinkAccount account = getStoredAccount(); account.setDiscordID(member.getId()); + account.setAddedBy(member.getId()); account.setAccountLinkCode(""); try { @@ -138,7 +139,7 @@ public class MinecraftAccount { guild.addRoleToMember(UserSnowflake.fromId(member.getId()), RoleManager.getLinkedRole()).queue(); } } catch (Exception e) { - if (sdLinkConfig.generalConfig.debugging) { + if (SDLinkConfig.INSTANCE.generalConfig.debugging) { e.printStackTrace(); } } @@ -194,7 +195,7 @@ public class MinecraftAccount { } SDLinkAccount account = getStoredAccount(); - account.setDiscordID(member.getId()); + account.setAddedBy(member.getId()); account.setWhitelistCode(""); try { @@ -203,7 +204,7 @@ public class MinecraftAccount { sdlinkDatabase.upsert(account); // Auto Linking is enabled, so we link the Discord and MC accounts - if (sdLinkConfig.whitelistingAndLinking.whitelisting.linkedWhitelist) { + if (SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.linkedWhitelist) { this.linkAccount(member, guild); } } @@ -230,10 +231,11 @@ public class MinecraftAccount { if (whitelistResult.isError()) { return whitelistResult; } else { - sdlinkDatabase.remove(account, SDLinkAccount.class); + account.setWhitelisted(false); + sdlinkDatabase.upsert(account); // Auto Linking is enabled. So we unlink the account - if (sdLinkConfig.whitelistingAndLinking.whitelisting.linkedWhitelist) { + if (SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.linkedWhitelist) { this.unlinkAccount(); } diff --git a/src/main/java/com/hypherionmc/sdlink/core/config/ConfigController.java b/src/main/java/com/hypherionmc/sdlink/core/config/ConfigController.java index 2b98a1e..3585b11 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/config/ConfigController.java +++ b/src/main/java/com/hypherionmc/sdlink/core/config/ConfigController.java @@ -4,41 +4,27 @@ */ package com.hypherionmc.sdlink.core.config; -import me.hypherionmc.moonconfig.core.CommentedConfig; -import me.hypherionmc.moonconfig.core.Config; -import me.hypherionmc.moonconfig.core.conversion.ObjectConverter; -import me.hypherionmc.moonconfig.core.file.CommentedFileConfig; -import com.hypherionmc.sdlink.core.util.EncryptionUtil; - -import java.io.File; - /** * @author HypherionSA * Main Config class for Loading, Saving and Upgrading configs */ -public class ConfigController { +/*@NoConfigScreen +public class ConfigController extends ModuleConfig { // Private internal variables - private final File configFile; - public static int configVer = 1; + public static transient int configVer = 1; // Instance of the currently loaded config - public static SDLinkConfig sdLinkConfig; + public static transient SDLinkConfig sdLinkConfig; public ConfigController() { - File path = new File("config/"); - if (!path.exists()) - path.mkdirs(); - - this.configFile = new File(path.getAbsolutePath() + File.separator + "simple-discord-link.toml"); + super("sdlink", "simple-discord-link"); initConfig(); } - /** - * Set up the Config File as needed. - * This will either Create, Upgrade or load an existing config file - */ - private void initConfig() { + + @Override + public void registerAndSetup(ModuleConfig conf) { Config.setInsertionOrderPreserved(true); if (!configFile.exists() || configFile.length() < 10) { SDLinkConfig config = new SDLinkConfig(); @@ -49,11 +35,19 @@ public class ConfigController { performEncryption(); } loadConfig(); + + if (this.getConfigPath().exists() && this.getConfigPath().length() >= 2L) { + this.migrateConfig(conf); + } else { + saveConfig(new SDLinkConfig()); + performEncryption(); + } + + com.hypherionmc.craterlib.core.config.ConfigController.register_config(this); + this.configReloaded(); } - /** - * Serialize an existing config file into an instance of {@link SDLinkConfig} - */ + private void loadConfig() { ObjectConverter converter = new ObjectConverter(); CommentedFileConfig config = CommentedFileConfig.builder(configFile).build(); @@ -62,10 +56,7 @@ public class ConfigController { config.close(); } - /** - * Serialize an instance of {@link SDLinkConfig} to the config file - * @param conf An instance of the config to save - */ + public void saveConfig(Object conf) { ObjectConverter converter = new ObjectConverter(); CommentedFileConfig config = CommentedFileConfig.builder(configFile).build(); @@ -75,9 +66,7 @@ public class ConfigController { config.close(); } - /** - * Handle config structure changes between version changes - */ + private void configUpgrade() { CommentedFileConfig oldConfig = CommentedFileConfig.builder(configFile).build(); CommentedFileConfig newConfig = CommentedFileConfig.builder(configFile).build(); @@ -116,9 +105,7 @@ public class ConfigController { oldConfig.close(); } - /** - * Apply encryption to Bot-Token and Webhook URLS - */ + private void performEncryption() { CommentedFileConfig oldConfig = CommentedFileConfig.builder(configFile).build(); oldConfig.load(); @@ -151,4 +138,4 @@ public class ConfigController { oldConfig.save(); oldConfig.close(); } -} +}*/ diff --git a/src/main/java/com/hypherionmc/sdlink/core/config/SDLinkConfig.java b/src/main/java/com/hypherionmc/sdlink/core/config/SDLinkConfig.java index 57331a1..0631f6c 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/config/SDLinkConfig.java +++ b/src/main/java/com/hypherionmc/sdlink/core/config/SDLinkConfig.java @@ -4,15 +4,27 @@ */ package com.hypherionmc.sdlink.core.config; +import com.hypherionmc.craterlib.core.config.ConfigController; +import com.hypherionmc.craterlib.core.config.ModuleConfig; +import com.hypherionmc.craterlib.core.config.annotations.NoConfigScreen; +import com.hypherionmc.sdlink.core.config.impl.*; +import com.hypherionmc.sdlink.core.util.EncryptionUtil; +import me.hypherionmc.moonconfig.core.conversion.ObjectConverter; import me.hypherionmc.moonconfig.core.conversion.Path; import me.hypherionmc.moonconfig.core.conversion.SpecComment; -import com.hypherionmc.sdlink.core.config.impl.*; +import me.hypherionmc.moonconfig.core.file.CommentedFileConfig; /** * @author HypherionSA * The main mod config Structure */ -public class SDLinkConfig { +@NoConfigScreen +public class SDLinkConfig extends ModuleConfig { + + // DO NOT REMOVE TRANSIENT HERE... OTHERWISE, THE STUPID CONFIG LIBRARY + // WILL TRY TO WRITE THESE TO THE CONFIG + public transient static SDLinkConfig INSTANCE; + public transient static int configVer = 1; @Path("general") @SpecComment("General Mod Config") @@ -49,4 +61,83 @@ public class SDLinkConfig { @Path("linkedCommands") @SpecComment("Execute Minecraft commands in Discord") public LinkedCommandsConfig linkedCommands = new LinkedCommandsConfig(); + + public SDLinkConfig() { + super("sdlink", "simple-discord-link"); + registerAndSetup(this); + } + + @Override + public void registerAndSetup(ModuleConfig config) { + if (this.getConfigPath().exists() && this.getConfigPath().length() >= 2L) { + this.migrateConfig(config); + } else { + this.saveConfig(config); + } + + performEncryption(); + ConfigController.register_config(this); + this.configReloaded(); + } + + @Override + public void migrateConfig(ModuleConfig conf) { + CommentedFileConfig config = CommentedFileConfig.builder(getConfigPath()).build(); + CommentedFileConfig newConfig = CommentedFileConfig.builder(getConfigPath()).build(); + config.load(); + + if (config.getInt("general.configVersion") == configVer) { + newConfig.close(); + config.close(); + return; + } + + new ObjectConverter().toConfig(conf, newConfig); + this.updateConfigValues(config, newConfig, newConfig, ""); + newConfig.save(); + + newConfig.close(); + config.close(); + } + + @Override + public void configReloaded() { + INSTANCE = loadConfig(this); + } + + /** + * Apply encryption to Bot-Token and Webhook URLS + */ + private void performEncryption() { + CommentedFileConfig oldConfig = CommentedFileConfig.builder(this.getConfigPath()).build(); + oldConfig.load(); + + String botToken = oldConfig.getOrElse("botConfig.botToken", ""); + String chatWebhook = oldConfig.getOrElse("channelsAndWebhooks.webhooks.chatWebhook", ""); + String eventsWebhook = oldConfig.getOrElse("channelsAndWebhooks.webhooks.eventsWebhook", ""); + String consoleWebhook = oldConfig.getOrElse("channelsAndWebhooks.webhooks.consoleWebhook", ""); + + if (!botToken.isEmpty()) { + botToken = EncryptionUtil.INSTANCE.encrypt(botToken); + oldConfig.set("botConfig.botToken", botToken); + } + + if (!chatWebhook.isEmpty()) { + chatWebhook = EncryptionUtil.INSTANCE.encrypt(chatWebhook); + oldConfig.set("channelsAndWebhooks.webhooks.chatWebhook", chatWebhook); + } + + if (!eventsWebhook.isEmpty()) { + eventsWebhook = EncryptionUtil.INSTANCE.encrypt(eventsWebhook); + oldConfig.set("channelsAndWebhooks.webhooks.eventsWebhook", eventsWebhook); + } + + if (!consoleWebhook.isEmpty()) { + consoleWebhook = EncryptionUtil.INSTANCE.encrypt(consoleWebhook); + oldConfig.set("channelsAndWebhooks.webhooks.consoleWebhook", consoleWebhook); + } + + oldConfig.save(); + oldConfig.close(); + } } diff --git a/src/main/java/com/hypherionmc/sdlink/core/config/impl/ChatSettingsConfig.java b/src/main/java/com/hypherionmc/sdlink/core/config/impl/ChatSettingsConfig.java index 069424c..8ffb97d 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/config/impl/ChatSettingsConfig.java +++ b/src/main/java/com/hypherionmc/sdlink/core/config/impl/ChatSettingsConfig.java @@ -4,9 +4,9 @@ */ package com.hypherionmc.sdlink.core.config.impl; +import com.hypherionmc.sdlink.core.config.AvatarType; import me.hypherionmc.moonconfig.core.conversion.Path; import me.hypherionmc.moonconfig.core.conversion.SpecComment; -import com.hypherionmc.sdlink.core.config.AvatarType; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/com/hypherionmc/sdlink/core/config/impl/GeneralConfigSettings.java b/src/main/java/com/hypherionmc/sdlink/core/config/impl/GeneralConfigSettings.java index 56b925a..fff5a3d 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/config/impl/GeneralConfigSettings.java +++ b/src/main/java/com/hypherionmc/sdlink/core/config/impl/GeneralConfigSettings.java @@ -4,9 +4,9 @@ */ package com.hypherionmc.sdlink.core.config.impl; +import com.hypherionmc.sdlink.core.config.SDLinkConfig; import me.hypherionmc.moonconfig.core.conversion.Path; import me.hypherionmc.moonconfig.core.conversion.SpecComment; -import com.hypherionmc.sdlink.core.config.ConfigController; /** * @author HypherionSA @@ -24,5 +24,5 @@ public class GeneralConfigSettings { @Path("configVersion") @SpecComment("Internal version control. DO NOT TOUCH!") - public int configVersion = ConfigController.configVer; + public int configVersion = SDLinkConfig.configVer; } diff --git a/src/main/java/com/hypherionmc/sdlink/core/config/impl/LinkedCommandsConfig.java b/src/main/java/com/hypherionmc/sdlink/core/config/impl/LinkedCommandsConfig.java index 247f8df..e4ae3c7 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/config/impl/LinkedCommandsConfig.java +++ b/src/main/java/com/hypherionmc/sdlink/core/config/impl/LinkedCommandsConfig.java @@ -26,11 +26,11 @@ public class LinkedCommandsConfig { public static class Command { @Path("mcCommand") - @SpecComment("The Minecraft Command. Use %args% and %args(1-9)% (for example %args1%) to pass everything after the discordCommand to Minecraft") + @SpecComment("The Minecraft Command. Use %args% to pass everything after the discordCommand to Minecraft") public String mcCommand; @Path("discordCommand") - @SpecComment("The command slug in discord. To be used as /mc slug or ~mc slug") + @SpecComment("The command slug in discord. To be used as /mc slug") public String discordCommand; @Path("discordRole") diff --git a/src/main/java/com/hypherionmc/sdlink/core/config/impl/MessageChannelConfig.java b/src/main/java/com/hypherionmc/sdlink/core/config/impl/MessageChannelConfig.java index 782575c..4a8a0e4 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/config/impl/MessageChannelConfig.java +++ b/src/main/java/com/hypherionmc/sdlink/core/config/impl/MessageChannelConfig.java @@ -4,9 +4,9 @@ */ package com.hypherionmc.sdlink.core.config.impl; +import com.hypherionmc.sdlink.core.messaging.MessageDestination; import me.hypherionmc.moonconfig.core.conversion.Path; import me.hypherionmc.moonconfig.core.conversion.SpecComment; -import com.hypherionmc.sdlink.core.messaging.MessageDestination; /** * @author HypherionSA diff --git a/src/main/java/com/hypherionmc/sdlink/core/discord/BotController.java b/src/main/java/com/hypherionmc/sdlink/core/discord/BotController.java index d9ec790..45ba693 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/discord/BotController.java +++ b/src/main/java/com/hypherionmc/sdlink/core/discord/BotController.java @@ -4,7 +4,7 @@ */ package com.hypherionmc.sdlink.core.discord; -import com.hypherionmc.sdlink.core.config.ConfigController; +import com.hypherionmc.sdlink.core.config.SDLinkConfig; import com.hypherionmc.sdlink.core.discord.commands.CommandManager; import com.hypherionmc.sdlink.core.discord.events.DiscordEventHandler; import com.hypherionmc.sdlink.core.managers.DatabaseManager; @@ -26,8 +26,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig; - /** * @author HypherionSA * The main Discord Bot class. This controls everything surrounding the bot itself @@ -64,7 +62,7 @@ public class BotController { INSTANCE = this; this.logger = logger; - new ConfigController(); + new SDLinkConfig(); DatabaseManager.initialize(); @@ -76,21 +74,21 @@ public class BotController { * Start the bot and handle all the startup work */ public void initializeBot() { - if (sdLinkConfig == null) { + if (SDLinkConfig.INSTANCE == null) { logger.error("Failed to load config. Check your log for errors"); return; } - if (sdLinkConfig.botConfig.botToken.isEmpty()) { + if (SDLinkConfig.INSTANCE.botConfig.botToken.isEmpty()) { logger.error("Missing bot token. Mod will be disabled"); return; } - if (!sdLinkConfig.generalConfig.enabled) + if (!SDLinkConfig.INSTANCE.generalConfig.enabled) return; try { - String token = EncryptionUtil.INSTANCE.decrypt(sdLinkConfig.botConfig.botToken); + String token = EncryptionUtil.INSTANCE.decrypt(SDLinkConfig.INSTANCE.botConfig.botToken); _jda = JDABuilder.createLight( token, GatewayIntent.GUILD_MEMBERS, @@ -127,10 +125,10 @@ public class BotController { * Check if the bot is in a state to send messages to discord */ public boolean isBotReady() { - if (sdLinkConfig == null) + if (SDLinkConfig.INSTANCE == null) return false; - if (!sdLinkConfig.generalConfig.enabled) + if (!SDLinkConfig.INSTANCE.generalConfig.enabled) return false; if (_jda == null) @@ -173,7 +171,7 @@ public class BotController { * Ensure that whitelisting is set up properly, so the bot can use the feature */ public void checkWhiteListing() { - if (!sdLinkConfig.whitelistingAndLinking.whitelisting.whitelisting) + if (!SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.whitelisting) return; if (SDLinkPlatform.minecraftHelper.checkWhitelisting().isError()) { diff --git a/src/main/java/com/hypherionmc/sdlink/core/discord/commands/CommandManager.java b/src/main/java/com/hypherionmc/sdlink/core/discord/commands/CommandManager.java index 8accc06..12af504 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/discord/commands/CommandManager.java +++ b/src/main/java/com/hypherionmc/sdlink/core/discord/commands/CommandManager.java @@ -4,6 +4,7 @@ */ package com.hypherionmc.sdlink.core.discord.commands; +import com.hypherionmc.sdlink.core.config.SDLinkConfig; import com.hypherionmc.sdlink.core.discord.commands.slash.general.HelpSlashCommand; import com.hypherionmc.sdlink.core.discord.commands.slash.general.PlayerListSlashCommand; import com.hypherionmc.sdlink.core.discord.commands.slash.general.ServerStatusSlashCommand; @@ -11,6 +12,7 @@ import com.hypherionmc.sdlink.core.discord.commands.slash.linking.ConfirmAccount import com.hypherionmc.sdlink.core.discord.commands.slash.linking.LinkAccountCommand; import com.hypherionmc.sdlink.core.discord.commands.slash.linking.UnlinkAccountSlashCommand; import com.hypherionmc.sdlink.core.discord.commands.slash.linking.ViewLinkedAccountsCommand; +import com.hypherionmc.sdlink.core.discord.commands.slash.mc.MCSlashCommand; import com.hypherionmc.sdlink.core.discord.commands.slash.whitelist.ConfirmWhitelistSlashCommand; import com.hypherionmc.sdlink.core.discord.commands.slash.whitelist.UnWhitelistAccountSlashCommand; import com.hypherionmc.sdlink.core.discord.commands.slash.whitelist.ViewWhitelistedAccountsSlashCommand; @@ -21,8 +23,6 @@ import com.jagrosh.jdautilities.command.SlashCommand; import java.util.HashSet; import java.util.Set; -import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig; - /** * @author HypherionSA * Command Manager class to control how commands are registered to discord @@ -39,7 +39,7 @@ public class CommandManager { private void addCommands() { // Register Account Linking commands, if linking is enabled - if (sdLinkConfig.whitelistingAndLinking.accountLinking.accountLinking) { + if (SDLinkConfig.INSTANCE.whitelistingAndLinking.accountLinking.accountLinking) { commands.add(new LinkAccountCommand()); commands.add(new ConfirmAccountLinkSlashCommand()); commands.add(new UnlinkAccountSlashCommand()); @@ -47,7 +47,7 @@ public class CommandManager { } // Register Whitelist commands, if whitelisting is enabled - if (sdLinkConfig.whitelistingAndLinking.whitelisting.whitelisting) { + if (SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.whitelisting) { commands.add(new WhitelistAccountCommand()); commands.add(new ConfirmWhitelistSlashCommand()); commands.add(new ViewWhitelistedAccountsSlashCommand()); @@ -55,19 +55,23 @@ public class CommandManager { } // Enable the Server Status command - if (sdLinkConfig.botCommands.allowServerStatus) { + if (SDLinkConfig.INSTANCE.botCommands.allowServerStatus) { commands.add(new ServerStatusSlashCommand()); } // Enable the Player List command - if (sdLinkConfig.botCommands.allowPlayerList) { + if (SDLinkConfig.INSTANCE.botCommands.allowPlayerList) { commands.add(new PlayerListSlashCommand()); } // Enable the Help command - if (sdLinkConfig.botCommands.allowHelpCommand) { + if (SDLinkConfig.INSTANCE.botCommands.allowHelpCommand) { commands.add(new HelpSlashCommand()); } + + if (SDLinkConfig.INSTANCE.linkedCommands.enabled) { + commands.add(new MCSlashCommand()); + } } /** diff --git a/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/LINKEDSLASHCOMMANDS b/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/LINKEDSLASHCOMMANDS deleted file mode 100644 index 58063e3..0000000 --- a/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/LINKEDSLASHCOMMANDS +++ /dev/null @@ -1 +0,0 @@ -// TODO Don't Forget This \ No newline at end of file diff --git a/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/linking/LinkAccountCommand.java b/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/linking/LinkAccountCommand.java index 3ac916f..909fe62 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/linking/LinkAccountCommand.java +++ b/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/linking/LinkAccountCommand.java @@ -58,7 +58,7 @@ public class LinkAccountCommand extends SDLinkSlashCommand { event.reply("Could not start account linking process. Please notify the server owner").setEphemeral(true).queue(); } } else { - if (account.getDiscordID() != null || !account.getDiscordID().isEmpty()) { + if (account.getDiscordID() != null && !account.getDiscordID().isEmpty()) { event.reply("Sorry, this Minecraft account is already linked to a discord account").setEphemeral(true).queue(); return; } diff --git a/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/mc/MCSlashCommand.java b/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/mc/MCSlashCommand.java new file mode 100644 index 0000000..e164e72 --- /dev/null +++ b/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/mc/MCSlashCommand.java @@ -0,0 +1,90 @@ +package com.hypherionmc.sdlink.core.discord.commands.slash.mc; + +import com.hypherionmc.sdlink.core.config.SDLinkConfig; +import com.hypherionmc.sdlink.core.config.impl.LinkedCommandsConfig; +import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand; +import com.hypherionmc.sdlink.core.managers.RoleManager; +import com.hypherionmc.sdlink.core.messaging.Result; +import com.hypherionmc.sdlink.core.services.SDLinkPlatform; +import com.jagrosh.jdautilities.command.SlashCommandEvent; +import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.OptionData; + +import java.util.ArrayList; +import java.util.Optional; + +public class MCSlashCommand extends SDLinkSlashCommand { + + public MCSlashCommand() { + super(false); + this.name = "mc"; + this.help = "Execute Minecraft Command from Discord"; + + this.options = new ArrayList<>() {{ + add(new OptionData(OptionType.STRING, "slug", "The discordCommand slug defined in the config").setRequired(true)); + add(new OptionData(OptionType.STRING, "args0", "Additional arguments to pass to the %args% variable").setRequired(false)); + add(new OptionData(OptionType.STRING, "args1", "Additional arguments to pass to the %args% variable").setRequired(false)); + add(new OptionData(OptionType.STRING, "args2", "Additional arguments to pass to the %args% variable").setRequired(false)); + add(new OptionData(OptionType.STRING, "args3", "Additional arguments to pass to the %args% variable").setRequired(false)); + add(new OptionData(OptionType.STRING, "args4", "Additional arguments to pass to the %args% variable").setRequired(false)); + add(new OptionData(OptionType.STRING, "args5", "Additional arguments to pass to the %args% variable").setRequired(false)); + }}; + } + + @Override + protected void execute(SlashCommandEvent event) { + if (SDLinkConfig.INSTANCE.linkedCommands.enabled) { + String slug = event.getOption("slug") != null ? event.getOption("slug").getAsString() : ""; + String args0 = event.getOption("args0") != null ? event.getOption("args0").getAsString() : ""; + String args1 = event.getOption("args1") != null ? event.getOption("args1").getAsString() : ""; + String args2 = event.getOption("args2") != null ? event.getOption("args2").getAsString() : ""; + String args3 = event.getOption("args3") != null ? event.getOption("args3").getAsString() : ""; + String args4 = event.getOption("args4") != null ? event.getOption("args4").getAsString() : ""; + String args5 = event.getOption("args5") != null ? event.getOption("args5").getAsString() : ""; + + Optional linkedCommand = SDLinkConfig.INSTANCE.linkedCommands.commands.stream().filter(c -> c.discordCommand.equalsIgnoreCase(slug)).findFirst(); + + StringBuilder args = new StringBuilder(); + if (!args0.isEmpty()) + args.append(args0); + if (!args1.isEmpty()) + args.append(" ").append(args1); + if (!args2.isEmpty()) + args.append(" ").append(args2); + if (!args3.isEmpty()) + args.append(" ").append(args3); + if (!args4.isEmpty()) + args.append(" ").append(args4); + if (!args5.isEmpty()) + args.append(" ").append(args5); + + linkedCommand.ifPresent(command -> { + if (!command.discordRole.isEmpty()) { + Role role = RoleManager.getCommandRoles().isEmpty() ? null : RoleManager.getCommandRoles().get(command.discordCommand); + + boolean userRole = role != null && event.getMember().getRoles().stream().anyMatch(r -> r.getIdLong() == role.getIdLong()); + if (userRole) { + executeCommand(event, command, args.toString()); + } else { + event.reply("You need the " + role.getName() + " role to perform this action").setEphemeral(true).queue(); + } + } else { + executeCommand(event, command, args.toString()); + } + }); + + if (linkedCommand.isEmpty()) { + event.reply("Cannot find linked command " + slug).setEphemeral(true).queue(); + } + + } else { + event.reply("Linked commands are not enabled!").setEphemeral(true).queue(); + } + } + + private void executeCommand(SlashCommandEvent event, LinkedCommandsConfig.Command mcCommand, String args) { + Result result = SDLinkPlatform.minecraftHelper.executeMinecraftCommand(mcCommand.mcCommand, args); + event.reply(result.getMessage()).setEphemeral(true).queue(); + } +} diff --git a/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/whitelist/UnWhitelistAccountSlashCommand.java b/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/whitelist/UnWhitelistAccountSlashCommand.java index 6f80983..0139084 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/whitelist/UnWhitelistAccountSlashCommand.java +++ b/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/whitelist/UnWhitelistAccountSlashCommand.java @@ -37,7 +37,7 @@ public class UnWhitelistAccountSlashCommand extends SDLinkSlashCommand { } for (SDLinkAccount account : accounts) { - if (account.getDiscordID().equalsIgnoreCase(event.getMember().getId())) { + if (account.getAddedBy().equalsIgnoreCase(event.getMember().getId())) { MinecraftAccount minecraftAccount = MinecraftAccount.standard(account.getUsername()); if (SDLinkPlatform.minecraftHelper.isPlayerWhitelisted(minecraftAccount).isError()) { event.reply("Your account is not whitelisted in Minecraft. Cannot remove your account").setEphemeral(true).queue(); diff --git a/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/whitelist/WhitelistAccountCommand.java b/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/whitelist/WhitelistAccountCommand.java index d1c930f..6f5f3a0 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/whitelist/WhitelistAccountCommand.java +++ b/src/main/java/com/hypherionmc/sdlink/core/discord/commands/slash/whitelist/WhitelistAccountCommand.java @@ -5,6 +5,7 @@ package com.hypherionmc.sdlink.core.discord.commands.slash.whitelist; import com.hypherionmc.sdlink.core.accounts.MinecraftAccount; +import com.hypherionmc.sdlink.core.config.SDLinkConfig; import com.hypherionmc.sdlink.core.database.SDLinkAccount; import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand; import com.hypherionmc.sdlink.core.services.SDLinkPlatform; @@ -16,7 +17,6 @@ import net.dv8tion.jda.api.interactions.commands.build.OptionData; import java.util.Collections; -import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig; import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase; /** @@ -28,7 +28,7 @@ import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabas public class WhitelistAccountCommand extends SDLinkSlashCommand { public WhitelistAccountCommand() { - super(sdLinkConfig.whitelistingAndLinking.whitelisting.staffOnlyWhitelist); + super(SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.staffOnlyWhitelist); this.name = "whitelist"; this.help = "Start the process of Whitelisting your Minecraft Account"; @@ -61,7 +61,7 @@ public class WhitelistAccountCommand extends SDLinkSlashCommand { event.reply("Could not start account whitelisting process. Please notify the server owner").setEphemeral(true).queue(); } } else { - if (!account.getDiscordID().isEmpty() || SDLinkPlatform.minecraftHelper.isPlayerWhitelisted(minecraftAccount).isError()) { + if (account.isWhitelisted() || !SDLinkPlatform.minecraftHelper.isPlayerWhitelisted(minecraftAccount).isError()) { event.reply("Sorry, this Minecraft account is already whitelisted").setEphemeral(true).queue(); return; } diff --git a/src/main/java/com/hypherionmc/sdlink/core/discord/events/DiscordEventHandler.java b/src/main/java/com/hypherionmc/sdlink/core/discord/events/DiscordEventHandler.java index 9d58ffa..64d524d 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/discord/events/DiscordEventHandler.java +++ b/src/main/java/com/hypherionmc/sdlink/core/discord/events/DiscordEventHandler.java @@ -4,10 +4,12 @@ */ package com.hypherionmc.sdlink.core.discord.events; +import com.hypherionmc.craterlib.core.event.CraterEventBus; import com.hypherionmc.sdlink.core.discord.BotController; import com.hypherionmc.sdlink.core.discord.commands.slash.general.ServerStatusSlashCommand; import com.hypherionmc.sdlink.core.discord.hooks.BotReadyHooks; import com.hypherionmc.sdlink.core.discord.hooks.DiscordMessageHooks; +import com.hypherionmc.sdlink.core.events.SDLinkReadyEvent; import com.hypherionmc.sdlink.core.managers.ChannelManager; import com.hypherionmc.sdlink.core.managers.PermissionChecker; import net.dv8tion.jda.api.JDA; @@ -54,6 +56,7 @@ public class DiscordEventHandler extends ListenerAdapter { ChannelManager.loadChannels(); BotReadyHooks.startActivityUpdates(event); BotReadyHooks.startTopicUpdates(); + CraterEventBus.INSTANCE.postEvent(new SDLinkReadyEvent()); } } diff --git a/src/main/java/com/hypherionmc/sdlink/core/discord/hooks/BotReadyHooks.java b/src/main/java/com/hypherionmc/sdlink/core/discord/hooks/BotReadyHooks.java index 7316617..33436ed 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/discord/hooks/BotReadyHooks.java +++ b/src/main/java/com/hypherionmc/sdlink/core/discord/hooks/BotReadyHooks.java @@ -4,6 +4,7 @@ */ package com.hypherionmc.sdlink.core.discord.hooks; +import com.hypherionmc.sdlink.core.config.SDLinkConfig; import com.hypherionmc.sdlink.core.discord.BotController; import com.hypherionmc.sdlink.core.managers.ChannelManager; import com.hypherionmc.sdlink.core.messaging.MessageDestination; @@ -16,8 +17,6 @@ import net.dv8tion.jda.api.events.session.ReadyEvent; import java.util.concurrent.TimeUnit; -import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig; - /** * @author HypherionSA * Hooks to run when the bot is ready @@ -32,40 +31,40 @@ public class BotReadyHooks { BotController.taskManager.scheduleAtFixedRate(() -> { try { if (event.getJDA().getStatus() == JDA.Status.CONNECTED) { - Activity act = Activity.of(sdLinkConfig.botConfig.botStatus.botStatusType, sdLinkConfig.botConfig.botStatus.botStatus + Activity act = Activity.of(SDLinkConfig.INSTANCE.botConfig.botStatus.botStatusType, SDLinkConfig.INSTANCE.botConfig.botStatus.botStatus .replace("%players%", String.valueOf(SDLinkPlatform.minecraftHelper.getPlayerCounts().getLeft())) .replace("%maxplayers%", String.valueOf(SDLinkPlatform.minecraftHelper.getPlayerCounts().getRight()))); - if (sdLinkConfig.botConfig.botStatus.botStatusType == Activity.ActivityType.STREAMING) { - act = Activity.of(sdLinkConfig.botConfig.botStatus.botStatusType, sdLinkConfig.botConfig.botStatus.botStatus + if (SDLinkConfig.INSTANCE.botConfig.botStatus.botStatusType == Activity.ActivityType.STREAMING) { + act = Activity.of(SDLinkConfig.INSTANCE.botConfig.botStatus.botStatusType, SDLinkConfig.INSTANCE.botConfig.botStatus.botStatus .replace("%players%", String.valueOf(SDLinkPlatform.minecraftHelper.getPlayerCounts().getLeft())) .replace("%maxplayers%", String.valueOf(SDLinkPlatform.minecraftHelper.getPlayerCounts().getRight())), - sdLinkConfig.botConfig.botStatus.botStatusStreamingURL); + SDLinkConfig.INSTANCE.botConfig.botStatus.botStatusStreamingURL); } event.getJDA().getPresence().setActivity(act); } } catch (Exception e) { - if (sdLinkConfig.generalConfig.debugging) { + if (SDLinkConfig.INSTANCE.generalConfig.debugging) { BotController.INSTANCE.getLogger().info(e.getMessage()); } } - }, sdLinkConfig.botConfig.statusUpdateInterval, sdLinkConfig.botConfig.statusUpdateInterval, TimeUnit.SECONDS); + }, SDLinkConfig.INSTANCE.botConfig.statusUpdateInterval, SDLinkConfig.INSTANCE.botConfig.statusUpdateInterval, TimeUnit.SECONDS); } /** * Update the Chat Channel topic, if enabled */ public static void startTopicUpdates() { - if (!sdLinkConfig.botConfig.channelTopic.doTopicUpdates) + if (!SDLinkConfig.INSTANCE.botConfig.channelTopic.doTopicUpdates) return; BotController.taskManager.scheduleAtFixedRate(() -> { try { - if (BotController.INSTANCE.isBotReady() && (sdLinkConfig.botConfig.channelTopic.channelTopic != null && !sdLinkConfig.botConfig.channelTopic.channelTopic.isEmpty())) { + if (BotController.INSTANCE.isBotReady() && (SDLinkConfig.INSTANCE.botConfig.channelTopic.channelTopic != null && !SDLinkConfig.INSTANCE.botConfig.channelTopic.channelTopic.isEmpty())) { StandardGuildMessageChannel channel = ChannelManager.getDestinationChannel(MessageDestination.CHAT); if (channel != null) { - String topic = sdLinkConfig.botConfig.channelTopic.channelTopic + String topic = SDLinkConfig.INSTANCE.botConfig.channelTopic.channelTopic .replace("%players%", String.valueOf(SDLinkPlatform.minecraftHelper.getPlayerCounts().getLeft())) .replace("%maxplayers%", String.valueOf(SDLinkPlatform.minecraftHelper.getPlayerCounts().getRight())) .replace("%uptime%", SystemUtils.secondsToTimestamp(SDLinkPlatform.minecraftHelper.getServerUptime())); @@ -73,7 +72,7 @@ public class BotReadyHooks { } } } catch (Exception e) { - if (sdLinkConfig.generalConfig.debugging) { + if (SDLinkConfig.INSTANCE.generalConfig.debugging) { BotController.INSTANCE.getLogger().info(e.getMessage()); } } diff --git a/src/main/java/com/hypherionmc/sdlink/core/discord/hooks/DiscordMessageHooks.java b/src/main/java/com/hypherionmc/sdlink/core/discord/hooks/DiscordMessageHooks.java index ad42d09..6b72fbd 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/discord/hooks/DiscordMessageHooks.java +++ b/src/main/java/com/hypherionmc/sdlink/core/discord/hooks/DiscordMessageHooks.java @@ -4,14 +4,13 @@ */ package com.hypherionmc.sdlink.core.discord.hooks; +import com.hypherionmc.sdlink.core.config.SDLinkConfig; import com.hypherionmc.sdlink.core.discord.BotController; import com.hypherionmc.sdlink.core.managers.ChannelManager; import com.hypherionmc.sdlink.core.messaging.MessageDestination; import com.hypherionmc.sdlink.core.services.SDLinkPlatform; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig; - /** * @author HypherionSA * Hook class to handle messages the bot receives @@ -26,15 +25,15 @@ public class DiscordMessageHooks { if (event.getChannel().getIdLong() != ChannelManager.getDestinationChannel(MessageDestination.CHAT).getIdLong()) return; - if (event.getAuthor().isBot() && sdLinkConfig.chatConfig.ignoreBots) + if (event.getAuthor().isBot() && SDLinkConfig.INSTANCE.chatConfig.ignoreBots) return; - if (sdLinkConfig.generalConfig.debugging) { + if (SDLinkConfig.INSTANCE.generalConfig.debugging) { BotController.INSTANCE.getLogger().info("Sending Message from {}: {}", event.getAuthor().getName(), event.getMessage().getContentStripped()); } SDLinkPlatform.minecraftHelper.discordMessageReceived(event.getMember().getEffectiveName(), event.getMessage().getContentRaw()); } catch (Exception e) { - if (sdLinkConfig.generalConfig.debugging) { + if (SDLinkConfig.INSTANCE.generalConfig.debugging) { e.printStackTrace(); } } diff --git a/src/main/java/com/hypherionmc/sdlink/core/events/SDLinkReadyEvent.java b/src/main/java/com/hypherionmc/sdlink/core/events/SDLinkReadyEvent.java new file mode 100644 index 0000000..331f414 --- /dev/null +++ b/src/main/java/com/hypherionmc/sdlink/core/events/SDLinkReadyEvent.java @@ -0,0 +1,14 @@ +package com.hypherionmc.sdlink.core.events; + +import com.hypherionmc.craterlib.core.event.CraterEvent; + +public class SDLinkReadyEvent extends CraterEvent { + + public SDLinkReadyEvent() { + } + + @Override + public boolean canCancel() { + return false; + } +} diff --git a/src/main/java/com/hypherionmc/sdlink/core/managers/ChannelManager.java b/src/main/java/com/hypherionmc/sdlink/core/managers/ChannelManager.java index 4a84eec..8250aae 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/managers/ChannelManager.java +++ b/src/main/java/com/hypherionmc/sdlink/core/managers/ChannelManager.java @@ -4,6 +4,7 @@ */ package com.hypherionmc.sdlink.core.managers; +import com.hypherionmc.sdlink.core.config.SDLinkConfig; import com.hypherionmc.sdlink.core.discord.BotController; import com.hypherionmc.sdlink.core.messaging.MessageDestination; import net.dv8tion.jda.api.JDA; @@ -12,8 +13,6 @@ import org.apache.commons.lang3.tuple.Pair; import java.util.HashMap; -import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig; - /** * @author HypherionSA * Load and Cache configured channels for later use @@ -32,9 +31,9 @@ public class ChannelManager { JDA jda = BotController.INSTANCE.getJDA(); - StandardGuildMessageChannel chatChannel = jda.getChannelById(StandardGuildMessageChannel.class, sdLinkConfig.channelsAndWebhooks.channels.chatChannelID); - StandardGuildMessageChannel eventChannel = jda.getChannelById(StandardGuildMessageChannel.class, sdLinkConfig.channelsAndWebhooks.channels.eventsChannelID); - consoleChannel = jda.getChannelById(StandardGuildMessageChannel.class, sdLinkConfig.channelsAndWebhooks.channels.consoleChannelID); + StandardGuildMessageChannel chatChannel = jda.getChannelById(StandardGuildMessageChannel.class, SDLinkConfig.INSTANCE.channelsAndWebhooks.channels.chatChannelID); + StandardGuildMessageChannel eventChannel = jda.getChannelById(StandardGuildMessageChannel.class, SDLinkConfig.INSTANCE.channelsAndWebhooks.channels.eventsChannelID); + consoleChannel = jda.getChannelById(StandardGuildMessageChannel.class, SDLinkConfig.INSTANCE.channelsAndWebhooks.channels.consoleChannelID); if (chatChannel != null) { channelMap.put(MessageDestination.CHAT, Pair.of(chatChannel, false)); diff --git a/src/main/java/com/hypherionmc/sdlink/core/managers/PermissionChecker.java b/src/main/java/com/hypherionmc/sdlink/core/managers/PermissionChecker.java index c89d0b9..1c5d557 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/managers/PermissionChecker.java +++ b/src/main/java/com/hypherionmc/sdlink/core/managers/PermissionChecker.java @@ -4,6 +4,7 @@ */ package com.hypherionmc.sdlink.core.managers; +import com.hypherionmc.sdlink.core.config.SDLinkConfig; import com.hypherionmc.sdlink.core.discord.BotController; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Guild; @@ -15,8 +16,6 @@ import java.util.EnumSet; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig; - /** * @author HypherionSA * Startup permission checker hook to check if the bot has all the required permissions to function @@ -88,7 +87,7 @@ public class PermissionChecker { checkBotPerms(errCount, builder, botPerms); checkChannelPerms( - sdLinkConfig.channelsAndWebhooks.channels.chatChannelID, + SDLinkConfig.INSTANCE.channelsAndWebhooks.channels.chatChannelID, "Chat Channel", errCount, builder, @@ -98,7 +97,7 @@ public class PermissionChecker { ); checkChannelPerms( - sdLinkConfig.channelsAndWebhooks.channels.eventsChannelID, + SDLinkConfig.INSTANCE.channelsAndWebhooks.channels.eventsChannelID, "Events Channel", errCount, builder, @@ -108,7 +107,7 @@ public class PermissionChecker { ); checkChannelPerms( - sdLinkConfig.channelsAndWebhooks.channels.consoleChannelID, + SDLinkConfig.INSTANCE.channelsAndWebhooks.channels.consoleChannelID, "Console Channel", errCount, builder, @@ -177,7 +176,7 @@ public class PermissionChecker { }); if (isChat) { - if (sdLinkConfig.botConfig.channelTopic.doTopicUpdates && !chatPerms.contains(Permission.MANAGE_CHANNEL)) { + if (SDLinkConfig.INSTANCE.botConfig.channelTopic.doTopicUpdates && !chatPerms.contains(Permission.MANAGE_CHANNEL)) { errCount.incrementAndGet(); builder.append(errCount.get()).append(") ").append("Missing Chat Channel Permission: Manage Channel. Topic updates will not work").append("\r\n"); } diff --git a/src/main/java/com/hypherionmc/sdlink/core/managers/RoleManager.java b/src/main/java/com/hypherionmc/sdlink/core/managers/RoleManager.java index f5cd344..2936667 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/managers/RoleManager.java +++ b/src/main/java/com/hypherionmc/sdlink/core/managers/RoleManager.java @@ -4,6 +4,7 @@ */ package com.hypherionmc.sdlink.core.managers; +import com.hypherionmc.sdlink.core.config.SDLinkConfig; import com.hypherionmc.sdlink.core.discord.BotController; import net.dv8tion.jda.api.entities.Role; @@ -11,8 +12,6 @@ import java.util.HashMap; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig; - /** * @author HypherionSA * Load and Cache roles needed by the bot @@ -30,21 +29,21 @@ public class RoleManager { * @param builder */ public static void loadRequiredRoles(AtomicInteger errCount, StringBuilder builder) { - if (!sdLinkConfig.botConfig.staffRole.isEmpty()) { - staffRole = getRole(errCount, builder, "Staff", sdLinkConfig.botConfig.staffRole); + if (!SDLinkConfig.INSTANCE.botConfig.staffRole.isEmpty()) { + staffRole = getRole(errCount, builder, "Staff", SDLinkConfig.INSTANCE.botConfig.staffRole); } - if (!sdLinkConfig.whitelistingAndLinking.whitelisting.autoWhitelistRole.isEmpty()) { - whitelistedRole = getRole(errCount, builder, "Whitelist", sdLinkConfig.whitelistingAndLinking.whitelisting.autoWhitelistRole); + if (!SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.autoWhitelistRole.isEmpty()) { + whitelistedRole = getRole(errCount, builder, "Whitelist", SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.autoWhitelistRole); } - if (!sdLinkConfig.whitelistingAndLinking.accountLinking.linkedRole.isEmpty()) { - linkedRole = getRole(errCount, builder, "Linked Account", sdLinkConfig.whitelistingAndLinking.accountLinking.linkedRole); + if (!SDLinkConfig.INSTANCE.whitelistingAndLinking.accountLinking.linkedRole.isEmpty()) { + linkedRole = getRole(errCount, builder, "Linked Account", SDLinkConfig.INSTANCE.whitelistingAndLinking.accountLinking.linkedRole); } - if (sdLinkConfig.linkedCommands.enabled) { + if (SDLinkConfig.INSTANCE.linkedCommands.enabled) { commandRoles.clear(); - sdLinkConfig.linkedCommands.commands.forEach(cmd -> { + SDLinkConfig.INSTANCE.linkedCommands.commands.forEach(cmd -> { if (!cmd.discordRole.isEmpty()) { Role role = getRole(errCount, builder, cmd.discordCommand + " usage", cmd.discordRole); if (role != null) { diff --git a/src/main/java/com/hypherionmc/sdlink/core/managers/WebhookManager.java b/src/main/java/com/hypherionmc/sdlink/core/managers/WebhookManager.java index f4faa59..506726b 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/managers/WebhookManager.java +++ b/src/main/java/com/hypherionmc/sdlink/core/managers/WebhookManager.java @@ -5,6 +5,7 @@ package com.hypherionmc.sdlink.core.managers; import club.minnced.discord.webhook.WebhookClient; +import com.hypherionmc.sdlink.core.config.SDLinkConfig; import com.hypherionmc.sdlink.core.discord.BotController; import com.hypherionmc.sdlink.core.messaging.MessageDestination; import com.hypherionmc.sdlink.core.messaging.SDLinkWebhookClient; @@ -12,8 +13,6 @@ import com.hypherionmc.sdlink.core.util.EncryptionUtil; import java.util.HashMap; -import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig; - /** * @author HypherionSA * Load and cache Webhook clients for later use @@ -30,32 +29,32 @@ public class WebhookManager { public static void init() { clientMap.clear(); - if (sdLinkConfig == null || !sdLinkConfig.channelsAndWebhooks.webhooks.enabled) + if (SDLinkConfig.INSTANCE == null || !SDLinkConfig.INSTANCE.channelsAndWebhooks.webhooks.enabled) return; - if (!sdLinkConfig.generalConfig.enabled) + if (!SDLinkConfig.INSTANCE.generalConfig.enabled) return; - if (!sdLinkConfig.channelsAndWebhooks.webhooks.chatWebhook.isEmpty()) { + if (!SDLinkConfig.INSTANCE.channelsAndWebhooks.webhooks.chatWebhook.isEmpty()) { chatWebhookClient = new SDLinkWebhookClient( "Chat", - EncryptionUtil.INSTANCE.decrypt(sdLinkConfig.channelsAndWebhooks.webhooks.chatWebhook) + EncryptionUtil.INSTANCE.decrypt(SDLinkConfig.INSTANCE.channelsAndWebhooks.webhooks.chatWebhook) ).build(); BotController.INSTANCE.getLogger().info("Using Webhook for Chat Messages"); } - if (!sdLinkConfig.channelsAndWebhooks.webhooks.eventsWebhook.isEmpty()) { + if (!SDLinkConfig.INSTANCE.channelsAndWebhooks.webhooks.eventsWebhook.isEmpty()) { eventWebhookClient = new SDLinkWebhookClient( "Events", - EncryptionUtil.INSTANCE.decrypt(sdLinkConfig.channelsAndWebhooks.webhooks.eventsWebhook) + EncryptionUtil.INSTANCE.decrypt(SDLinkConfig.INSTANCE.channelsAndWebhooks.webhooks.eventsWebhook) ).build(); BotController.INSTANCE.getLogger().info("Using Webhook for Event Messages"); } - if (!sdLinkConfig.channelsAndWebhooks.webhooks.consoleWebhook.isEmpty()) { + if (!SDLinkConfig.INSTANCE.channelsAndWebhooks.webhooks.consoleWebhook.isEmpty()) { consoleWebhookClient = new SDLinkWebhookClient( "Console", - EncryptionUtil.INSTANCE.decrypt(sdLinkConfig.channelsAndWebhooks.webhooks.consoleWebhook) + EncryptionUtil.INSTANCE.decrypt(SDLinkConfig.INSTANCE.channelsAndWebhooks.webhooks.consoleWebhook) ).build(); BotController.INSTANCE.getLogger().info("Using Webhook for Console Messages"); } diff --git a/src/main/java/com/hypherionmc/sdlink/core/messaging/discord/DiscordMessage.java b/src/main/java/com/hypherionmc/sdlink/core/messaging/discord/DiscordMessage.java index 3f86d0e..aec2463 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/messaging/discord/DiscordMessage.java +++ b/src/main/java/com/hypherionmc/sdlink/core/messaging/discord/DiscordMessage.java @@ -9,6 +9,7 @@ import club.minnced.discord.webhook.send.WebhookEmbed; import club.minnced.discord.webhook.send.WebhookEmbedBuilder; import club.minnced.discord.webhook.send.WebhookMessageBuilder; import com.hypherionmc.sdlink.core.accounts.DiscordAuthor; +import com.hypherionmc.sdlink.core.config.SDLinkConfig; import com.hypherionmc.sdlink.core.config.impl.MessageChannelConfig; import com.hypherionmc.sdlink.core.discord.BotController; import com.hypherionmc.sdlink.core.managers.ChannelManager; @@ -18,8 +19,6 @@ import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.channel.middleman.StandardGuildMessageChannel; import org.apache.commons.lang3.tuple.Triple; -import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig; - /** * @author HypherionSA * Represents a message sent from Minecraft to Discord @@ -56,7 +55,7 @@ public final class DiscordMessage { sendNormalMessage(); } } catch (Exception e) { - if (sdLinkConfig.generalConfig.debugging) { + if (SDLinkConfig.INSTANCE.generalConfig.debugging) { BotController.INSTANCE.getLogger().error("Failed to send Discord Message", e); } } @@ -69,7 +68,7 @@ public final class DiscordMessage { Triple channel = resolveDestination(); // Check if a webhook is configured, and use that instead - if (channel.getMiddle() != null && sdLinkConfig.channelsAndWebhooks.webhooks.enabled) { + if (channel.getMiddle() != null && SDLinkConfig.INSTANCE.channelsAndWebhooks.webhooks.enabled) { WebhookMessageBuilder builder = new WebhookMessageBuilder(); builder.setUsername(this.author.getUsername()); if (!this.author.getAvatar().isEmpty()) { @@ -85,21 +84,26 @@ public final class DiscordMessage { builder.setContent(message); } - channel.getMiddle().send(builder.build()); + channel.getMiddle().send(builder.build()).thenRun(() -> { + if (afterSend != null) + afterSend.run(); + }); } else { // Use the configured channel instead if (channel.getRight()) { EmbedBuilder eb = buildEmbed(true); - channel.getLeft().sendMessageEmbeds(eb.build()).queue(); + channel.getLeft().sendMessageEmbeds(eb.build()).queue(success -> { + if (afterSend != null) + afterSend.run(); + }); } else { channel.getLeft().sendMessage( this.messageType == MessageType.CHAT ? - sdLinkConfig.messageFormatting.chat.replace("%player%", author.getUsername()).replace("%message%", message) + SDLinkConfig.INSTANCE.messageFormatting.chat.replace("%player%", author.getUsername()).replace("%message%", message) : message) .queue(success -> { - if (afterSend != null) { + if (afterSend != null) afterSend.run(); - } }); } } @@ -110,7 +114,7 @@ public final class DiscordMessage { */ private void sendConsoleMessage() { try { - if (!BotController.INSTANCE.isBotReady() || !sdLinkConfig.chatConfig.sendConsoleMessages) + if (!BotController.INSTANCE.isBotReady() || !SDLinkConfig.INSTANCE.chatConfig.sendConsoleMessages) return; StandardGuildMessageChannel channel = ChannelManager.getConsoleChannel(); @@ -118,14 +122,13 @@ public final class DiscordMessage { channel.sendMessage(this.message).queue(); } } catch (Exception e) { - if (sdLinkConfig.generalConfig.debugging) { + if (SDLinkConfig.INSTANCE.generalConfig.debugging) { BotController.INSTANCE.getLogger().error("Failed to send console message", e); } } - if (afterSend != null) { + if (afterSend != null) afterSend.run(); - } } /** @@ -153,7 +156,7 @@ public final class DiscordMessage { private Triple resolveDestination() { switch (messageType) { case CHAT -> { - MessageChannelConfig.DestinationObject chat = sdLinkConfig.messageDestinations.chat; + MessageChannelConfig.DestinationObject chat = SDLinkConfig.INSTANCE.messageDestinations.chat; return Triple.of( ChannelManager.getDestinationChannel(chat.channel), WebhookManager.getWebhookClient(chat.channel), @@ -161,7 +164,7 @@ public final class DiscordMessage { ); } case START_STOP -> { - MessageChannelConfig.DestinationObject startStop = sdLinkConfig.messageDestinations.startStop; + MessageChannelConfig.DestinationObject startStop = SDLinkConfig.INSTANCE.messageDestinations.startStop; return Triple.of( ChannelManager.getDestinationChannel(startStop.channel), WebhookManager.getWebhookClient(startStop.channel), @@ -169,7 +172,7 @@ public final class DiscordMessage { ); } case JOIN_LEAVE -> { - MessageChannelConfig.DestinationObject joinLeave = sdLinkConfig.messageDestinations.joinLeave; + MessageChannelConfig.DestinationObject joinLeave = SDLinkConfig.INSTANCE.messageDestinations.joinLeave; return Triple.of( ChannelManager.getDestinationChannel(joinLeave.channel), WebhookManager.getWebhookClient(joinLeave.channel), @@ -177,7 +180,7 @@ public final class DiscordMessage { ); } case ADVANCEMENT -> { - MessageChannelConfig.DestinationObject advancement = sdLinkConfig.messageDestinations.advancements; + MessageChannelConfig.DestinationObject advancement = SDLinkConfig.INSTANCE.messageDestinations.advancements; return Triple.of( ChannelManager.getDestinationChannel(advancement.channel), WebhookManager.getWebhookClient(advancement.channel), @@ -185,7 +188,7 @@ public final class DiscordMessage { ); } case DEATH -> { - MessageChannelConfig.DestinationObject death = sdLinkConfig.messageDestinations.death; + MessageChannelConfig.DestinationObject death = SDLinkConfig.INSTANCE.messageDestinations.death; return Triple.of( ChannelManager.getDestinationChannel(death.channel), WebhookManager.getWebhookClient(death.channel), @@ -193,7 +196,7 @@ public final class DiscordMessage { ); } case COMMAND -> { - MessageChannelConfig.DestinationObject command = sdLinkConfig.messageDestinations.commands; + MessageChannelConfig.DestinationObject command = SDLinkConfig.INSTANCE.messageDestinations.commands; return Triple.of( ChannelManager.getDestinationChannel(command.channel), WebhookManager.getWebhookClient(command.channel), @@ -203,7 +206,7 @@ public final class DiscordMessage { } // This code should never be reached, but it's added here as a fail-safe - MessageChannelConfig.DestinationObject chat = sdLinkConfig.messageDestinations.chat; + MessageChannelConfig.DestinationObject chat = SDLinkConfig.INSTANCE.messageDestinations.chat; return Triple.of(ChannelManager.getDestinationChannel(chat.channel), WebhookManager.getWebhookClient(chat.channel), chat.useEmbed); } } diff --git a/src/main/java/com/hypherionmc/sdlink/core/util/LogReader.java b/src/main/java/com/hypherionmc/sdlink/core/util/LogReader.java index 43b9cb7..a592300 100644 --- a/src/main/java/com/hypherionmc/sdlink/core/util/LogReader.java +++ b/src/main/java/com/hypherionmc/sdlink/core/util/LogReader.java @@ -5,6 +5,7 @@ package com.hypherionmc.sdlink.core.util; import com.hypherionmc.sdlink.core.accounts.DiscordAuthor; +import com.hypherionmc.sdlink.core.config.SDLinkConfig; import com.hypherionmc.sdlink.core.discord.BotController; import com.hypherionmc.sdlink.core.messaging.MessageType; import com.hypherionmc.sdlink.core.messaging.discord.DiscordMessage; @@ -26,8 +27,6 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; -import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig; - /** * @author HypherionSA * Log Appender to allow messages to be relayed from the Game Console to Discord @@ -104,7 +103,7 @@ public class LogReader extends AbstractAppender { .author(DiscordAuthor.SERVER) .build(); - if (sdLinkConfig.chatConfig.sendConsoleMessages) { + if (SDLinkConfig.INSTANCE.chatConfig.sendConsoleMessages) { discordMessage.sendMessage(); } @@ -114,7 +113,7 @@ public class LogReader extends AbstractAppender { try { Thread.sleep(30); } catch (InterruptedException e) { - if (sdLinkConfig.generalConfig.debugging) { + if (SDLinkConfig.INSTANCE.generalConfig.debugging) { BotController.INSTANCE.getLogger().error("Failed to send console message: {}", e.getMessage()); } }