CraterLib integration and final code to reach feature parity with V2

This commit is contained in:
2023-06-11 18:03:54 +02:00
parent ffb5800924
commit 6e9e344987
27 changed files with 340 additions and 155 deletions

View File

@@ -44,9 +44,10 @@ dependencies {
shaded("io.jsondb:jsondb-core:${json_db}") shaded("io.jsondb:jsondb-core:${json_db}")
// Config // Config
shaded("me.hypherionmc.moon-config:core:${moonconfig}") implementation("me.hypherionmc.moon-config:core:${moonconfig}")
shaded("me.hypherionmc.moon-config:toml:${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 // Compile Only, Not Shaded
@@ -88,7 +89,7 @@ shadowJar {
relocate 'com.iwebpp', shade_group + 'iwebpp' relocate 'com.iwebpp', shade_group + 'iwebpp'
relocate 'com.jagrosh', shade_group + 'jagrosh' relocate 'com.jagrosh', shade_group + 'jagrosh'
relocate 'com.neovisionaries', shade_group + 'neovisionaries' 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 'me.hypherionmc.jqlite', shade_group + 'jqlite'
relocate 'net.dv8tion', shade_group + 'dv8tion' relocate 'net.dv8tion', shade_group + 'dv8tion'
relocate 'okhttp3', shade_group + 'okhttp3' relocate 'okhttp3', shade_group + 'okhttp3'

View File

@@ -1,6 +1,6 @@
version_major=0 version_major=0
version_minor=0 version_minor=0
version_patch=2 version_patch=1
shade_group=com.hypherionmc.sdlink.shaded. shade_group=com.hypherionmc.sdlink.shaded.
@@ -19,3 +19,4 @@ log4j=2.17.2
commons=3.12.0 commons=3.12.0
commonsio=2.11.0 commonsio=2.11.0
gson=2.10.1 gson=2.10.1
craterlib=1.0.0

View File

@@ -4,10 +4,9 @@
*/ */
package com.hypherionmc.sdlink.core.accounts; package com.hypherionmc.sdlink.core.accounts;
import com.hypherionmc.sdlink.core.config.SDLinkConfig;
import com.hypherionmc.sdlink.core.services.SDLinkPlatform; import com.hypherionmc.sdlink.core.services.SDLinkPlatform;
import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig;
/** /**
* @author HypherionSA * @author HypherionSA
* Represents a Message Author for messages sent from Minecraft to Discord * 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 { public class DiscordAuthor {
// User used for Server Messages // 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 username;
private final String avatar; private final String avatar;
@@ -42,7 +41,7 @@ public class DiscordAuthor {
public static DiscordAuthor of(String username, String uuid) { public static DiscordAuthor of(String username, String uuid) {
return new DiscordAuthor( return new DiscordAuthor(
username, username,
SDLinkPlatform.minecraftHelper.isOnlineMode() ? sdLinkConfig.chatConfig.playerAvatarType.resolve(uuid) : username, SDLinkConfig.INSTANCE.chatConfig.playerAvatarType.resolve(SDLinkPlatform.minecraftHelper.isOnlineMode() ? uuid : username),
false false
); );
} }

View File

@@ -4,6 +4,7 @@
*/ */
package com.hypherionmc.sdlink.core.accounts; 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.database.SDLinkAccount;
import com.hypherionmc.sdlink.core.discord.BotController; import com.hypherionmc.sdlink.core.discord.BotController;
import com.hypherionmc.sdlink.core.managers.RoleManager; import com.hypherionmc.sdlink.core.managers.RoleManager;
@@ -27,7 +28,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig;
import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase; import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase;
/** /**
@@ -116,6 +116,7 @@ public class MinecraftAccount {
SDLinkAccount account = getStoredAccount(); SDLinkAccount account = getStoredAccount();
account.setDiscordID(member.getId()); account.setDiscordID(member.getId());
account.setAddedBy(member.getId());
account.setAccountLinkCode(""); account.setAccountLinkCode("");
try { try {
@@ -138,7 +139,7 @@ public class MinecraftAccount {
guild.addRoleToMember(UserSnowflake.fromId(member.getId()), RoleManager.getLinkedRole()).queue(); guild.addRoleToMember(UserSnowflake.fromId(member.getId()), RoleManager.getLinkedRole()).queue();
} }
} catch (Exception e) { } catch (Exception e) {
if (sdLinkConfig.generalConfig.debugging) { if (SDLinkConfig.INSTANCE.generalConfig.debugging) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@@ -194,7 +195,7 @@ public class MinecraftAccount {
} }
SDLinkAccount account = getStoredAccount(); SDLinkAccount account = getStoredAccount();
account.setDiscordID(member.getId()); account.setAddedBy(member.getId());
account.setWhitelistCode(""); account.setWhitelistCode("");
try { try {
@@ -203,7 +204,7 @@ public class MinecraftAccount {
sdlinkDatabase.upsert(account); sdlinkDatabase.upsert(account);
// Auto Linking is enabled, so we link the Discord and MC accounts // 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); this.linkAccount(member, guild);
} }
} }
@@ -230,10 +231,11 @@ public class MinecraftAccount {
if (whitelistResult.isError()) { if (whitelistResult.isError()) {
return whitelistResult; return whitelistResult;
} else { } else {
sdlinkDatabase.remove(account, SDLinkAccount.class); account.setWhitelisted(false);
sdlinkDatabase.upsert(account);
// Auto Linking is enabled. So we unlink the account // Auto Linking is enabled. So we unlink the account
if (sdLinkConfig.whitelistingAndLinking.whitelisting.linkedWhitelist) { if (SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.linkedWhitelist) {
this.unlinkAccount(); this.unlinkAccount();
} }

View File

@@ -4,41 +4,27 @@
*/ */
package com.hypherionmc.sdlink.core.config; 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 * @author HypherionSA
* Main Config class for Loading, Saving and Upgrading configs * Main Config class for Loading, Saving and Upgrading configs
*/ */
public class ConfigController { /*@NoConfigScreen
public class ConfigController extends ModuleConfig {
// Private internal variables // Private internal variables
private final File configFile; public static transient int configVer = 1;
public static int configVer = 1;
// Instance of the currently loaded config // Instance of the currently loaded config
public static SDLinkConfig sdLinkConfig; public static transient SDLinkConfig sdLinkConfig;
public ConfigController() { public ConfigController() {
File path = new File("config/"); super("sdlink", "simple-discord-link");
if (!path.exists())
path.mkdirs();
this.configFile = new File(path.getAbsolutePath() + File.separator + "simple-discord-link.toml");
initConfig(); initConfig();
} }
/**
* Set up the Config File as needed. @Override
* This will either Create, Upgrade or load an existing config file public void registerAndSetup(ModuleConfig conf) {
*/
private void initConfig() {
Config.setInsertionOrderPreserved(true); Config.setInsertionOrderPreserved(true);
if (!configFile.exists() || configFile.length() < 10) { if (!configFile.exists() || configFile.length() < 10) {
SDLinkConfig config = new SDLinkConfig(); SDLinkConfig config = new SDLinkConfig();
@@ -49,11 +35,19 @@ public class ConfigController {
performEncryption(); performEncryption();
} }
loadConfig(); 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);
* Serialize an existing config file into an instance of {@link SDLinkConfig} this.configReloaded();
*/ }
private void loadConfig() { private void loadConfig() {
ObjectConverter converter = new ObjectConverter(); ObjectConverter converter = new ObjectConverter();
CommentedFileConfig config = CommentedFileConfig.builder(configFile).build(); CommentedFileConfig config = CommentedFileConfig.builder(configFile).build();
@@ -62,10 +56,7 @@ public class ConfigController {
config.close(); 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) { public void saveConfig(Object conf) {
ObjectConverter converter = new ObjectConverter(); ObjectConverter converter = new ObjectConverter();
CommentedFileConfig config = CommentedFileConfig.builder(configFile).build(); CommentedFileConfig config = CommentedFileConfig.builder(configFile).build();
@@ -75,9 +66,7 @@ public class ConfigController {
config.close(); config.close();
} }
/**
* Handle config structure changes between version changes
*/
private void configUpgrade() { private void configUpgrade() {
CommentedFileConfig oldConfig = CommentedFileConfig.builder(configFile).build(); CommentedFileConfig oldConfig = CommentedFileConfig.builder(configFile).build();
CommentedFileConfig newConfig = CommentedFileConfig.builder(configFile).build(); CommentedFileConfig newConfig = CommentedFileConfig.builder(configFile).build();
@@ -116,9 +105,7 @@ public class ConfigController {
oldConfig.close(); oldConfig.close();
} }
/**
* Apply encryption to Bot-Token and Webhook URLS
*/
private void performEncryption() { private void performEncryption() {
CommentedFileConfig oldConfig = CommentedFileConfig.builder(configFile).build(); CommentedFileConfig oldConfig = CommentedFileConfig.builder(configFile).build();
oldConfig.load(); oldConfig.load();
@@ -151,4 +138,4 @@ public class ConfigController {
oldConfig.save(); oldConfig.save();
oldConfig.close(); oldConfig.close();
} }
} }*/

View File

@@ -4,15 +4,27 @@
*/ */
package com.hypherionmc.sdlink.core.config; 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.Path;
import me.hypherionmc.moonconfig.core.conversion.SpecComment; import me.hypherionmc.moonconfig.core.conversion.SpecComment;
import com.hypherionmc.sdlink.core.config.impl.*; import me.hypherionmc.moonconfig.core.file.CommentedFileConfig;
/** /**
* @author HypherionSA * @author HypherionSA
* The main mod config Structure * 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") @Path("general")
@SpecComment("General Mod Config") @SpecComment("General Mod Config")
@@ -49,4 +61,83 @@ public class SDLinkConfig {
@Path("linkedCommands") @Path("linkedCommands")
@SpecComment("Execute Minecraft commands in Discord") @SpecComment("Execute Minecraft commands in Discord")
public LinkedCommandsConfig linkedCommands = new LinkedCommandsConfig(); 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();
}
} }

View File

@@ -4,9 +4,9 @@
*/ */
package com.hypherionmc.sdlink.core.config.impl; 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.Path;
import me.hypherionmc.moonconfig.core.conversion.SpecComment; import me.hypherionmc.moonconfig.core.conversion.SpecComment;
import com.hypherionmc.sdlink.core.config.AvatarType;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;

View File

@@ -4,9 +4,9 @@
*/ */
package com.hypherionmc.sdlink.core.config.impl; 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.Path;
import me.hypherionmc.moonconfig.core.conversion.SpecComment; import me.hypherionmc.moonconfig.core.conversion.SpecComment;
import com.hypherionmc.sdlink.core.config.ConfigController;
/** /**
* @author HypherionSA * @author HypherionSA
@@ -24,5 +24,5 @@ public class GeneralConfigSettings {
@Path("configVersion") @Path("configVersion")
@SpecComment("Internal version control. DO NOT TOUCH!") @SpecComment("Internal version control. DO NOT TOUCH!")
public int configVersion = ConfigController.configVer; public int configVersion = SDLinkConfig.configVer;
} }

View File

@@ -26,11 +26,11 @@ public class LinkedCommandsConfig {
public static class Command { public static class Command {
@Path("mcCommand") @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; public String mcCommand;
@Path("discordCommand") @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; public String discordCommand;
@Path("discordRole") @Path("discordRole")

View File

@@ -4,9 +4,9 @@
*/ */
package com.hypherionmc.sdlink.core.config.impl; 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.Path;
import me.hypherionmc.moonconfig.core.conversion.SpecComment; import me.hypherionmc.moonconfig.core.conversion.SpecComment;
import com.hypherionmc.sdlink.core.messaging.MessageDestination;
/** /**
* @author HypherionSA * @author HypherionSA

View File

@@ -4,7 +4,7 @@
*/ */
package com.hypherionmc.sdlink.core.discord; 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.commands.CommandManager;
import com.hypherionmc.sdlink.core.discord.events.DiscordEventHandler; import com.hypherionmc.sdlink.core.discord.events.DiscordEventHandler;
import com.hypherionmc.sdlink.core.managers.DatabaseManager; 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.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig;
/** /**
* @author HypherionSA * @author HypherionSA
* The main Discord Bot class. This controls everything surrounding the bot itself * The main Discord Bot class. This controls everything surrounding the bot itself
@@ -64,7 +62,7 @@ public class BotController {
INSTANCE = this; INSTANCE = this;
this.logger = logger; this.logger = logger;
new ConfigController(); new SDLinkConfig();
DatabaseManager.initialize(); DatabaseManager.initialize();
@@ -76,21 +74,21 @@ public class BotController {
* Start the bot and handle all the startup work * Start the bot and handle all the startup work
*/ */
public void initializeBot() { public void initializeBot() {
if (sdLinkConfig == null) { if (SDLinkConfig.INSTANCE == null) {
logger.error("Failed to load config. Check your log for errors"); logger.error("Failed to load config. Check your log for errors");
return; return;
} }
if (sdLinkConfig.botConfig.botToken.isEmpty()) { if (SDLinkConfig.INSTANCE.botConfig.botToken.isEmpty()) {
logger.error("Missing bot token. Mod will be disabled"); logger.error("Missing bot token. Mod will be disabled");
return; return;
} }
if (!sdLinkConfig.generalConfig.enabled) if (!SDLinkConfig.INSTANCE.generalConfig.enabled)
return; return;
try { try {
String token = EncryptionUtil.INSTANCE.decrypt(sdLinkConfig.botConfig.botToken); String token = EncryptionUtil.INSTANCE.decrypt(SDLinkConfig.INSTANCE.botConfig.botToken);
_jda = JDABuilder.createLight( _jda = JDABuilder.createLight(
token, token,
GatewayIntent.GUILD_MEMBERS, GatewayIntent.GUILD_MEMBERS,
@@ -127,10 +125,10 @@ public class BotController {
* Check if the bot is in a state to send messages to discord * Check if the bot is in a state to send messages to discord
*/ */
public boolean isBotReady() { public boolean isBotReady() {
if (sdLinkConfig == null) if (SDLinkConfig.INSTANCE == null)
return false; return false;
if (!sdLinkConfig.generalConfig.enabled) if (!SDLinkConfig.INSTANCE.generalConfig.enabled)
return false; return false;
if (_jda == null) if (_jda == null)
@@ -173,7 +171,7 @@ public class BotController {
* Ensure that whitelisting is set up properly, so the bot can use the feature * Ensure that whitelisting is set up properly, so the bot can use the feature
*/ */
public void checkWhiteListing() { public void checkWhiteListing() {
if (!sdLinkConfig.whitelistingAndLinking.whitelisting.whitelisting) if (!SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.whitelisting)
return; return;
if (SDLinkPlatform.minecraftHelper.checkWhitelisting().isError()) { if (SDLinkPlatform.minecraftHelper.checkWhitelisting().isError()) {

View File

@@ -4,6 +4,7 @@
*/ */
package com.hypherionmc.sdlink.core.discord.commands; 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.HelpSlashCommand;
import com.hypherionmc.sdlink.core.discord.commands.slash.general.PlayerListSlashCommand; import com.hypherionmc.sdlink.core.discord.commands.slash.general.PlayerListSlashCommand;
import com.hypherionmc.sdlink.core.discord.commands.slash.general.ServerStatusSlashCommand; 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.LinkAccountCommand;
import com.hypherionmc.sdlink.core.discord.commands.slash.linking.UnlinkAccountSlashCommand; 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.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.ConfirmWhitelistSlashCommand;
import com.hypherionmc.sdlink.core.discord.commands.slash.whitelist.UnWhitelistAccountSlashCommand; import com.hypherionmc.sdlink.core.discord.commands.slash.whitelist.UnWhitelistAccountSlashCommand;
import com.hypherionmc.sdlink.core.discord.commands.slash.whitelist.ViewWhitelistedAccountsSlashCommand; 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.HashSet;
import java.util.Set; import java.util.Set;
import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig;
/** /**
* @author HypherionSA * @author HypherionSA
* Command Manager class to control how commands are registered to discord * Command Manager class to control how commands are registered to discord
@@ -39,7 +39,7 @@ public class CommandManager {
private void addCommands() { private void addCommands() {
// Register Account Linking commands, if linking is enabled // 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 LinkAccountCommand());
commands.add(new ConfirmAccountLinkSlashCommand()); commands.add(new ConfirmAccountLinkSlashCommand());
commands.add(new UnlinkAccountSlashCommand()); commands.add(new UnlinkAccountSlashCommand());
@@ -47,7 +47,7 @@ public class CommandManager {
} }
// Register Whitelist commands, if whitelisting is enabled // 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 WhitelistAccountCommand());
commands.add(new ConfirmWhitelistSlashCommand()); commands.add(new ConfirmWhitelistSlashCommand());
commands.add(new ViewWhitelistedAccountsSlashCommand()); commands.add(new ViewWhitelistedAccountsSlashCommand());
@@ -55,19 +55,23 @@ public class CommandManager {
} }
// Enable the Server Status command // Enable the Server Status command
if (sdLinkConfig.botCommands.allowServerStatus) { if (SDLinkConfig.INSTANCE.botCommands.allowServerStatus) {
commands.add(new ServerStatusSlashCommand()); commands.add(new ServerStatusSlashCommand());
} }
// Enable the Player List command // Enable the Player List command
if (sdLinkConfig.botCommands.allowPlayerList) { if (SDLinkConfig.INSTANCE.botCommands.allowPlayerList) {
commands.add(new PlayerListSlashCommand()); commands.add(new PlayerListSlashCommand());
} }
// Enable the Help command // Enable the Help command
if (sdLinkConfig.botCommands.allowHelpCommand) { if (SDLinkConfig.INSTANCE.botCommands.allowHelpCommand) {
commands.add(new HelpSlashCommand()); commands.add(new HelpSlashCommand());
} }
if (SDLinkConfig.INSTANCE.linkedCommands.enabled) {
commands.add(new MCSlashCommand());
}
} }
/** /**

View File

@@ -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(); event.reply("Could not start account linking process. Please notify the server owner").setEphemeral(true).queue();
} }
} else { } 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(); event.reply("Sorry, this Minecraft account is already linked to a discord account").setEphemeral(true).queue();
return; return;
} }

View File

@@ -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<LinkedCommandsConfig.Command> 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();
}
}

View File

@@ -37,7 +37,7 @@ public class UnWhitelistAccountSlashCommand extends SDLinkSlashCommand {
} }
for (SDLinkAccount account : accounts) { for (SDLinkAccount account : accounts) {
if (account.getDiscordID().equalsIgnoreCase(event.getMember().getId())) { if (account.getAddedBy().equalsIgnoreCase(event.getMember().getId())) {
MinecraftAccount minecraftAccount = MinecraftAccount.standard(account.getUsername()); MinecraftAccount minecraftAccount = MinecraftAccount.standard(account.getUsername());
if (SDLinkPlatform.minecraftHelper.isPlayerWhitelisted(minecraftAccount).isError()) { if (SDLinkPlatform.minecraftHelper.isPlayerWhitelisted(minecraftAccount).isError()) {
event.reply("Your account is not whitelisted in Minecraft. Cannot remove your account").setEphemeral(true).queue(); event.reply("Your account is not whitelisted in Minecraft. Cannot remove your account").setEphemeral(true).queue();

View File

@@ -5,6 +5,7 @@
package com.hypherionmc.sdlink.core.discord.commands.slash.whitelist; package com.hypherionmc.sdlink.core.discord.commands.slash.whitelist;
import com.hypherionmc.sdlink.core.accounts.MinecraftAccount; 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.database.SDLinkAccount;
import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand; import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand;
import com.hypherionmc.sdlink.core.services.SDLinkPlatform; 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 java.util.Collections;
import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig;
import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase; 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 class WhitelistAccountCommand extends SDLinkSlashCommand {
public WhitelistAccountCommand() { public WhitelistAccountCommand() {
super(sdLinkConfig.whitelistingAndLinking.whitelisting.staffOnlyWhitelist); super(SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.staffOnlyWhitelist);
this.name = "whitelist"; this.name = "whitelist";
this.help = "Start the process of Whitelisting your Minecraft Account"; 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(); event.reply("Could not start account whitelisting process. Please notify the server owner").setEphemeral(true).queue();
} }
} else { } 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(); event.reply("Sorry, this Minecraft account is already whitelisted").setEphemeral(true).queue();
return; return;
} }

View File

@@ -4,10 +4,12 @@
*/ */
package com.hypherionmc.sdlink.core.discord.events; 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.BotController;
import com.hypherionmc.sdlink.core.discord.commands.slash.general.ServerStatusSlashCommand; 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.BotReadyHooks;
import com.hypherionmc.sdlink.core.discord.hooks.DiscordMessageHooks; 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.ChannelManager;
import com.hypherionmc.sdlink.core.managers.PermissionChecker; import com.hypherionmc.sdlink.core.managers.PermissionChecker;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDA;
@@ -54,6 +56,7 @@ public class DiscordEventHandler extends ListenerAdapter {
ChannelManager.loadChannels(); ChannelManager.loadChannels();
BotReadyHooks.startActivityUpdates(event); BotReadyHooks.startActivityUpdates(event);
BotReadyHooks.startTopicUpdates(); BotReadyHooks.startTopicUpdates();
CraterEventBus.INSTANCE.postEvent(new SDLinkReadyEvent());
} }
} }

View File

@@ -4,6 +4,7 @@
*/ */
package com.hypherionmc.sdlink.core.discord.hooks; 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.discord.BotController;
import com.hypherionmc.sdlink.core.managers.ChannelManager; import com.hypherionmc.sdlink.core.managers.ChannelManager;
import com.hypherionmc.sdlink.core.messaging.MessageDestination; 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 java.util.concurrent.TimeUnit;
import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig;
/** /**
* @author HypherionSA * @author HypherionSA
* Hooks to run when the bot is ready * Hooks to run when the bot is ready
@@ -32,40 +31,40 @@ public class BotReadyHooks {
BotController.taskManager.scheduleAtFixedRate(() -> { BotController.taskManager.scheduleAtFixedRate(() -> {
try { try {
if (event.getJDA().getStatus() == JDA.Status.CONNECTED) { 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("%players%", String.valueOf(SDLinkPlatform.minecraftHelper.getPlayerCounts().getLeft()))
.replace("%maxplayers%", String.valueOf(SDLinkPlatform.minecraftHelper.getPlayerCounts().getRight()))); .replace("%maxplayers%", String.valueOf(SDLinkPlatform.minecraftHelper.getPlayerCounts().getRight())));
if (sdLinkConfig.botConfig.botStatus.botStatusType == Activity.ActivityType.STREAMING) { if (SDLinkConfig.INSTANCE.botConfig.botStatus.botStatusType == Activity.ActivityType.STREAMING) {
act = Activity.of(sdLinkConfig.botConfig.botStatus.botStatusType, sdLinkConfig.botConfig.botStatus.botStatus act = Activity.of(SDLinkConfig.INSTANCE.botConfig.botStatus.botStatusType, SDLinkConfig.INSTANCE.botConfig.botStatus.botStatus
.replace("%players%", String.valueOf(SDLinkPlatform.minecraftHelper.getPlayerCounts().getLeft())) .replace("%players%", String.valueOf(SDLinkPlatform.minecraftHelper.getPlayerCounts().getLeft()))
.replace("%maxplayers%", String.valueOf(SDLinkPlatform.minecraftHelper.getPlayerCounts().getRight())), .replace("%maxplayers%", String.valueOf(SDLinkPlatform.minecraftHelper.getPlayerCounts().getRight())),
sdLinkConfig.botConfig.botStatus.botStatusStreamingURL); SDLinkConfig.INSTANCE.botConfig.botStatus.botStatusStreamingURL);
} }
event.getJDA().getPresence().setActivity(act); event.getJDA().getPresence().setActivity(act);
} }
} catch (Exception e) { } catch (Exception e) {
if (sdLinkConfig.generalConfig.debugging) { if (SDLinkConfig.INSTANCE.generalConfig.debugging) {
BotController.INSTANCE.getLogger().info(e.getMessage()); 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 * Update the Chat Channel topic, if enabled
*/ */
public static void startTopicUpdates() { public static void startTopicUpdates() {
if (!sdLinkConfig.botConfig.channelTopic.doTopicUpdates) if (!SDLinkConfig.INSTANCE.botConfig.channelTopic.doTopicUpdates)
return; return;
BotController.taskManager.scheduleAtFixedRate(() -> { BotController.taskManager.scheduleAtFixedRate(() -> {
try { 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); StandardGuildMessageChannel channel = ChannelManager.getDestinationChannel(MessageDestination.CHAT);
if (channel != null) { 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("%players%", String.valueOf(SDLinkPlatform.minecraftHelper.getPlayerCounts().getLeft()))
.replace("%maxplayers%", String.valueOf(SDLinkPlatform.minecraftHelper.getPlayerCounts().getRight())) .replace("%maxplayers%", String.valueOf(SDLinkPlatform.minecraftHelper.getPlayerCounts().getRight()))
.replace("%uptime%", SystemUtils.secondsToTimestamp(SDLinkPlatform.minecraftHelper.getServerUptime())); .replace("%uptime%", SystemUtils.secondsToTimestamp(SDLinkPlatform.minecraftHelper.getServerUptime()));
@@ -73,7 +72,7 @@ public class BotReadyHooks {
} }
} }
} catch (Exception e) { } catch (Exception e) {
if (sdLinkConfig.generalConfig.debugging) { if (SDLinkConfig.INSTANCE.generalConfig.debugging) {
BotController.INSTANCE.getLogger().info(e.getMessage()); BotController.INSTANCE.getLogger().info(e.getMessage());
} }
} }

View File

@@ -4,14 +4,13 @@
*/ */
package com.hypherionmc.sdlink.core.discord.hooks; 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.discord.BotController;
import com.hypherionmc.sdlink.core.managers.ChannelManager; import com.hypherionmc.sdlink.core.managers.ChannelManager;
import com.hypherionmc.sdlink.core.messaging.MessageDestination; import com.hypherionmc.sdlink.core.messaging.MessageDestination;
import com.hypherionmc.sdlink.core.services.SDLinkPlatform; import com.hypherionmc.sdlink.core.services.SDLinkPlatform;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig;
/** /**
* @author HypherionSA * @author HypherionSA
* Hook class to handle messages the bot receives * Hook class to handle messages the bot receives
@@ -26,15 +25,15 @@ public class DiscordMessageHooks {
if (event.getChannel().getIdLong() != ChannelManager.getDestinationChannel(MessageDestination.CHAT).getIdLong()) if (event.getChannel().getIdLong() != ChannelManager.getDestinationChannel(MessageDestination.CHAT).getIdLong())
return; return;
if (event.getAuthor().isBot() && sdLinkConfig.chatConfig.ignoreBots) if (event.getAuthor().isBot() && SDLinkConfig.INSTANCE.chatConfig.ignoreBots)
return; return;
if (sdLinkConfig.generalConfig.debugging) { if (SDLinkConfig.INSTANCE.generalConfig.debugging) {
BotController.INSTANCE.getLogger().info("Sending Message from {}: {}", event.getAuthor().getName(), event.getMessage().getContentStripped()); BotController.INSTANCE.getLogger().info("Sending Message from {}: {}", event.getAuthor().getName(), event.getMessage().getContentStripped());
} }
SDLinkPlatform.minecraftHelper.discordMessageReceived(event.getMember().getEffectiveName(), event.getMessage().getContentRaw()); SDLinkPlatform.minecraftHelper.discordMessageReceived(event.getMember().getEffectiveName(), event.getMessage().getContentRaw());
} catch (Exception e) { } catch (Exception e) {
if (sdLinkConfig.generalConfig.debugging) { if (SDLinkConfig.INSTANCE.generalConfig.debugging) {
e.printStackTrace(); e.printStackTrace();
} }
} }

View File

@@ -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;
}
}

View File

@@ -4,6 +4,7 @@
*/ */
package com.hypherionmc.sdlink.core.managers; 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.discord.BotController;
import com.hypherionmc.sdlink.core.messaging.MessageDestination; import com.hypherionmc.sdlink.core.messaging.MessageDestination;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDA;
@@ -12,8 +13,6 @@ import org.apache.commons.lang3.tuple.Pair;
import java.util.HashMap; import java.util.HashMap;
import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig;
/** /**
* @author HypherionSA * @author HypherionSA
* Load and Cache configured channels for later use * Load and Cache configured channels for later use
@@ -32,9 +31,9 @@ public class ChannelManager {
JDA jda = BotController.INSTANCE.getJDA(); JDA jda = BotController.INSTANCE.getJDA();
StandardGuildMessageChannel chatChannel = jda.getChannelById(StandardGuildMessageChannel.class, sdLinkConfig.channelsAndWebhooks.channels.chatChannelID); StandardGuildMessageChannel chatChannel = jda.getChannelById(StandardGuildMessageChannel.class, SDLinkConfig.INSTANCE.channelsAndWebhooks.channels.chatChannelID);
StandardGuildMessageChannel eventChannel = jda.getChannelById(StandardGuildMessageChannel.class, sdLinkConfig.channelsAndWebhooks.channels.eventsChannelID); StandardGuildMessageChannel eventChannel = jda.getChannelById(StandardGuildMessageChannel.class, SDLinkConfig.INSTANCE.channelsAndWebhooks.channels.eventsChannelID);
consoleChannel = jda.getChannelById(StandardGuildMessageChannel.class, sdLinkConfig.channelsAndWebhooks.channels.consoleChannelID); consoleChannel = jda.getChannelById(StandardGuildMessageChannel.class, SDLinkConfig.INSTANCE.channelsAndWebhooks.channels.consoleChannelID);
if (chatChannel != null) { if (chatChannel != null) {
channelMap.put(MessageDestination.CHAT, Pair.of(chatChannel, false)); channelMap.put(MessageDestination.CHAT, Pair.of(chatChannel, false));

View File

@@ -4,6 +4,7 @@
*/ */
package com.hypherionmc.sdlink.core.managers; 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.discord.BotController;
import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
@@ -15,8 +16,6 @@ import java.util.EnumSet;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig;
/** /**
* @author HypherionSA * @author HypherionSA
* Startup permission checker hook to check if the bot has all the required permissions to function * 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); checkBotPerms(errCount, builder, botPerms);
checkChannelPerms( checkChannelPerms(
sdLinkConfig.channelsAndWebhooks.channels.chatChannelID, SDLinkConfig.INSTANCE.channelsAndWebhooks.channels.chatChannelID,
"Chat Channel", "Chat Channel",
errCount, errCount,
builder, builder,
@@ -98,7 +97,7 @@ public class PermissionChecker {
); );
checkChannelPerms( checkChannelPerms(
sdLinkConfig.channelsAndWebhooks.channels.eventsChannelID, SDLinkConfig.INSTANCE.channelsAndWebhooks.channels.eventsChannelID,
"Events Channel", "Events Channel",
errCount, errCount,
builder, builder,
@@ -108,7 +107,7 @@ public class PermissionChecker {
); );
checkChannelPerms( checkChannelPerms(
sdLinkConfig.channelsAndWebhooks.channels.consoleChannelID, SDLinkConfig.INSTANCE.channelsAndWebhooks.channels.consoleChannelID,
"Console Channel", "Console Channel",
errCount, errCount,
builder, builder,
@@ -177,7 +176,7 @@ public class PermissionChecker {
}); });
if (isChat) { 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(); errCount.incrementAndGet();
builder.append(errCount.get()).append(") ").append("Missing Chat Channel Permission: Manage Channel. Topic updates will not work").append("\r\n"); builder.append(errCount.get()).append(") ").append("Missing Chat Channel Permission: Manage Channel. Topic updates will not work").append("\r\n");
} }

View File

@@ -4,6 +4,7 @@
*/ */
package com.hypherionmc.sdlink.core.managers; 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.discord.BotController;
import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.Role;
@@ -11,8 +12,6 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig;
/** /**
* @author HypherionSA * @author HypherionSA
* Load and Cache roles needed by the bot * Load and Cache roles needed by the bot
@@ -30,21 +29,21 @@ public class RoleManager {
* @param builder * @param builder
*/ */
public static void loadRequiredRoles(AtomicInteger errCount, StringBuilder builder) { public static void loadRequiredRoles(AtomicInteger errCount, StringBuilder builder) {
if (!sdLinkConfig.botConfig.staffRole.isEmpty()) { if (!SDLinkConfig.INSTANCE.botConfig.staffRole.isEmpty()) {
staffRole = getRole(errCount, builder, "Staff", sdLinkConfig.botConfig.staffRole); staffRole = getRole(errCount, builder, "Staff", SDLinkConfig.INSTANCE.botConfig.staffRole);
} }
if (!sdLinkConfig.whitelistingAndLinking.whitelisting.autoWhitelistRole.isEmpty()) { if (!SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.autoWhitelistRole.isEmpty()) {
whitelistedRole = getRole(errCount, builder, "Whitelist", sdLinkConfig.whitelistingAndLinking.whitelisting.autoWhitelistRole); whitelistedRole = getRole(errCount, builder, "Whitelist", SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.autoWhitelistRole);
} }
if (!sdLinkConfig.whitelistingAndLinking.accountLinking.linkedRole.isEmpty()) { if (!SDLinkConfig.INSTANCE.whitelistingAndLinking.accountLinking.linkedRole.isEmpty()) {
linkedRole = getRole(errCount, builder, "Linked Account", sdLinkConfig.whitelistingAndLinking.accountLinking.linkedRole); linkedRole = getRole(errCount, builder, "Linked Account", SDLinkConfig.INSTANCE.whitelistingAndLinking.accountLinking.linkedRole);
} }
if (sdLinkConfig.linkedCommands.enabled) { if (SDLinkConfig.INSTANCE.linkedCommands.enabled) {
commandRoles.clear(); commandRoles.clear();
sdLinkConfig.linkedCommands.commands.forEach(cmd -> { SDLinkConfig.INSTANCE.linkedCommands.commands.forEach(cmd -> {
if (!cmd.discordRole.isEmpty()) { if (!cmd.discordRole.isEmpty()) {
Role role = getRole(errCount, builder, cmd.discordCommand + " usage", cmd.discordRole); Role role = getRole(errCount, builder, cmd.discordCommand + " usage", cmd.discordRole);
if (role != null) { if (role != null) {

View File

@@ -5,6 +5,7 @@
package com.hypherionmc.sdlink.core.managers; package com.hypherionmc.sdlink.core.managers;
import club.minnced.discord.webhook.WebhookClient; 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.discord.BotController;
import com.hypherionmc.sdlink.core.messaging.MessageDestination; import com.hypherionmc.sdlink.core.messaging.MessageDestination;
import com.hypherionmc.sdlink.core.messaging.SDLinkWebhookClient; import com.hypherionmc.sdlink.core.messaging.SDLinkWebhookClient;
@@ -12,8 +13,6 @@ import com.hypherionmc.sdlink.core.util.EncryptionUtil;
import java.util.HashMap; import java.util.HashMap;
import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig;
/** /**
* @author HypherionSA * @author HypherionSA
* Load and cache Webhook clients for later use * Load and cache Webhook clients for later use
@@ -30,32 +29,32 @@ public class WebhookManager {
public static void init() { public static void init() {
clientMap.clear(); clientMap.clear();
if (sdLinkConfig == null || !sdLinkConfig.channelsAndWebhooks.webhooks.enabled) if (SDLinkConfig.INSTANCE == null || !SDLinkConfig.INSTANCE.channelsAndWebhooks.webhooks.enabled)
return; return;
if (!sdLinkConfig.generalConfig.enabled) if (!SDLinkConfig.INSTANCE.generalConfig.enabled)
return; return;
if (!sdLinkConfig.channelsAndWebhooks.webhooks.chatWebhook.isEmpty()) { if (!SDLinkConfig.INSTANCE.channelsAndWebhooks.webhooks.chatWebhook.isEmpty()) {
chatWebhookClient = new SDLinkWebhookClient( chatWebhookClient = new SDLinkWebhookClient(
"Chat", "Chat",
EncryptionUtil.INSTANCE.decrypt(sdLinkConfig.channelsAndWebhooks.webhooks.chatWebhook) EncryptionUtil.INSTANCE.decrypt(SDLinkConfig.INSTANCE.channelsAndWebhooks.webhooks.chatWebhook)
).build(); ).build();
BotController.INSTANCE.getLogger().info("Using Webhook for Chat Messages"); 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( eventWebhookClient = new SDLinkWebhookClient(
"Events", "Events",
EncryptionUtil.INSTANCE.decrypt(sdLinkConfig.channelsAndWebhooks.webhooks.eventsWebhook) EncryptionUtil.INSTANCE.decrypt(SDLinkConfig.INSTANCE.channelsAndWebhooks.webhooks.eventsWebhook)
).build(); ).build();
BotController.INSTANCE.getLogger().info("Using Webhook for Event Messages"); 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( consoleWebhookClient = new SDLinkWebhookClient(
"Console", "Console",
EncryptionUtil.INSTANCE.decrypt(sdLinkConfig.channelsAndWebhooks.webhooks.consoleWebhook) EncryptionUtil.INSTANCE.decrypt(SDLinkConfig.INSTANCE.channelsAndWebhooks.webhooks.consoleWebhook)
).build(); ).build();
BotController.INSTANCE.getLogger().info("Using Webhook for Console Messages"); BotController.INSTANCE.getLogger().info("Using Webhook for Console Messages");
} }

View File

@@ -9,6 +9,7 @@ import club.minnced.discord.webhook.send.WebhookEmbed;
import club.minnced.discord.webhook.send.WebhookEmbedBuilder; import club.minnced.discord.webhook.send.WebhookEmbedBuilder;
import club.minnced.discord.webhook.send.WebhookMessageBuilder; import club.minnced.discord.webhook.send.WebhookMessageBuilder;
import com.hypherionmc.sdlink.core.accounts.DiscordAuthor; 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.config.impl.MessageChannelConfig;
import com.hypherionmc.sdlink.core.discord.BotController; import com.hypherionmc.sdlink.core.discord.BotController;
import com.hypherionmc.sdlink.core.managers.ChannelManager; 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 net.dv8tion.jda.api.entities.channel.middleman.StandardGuildMessageChannel;
import org.apache.commons.lang3.tuple.Triple; import org.apache.commons.lang3.tuple.Triple;
import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig;
/** /**
* @author HypherionSA * @author HypherionSA
* Represents a message sent from Minecraft to Discord * Represents a message sent from Minecraft to Discord
@@ -56,7 +55,7 @@ public final class DiscordMessage {
sendNormalMessage(); sendNormalMessage();
} }
} catch (Exception e) { } catch (Exception e) {
if (sdLinkConfig.generalConfig.debugging) { if (SDLinkConfig.INSTANCE.generalConfig.debugging) {
BotController.INSTANCE.getLogger().error("Failed to send Discord Message", e); BotController.INSTANCE.getLogger().error("Failed to send Discord Message", e);
} }
} }
@@ -69,7 +68,7 @@ public final class DiscordMessage {
Triple<StandardGuildMessageChannel, WebhookClient, Boolean> channel = resolveDestination(); Triple<StandardGuildMessageChannel, WebhookClient, Boolean> channel = resolveDestination();
// Check if a webhook is configured, and use that instead // 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(); WebhookMessageBuilder builder = new WebhookMessageBuilder();
builder.setUsername(this.author.getUsername()); builder.setUsername(this.author.getUsername());
if (!this.author.getAvatar().isEmpty()) { if (!this.author.getAvatar().isEmpty()) {
@@ -85,21 +84,26 @@ public final class DiscordMessage {
builder.setContent(message); builder.setContent(message);
} }
channel.getMiddle().send(builder.build()); channel.getMiddle().send(builder.build()).thenRun(() -> {
if (afterSend != null)
afterSend.run();
});
} else { } else {
// Use the configured channel instead // Use the configured channel instead
if (channel.getRight()) { if (channel.getRight()) {
EmbedBuilder eb = buildEmbed(true); EmbedBuilder eb = buildEmbed(true);
channel.getLeft().sendMessageEmbeds(eb.build()).queue(); channel.getLeft().sendMessageEmbeds(eb.build()).queue(success -> {
if (afterSend != null)
afterSend.run();
});
} else { } else {
channel.getLeft().sendMessage( channel.getLeft().sendMessage(
this.messageType == MessageType.CHAT ? 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) : message)
.queue(success -> { .queue(success -> {
if (afterSend != null) { if (afterSend != null)
afterSend.run(); afterSend.run();
}
}); });
} }
} }
@@ -110,7 +114,7 @@ public final class DiscordMessage {
*/ */
private void sendConsoleMessage() { private void sendConsoleMessage() {
try { try {
if (!BotController.INSTANCE.isBotReady() || !sdLinkConfig.chatConfig.sendConsoleMessages) if (!BotController.INSTANCE.isBotReady() || !SDLinkConfig.INSTANCE.chatConfig.sendConsoleMessages)
return; return;
StandardGuildMessageChannel channel = ChannelManager.getConsoleChannel(); StandardGuildMessageChannel channel = ChannelManager.getConsoleChannel();
@@ -118,15 +122,14 @@ public final class DiscordMessage {
channel.sendMessage(this.message).queue(); channel.sendMessage(this.message).queue();
} }
} catch (Exception e) { } catch (Exception e) {
if (sdLinkConfig.generalConfig.debugging) { if (SDLinkConfig.INSTANCE.generalConfig.debugging) {
BotController.INSTANCE.getLogger().error("Failed to send console message", e); BotController.INSTANCE.getLogger().error("Failed to send console message", e);
} }
} }
if (afterSend != null) { if (afterSend != null)
afterSend.run(); afterSend.run();
} }
}
/** /**
* Build an embed with the supplied information * Build an embed with the supplied information
@@ -153,7 +156,7 @@ public final class DiscordMessage {
private Triple<StandardGuildMessageChannel, WebhookClient, Boolean> resolveDestination() { private Triple<StandardGuildMessageChannel, WebhookClient, Boolean> resolveDestination() {
switch (messageType) { switch (messageType) {
case CHAT -> { case CHAT -> {
MessageChannelConfig.DestinationObject chat = sdLinkConfig.messageDestinations.chat; MessageChannelConfig.DestinationObject chat = SDLinkConfig.INSTANCE.messageDestinations.chat;
return Triple.of( return Triple.of(
ChannelManager.getDestinationChannel(chat.channel), ChannelManager.getDestinationChannel(chat.channel),
WebhookManager.getWebhookClient(chat.channel), WebhookManager.getWebhookClient(chat.channel),
@@ -161,7 +164,7 @@ public final class DiscordMessage {
); );
} }
case START_STOP -> { case START_STOP -> {
MessageChannelConfig.DestinationObject startStop = sdLinkConfig.messageDestinations.startStop; MessageChannelConfig.DestinationObject startStop = SDLinkConfig.INSTANCE.messageDestinations.startStop;
return Triple.of( return Triple.of(
ChannelManager.getDestinationChannel(startStop.channel), ChannelManager.getDestinationChannel(startStop.channel),
WebhookManager.getWebhookClient(startStop.channel), WebhookManager.getWebhookClient(startStop.channel),
@@ -169,7 +172,7 @@ public final class DiscordMessage {
); );
} }
case JOIN_LEAVE -> { case JOIN_LEAVE -> {
MessageChannelConfig.DestinationObject joinLeave = sdLinkConfig.messageDestinations.joinLeave; MessageChannelConfig.DestinationObject joinLeave = SDLinkConfig.INSTANCE.messageDestinations.joinLeave;
return Triple.of( return Triple.of(
ChannelManager.getDestinationChannel(joinLeave.channel), ChannelManager.getDestinationChannel(joinLeave.channel),
WebhookManager.getWebhookClient(joinLeave.channel), WebhookManager.getWebhookClient(joinLeave.channel),
@@ -177,7 +180,7 @@ public final class DiscordMessage {
); );
} }
case ADVANCEMENT -> { case ADVANCEMENT -> {
MessageChannelConfig.DestinationObject advancement = sdLinkConfig.messageDestinations.advancements; MessageChannelConfig.DestinationObject advancement = SDLinkConfig.INSTANCE.messageDestinations.advancements;
return Triple.of( return Triple.of(
ChannelManager.getDestinationChannel(advancement.channel), ChannelManager.getDestinationChannel(advancement.channel),
WebhookManager.getWebhookClient(advancement.channel), WebhookManager.getWebhookClient(advancement.channel),
@@ -185,7 +188,7 @@ public final class DiscordMessage {
); );
} }
case DEATH -> { case DEATH -> {
MessageChannelConfig.DestinationObject death = sdLinkConfig.messageDestinations.death; MessageChannelConfig.DestinationObject death = SDLinkConfig.INSTANCE.messageDestinations.death;
return Triple.of( return Triple.of(
ChannelManager.getDestinationChannel(death.channel), ChannelManager.getDestinationChannel(death.channel),
WebhookManager.getWebhookClient(death.channel), WebhookManager.getWebhookClient(death.channel),
@@ -193,7 +196,7 @@ public final class DiscordMessage {
); );
} }
case COMMAND -> { case COMMAND -> {
MessageChannelConfig.DestinationObject command = sdLinkConfig.messageDestinations.commands; MessageChannelConfig.DestinationObject command = SDLinkConfig.INSTANCE.messageDestinations.commands;
return Triple.of( return Triple.of(
ChannelManager.getDestinationChannel(command.channel), ChannelManager.getDestinationChannel(command.channel),
WebhookManager.getWebhookClient(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 // 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); return Triple.of(ChannelManager.getDestinationChannel(chat.channel), WebhookManager.getWebhookClient(chat.channel), chat.useEmbed);
} }
} }

View File

@@ -5,6 +5,7 @@
package com.hypherionmc.sdlink.core.util; package com.hypherionmc.sdlink.core.util;
import com.hypherionmc.sdlink.core.accounts.DiscordAuthor; 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.discord.BotController;
import com.hypherionmc.sdlink.core.messaging.MessageType; import com.hypherionmc.sdlink.core.messaging.MessageType;
import com.hypherionmc.sdlink.core.messaging.discord.DiscordMessage; import com.hypherionmc.sdlink.core.messaging.discord.DiscordMessage;
@@ -26,8 +27,6 @@ import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import static com.hypherionmc.sdlink.core.config.ConfigController.sdLinkConfig;
/** /**
* @author HypherionSA * @author HypherionSA
* Log Appender to allow messages to be relayed from the Game Console to Discord * 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) .author(DiscordAuthor.SERVER)
.build(); .build();
if (sdLinkConfig.chatConfig.sendConsoleMessages) { if (SDLinkConfig.INSTANCE.chatConfig.sendConsoleMessages) {
discordMessage.sendMessage(); discordMessage.sendMessage();
} }
@@ -114,7 +113,7 @@ public class LogReader extends AbstractAppender {
try { try {
Thread.sleep(30); Thread.sleep(30);
} catch (InterruptedException e) { } catch (InterruptedException e) {
if (sdLinkConfig.generalConfig.debugging) { if (SDLinkConfig.INSTANCE.generalConfig.debugging) {
BotController.INSTANCE.getLogger().error("Failed to send console message: {}", e.getMessage()); BotController.INSTANCE.getLogger().error("Failed to send console message: {}", e.getMessage());
} }
} }