diff --git a/pom.xml b/pom.xml index 816ba03..3b9fb8b 100644 --- a/pom.xml +++ b/pom.xml @@ -1,163 +1,163 @@ - - - 4.0.0 - - com.greazi - discordbotfoundation - - DiscordBotFoundation - 0.17.4 - jar - - - Greazi - com.greazi.discordbotfoundation.SimpleBot - - 17 - - 17 - 17 - - UTF-8 - - - - - jitpack.io - https://jitpack.io - - - - - - - net.dv8tion - JDA - 5.0.0-alpha.22 - - - - - org.slf4j - slf4j-jdk14 - 2.0.3 - test - - - - - org.kohsuke - github-api - 1.313 - - - - - com.mysql - mysql-connector-j - 8.0.31 - - - - - - org.json - json - 20220924 - - - - - com.google.guava - guava - 31.1-jre - - - - - org.quartz-scheduler - quartz - 2.3.2 - - - - - org.yaml - snakeyaml - 1.33 - - - - - org.projectlombok - lombok - 1.18.24 - provided - - - - - org.jooq - jooq - 3.17.5 - - - - - org.jooq - jooq-meta - 3.17.5 - - - - - org.jooq - jooq-codegen - 3.17.5 - - - - - - - ${project.name}-${project.version} - - - org.apache.maven.plugins - maven-site-plugin - 3.7.1 - - - org.apache.maven.plugins - maven-jar-plugin - 3.2.2 - - - org.apache.maven.plugins - maven-compiler-plugin - 3.10.1 - - 17 - 17 - - - - org.apache.maven.plugins - maven-shade-plugin - 3.4.1 - - false - - - - - - src/main/resources - true - - - - + + + 4.0.0 + + com.greazi + discordbotfoundation + + DiscordBotFoundation + 0.17.4 + jar + + + Greazi + com.greazi.discordbotfoundation.SimpleBot + + 17 + + 17 + 17 + + UTF-8 + + + + + jitpack.io + https://jitpack.io + + + + + + + net.dv8tion + JDA + 5.0.0-alpha.22 + + + + + org.slf4j + slf4j-jdk14 + 2.0.3 + test + + + + + org.kohsuke + github-api + 1.313 + + + + + com.mysql + mysql-connector-j + 8.0.31 + + + + + + org.json + json + 20220924 + + + + + com.google.guava + guava + 31.1-jre + + + + + org.quartz-scheduler + quartz + 2.3.2 + + + + + org.yaml + snakeyaml + 1.33 + + + + + org.projectlombok + lombok + 1.18.24 + provided + + + + + org.jooq + jooq + 3.17.5 + + + + + org.jooq + jooq-meta + 3.17.5 + + + + + org.jooq + jooq-codegen + 3.17.5 + + + + + + + ${project.name}-${project.version} + + + org.apache.maven.plugins + maven-site-plugin + 3.7.1 + + + org.apache.maven.plugins + maven-jar-plugin + 3.2.2 + + + org.apache.maven.plugins + maven-compiler-plugin + 3.10.1 + + 17 + 17 + + + + org.apache.maven.plugins + maven-shade-plugin + 3.4.1 + + false + + + + + + src/main/resources + true + + + + \ No newline at end of file diff --git a/src/main/java/com/greazi/discordbotfoundation/SimpleBot.java b/src/main/java/com/greazi/discordbotfoundation/SimpleBot.java index e1306a8..af0d905 100644 --- a/src/main/java/com/greazi/discordbotfoundation/SimpleBot.java +++ b/src/main/java/com/greazi/discordbotfoundation/SimpleBot.java @@ -1,769 +1,769 @@ -package com.greazi.discordbotfoundation; - -import com.greazi.discordbotfoundation.command.core.AboutCommand; -import com.greazi.discordbotfoundation.command.core.StopCommand; -import com.greazi.discordbotfoundation.command.general.PingCommand; -import com.greazi.discordbotfoundation.console.ClearConsoleCommand; -import com.greazi.discordbotfoundation.console.HelpConsoleCommand; -import com.greazi.discordbotfoundation.console.StopConsoleCommand; -import com.greazi.discordbotfoundation.constants.Constants; -import com.greazi.discordbotfoundation.debug.Debugger; -import com.greazi.discordbotfoundation.handlers.buttons.ButtonHandler; -import com.greazi.discordbotfoundation.handlers.buttons.SimpleButton; -import com.greazi.discordbotfoundation.handlers.commands.SimpleSlashCommand; -import com.greazi.discordbotfoundation.handlers.commands.SlashCommandHandler; -import com.greazi.discordbotfoundation.handlers.console.ConsoleCommandHandler; -import com.greazi.discordbotfoundation.handlers.console.SimpleConsoleCommand; -import com.greazi.discordbotfoundation.handlers.crons.CronHandler; -import com.greazi.discordbotfoundation.handlers.modals.ModalHandler; -import com.greazi.discordbotfoundation.handlers.modals.SimpleModal; -import com.greazi.discordbotfoundation.handlers.selectmenu.SelectMenuHandler; -import com.greazi.discordbotfoundation.handlers.selectmenu.SimpleSelectMenu; -import com.greazi.discordbotfoundation.mysql.SqlManager; -import com.greazi.discordbotfoundation.settings.SimpleSettings; -import com.greazi.discordbotfoundation.utils.color.ConsoleColor; -import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.JDABuilder; -import net.dv8tion.jda.api.entities.Activity; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.SelfUser; -import net.dv8tion.jda.api.hooks.AnnotatedEventManager; -import net.dv8tion.jda.api.interactions.commands.Command; -import net.dv8tion.jda.api.requests.GatewayIntent; -import net.dv8tion.jda.api.utils.ChunkingFilter; -import net.dv8tion.jda.api.utils.MemberCachePolicy; -import net.dv8tion.jda.api.utils.cache.CacheFlag; - -import java.util.HashMap; - -// TODO: ALL FILES!!!! -// Check all files for comments and add them if needed - -// TODO: Create an events adder method that adds all events to the event manager - -// TODO: Fix the reload system - -/** - * A basic discord bot that represents the discord bot library - */ -public abstract class SimpleBot { - - // ---------------------------------------------------------------------------------------- - // Static - // ---------------------------------------------------------------------------------------- - - // Instances - private static volatile SimpleBot instance; - public static JDA jda; - - // Important variables - private static Guild mainGuild; - private static SelfUser self; - - // Handlers - private static SlashCommandHandler slashCommandHandler; - private static ButtonHandler buttonHandler; - private static ModalHandler modalHandler; - private static SelectMenuHandler menuHandler; - private static ConsoleCommandHandler consoleCommandHandler; - private static CronHandler cronHandler; - private static SqlManager sqlManager; - - private boolean enabled; - - // ---------------------------------------------------------------------------------------- - // Instance specific - // ---------------------------------------------------------------------------------------- - - /** - * Returns the instance of {@link SimpleBot}. - *

- * It is recommended to override this in your own {@link SimpleBot} - * implementation, so you will get the instance of that, directly. - * - * @return this instance - */ - public static SimpleBot getInstance() { - return instance; - } - - /** - * Get if the instance that is used across the library has been set. Normally it - * is always set, except for testing. - * - * @return if the instance has been set. - */ - public static boolean hasInstance() { - return instance != null; - } - - // ---------------------------------------------------------------------------------------- - // Main methods - // ---------------------------------------------------------------------------------------- - - /** - * The main method that is the beginning of the bot - *

- * By default, it will start the bot with the {@link #registerJda(String, Activity)} method - */ - public SimpleBot() { - this.enabled = false; - - if (getStartupLogo() != null) { - Debugger.debug("StartupLogo", "Startup logo isn't empty"); - Common.logNoPrefix(getStartupLogo()); - } else { - Debugger.debug("StartupLogo", "Startup logo is empty"); - } - - // Load the settings from the config file - SimpleSettings.init(); - - // Set the instance of the bot - instance = this; - - // Load the sql manager - sqlManager = new SqlManager(); - - // Load way before the bot starts to avoid any issues - onPreLoad(); - - // Check the activity for the bot - final Activity activityType; - final String activity = SimpleSettings.Activity.Message(); - switch (SimpleSettings.Activity.Type().toLowerCase()) { - case "watching": - activityType = Activity.watching(activity); - break; - case "playing": - activityType = Activity.playing(activity); - break; - case "streaming": - activityType = Activity.streaming(activity, getDeveloperWebsite()); - break; - case "listening": - activityType = Activity.listening(activity); - break; - default: - activityType = Activity.watching(getName()); - } - - // Initialize the bot - registerJda(SimpleSettings.Bot.Token(), activityType); - - // Get the main guild ID from the settings - final long mainGuildId = SimpleSettings.Bot.MainGuild(); - - // Set the main guild of the bot - if (mainGuildId != 0) { - // Get the guild by ID - final Guild guild = jda.getGuildById(mainGuildId); - // Check if the guild could be found - if (guild != null) { - // Set the main guild - mainGuild = guild; - // Log that the main guild has been set - Common.log("Main guild set to: " + ConsoleColor.CYAN + guild.getName() + ConsoleColor.BLACK_BRIGHT + " (" + guild.getId() + ")"); - // No guild by that ID could be found - } else { - // Error message that the guild could not be found - Common.error( - "The main guild ID is not valid! Please check the config file!", - "Now using the first guild as the main guild!" - ); - // Set the main guild to the first guild in the list - mainGuild = jda.getGuilds().get(0); - } - // Guild option couldn't be found - } else { - // Error message that the guild could not be found - Common.error( - "The main guild ID is not configured! Please check the config file!", - "Now using the first guild as the main guild!" - ); - // Set the main guild to the first guild in the list - mainGuild = jda.getGuilds().get(0); - } - - // Load after the bot has been initialized - onBotLoad(); - - // Set up the command manager that handles slash commands - setupCommandManager(); - - // This is a method that will be ren everytime the bot is reloaded - // In here you add all the commands and events - /** {@link #onReloadableStart()} */ - onReload(); - - // TODO: Create a check if the bot is fully enabled - setEnabled(); - - // A check if the bot is truly enabled !!!NOT YET FINISHED!!! - if (enabled) { - // Message that the bot has started - Common.success("Bot is ready"); - } else { - Common.error("The bot failed to enable something is wrong!"); - } - - for (final Command command : getJDA().retrieveCommands().complete()) { - Debugger.debug("SlashCommand", command.getName() + "" + command.getDescription()); - } - } - - /** - * The pre start of the bot. Register the bot and do some simple checks - */ - public final void setupCommandManager() { - Common.log("Setting up the system managers"); - slashCommandHandler = new SlashCommandHandler(); - buttonHandler = new ButtonHandler(); - modalHandler = new ModalHandler(); - menuHandler = new SelectMenuHandler(); - consoleCommandHandler = new ConsoleCommandHandler(); - cronHandler = new CronHandler(); - Common.log("System managers have been set up"); - } - - /** - * A method that is called when the bot is reloaded - */ - public void onReload() { - // Check if the bot is enabled before doing anything - if (enabled) { - Common.error("The bot is already enabled!"); - return; - } - - // Close old SQL connection safely before opening a new one - /*try { - sqlManager.getConnection().close(); - } catch (final SQLException e) { - e.printStackTrace(); - } - - // Create a new SQL connection - sqlManager = new SqlManager();*/ - - // Load the static commands - registerCommands( - new PingCommand(), - new AboutCommand() - ); - if (SimpleSettings.Stop.Enabled()) { - registerCommand(new StopCommand()); - } - - // Load the static console commands - registerConsoleCommands( - new HelpConsoleCommand(), - new ClearConsoleCommand(), - new StopConsoleCommand() - ); - - // Run the onReloadableStart() method - onReloadableStart(); - - // Register commands to JDA - slashCommandHandler.registerCommands(); - - // Register cron jobs - cronHandler.scheduleJobs(); - - // A boolean that says the bot is loaded and enabled - enabled = true; - - // A log option to show how many things are registered - Common.log("Loaded a total of " + ConsoleColor.CYAN + getSlashCommandHandler().getTotal() + ConsoleColor.RESET + " slash commands " + ConsoleColor.CYAN + getSlashCommandHandler().getGuildTotal() + ConsoleColor.RESET + " main guild and " + ConsoleColor.CYAN + getSlashCommandHandler().getPublicTotal() + ConsoleColor.RESET + " public"); - Common.log("Loaded a total of " + ConsoleColor.CYAN + getConsoleCommandHandler().getTotal() + ConsoleColor.RESET + " console commands"); - Common.log("Loaded a total of " + ConsoleColor.CYAN + getSelectMenuHandler().getTotal() + ConsoleColor.RESET + " menus"); - Common.log("Loaded a total of " + ConsoleColor.CYAN + getButtonHandler().getTotal() + ConsoleColor.RESET + " buttons"); - Common.log("Loaded a total of " + ConsoleColor.CYAN + getModalHandler().getTotal() + ConsoleColor.RESET + " modals"); - } - - /** - * Registration of the bot itself - * - * @param token = The token of the bot - * @param activity = The activity status of the bot - */ - private static void registerJda(final String token, final Activity activity) { - Common.log("Registering JDA..."); - try { - jda = JDABuilder.createDefault(token) - .setEnabledIntents(GatewayIntent.getIntents(GatewayIntent.DEFAULT | GatewayIntent.GUILD_MEMBERS.getRawValue() | GatewayIntent.GUILD_BANS.getRawValue())) - .setDisabledIntents(GatewayIntent.DIRECT_MESSAGE_TYPING, GatewayIntent.GUILD_MESSAGE_TYPING) - .disableCache(CacheFlag.ACTIVITY, CacheFlag.VOICE_STATE, CacheFlag.ONLINE_STATUS) - .setMemberCachePolicy(MemberCachePolicy.ALL) - .setChunkingFilter(ChunkingFilter.ALL) - .setActivity(activity) - .setEventManager(new AnnotatedEventManager()) - .build().awaitReady(); - - // Set self to the bot - self = jda.getSelfUser(); - Common.log("JDA registered"); - } catch (final InterruptedException ex) { - Common.throwError(ex, "Failed to register JDA"); - } - } - - public void stop() { - new Thread(() -> { - Common.log("Stopping JDA"); - jda.shutdown(); - - int jdaShutdownTimeout = 0; - while (jda.getStatus() != JDA.Status.SHUTDOWN) { - if (jdaShutdownTimeout > 15) { - Common.warning("JDA shutdown timeout reached, forcing shutdown"); - jda.shutdownNow(); - break; - } - - try { - Thread.sleep(1000); - } catch (final InterruptedException e) { - e.printStackTrace(); - } - jdaShutdownTimeout++; - } - Common.log("JDA stopped"); - - cronHandler.stop(); - - int cronShutdownTimeout = 0; - while (!cronHandler.isShutdown()) { - if (cronShutdownTimeout > 15) { - Common.warning("Cron shutdown timeout reached, forcing shutdown"); - break; - } - - try { - Thread.sleep(1000); - } catch (final InterruptedException e) { - e.printStackTrace(); - } - cronShutdownTimeout++; - } - - try { - Thread.sleep(1000); - } catch (final InterruptedException e) { - e.printStackTrace(); - } - - Common.log("Stopping bot it self"); - System.exit(0); - }).start(); - - onBotStop(); - } - - // ---------------------------------------------------------------------------------------- - // Registration methods <- Used to register your commands, buttons, menus, modals and console commands - // ---------------------------------------------------------------------------------------- - - /** - * Register a new command in the slash command list - * - * @param command SimpleSlashCommand - */ - protected final void registerCommand(final SimpleSlashCommand command) { - getSlashCommandHandler().addCommand(command); - } - - /** - * Register new commands in the slash command list at once - * - * @param commands SimpleSlashCommands - */ - protected final void registerCommands(final SimpleSlashCommand... commands) { - for (final SimpleSlashCommand command : commands) { - getSlashCommandHandler().addCommand(command); - } - } - - /** - * Register a new button in the button list - * - * @param button SimpleButton - * @deprecated Use build() instead - */ - @Deprecated(since = "2.0.0", forRemoval = true) - protected final void registerButton(final SimpleButton button) { - getButtonHandler().addButtonListener(button); - } - - /** - * Register new buttons in the button list at once - * - * @param buttons SimpleButton - * @deprecated Use build() instead - */ - @Deprecated(since = "2.0.0", forRemoval = true) - protected final void registerButtons(final SimpleButton... buttons) { - for (final SimpleButton button : buttons) { - getButtonHandler().addButtonListener(button); - } - } - - /** - * Register a new menu in the menu list - * - * @param menu SimpleSelectMenu - * @deprecated Use build() instead - */ - @Deprecated(since = "2.0.0", forRemoval = true) - protected final void registerMenu(final SimpleSelectMenu menu) { - getSelectMenuHandler().addMenuListener(menu); - } - - /** - * Register new menus in the menu list at once - * - * @param menus SimpleSelectMenu - * @deprecated Use build() instead - */ - @Deprecated(since = "2.0.0", forRemoval = true) - protected final void registerMenus(final SimpleSelectMenu... menus) { - for (final SimpleSelectMenu menu : menus) { - getSelectMenuHandler().addMenuListener(menu); - } - } - - /** - * Register a new modal in the modal list - * - * @param modal SimpleModal - * @deprecated Use build() instead - */ - @Deprecated(since = "2.0.0", forRemoval = true) - protected final void registerModal(final SimpleModal modal) { - getModalHandler().addModalListener(modal); - } - - /** - * Register new modals in the modal list at once - * - * @param modals SimpleModal - * @deprecated Use build() instead - */ - @Deprecated(since = "2.0.0", forRemoval = true) - protected final void registerModals(final SimpleModal... modals) { - for (final SimpleModal modal : modals) { - getModalHandler().addModalListener(modal); - } - } - - /** - * Register a new console command in the console command list - * - * @param command SimpleConsoleCommand - */ - protected final void registerConsoleCommand(final SimpleConsoleCommand command) { - getConsoleCommandHandler().addCommand(command); - } - - /** - * Register new console commands in the console commands list - * - * @param commands SimpleConsoleCommand - */ - protected final void registerConsoleCommands(final SimpleConsoleCommand... commands) { - for (final SimpleConsoleCommand command : commands) { - getConsoleCommandHandler().addCommand(command); - } - } - - // ---------------------------------------------------------------------------------------- - // Delegate methods <-- Methods that can be used to load your stuff - // ---------------------------------------------------------------------------------------- - - /** - * Called way before everything starts (Not recommended to use) - */ - protected void onPreLoad() { - } - - - /** - * Called just before the bot starts - */ - protected void onBotLoad() { - } - - //Copyright - - /** - * The main loading method, called when we are ready to load - */ - protected abstract void onBotStart(); - - /** - * The main method called when we are about to shut down - */ - protected void onBotStop() { - } - - /** - * Invoked before settings were reloaded. - */ - protected void onBotPreReload() { - } - - /** - * Invoked after settings were reloaded. - */ - protected void onBotReload() { - } - - /** - * Register your commands, events, tasks and files here. - *

- * This is invoked when you do `/reload` - */ - protected void onReloadableStart() { - } - - // ---------------------------------------------------------------------------------------- - // Foundation handle settings - // ---------------------------------------------------------------------------------------- - - /** - * Should every message be divided by \n by an own method (tends to work more - * than split("\n")) - * - * @return If the system need to force a new line with \n - */ - public boolean enforceNewLine() { - return false; - } - - // ---------------------------------------------------------------------------------------- - // Main setters - // ---------------------------------------------------------------------------------------- - - /** - * Set the bot as status enabled - */ - private void setEnabled() { - this.enabled = true; - } - - // ---------------------------------------------------------------------------------------- - // Main getters - // ---------------------------------------------------------------------------------------- - - /** - * Retrieve the JDA instance - * - * @return JDA instance - */ - public static JDA getJDA() { - return jda; - } - - /** - * Retrieve the bot instance - * - * @return Bot instance - */ - public static SimpleBot getBot() { - return instance; - } - - /** - * Retrieve the bots main guild - * - * @return Main guild - */ - public static Guild getMainGuild() { - return mainGuild; - } - - /** - * Retrieve the bot members self - * - * @return Self - */ - public static SelfUser getSelf() { - return self; - } - - /** - * Retrieve the slash command handler - * - * @return Slash command handler - */ - private static SlashCommandHandler getSlashCommandHandler() { - return slashCommandHandler; - } - - /** - * Retrieve the button handler - * - * @return Button handler - */ - public static ButtonHandler getButtonHandler() { - return buttonHandler; - } - - /** - * Retrieve the modal handler - * - * @return Modal handler - */ - public static ModalHandler getModalHandler() { - return modalHandler; - } - - /** - * Retrieve the select menu handler - * - * @return SelectMenu handler - */ - private static SelectMenuHandler getSelectMenuHandler() { - return menuHandler; - } - - /** - * Retrieve the console command handler - * - * @return Console command handler - */ - private static ConsoleCommandHandler getConsoleCommandHandler() { - return consoleCommandHandler; - } - - /** - * Retrieve the cron jobs handler - * - * @return Console cron jobs handler - */ - public static CronHandler getCronHandler() { - return cronHandler; - } - - /** - * Retrieve the sql manager - * - * @return Sql manager - */ - public static SqlManager getSqlManager() { - return sqlManager; - } - - /** - * Get a modal from the modal from the modal handler - * - * @param button_id The ID of the button - * @return SimpleButton - */ - public static SimpleButton getButton(final String button_id) { - return getButtonHandler().getButton(button_id); - } - - public static SimpleSelectMenu getSelectMenu(final String menu_id) { - return getSelectMenuHandler().getMenu(menu_id); - } - - /** - * Get a modal from the modal from the modal handler - * - * @param modal_id The ID of the modal - * @return SimpleModal - */ - public static SimpleModal getModal(final String modal_id) { - return getModalHandler().getModal(modal_id); - } - - /** - * Get a console command from the console command handler - * - * @param consoleCommand The console command - * @return Console Command - */ - public static SimpleConsoleCommand getConsoleCommand(final String consoleCommand) { - return getConsoleCommandHandler().getCommand(consoleCommand); - } - - /** - * Get all console commands from the console command handler - * - * @return Console Command HashMap - */ - public static HashMap getConsoleCommands() { - return getConsoleCommandHandler().getCommandList(); - } - - // ---------------------------------------------------------------------------------------- - // Additional features - // ---------------------------------------------------------------------------------------- - - // TODO: Fix this so it works properly with a @Override - - /** - * The start-up fancy logo - * - * @return null by default - */ - protected String[] getStartupLogo() { - return null; - } - - /** - * Get the year of foundation displayed on the about command - * - * @return -1 by default, or the founded year - */ - public int getFoundedYear() { - return -1; - } - - /** - * Retrieve the version of the bot - * - * @return Version - */ - public static String getVersion() { - return Constants.Version.FOUNDATION; - } - - /** - * Retrieve the name of the bot - * - * @return Name - */ - public static String getName() { - return SimpleSettings.Bot.Name(); - } - - /** - * Retrieve the developer of the bot - * - * @return Developer - */ - public String getDeveloperName() { - return SimpleSettings.Developer.Name(); - } - - /** - * Get the embed author link - * - * @return Author link - */ - public String getDeveloperWebsite() { - return SimpleSettings.Developer.Website(); - } - - /** - * Check if the bot is enabled - * - * @return Bot enabled - */ - public boolean isEnabled() { - return enabled; - } -} +package com.greazi.discordbotfoundation; + +import com.greazi.discordbotfoundation.command.core.AboutCommand; +import com.greazi.discordbotfoundation.command.core.StopCommand; +import com.greazi.discordbotfoundation.command.general.PingCommand; +import com.greazi.discordbotfoundation.console.ClearConsoleCommand; +import com.greazi.discordbotfoundation.console.HelpConsoleCommand; +import com.greazi.discordbotfoundation.console.StopConsoleCommand; +import com.greazi.discordbotfoundation.constants.Constants; +import com.greazi.discordbotfoundation.debug.Debugger; +import com.greazi.discordbotfoundation.handlers.buttons.ButtonHandler; +import com.greazi.discordbotfoundation.handlers.buttons.SimpleButton; +import com.greazi.discordbotfoundation.handlers.commands.SimpleSlashCommand; +import com.greazi.discordbotfoundation.handlers.commands.SlashCommandHandler; +import com.greazi.discordbotfoundation.handlers.console.ConsoleCommandHandler; +import com.greazi.discordbotfoundation.handlers.console.SimpleConsoleCommand; +import com.greazi.discordbotfoundation.handlers.crons.CronHandler; +import com.greazi.discordbotfoundation.handlers.modals.ModalHandler; +import com.greazi.discordbotfoundation.handlers.modals.SimpleModal; +import com.greazi.discordbotfoundation.handlers.selectmenu.SelectMenuHandler; +import com.greazi.discordbotfoundation.handlers.selectmenu.SimpleSelectMenu; +import com.greazi.discordbotfoundation.mysql.SqlManager; +import com.greazi.discordbotfoundation.settings.SimpleSettings; +import com.greazi.discordbotfoundation.utils.color.ConsoleColor; +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.JDABuilder; +import net.dv8tion.jda.api.entities.Activity; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.SelfUser; +import net.dv8tion.jda.api.hooks.AnnotatedEventManager; +import net.dv8tion.jda.api.interactions.commands.Command; +import net.dv8tion.jda.api.requests.GatewayIntent; +import net.dv8tion.jda.api.utils.ChunkingFilter; +import net.dv8tion.jda.api.utils.MemberCachePolicy; +import net.dv8tion.jda.api.utils.cache.CacheFlag; + +import java.util.HashMap; + +// TODO: ALL FILES!!!! +// Check all files for comments and add them if needed + +// TODO: Create an events adder method that adds all events to the event manager + +// TODO: Fix the reload system + +/** + * A basic discord bot that represents the discord bot library + */ +public abstract class SimpleBot { + + // ---------------------------------------------------------------------------------------- + // Static + // ---------------------------------------------------------------------------------------- + + // Instances + private static volatile SimpleBot instance; + public static JDA jda; + + // Important variables + private static Guild mainGuild; + private static SelfUser self; + + // Handlers + private static SlashCommandHandler slashCommandHandler; + private static ButtonHandler buttonHandler; + private static ModalHandler modalHandler; + private static SelectMenuHandler menuHandler; + private static ConsoleCommandHandler consoleCommandHandler; + private static CronHandler cronHandler; + private static SqlManager sqlManager; + + private boolean enabled; + + // ---------------------------------------------------------------------------------------- + // Instance specific + // ---------------------------------------------------------------------------------------- + + /** + * Returns the instance of {@link SimpleBot}. + *

+ * It is recommended to override this in your own {@link SimpleBot} + * implementation, so you will get the instance of that, directly. + * + * @return this instance + */ + public static SimpleBot getInstance() { + return instance; + } + + /** + * Get if the instance that is used across the library has been set. Normally it + * is always set, except for testing. + * + * @return if the instance has been set. + */ + public static boolean hasInstance() { + return instance != null; + } + + // ---------------------------------------------------------------------------------------- + // Main methods + // ---------------------------------------------------------------------------------------- + + /** + * The main method that is the beginning of the bot + *

+ * By default, it will start the bot with the {@link #registerJda(String, Activity)} method + */ + public SimpleBot() { + this.enabled = false; + + if (getStartupLogo() != null) { + Debugger.debug("StartupLogo", "Startup logo isn't empty"); + Common.logNoPrefix(getStartupLogo()); + } else { + Debugger.debug("StartupLogo", "Startup logo is empty"); + } + + // Load the settings from the config file + SimpleSettings.init(); + + // Set the instance of the bot + instance = this; + + // Load the sql manager + sqlManager = new SqlManager(); + + // Load way before the bot starts to avoid any issues + onPreLoad(); + + // Check the activity for the bot + final Activity activityType; + final String activity = SimpleSettings.Activity.Message(); + switch (SimpleSettings.Activity.Type().toLowerCase()) { + case "watching": + activityType = Activity.watching(activity); + break; + case "playing": + activityType = Activity.playing(activity); + break; + case "streaming": + activityType = Activity.streaming(activity, getDeveloperWebsite()); + break; + case "listening": + activityType = Activity.listening(activity); + break; + default: + activityType = Activity.watching(getName()); + } + + // Initialize the bot + registerJda(SimpleSettings.Bot.Token(), activityType); + + // Get the main guild ID from the settings + final long mainGuildId = SimpleSettings.Bot.MainGuild(); + + // Set the main guild of the bot + if (mainGuildId != 0) { + // Get the guild by ID + final Guild guild = jda.getGuildById(mainGuildId); + // Check if the guild could be found + if (guild != null) { + // Set the main guild + mainGuild = guild; + // Log that the main guild has been set + Common.log("Main guild set to: " + ConsoleColor.CYAN + guild.getName() + ConsoleColor.BLACK_BRIGHT + " (" + guild.getId() + ")"); + // No guild by that ID could be found + } else { + // Error message that the guild could not be found + Common.error( + "The main guild ID is not valid! Please check the config file!", + "Now using the first guild as the main guild!" + ); + // Set the main guild to the first guild in the list + mainGuild = jda.getGuilds().get(0); + } + // Guild option couldn't be found + } else { + // Error message that the guild could not be found + Common.error( + "The main guild ID is not configured! Please check the config file!", + "Now using the first guild as the main guild!" + ); + // Set the main guild to the first guild in the list + mainGuild = jda.getGuilds().get(0); + } + + // Load after the bot has been initialized + onBotLoad(); + + // Set up the command manager that handles slash commands + setupCommandManager(); + + // This is a method that will be ren everytime the bot is reloaded + // In here you add all the commands and events + /** {@link #onReloadableStart()} */ + onReload(); + + // TODO: Create a check if the bot is fully enabled + setEnabled(); + + // A check if the bot is truly enabled !!!NOT YET FINISHED!!! + if (enabled) { + // Message that the bot has started + Common.success("Bot is ready"); + } else { + Common.error("The bot failed to enable something is wrong!"); + } + + for (final Command command : getJDA().retrieveCommands().complete()) { + Debugger.debug("SlashCommand", command.getName() + "" + command.getDescription()); + } + } + + /** + * The pre start of the bot. Register the bot and do some simple checks + */ + public final void setupCommandManager() { + Common.log("Setting up the system managers"); + slashCommandHandler = new SlashCommandHandler(); + buttonHandler = new ButtonHandler(); + modalHandler = new ModalHandler(); + menuHandler = new SelectMenuHandler(); + consoleCommandHandler = new ConsoleCommandHandler(); + cronHandler = new CronHandler(); + Common.log("System managers have been set up"); + } + + /** + * A method that is called when the bot is reloaded + */ + public void onReload() { + // Check if the bot is enabled before doing anything + if (enabled) { + Common.error("The bot is already enabled!"); + return; + } + + // Close old SQL connection safely before opening a new one + /*try { + sqlManager.getConnection().close(); + } catch (final SQLException e) { + e.printStackTrace(); + } + + // Create a new SQL connection + sqlManager = new SqlManager();*/ + + // Load the static commands + registerCommands( + new PingCommand(), + new AboutCommand() + ); + if (SimpleSettings.Stop.Enabled()) { + registerCommand(new StopCommand()); + } + + // Load the static console commands + registerConsoleCommands( + new HelpConsoleCommand(), + new ClearConsoleCommand(), + new StopConsoleCommand() + ); + + // Run the onReloadableStart() method + onReloadableStart(); + + // Register commands to JDA + slashCommandHandler.registerCommands(); + + // Register cron jobs + cronHandler.scheduleJobs(); + + // A boolean that says the bot is loaded and enabled + enabled = true; + + // A log option to show how many things are registered + Common.log("Loaded a total of " + ConsoleColor.CYAN + getSlashCommandHandler().getTotal() + ConsoleColor.RESET + " slash commands " + ConsoleColor.CYAN + getSlashCommandHandler().getGuildTotal() + ConsoleColor.RESET + " main guild and " + ConsoleColor.CYAN + getSlashCommandHandler().getPublicTotal() + ConsoleColor.RESET + " public"); + Common.log("Loaded a total of " + ConsoleColor.CYAN + getConsoleCommandHandler().getTotal() + ConsoleColor.RESET + " console commands"); + Common.log("Loaded a total of " + ConsoleColor.CYAN + getSelectMenuHandler().getTotal() + ConsoleColor.RESET + " menus"); + Common.log("Loaded a total of " + ConsoleColor.CYAN + getButtonHandler().getTotal() + ConsoleColor.RESET + " buttons"); + Common.log("Loaded a total of " + ConsoleColor.CYAN + getModalHandler().getTotal() + ConsoleColor.RESET + " modals"); + } + + /** + * Registration of the bot itself + * + * @param token = The token of the bot + * @param activity = The activity status of the bot + */ + private static void registerJda(final String token, final Activity activity) { + Common.log("Registering JDA..."); + try { + jda = JDABuilder.createDefault(token) + .setEnabledIntents(GatewayIntent.getIntents(GatewayIntent.DEFAULT | GatewayIntent.GUILD_MEMBERS.getRawValue() | GatewayIntent.GUILD_BANS.getRawValue())) + .setDisabledIntents(GatewayIntent.DIRECT_MESSAGE_TYPING, GatewayIntent.GUILD_MESSAGE_TYPING) + .disableCache(CacheFlag.ACTIVITY, CacheFlag.VOICE_STATE, CacheFlag.ONLINE_STATUS) + .setMemberCachePolicy(MemberCachePolicy.ALL) + .setChunkingFilter(ChunkingFilter.ALL) + .setActivity(activity) + .setEventManager(new AnnotatedEventManager()) + .build().awaitReady(); + + // Set self to the bot + self = jda.getSelfUser(); + Common.log("JDA registered"); + } catch (final InterruptedException ex) { + Common.throwError(ex, "Failed to register JDA"); + } + } + + public void stop() { + new Thread(() -> { + Common.log("Stopping JDA"); + jda.shutdown(); + + int jdaShutdownTimeout = 0; + while (jda.getStatus() != JDA.Status.SHUTDOWN) { + if (jdaShutdownTimeout > 15) { + Common.warning("JDA shutdown timeout reached, forcing shutdown"); + jda.shutdownNow(); + break; + } + + try { + Thread.sleep(1000); + } catch (final InterruptedException e) { + e.printStackTrace(); + } + jdaShutdownTimeout++; + } + Common.log("JDA stopped"); + + cronHandler.stop(); + + int cronShutdownTimeout = 0; + while (!cronHandler.isShutdown()) { + if (cronShutdownTimeout > 15) { + Common.warning("Cron shutdown timeout reached, forcing shutdown"); + break; + } + + try { + Thread.sleep(1000); + } catch (final InterruptedException e) { + e.printStackTrace(); + } + cronShutdownTimeout++; + } + + try { + Thread.sleep(1000); + } catch (final InterruptedException e) { + e.printStackTrace(); + } + + Common.log("Stopping bot it self"); + System.exit(0); + }).start(); + + onBotStop(); + } + + // ---------------------------------------------------------------------------------------- + // Registration methods <- Used to register your commands, buttons, menus, modals and console commands + // ---------------------------------------------------------------------------------------- + + /** + * Register a new command in the slash command list + * + * @param command SimpleSlashCommand + */ + protected final void registerCommand(final SimpleSlashCommand command) { + getSlashCommandHandler().addCommand(command); + } + + /** + * Register new commands in the slash command list at once + * + * @param commands SimpleSlashCommands + */ + protected final void registerCommands(final SimpleSlashCommand... commands) { + for (final SimpleSlashCommand command : commands) { + getSlashCommandHandler().addCommand(command); + } + } + + /** + * Register a new button in the button list + * + * @param button SimpleButton + * @deprecated Use build() instead + */ + @Deprecated(since = "2.0.0", forRemoval = true) + protected final void registerButton(final SimpleButton button) { + getButtonHandler().addButtonListener(button); + } + + /** + * Register new buttons in the button list at once + * + * @param buttons SimpleButton + * @deprecated Use build() instead + */ + @Deprecated(since = "2.0.0", forRemoval = true) + protected final void registerButtons(final SimpleButton... buttons) { + for (final SimpleButton button : buttons) { + getButtonHandler().addButtonListener(button); + } + } + + /** + * Register a new menu in the menu list + * + * @param menu SimpleSelectMenu + * @deprecated Use build() instead + */ + @Deprecated(since = "2.0.0", forRemoval = true) + protected final void registerMenu(final SimpleSelectMenu menu) { + getSelectMenuHandler().addMenuListener(menu); + } + + /** + * Register new menus in the menu list at once + * + * @param menus SimpleSelectMenu + * @deprecated Use build() instead + */ + @Deprecated(since = "2.0.0", forRemoval = true) + protected final void registerMenus(final SimpleSelectMenu... menus) { + for (final SimpleSelectMenu menu : menus) { + getSelectMenuHandler().addMenuListener(menu); + } + } + + /** + * Register a new modal in the modal list + * + * @param modal SimpleModal + * @deprecated Use build() instead + */ + @Deprecated(since = "2.0.0", forRemoval = true) + protected final void registerModal(final SimpleModal modal) { + getModalHandler().addModalListener(modal); + } + + /** + * Register new modals in the modal list at once + * + * @param modals SimpleModal + * @deprecated Use build() instead + */ + @Deprecated(since = "2.0.0", forRemoval = true) + protected final void registerModals(final SimpleModal... modals) { + for (final SimpleModal modal : modals) { + getModalHandler().addModalListener(modal); + } + } + + /** + * Register a new console command in the console command list + * + * @param command SimpleConsoleCommand + */ + protected final void registerConsoleCommand(final SimpleConsoleCommand command) { + getConsoleCommandHandler().addCommand(command); + } + + /** + * Register new console commands in the console commands list + * + * @param commands SimpleConsoleCommand + */ + protected final void registerConsoleCommands(final SimpleConsoleCommand... commands) { + for (final SimpleConsoleCommand command : commands) { + getConsoleCommandHandler().addCommand(command); + } + } + + // ---------------------------------------------------------------------------------------- + // Delegate methods <-- Methods that can be used to load your stuff + // ---------------------------------------------------------------------------------------- + + /** + * Called way before everything starts (Not recommended to use) + */ + protected void onPreLoad() { + } + + + /** + * Called just before the bot starts + */ + protected void onBotLoad() { + } + + //Copyright + + /** + * The main loading method, called when we are ready to load + */ + protected abstract void onBotStart(); + + /** + * The main method called when we are about to shut down + */ + protected void onBotStop() { + } + + /** + * Invoked before settings were reloaded. + */ + protected void onBotPreReload() { + } + + /** + * Invoked after settings were reloaded. + */ + protected void onBotReload() { + } + + /** + * Register your commands, events, tasks and files here. + *

+ * This is invoked when you do `/reload` + */ + protected void onReloadableStart() { + } + + // ---------------------------------------------------------------------------------------- + // Foundation handle settings + // ---------------------------------------------------------------------------------------- + + /** + * Should every message be divided by \n by an own method (tends to work more + * than split("\n")) + * + * @return If the system need to force a new line with \n + */ + public boolean enforceNewLine() { + return false; + } + + // ---------------------------------------------------------------------------------------- + // Main setters + // ---------------------------------------------------------------------------------------- + + /** + * Set the bot as status enabled + */ + private void setEnabled() { + this.enabled = true; + } + + // ---------------------------------------------------------------------------------------- + // Main getters + // ---------------------------------------------------------------------------------------- + + /** + * Retrieve the JDA instance + * + * @return JDA instance + */ + public static JDA getJDA() { + return jda; + } + + /** + * Retrieve the bot instance + * + * @return Bot instance + */ + public static SimpleBot getBot() { + return instance; + } + + /** + * Retrieve the bots main guild + * + * @return Main guild + */ + public static Guild getMainGuild() { + return mainGuild; + } + + /** + * Retrieve the bot members self + * + * @return Self + */ + public static SelfUser getSelf() { + return self; + } + + /** + * Retrieve the slash command handler + * + * @return Slash command handler + */ + private static SlashCommandHandler getSlashCommandHandler() { + return slashCommandHandler; + } + + /** + * Retrieve the button handler + * + * @return Button handler + */ + public static ButtonHandler getButtonHandler() { + return buttonHandler; + } + + /** + * Retrieve the modal handler + * + * @return Modal handler + */ + public static ModalHandler getModalHandler() { + return modalHandler; + } + + /** + * Retrieve the select menu handler + * + * @return SelectMenu handler + */ + private static SelectMenuHandler getSelectMenuHandler() { + return menuHandler; + } + + /** + * Retrieve the console command handler + * + * @return Console command handler + */ + private static ConsoleCommandHandler getConsoleCommandHandler() { + return consoleCommandHandler; + } + + /** + * Retrieve the cron jobs handler + * + * @return Console cron jobs handler + */ + public static CronHandler getCronHandler() { + return cronHandler; + } + + /** + * Retrieve the sql manager + * + * @return Sql manager + */ + public static SqlManager getSqlManager() { + return sqlManager; + } + + /** + * Get a modal from the modal from the modal handler + * + * @param button_id The ID of the button + * @return SimpleButton + */ + public static SimpleButton getButton(final String button_id) { + return getButtonHandler().getButton(button_id); + } + + public static SimpleSelectMenu getSelectMenu(final String menu_id) { + return getSelectMenuHandler().getMenu(menu_id); + } + + /** + * Get a modal from the modal from the modal handler + * + * @param modal_id The ID of the modal + * @return SimpleModal + */ + public static SimpleModal getModal(final String modal_id) { + return getModalHandler().getModal(modal_id); + } + + /** + * Get a console command from the console command handler + * + * @param consoleCommand The console command + * @return Console Command + */ + public static SimpleConsoleCommand getConsoleCommand(final String consoleCommand) { + return getConsoleCommandHandler().getCommand(consoleCommand); + } + + /** + * Get all console commands from the console command handler + * + * @return Console Command HashMap + */ + public static HashMap getConsoleCommands() { + return getConsoleCommandHandler().getCommandList(); + } + + // ---------------------------------------------------------------------------------------- + // Additional features + // ---------------------------------------------------------------------------------------- + + // TODO: Fix this so it works properly with a @Override + + /** + * The start-up fancy logo + * + * @return null by default + */ + protected String[] getStartupLogo() { + return null; + } + + /** + * Get the year of foundation displayed on the about command + * + * @return -1 by default, or the founded year + */ + public int getFoundedYear() { + return -1; + } + + /** + * Retrieve the version of the bot + * + * @return Version + */ + public static String getVersion() { + return Constants.Version.FOUNDATION; + } + + /** + * Retrieve the name of the bot + * + * @return Name + */ + public static String getName() { + return SimpleSettings.Bot.Name(); + } + + /** + * Retrieve the developer of the bot + * + * @return Developer + */ + public String getDeveloperName() { + return SimpleSettings.Developer.Name(); + } + + /** + * Get the embed author link + * + * @return Author link + */ + public String getDeveloperWebsite() { + return SimpleSettings.Developer.Website(); + } + + /** + * Check if the bot is enabled + * + * @return Bot enabled + */ + public boolean isEnabled() { + return enabled; + } +} diff --git a/src/main/java/com/greazi/discordbotfoundation/handlers/buttons/ButtonHandler.java b/src/main/java/com/greazi/discordbotfoundation/handlers/buttons/ButtonHandler.java index de59454..fdf7123 100644 --- a/src/main/java/com/greazi/discordbotfoundation/handlers/buttons/ButtonHandler.java +++ b/src/main/java/com/greazi/discordbotfoundation/handlers/buttons/ButtonHandler.java @@ -1,154 +1,154 @@ -/* - * Copyright (c) 2021 - 2022. Greazi - All rights reservered - * - * Unauthorized copying of this file, via any medium is strictly prohibited - * Proprietary and confidential - */ - -package com.greazi.discordbotfoundation.handlers.buttons; - -import com.greazi.discordbotfoundation.Common; -import com.greazi.discordbotfoundation.SimpleBot; -import com.greazi.discordbotfoundation.debug.Debugger; -import com.greazi.discordbotfoundation.utils.SimpleEmbedBuilder; -import com.greazi.discordbotfoundation.utils.color.ConsoleColor; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import net.dv8tion.jda.api.hooks.SubscribeEvent; -import org.jetbrains.annotations.NotNull; - -import java.util.HashMap; - -/** - * The button handler that handles the whole button event. - * Uses the information of {@link SimpleButton} - */ -public class ButtonHandler extends ListenerAdapter { - - public ButtonHandler() { - Debugger.debug("Button", "Buttons main method"); - SimpleBot.getJDA().addEventListener(this); - } - - /** - * A HasMap of all the buttons that have been added - */ - private final HashMap buttonList = new HashMap<>(); - - /** - * Add the button to the button list - * - * @param module The button module - */ - public void addButtonListener(final SimpleButton module) { - Debugger.debug("Button", "Adding new button: " + module.getId()); - buttonList.put(module.getId(), module); - } - - /** - * Get a button by id - * - * @param button_id The button id - * @return this {@link SimpleButton} - */ - public SimpleButton getButton(final String button_id) { - return buttonList.get(button_id); - } - - /** - * The main event listener for the {@link ButtonInteractionEvent} event of JDA - * - * @param event ButtonInteractionEvent - */ - @Override - @SubscribeEvent - public void onButtonInteraction(@NotNull final ButtonInteractionEvent event) { - Common.log("User, " + ConsoleColor.CYAN + event.getMember().getEffectiveName() + ConsoleColor.RESET + " used Button: " + ConsoleColor.CYAN + event.getButton().getId() + ConsoleColor.RESET); - - // Retrieve the button class from the button that has been pressed - final SimpleButton module = buttonList.get(event.getButton().getId()); - - // Check if the button exists - if (module == null) { - event.replyEmbeds(new SimpleEmbedBuilder("ERROR - Button not found") - .text( - "The button you used does not exist or hasn't been activated!", - "Please contact an admin and report this error!" - ) - .error() - .setFooter("") - .build()).setEphemeral(true).queue(); - return; - } - - // Get the guild of the button and the main guild of the bot - final Guild guild = event.getGuild(); - final Guild mainGuild = SimpleBot.getMainGuild(); - assert guild != null : "Event guild is null!"; - - // Check if the button is for the main guild only - if (!guild.getId().equals(mainGuild.getId()) && module.getGuildOnly()) { - event.replyEmbeds(new SimpleEmbedBuilder("ERROR - Button main guild only") - .text( - "The button you used is only usable in the main guild of this bot!", - "If you feel like this is a problem please contact a admin!" - ) - .error() - .setFooter("") - .build()).setEphemeral(true).queue(); - return; - } - - // If the button is pressed inside a NSFW channel - if (!event.getChannel().asTextChannel().isNSFW() && module.getNsfwOnly()) { - event.replyEmbeds(new SimpleEmbedBuilder("ERROR - Button NSFW only") - .text( - "The button you used is only usable in a NSWF channel!", - "If you feel like this is a problem please contact a admin!" - ) - .error() - .setFooter("") - .build()).setEphemeral(true).queue(); - return; - } - - // TODO: Fix this ASAP AS WELL - -// // Get the member from the event -// Member member = event.getMember(); -// -// // If the member is allowed to use the button -// if(module.getDisabledUsers().contains(member.getIdLong())){ -// return; -// } -// if(!module.getEnabledUsers().isEmpty()){ -// if (!module.getEnabledUsers().contains(member.getIdLong())) { -// return; -// } -// } -// -// // If the member has the role to use the button -// if (member.getRoles().contains(module.getDisabledRoles())) { -// return; -// } -// if(!module.getEnabledRoles().isEmpty()){ -// if (member.getRoles().containsAll(module.getEnabledRoles())) { -// //run -// } -// } - - // If all checks are oke than execute the button logic - module.execute(event); - } - - /** - * Get the total amount of registered buttons - * - * @return Total registered buttons - */ - public int getTotal() { - return buttonList.size(); - } - -} +/* + * Copyright (c) 2021 - 2022. Greazi - All rights reservered + * + * Unauthorized copying of this file, via any medium is strictly prohibited + * Proprietary and confidential + */ + +package com.greazi.discordbotfoundation.handlers.buttons; + +import com.greazi.discordbotfoundation.Common; +import com.greazi.discordbotfoundation.SimpleBot; +import com.greazi.discordbotfoundation.debug.Debugger; +import com.greazi.discordbotfoundation.utils.SimpleEmbedBuilder; +import com.greazi.discordbotfoundation.utils.color.ConsoleColor; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; +import net.dv8tion.jda.api.hooks.SubscribeEvent; +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; + +/** + * The button handler that handles the whole button event. + * Uses the information of {@link SimpleButton} + */ +public class ButtonHandler extends ListenerAdapter { + + public ButtonHandler() { + Debugger.debug("Button", "Buttons main method"); + SimpleBot.getJDA().addEventListener(this); + } + + /** + * A HasMap of all the buttons that have been added + */ + private final HashMap buttonList = new HashMap<>(); + + /** + * Add the button to the button list + * + * @param module The button module + */ + public void addButtonListener(final SimpleButton module) { + Debugger.debug("Button", "Adding new button: " + module.getId()); + buttonList.put(module.getId(), module); + } + + /** + * Get a button by id + * + * @param button_id The button id + * @return this {@link SimpleButton} + */ + public SimpleButton getButton(final String button_id) { + return buttonList.get(button_id); + } + + /** + * The main event listener for the {@link ButtonInteractionEvent} event of JDA + * + * @param event ButtonInteractionEvent + */ + @Override + @SubscribeEvent + public void onButtonInteraction(@NotNull final ButtonInteractionEvent event) { + Common.log("User, " + ConsoleColor.CYAN + event.getMember().getEffectiveName() + ConsoleColor.RESET + " used Button: " + ConsoleColor.CYAN + event.getButton().getId() + ConsoleColor.RESET); + + // Retrieve the button class from the button that has been pressed + final SimpleButton module = buttonList.get(event.getButton().getId()); + + // Check if the button exists + if (module == null) { + event.replyEmbeds(new SimpleEmbedBuilder("ERROR - Button not found") + .text( + "The button you used does not exist or hasn't been activated!", + "Please contact an admin and report this error!" + ) + .error() + .setFooter("") + .build()).setEphemeral(true).queue(); + return; + } + + // Get the guild of the button and the main guild of the bot + final Guild guild = event.getGuild(); + final Guild mainGuild = SimpleBot.getMainGuild(); + assert guild != null : "Event guild is null!"; + + // Check if the button is for the main guild only + if (!guild.getId().equals(mainGuild.getId()) && module.getGuildOnly()) { + event.replyEmbeds(new SimpleEmbedBuilder("ERROR - Button main guild only") + .text( + "The button you used is only usable in the main guild of this bot!", + "If you feel like this is a problem please contact a admin!" + ) + .error() + .setFooter("") + .build()).setEphemeral(true).queue(); + return; + } + + // If the button is pressed inside a NSFW channel + if (!event.getChannel().asTextChannel().isNSFW() && module.getNsfwOnly()) { + event.replyEmbeds(new SimpleEmbedBuilder("ERROR - Button NSFW only") + .text( + "The button you used is only usable in a NSWF channel!", + "If you feel like this is a problem please contact a admin!" + ) + .error() + .setFooter("") + .build()).setEphemeral(true).queue(); + return; + } + + // TODO: Fix this ASAP AS WELL + +// // Get the member from the event +// Member member = event.getMember(); +// +// // If the member is allowed to use the button +// if(module.getDisabledUsers().contains(member.getIdLong())){ +// return; +// } +// if(!module.getEnabledUsers().isEmpty()){ +// if (!module.getEnabledUsers().contains(member.getIdLong())) { +// return; +// } +// } +// +// // If the member has the role to use the button +// if (member.getRoles().contains(module.getDisabledRoles())) { +// return; +// } +// if(!module.getEnabledRoles().isEmpty()){ +// if (member.getRoles().containsAll(module.getEnabledRoles())) { +// //run +// } +// } + + // If all checks are oke than execute the button logic + module.execute(event); + } + + /** + * Get the total amount of registered buttons + * + * @return Total registered buttons + */ + public int getTotal() { + return buttonList.size(); + } + +} diff --git a/src/main/java/com/greazi/discordbotfoundation/handlers/commands/SlashCommandHandler.java b/src/main/java/com/greazi/discordbotfoundation/handlers/commands/SlashCommandHandler.java index 467deec..4d5fc1b 100644 --- a/src/main/java/com/greazi/discordbotfoundation/handlers/commands/SlashCommandHandler.java +++ b/src/main/java/com/greazi/discordbotfoundation/handlers/commands/SlashCommandHandler.java @@ -1,200 +1,200 @@ -/* - * Copyright (c) 2021 - 2022. Greazi - All rights reservered - * - * Unauthorized copying of this file, via any medium is strictly prohibited - * Proprietary and confidential - */ - -package com.greazi.discordbotfoundation.handlers.commands; - -import com.greazi.discordbotfoundation.Common; -import com.greazi.discordbotfoundation.SimpleBot; -import com.greazi.discordbotfoundation.debug.Debugger; -import com.greazi.discordbotfoundation.utils.SimpleEmbedBuilder; -import com.greazi.discordbotfoundation.utils.color.ConsoleColor; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import net.dv8tion.jda.api.hooks.SubscribeEvent; -import net.dv8tion.jda.api.interactions.commands.build.*; -import org.jetbrains.annotations.NotNull; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - - -/** - * The slash command handler that handles the whole slash command event. - * Uses the information of {@link SimpleSlashCommand} - */ -public class SlashCommandHandler extends ListenerAdapter { - - // The hashmap and list of tall the slash commands - private final HashMap cmdList = new HashMap<>(); - private final List publicSlashCommands = new ArrayList<>(); - private final List mainGuildSlashCommands = new ArrayList<>(); - - /** - * The main slash command handler - */ - public SlashCommandHandler() { - Common.log("Initializing slash command handler"); - SimpleBot.getJDA().addEventListener(this); - } - - /** - * Add a slash command to the SlashCommand list - * - * @param module The SlashCommand module - * @return this - */ - public SlashCommandHandler addCommand(final SimpleSlashCommand module) { - // Retrieve the slash command data - final SlashCommandData command = Commands.slash(module.getCommand(), module.getDescription()); - - // add sub commands - final List moduleSubcommands = module.getSubCommands(); - for (final SubcommandData var : moduleSubcommands) { - command.addSubcommands(var); - } - - // Add sub command groups - final List moduleSubcommandGroup = module.getSubcommandGroup(); - for (final SubcommandGroupData var : moduleSubcommandGroup) { - command.addSubcommandGroups(var); - } - - // Get options if sub commands are empty - if (module.getSubCommands().isEmpty() && module.getSubcommandGroup().isEmpty() && !module.getOptions().isEmpty()) { - final List moduleOptions = module.getOptions(); - for (final OptionData var : moduleOptions) { - command.addOptions(var); - } - } - - // Set description - command.setDescription(module.getDescription()); - - - // TODO: When api has an update for the slash command system update it to that system - // Check it out here: https://github.com/DV8FromTheWorld/JDA/pull/2113 - // Add the slash command - if (module.getGuildOnly()) { - mainGuildSlashCommands.add(command); - Debugger.debug("SlashCommandRegistration", "Guild only for: " + command.getName()); - } else { - publicSlashCommands.add(command); - Debugger.debug("SlashCommandRegistration", "Public command for: " + command.getName()); - } - - // Add it to our internal list - cmdList.put(module.getCommand(), module); - - return this; - } - - /** - * Register all slash commands to JDA - */ - public void registerCommands() { -// for(Command command : SimpleBot.getJDA().retrieveCommands().complete()) { -// SimpleBot.getJDA().deleteCommandById(command.getIdLong()); -// } - - // Check if the slash commands isn't empty - if (mainGuildSlashCommands.isEmpty()) Common.warning("Be aware no main guild slash commands can be found!"); - if (publicSlashCommands.isEmpty()) Common.warning("Be aware no public slash commands can be found!"); - - Debugger.debug("SlashCommand", "Registering slash commands"); - - // Add all slash commands to the main guild - SimpleBot.getMainGuild().updateCommands() - .addCommands(mainGuildSlashCommands) - .queue(); - - // Add the commands to all the guilds PUBLIC!! - SimpleBot.getJDA().updateCommands() - .addCommands(publicSlashCommands) - .queue(); - } - - /** - * The main event listener for the slash command interaction event - * - * @param event SlashCommandInteractionEvent - */ - @Override - @SubscribeEvent - public void onSlashCommandInteraction(@NotNull final SlashCommandInteractionEvent event) { - Debugger.debug("SlashCommand", "A Slash Command has been used"); - - // Log who used a slash command - Common.log("User, " + ConsoleColor.CYAN + event.getMember().getEffectiveName() + ConsoleColor.RESET + " used Slash Command: " + ConsoleColor.CYAN + event.getCommandString() + ConsoleColor.RESET); - - // Retrieve the command class from the command that has been run - final SimpleSlashCommand module = cmdList.get(event.getName()); - - // If the module doesn't exist in the bot return an error - if (module == null) { - event.replyEmbeds(new SimpleEmbedBuilder("ERROR - command not found") - .text("The command that you have used does not exist or hasn't been activated!", - "Please contact an admin and report this error!") - .error() - .setFooter("") - .build()).setEphemeral(true).queue(); - return; - } - - // Get the guild of the button and the main guild of the bot - final Guild guild = event.getGuild(); - final Guild mainGuild = SimpleBot.getMainGuild(); - assert guild != null : "Event guild is null!"; - - // Check if the button is for the main guild only - if (!guild.getId().equals(mainGuild.getId()) && module.getGuildOnly()) { - event.replyEmbeds(new SimpleEmbedBuilder("ERROR - Button main guild only") - .text( - "The button you used is only usable in the main guild of this bot!", - "If you feel like this is a problem please contact a admin!" - ) - .error() - .setFooter("") - .build()).setEphemeral(true).queue(); - return; - } - - // Run the command logic - module.execute(event); - } - - // TODO: Make the total count better so it will show the actually registered commands with JDA instead of the count - // of the lists that are made - - /** - * Get the total amount of slash commands registered - * - * @return Total amount of slash commands - */ - public int getTotal() { - return cmdList.size(); - } - - /** - * Get the total amount of public registered slash commands - * - * @return Total amount of public slash commands - */ - public int getPublicTotal() { - return publicSlashCommands.size(); - } - - /** - * Get the total amount of private registered slash commands - * - * @return Total amount of private slash commands - */ - public int getGuildTotal() { - return mainGuildSlashCommands.size(); - } -} +/* + * Copyright (c) 2021 - 2022. Greazi - All rights reservered + * + * Unauthorized copying of this file, via any medium is strictly prohibited + * Proprietary and confidential + */ + +package com.greazi.discordbotfoundation.handlers.commands; + +import com.greazi.discordbotfoundation.Common; +import com.greazi.discordbotfoundation.SimpleBot; +import com.greazi.discordbotfoundation.debug.Debugger; +import com.greazi.discordbotfoundation.utils.SimpleEmbedBuilder; +import com.greazi.discordbotfoundation.utils.color.ConsoleColor; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; +import net.dv8tion.jda.api.hooks.SubscribeEvent; +import net.dv8tion.jda.api.interactions.commands.build.*; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + + +/** + * The slash command handler that handles the whole slash command event. + * Uses the information of {@link SimpleSlashCommand} + */ +public class SlashCommandHandler extends ListenerAdapter { + + // The hashmap and list of tall the slash commands + private final HashMap cmdList = new HashMap<>(); + private final List publicSlashCommands = new ArrayList<>(); + private final List mainGuildSlashCommands = new ArrayList<>(); + + /** + * The main slash command handler + */ + public SlashCommandHandler() { + Common.log("Initializing slash command handler"); + SimpleBot.getJDA().addEventListener(this); + } + + /** + * Add a slash command to the SlashCommand list + * + * @param module The SlashCommand module + * @return this + */ + public SlashCommandHandler addCommand(final SimpleSlashCommand module) { + // Retrieve the slash command data + final SlashCommandData command = Commands.slash(module.getCommand(), module.getDescription()); + + // add sub commands + final List moduleSubcommands = module.getSubCommands(); + for (final SubcommandData var : moduleSubcommands) { + command.addSubcommands(var); + } + + // Add sub command groups + final List moduleSubcommandGroup = module.getSubcommandGroup(); + for (final SubcommandGroupData var : moduleSubcommandGroup) { + command.addSubcommandGroups(var); + } + + // Get options if sub commands are empty + if (module.getSubCommands().isEmpty() && module.getSubcommandGroup().isEmpty() && !module.getOptions().isEmpty()) { + final List moduleOptions = module.getOptions(); + for (final OptionData var : moduleOptions) { + command.addOptions(var); + } + } + + // Set description + command.setDescription(module.getDescription()); + + + // TODO: When api has an update for the slash command system update it to that system + // Check it out here: https://github.com/DV8FromTheWorld/JDA/pull/2113 + // Add the slash command + if (module.getGuildOnly()) { + mainGuildSlashCommands.add(command); + Debugger.debug("SlashCommandRegistration", "Guild only for: " + command.getName()); + } else { + publicSlashCommands.add(command); + Debugger.debug("SlashCommandRegistration", "Public command for: " + command.getName()); + } + + // Add it to our internal list + cmdList.put(module.getCommand(), module); + + return this; + } + + /** + * Register all slash commands to JDA + */ + public void registerCommands() { +// for(Command command : SimpleBot.getJDA().retrieveCommands().complete()) { +// SimpleBot.getJDA().deleteCommandById(command.getIdLong()); +// } + + // Check if the slash commands isn't empty + if (mainGuildSlashCommands.isEmpty()) Common.warning("Be aware no main guild slash commands can be found!"); + if (publicSlashCommands.isEmpty()) Common.warning("Be aware no public slash commands can be found!"); + + Debugger.debug("SlashCommand", "Registering slash commands"); + + // Add all slash commands to the main guild + SimpleBot.getMainGuild().updateCommands() + .addCommands(mainGuildSlashCommands) + .queue(); + + // Add the commands to all the guilds PUBLIC!! + SimpleBot.getJDA().updateCommands() + .addCommands(publicSlashCommands) + .queue(); + } + + /** + * The main event listener for the slash command interaction event + * + * @param event SlashCommandInteractionEvent + */ + @Override + @SubscribeEvent + public void onSlashCommandInteraction(@NotNull final SlashCommandInteractionEvent event) { + Debugger.debug("SlashCommand", "A Slash Command has been used"); + + // Log who used a slash command + Common.log("User, " + ConsoleColor.CYAN + event.getMember().getEffectiveName() + ConsoleColor.RESET + " used Slash Command: " + ConsoleColor.CYAN + event.getCommandString() + ConsoleColor.RESET); + + // Retrieve the command class from the command that has been run + final SimpleSlashCommand module = cmdList.get(event.getName()); + + // If the module doesn't exist in the bot return an error + if (module == null) { + event.replyEmbeds(new SimpleEmbedBuilder("ERROR - command not found") + .text("The command that you have used does not exist or hasn't been activated!", + "Please contact an admin and report this error!") + .error() + .setFooter("") + .build()).setEphemeral(true).queue(); + return; + } + + // Get the guild of the button and the main guild of the bot + final Guild guild = event.getGuild(); + final Guild mainGuild = SimpleBot.getMainGuild(); + assert guild != null : "Event guild is null!"; + + // Check if the button is for the main guild only + if (!guild.getId().equals(mainGuild.getId()) && module.getGuildOnly()) { + event.replyEmbeds(new SimpleEmbedBuilder("ERROR - Button main guild only") + .text( + "The button you used is only usable in the main guild of this bot!", + "If you feel like this is a problem please contact a admin!" + ) + .error() + .setFooter("") + .build()).setEphemeral(true).queue(); + return; + } + + // Run the command logic + module.execute(event); + } + + // TODO: Make the total count better so it will show the actually registered commands with JDA instead of the count + // of the lists that are made + + /** + * Get the total amount of slash commands registered + * + * @return Total amount of slash commands + */ + public int getTotal() { + return cmdList.size(); + } + + /** + * Get the total amount of public registered slash commands + * + * @return Total amount of public slash commands + */ + public int getPublicTotal() { + return publicSlashCommands.size(); + } + + /** + * Get the total amount of private registered slash commands + * + * @return Total amount of private slash commands + */ + public int getGuildTotal() { + return mainGuildSlashCommands.size(); + } +} diff --git a/src/main/java/com/greazi/discordbotfoundation/handlers/modals/SimpleModal.java b/src/main/java/com/greazi/discordbotfoundation/handlers/modals/SimpleModal.java index 9afb6d5..c2721b9 100644 --- a/src/main/java/com/greazi/discordbotfoundation/handlers/modals/SimpleModal.java +++ b/src/main/java/com/greazi/discordbotfoundation/handlers/modals/SimpleModal.java @@ -1,203 +1,203 @@ -package com.greazi.discordbotfoundation.handlers.modals; - -import com.greazi.discordbotfoundation.SimpleBot; -import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent; -import net.dv8tion.jda.api.interactions.modals.Modal; - -import java.util.LinkedHashMap; - -public abstract class SimpleModal { - - // ---------------------------------------------------------------------------------------- - // Main options - // ---------------------------------------------------------------------------------------- - - private String id = "id"; - - private String title = "example"; - - private boolean guildOnly = false; - - private LinkedHashMap textInputs = new LinkedHashMap<>(); - - // Disabled because select menus are not compatible with modals - //private LinkedHashMap selectMenus = new LinkedHashMap<>(); - - // Disabled because buttons are not compatible with modals - //private ArrayList buttonIds = new ArrayList<>(); - - // ---------------------------------------------------------------------------------------- - // Main methods - // ---------------------------------------------------------------------------------------- - - /** - * Run the modal logic - * - * @param event ModalInteractionEvent - */ - protected abstract void execute(ModalInteractionEvent event); - - // ---------------------------------------------------------------------------------------- - // Setters - // ---------------------------------------------------------------------------------------- - - /** - * Set the id - */ - public SimpleModal(final String id) { - this.id = id; - } - - /** - * Set the title - */ - public void title(final String title) { - this.title = title; - } - - /** - * Add a textInput - */ - public void textInput(final SimpleTextInput textInput) { - this.textInputs.put(textInput.getId(), textInput); - } - - /** - * Add multiple textInputs - */ - public void textInputs(final SimpleTextInput... textInputs) { - for (final SimpleTextInput textInput : textInputs) { - this.textInputs.put(textInput.getId(), textInput); - } - } - - /** - * Set the textInputs - */ - public void textInputs(final LinkedHashMap textInputs) { - this.textInputs = textInputs; - } - - // Disabled because select menus are not compatible with modals -// /** -// * Set the selectMenus -// */ -// public void setSelectMenus(LinkedHashMap selectMenus) { -// this.selectMenus = selectMenus; -// } - - // Disabled because select menus are not compatible with modals -// /** -// * Add a selectMenu -// */ -// public void addSelectInput(SimpleSelect selectMenu) { -// this.selectMenus.put(selectMenu.getId(), selectMenu); -// } - - // Disabled because button are not compatible with modals -// /** -// * Set the buttons -// */ -// public void setButtons(ArrayList buttonIds) { -// this.buttonIds = buttonIds; -// } - - // Disabled because button are not compatible with modals -// /** -// * Add a button -// */ -// public void addButton(SimpleButton button) { -// this.buttonIds.add(button.getButton()); -// } - - // Disabled because button are not compatible with modals -// /** -// * Add a button -// */ -// public void addButton(String buttonId) { -// this.buttonIds.add(buttonId); -// } - - /** - * Set this modal as main guild only - */ - public void mainGuildOnly() { - this.guildOnly = true; - } - - // ---------------------------------------------------------------------------------------- - // Getters - // ---------------------------------------------------------------------------------------- - - /** - * Get the id - * - * @return the id - */ - public String getId() { - return id; - } - - /** - * Get the title - * - * @return the title - */ - public String getTitle() { - return title; - } - - /** - * Whether the button is restricted to the main guild of the bot - * - * @return the restricted guild - */ - public boolean isMainGuildOnly() { - return guildOnly; - } - - /** - * Get the textInputs - * - * @return the textInputs - */ - public LinkedHashMap getTextInputs() { - return textInputs; - } - - /** - * Get a textInput - * - * @return the textInput - */ - public SimpleTextInput getTextInput(final String id) { - return textInputs.get(id); - } - - /** - * Get the modal - * - * @return the modal - */ - public Modal build() { - final Modal.Builder modalBuilder = Modal.create(this.id, this.title); - - this.textInputs.forEach((id, textInput) -> { - modalBuilder.addActionRow(textInput.build()); - }); - // Disabled because select menus are not compatible with modals -// this.selectMenus.forEach((id, selectMenu) -> { -// modalBuilder.addActionRow(selectMenu.build()); -// }); - // Disabled because button are not compatible with modals -// this.buttonIds.forEach(buttonId -> { -// SimpleButton button = SimpleBot.getButtonHandler().getButton(buttonId); -// modalBuilder.addActionRow(button.build()); -// }); - - SimpleBot.getModalHandler().addModalListener(this); - - return modalBuilder.build(); - } - -} +package com.greazi.discordbotfoundation.handlers.modals; + +import com.greazi.discordbotfoundation.SimpleBot; +import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent; +import net.dv8tion.jda.api.interactions.modals.Modal; + +import java.util.LinkedHashMap; + +public abstract class SimpleModal { + + // ---------------------------------------------------------------------------------------- + // Main options + // ---------------------------------------------------------------------------------------- + + private String id = "id"; + + private String title = "example"; + + private boolean guildOnly = false; + + private LinkedHashMap textInputs = new LinkedHashMap<>(); + + // Disabled because select menus are not compatible with modals + //private LinkedHashMap selectMenus = new LinkedHashMap<>(); + + // Disabled because buttons are not compatible with modals + //private ArrayList buttonIds = new ArrayList<>(); + + // ---------------------------------------------------------------------------------------- + // Main methods + // ---------------------------------------------------------------------------------------- + + /** + * Run the modal logic + * + * @param event ModalInteractionEvent + */ + protected abstract void execute(ModalInteractionEvent event); + + // ---------------------------------------------------------------------------------------- + // Setters + // ---------------------------------------------------------------------------------------- + + /** + * Set the id + */ + public SimpleModal(final String id) { + this.id = id; + } + + /** + * Set the title + */ + public void title(final String title) { + this.title = title; + } + + /** + * Add a textInput + */ + public void textInput(final SimpleTextInput textInput) { + this.textInputs.put(textInput.getId(), textInput); + } + + /** + * Add multiple textInputs + */ + public void textInputs(final SimpleTextInput... textInputs) { + for (final SimpleTextInput textInput : textInputs) { + this.textInputs.put(textInput.getId(), textInput); + } + } + + /** + * Set the textInputs + */ + public void textInputs(final LinkedHashMap textInputs) { + this.textInputs = textInputs; + } + + // Disabled because select menus are not compatible with modals +// /** +// * Set the selectMenus +// */ +// public void setSelectMenus(LinkedHashMap selectMenus) { +// this.selectMenus = selectMenus; +// } + + // Disabled because select menus are not compatible with modals +// /** +// * Add a selectMenu +// */ +// public void addSelectInput(SimpleSelect selectMenu) { +// this.selectMenus.put(selectMenu.getId(), selectMenu); +// } + + // Disabled because button are not compatible with modals +// /** +// * Set the buttons +// */ +// public void setButtons(ArrayList buttonIds) { +// this.buttonIds = buttonIds; +// } + + // Disabled because button are not compatible with modals +// /** +// * Add a button +// */ +// public void addButton(SimpleButton button) { +// this.buttonIds.add(button.getButton()); +// } + + // Disabled because button are not compatible with modals +// /** +// * Add a button +// */ +// public void addButton(String buttonId) { +// this.buttonIds.add(buttonId); +// } + + /** + * Set this modal as main guild only + */ + public void mainGuildOnly() { + this.guildOnly = true; + } + + // ---------------------------------------------------------------------------------------- + // Getters + // ---------------------------------------------------------------------------------------- + + /** + * Get the id + * + * @return the id + */ + public String getId() { + return id; + } + + /** + * Get the title + * + * @return the title + */ + public String getTitle() { + return title; + } + + /** + * Whether the button is restricted to the main guild of the bot + * + * @return the restricted guild + */ + public boolean isMainGuildOnly() { + return guildOnly; + } + + /** + * Get the textInputs + * + * @return the textInputs + */ + public LinkedHashMap getTextInputs() { + return textInputs; + } + + /** + * Get a textInput + * + * @return the textInput + */ + public SimpleTextInput getTextInput(final String id) { + return textInputs.get(id); + } + + /** + * Get the modal + * + * @return the modal + */ + public Modal build() { + final Modal.Builder modalBuilder = Modal.create(this.id, this.title); + + this.textInputs.forEach((id, textInput) -> { + modalBuilder.addActionRow(textInput.build()); + }); + // Disabled because select menus are not compatible with modals +// this.selectMenus.forEach((id, selectMenu) -> { +// modalBuilder.addActionRow(selectMenu.build()); +// }); + // Disabled because button are not compatible with modals +// this.buttonIds.forEach(buttonId -> { +// SimpleButton button = SimpleBot.getButtonHandler().getButton(buttonId); +// modalBuilder.addActionRow(button.build()); +// }); + + SimpleBot.getModalHandler().addModalListener(this); + + return modalBuilder.build(); + } + +} diff --git a/src/main/java/com/greazi/discordbotfoundation/handlers/selectmenu/SelectMenuHandler.java b/src/main/java/com/greazi/discordbotfoundation/handlers/selectmenu/SelectMenuHandler.java index 764c0c6..6bad814 100644 --- a/src/main/java/com/greazi/discordbotfoundation/handlers/selectmenu/SelectMenuHandler.java +++ b/src/main/java/com/greazi/discordbotfoundation/handlers/selectmenu/SelectMenuHandler.java @@ -1,92 +1,92 @@ -package com.greazi.discordbotfoundation.handlers.selectmenu; - -import com.greazi.discordbotfoundation.Common; -import com.greazi.discordbotfoundation.SimpleBot; -import com.greazi.discordbotfoundation.debug.Debugger; -import com.greazi.discordbotfoundation.utils.SimpleEmbedBuilder; -import com.greazi.discordbotfoundation.utils.color.ConsoleColor; -import net.dv8tion.jda.api.events.interaction.component.StringSelectInteractionEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import net.dv8tion.jda.api.hooks.SubscribeEvent; -import org.jetbrains.annotations.NotNull; - -import java.util.HashMap; - -/** - * The selection menu andler that handles the whole selection menu event. - * Uses the information of {@link SimpleSelectMenu} - */ -public class SelectMenuHandler extends ListenerAdapter { - - /** - * The HasMap for the menus - */ - private final HashMap menuList = new HashMap<>(); - - /** - * The select menu handler - */ - public SelectMenuHandler() { - SimpleBot.getJDA().addEventListener(this); - } - - /** - * Add a new Menu Listener - * - * @param module - * @return this - */ - public SelectMenuHandler addMenuListener(final SimpleSelectMenu module) { - menuList.put(module.getId(), module); - return this; - } - - /** - * Get a menu by its ID - * - * @param modal_id - * @return The menu from an id - */ - public SimpleSelectMenu getMenu(final String modal_id) { - return menuList.get(modal_id); - } - - /** - * The event listener for menus - * - * @param event SelectMenuInteractionEvent - */ - @SubscribeEvent - public void onSelectMenuInteraction(@NotNull final StringSelectInteractionEvent event) { - Debugger.debug("SelectMenu", "A menu has been filled in"); - - // Get the list of menus - final SimpleSelectMenu module = menuList.get(event.getSelectMenu().getId()); - - Common.log("User, " + ConsoleColor.CYAN + event.getMember().getEffectiveName() + ConsoleColor.RESET + " used Menu: " + ConsoleColor.CYAN + event.getId() + ConsoleColor.RESET); - - // Check if the select menu exists - if (module == null) { - event.replyEmbeds(new SimpleEmbedBuilder("ERROR - menu not found") - .text("The select menu you used does not exist or hasn't been activated!", - "Please contact an admin and report this error!") - .error() - .setFooter("") - .build()).setEphemeral(true).queue(); - return; - } - - Debugger.debug("SelectMenu", "Executing Menu logic"); - // Execute the menu logic - module.execute(event); - } - - /** - * Get the total amount of menus registered - * - * @return Total amount of menus - */ - public int getTotal() { - return menuList.size(); - } -} +package com.greazi.discordbotfoundation.handlers.selectmenu; + +import com.greazi.discordbotfoundation.Common; +import com.greazi.discordbotfoundation.SimpleBot; +import com.greazi.discordbotfoundation.debug.Debugger; +import com.greazi.discordbotfoundation.utils.SimpleEmbedBuilder; +import com.greazi.discordbotfoundation.utils.color.ConsoleColor; +import net.dv8tion.jda.api.events.interaction.component.StringSelectInteractionEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; +import net.dv8tion.jda.api.hooks.SubscribeEvent; +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; + +/** + * The selection menu andler that handles the whole selection menu event. + * Uses the information of {@link SimpleSelectMenu} + */ +public class SelectMenuHandler extends ListenerAdapter { + + /** + * The HasMap for the menus + */ + private final HashMap menuList = new HashMap<>(); + + /** + * The select menu handler + */ + public SelectMenuHandler() { + SimpleBot.getJDA().addEventListener(this); + } + + /** + * Add a new Menu Listener + * + * @param module + * @return this + */ + public SelectMenuHandler addMenuListener(final SimpleSelectMenu module) { + menuList.put(module.getId(), module); + return this; + } + + /** + * Get a menu by its ID + * + * @param modal_id + * @return The menu from an id + */ + public SimpleSelectMenu getMenu(final String modal_id) { + return menuList.get(modal_id); + } + + /** + * The event listener for menus + * + * @param event SelectMenuInteractionEvent + */ + @SubscribeEvent + public void onSelectMenuInteraction(@NotNull final StringSelectInteractionEvent event) { + Debugger.debug("SelectMenu", "A menu has been filled in"); + + // Get the list of menus + final SimpleSelectMenu module = menuList.get(event.getSelectMenu().getId()); + + Common.log("User, " + ConsoleColor.CYAN + event.getMember().getEffectiveName() + ConsoleColor.RESET + " used Menu: " + ConsoleColor.CYAN + event.getId() + ConsoleColor.RESET); + + // Check if the select menu exists + if (module == null) { + event.replyEmbeds(new SimpleEmbedBuilder("ERROR - menu not found") + .text("The select menu you used does not exist or hasn't been activated!", + "Please contact an admin and report this error!") + .error() + .setFooter("") + .build()).setEphemeral(true).queue(); + return; + } + + Debugger.debug("SelectMenu", "Executing Menu logic"); + // Execute the menu logic + module.execute(event); + } + + /** + * Get the total amount of menus registered + * + * @return Total amount of menus + */ + public int getTotal() { + return menuList.size(); + } +}