From 9a8a7693aea1ca3dcdeeed2b95e2e0770518689d Mon Sep 17 00:00:00 2001 From: SebClem Date: Fri, 10 Jun 2022 13:15:32 +0200 Subject: [PATCH] :hammer: migrate env to config prop --- .../net/Broken/Api/Services/GuildService.java | 1 - src/main/java/net/Broken/BotConfigLoader.java | 13 ++ src/main/java/net/Broken/BotListener.java | 6 +- src/main/java/net/Broken/Init.java | 113 +++--------------- src/main/java/net/Broken/MainBot.java | 32 ++--- .../java/net/Broken/SlashCommands/Rank.java | 5 +- .../Broken/Tools/Command/CommandLoader.java | 58 --------- .../Tools/Command/SlashCommandLoader.java | 5 +- .../net/Broken/Tools/EmbedMessageUtils.java | 45 +++++-- .../java/net/Broken/Tools/TrueRandom.java | 13 +- src/main/resources/application.yml | 15 +-- 11 files changed, 103 insertions(+), 203 deletions(-) create mode 100644 src/main/java/net/Broken/BotConfigLoader.java delete mode 100644 src/main/java/net/Broken/Tools/Command/CommandLoader.java diff --git a/src/main/java/net/Broken/Api/Services/GuildService.java b/src/main/java/net/Broken/Api/Services/GuildService.java index 9a3602c..d5d3582 100644 --- a/src/main/java/net/Broken/Api/Services/GuildService.java +++ b/src/main/java/net/Broken/Api/Services/GuildService.java @@ -2,7 +2,6 @@ package net.Broken.Api.Services; import net.Broken.Api.Data.Guild; import net.Broken.DB.Entity.UserEntity; -import net.Broken.MainBot; import net.Broken.Tools.CacheTools; import net.dv8tion.jda.api.entities.User; import org.springframework.stereotype.Service; diff --git a/src/main/java/net/Broken/BotConfigLoader.java b/src/main/java/net/Broken/BotConfigLoader.java new file mode 100644 index 0000000..702cbe9 --- /dev/null +++ b/src/main/java/net/Broken/BotConfigLoader.java @@ -0,0 +1,13 @@ +package net.Broken; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.ConstructorBinding; +import org.springframework.context.annotation.Configuration; +@ConfigurationProperties(prefix = "discord.bot") +@ConstructorBinding +public record BotConfigLoader ( + String token, + String url, + String mode, + String randomApiKey +){} diff --git a/src/main/java/net/Broken/BotListener.java b/src/main/java/net/Broken/BotListener.java index 03214c4..fcac4cf 100644 --- a/src/main/java/net/Broken/BotListener.java +++ b/src/main/java/net/Broken/BotListener.java @@ -35,12 +35,14 @@ import java.util.List; */ public class BotListener extends ListenerAdapter { private final GuildPreferenceRepository guildPreferenceRepository; + private final BotConfigLoader botConfig; private final Logger logger = LogManager.getLogger(); public BotListener() { ApplicationContext context = SpringContext.getAppContext(); - guildPreferenceRepository = (GuildPreferenceRepository) context.getBean("guildPreferenceRepository"); + guildPreferenceRepository = context.getBean(GuildPreferenceRepository.class); + botConfig = context.getBean(BotConfigLoader.class); } @Override @@ -194,7 +196,7 @@ public class BotListener extends ListenerAdapter { EmbedBuilder eb = new EmbedBuilder().setColor(Color.GREEN) .setTitle("Hello there !") .setDescription("Allow me to introduce myself -- I am a CL4P-TP the discord bot, but my friends call me Claptrap ! Or they would, if any of them were real...\n" + - "\nYou can access to my web UI with: " + MainBot.url) + "\nYou can access to my web UI with: " + botConfig.url()) .setImage("https://i.imgur.com/Anf1Srg.gif"); Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.buildStandar(eb)).build(); diff --git a/src/main/java/net/Broken/Init.java b/src/main/java/net/Broken/Init.java index 3c7f9cd..a773e04 100644 --- a/src/main/java/net/Broken/Init.java +++ b/src/main/java/net/Broken/Init.java @@ -3,7 +3,6 @@ package net.Broken; import net.Broken.DB.Entity.UserEntity; import net.Broken.DB.Repository.UserRepository; import net.Broken.RestApi.ApiCommandLoader; -import net.Broken.Tools.Command.CommandLoader; import net.Broken.Tools.Command.SlashCommandLoader; import net.Broken.Tools.DayListener.DayListener; import net.Broken.Tools.DayListener.Listeners.DailyMadame; @@ -24,78 +23,56 @@ import java.util.List; public class Init { - static private Logger logger = LogManager.getLogger(); + static private final Logger logger = LogManager.getLogger(); - /** - * Initialize all bot functionality - * - * @param token bot user token - * @return JDA object - */ - static JDA initJda(String token) { - JDA jda = null; + static JDA initJda(BotConfigLoader config) { logger.info("-----------------------INIT-----------------------"); - - //Bot démarrer sans token - if (token == null) { + if (config == null) { logger.fatal("Please enter bot token as an argument."); + return null; } else { - //Token présent try { - logger.info("Connecting to Discord api..."); - //connection au bot - JDABuilder jdaB = JDABuilder.createDefault(token).enableIntents(GatewayIntent.GUILD_MEMBERS) - .setMemberCachePolicy(MemberCachePolicy.ALL); - jdaB.setBulkDeleteSplittingEnabled(false); - jda = jdaB.build(); - jda = jda.awaitReady(); - MainBot.jda = jda; - jda.setAutoReconnect(true); + JDA jda = JDABuilder + .createDefault(config.token()) + .enableIntents(GatewayIntent.GUILD_MEMBERS) + .setMemberCachePolicy(MemberCachePolicy.ALL) + .setBulkDeleteSplittingEnabled(false) + .build(); - /************************************* - * Definition des commande * - *************************************/ + jda.awaitReady() + .setAutoReconnect(true); jda.getPresence().setPresence(OnlineStatus.DO_NOT_DISTURB, Activity.playing("Loading...")); - - //On recupere le l'id serveur - logger.info("Connected on " + jda.getGuilds().size() + " Guilds:"); - for (Guild server : jda.getGuilds()) { server.loadMembers().get(); - //on recupere les utilisateur logger.info("... " + server.getName() + " " + server.getMembers().size() + " Members"); } - - + return jda; } catch (LoginException | InterruptedException e) { logger.catching(e); + return null; } } - - return jda; } - static void polish(JDA jda) { + static void polish(JDA jda, BotConfigLoader config) { logger.info("Check database..."); checkDatabase(); - CommandLoader.load(); - SlashCommandLoader.load(); + logger.info("Loading commands"); + SlashCommandLoader.load(config); SlashCommandLoader.registerSlashCommands(jda.updateCommands()); ApiCommandLoader.load(); DayListener dayListener = DayListener.getInstance(); dayListener.addListener(new DailyMadame()); dayListener.start(); jda.addEventListener(new BotListener()); - jda.getPresence().setPresence(OnlineStatus.ONLINE, Activity.playing(MainBot.url)); + jda.getPresence().setPresence(OnlineStatus.ONLINE, Activity.playing(config.url())); logger.info("-----------------------END INIT-----------------------"); - - } @@ -113,58 +90,4 @@ public class Init { } - - - public static boolean checkEnv() { - boolean ok = true; - - - if (System.getenv("PORT") == null) { - logger.fatal("Missing PORT ENV variable."); - ok = false; - } - - if (System.getenv("DB_URL") == null) { - logger.fatal("Missing DB_URL ENV variable."); - ok = false; - } - - if (System.getenv("DB_USER") == null) { - logger.fatal("Missing DB_USER ENV variable."); - ok = false; - } - - - if (System.getenv("DB_PWD") == null) { - logger.fatal("Missing DB_PWD ENV variable."); - ok = false; - } - - if (System.getenv("OAUTH_URL") == null) { - logger.fatal("Missing OAUTH_URL ENV variable."); - ok = false; - } - - if (System.getenv("DISCORD_TOKEN") == null) { - logger.fatal("Missing DISCORD_TOKEN ENV variable."); - ok = false; - } - - if (System.getenv("GOOGLE_API_KEY") == null) { - logger.fatal("Missing GOOGLE_API_KEY ENV variable."); - ok = false; - } - - if (System.getenv("RANDOM_API_KEY") == null) { - logger.fatal("Missing GOOGLE_API_KEY ENV variable."); - ok = false; - } - - if (System.getenv("LOG_LEVEL") == null) { - logger.fatal("Missing LOG_LEVEL ENV variable."); - ok = false; - } - - return ok; - } } diff --git a/src/main/java/net/Broken/MainBot.java b/src/main/java/net/Broken/MainBot.java index a967cc7..98e7144 100644 --- a/src/main/java/net/Broken/MainBot.java +++ b/src/main/java/net/Broken/MainBot.java @@ -1,24 +1,21 @@ package net.Broken; import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.boot.ExitCodeGenerator; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.ConfigurationPropertiesScan; import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.stereotype.Controller; -import java.util.ArrayList; import java.util.HashMap; /** * Main Class */ @SpringBootApplication -@Controller +@ConfigurationPropertiesScan public class MainBot { public static HashMap commandes = new HashMap<>(); @@ -27,37 +24,23 @@ public class MainBot { public static boolean roleFlag = false; public static JDA jda; public static boolean ready = false; - public static boolean dev = false; - - public static String url = "claptrapbot.com"; - public static int messageTimeOut = 10; public static int gifMessageTimeOut = 30; - private static Logger logger = LogManager.getLogger(); + private static final Logger logger = LogManager.getLogger(); public static void main(String[] args) { - - if (!Init.checkEnv()) - System.exit(1); + ConfigurableApplicationContext ctx = SpringApplication.run(MainBot.class, args); + BotConfigLoader config = ctx.getBean(BotConfigLoader.class); logger.info("======================================="); logger.info("--------------Starting Bot-------------"); logger.info("======================================="); - if (System.getenv("DEV") != null) { - dev = Boolean.parseBoolean(System.getenv("DEV")); - } - - String token = System.getenv("DISCORD_TOKEN"); - - jda = Init.initJda(token); - - - ConfigurableApplicationContext ctx = SpringApplication.run(MainBot.class, args); + jda = Init.initJda(config); if (jda == null) { System.exit(SpringApplication.exit(ctx, (ExitCodeGenerator) () -> { logger.fatal("Init error! Close application!"); @@ -65,8 +48,7 @@ public class MainBot { })); } - Init.polish(jda); + Init.polish(jda, config); ready = true; - } } diff --git a/src/main/java/net/Broken/SlashCommands/Rank.java b/src/main/java/net/Broken/SlashCommands/Rank.java index 46e71ff..762edeb 100644 --- a/src/main/java/net/Broken/SlashCommands/Rank.java +++ b/src/main/java/net/Broken/SlashCommands/Rank.java @@ -1,7 +1,9 @@ package net.Broken.SlashCommands; +import net.Broken.BotConfigLoader; import net.Broken.MainBot; import net.Broken.SlashCommand; +import net.Broken.SpringContext; import net.Broken.Tools.UserManager.Stats.UserStatsUtils; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; @@ -14,11 +16,12 @@ import java.util.List; public class Rank implements SlashCommand { @Override public void action(SlashCommandEvent event) { + String url = SpringContext.getAppContext().getBean(BotConfigLoader.class).url(); event.deferReply().queue(); UserStatsUtils userStats = UserStatsUtils.getINSTANCE(); MessageEmbed messageEmbed = userStats.getRankMessage(event.getMember()); event.getHook().sendMessageEmbeds(messageEmbed).addActionRow( - Button.link("https://" + MainBot.url + "/rank", "More stats") + Button.link("https://" + url + "/rank", "More stats") ).queue(); } diff --git a/src/main/java/net/Broken/Tools/Command/CommandLoader.java b/src/main/java/net/Broken/Tools/Command/CommandLoader.java deleted file mode 100644 index 182c136..0000000 --- a/src/main/java/net/Broken/Tools/Command/CommandLoader.java +++ /dev/null @@ -1,58 +0,0 @@ -package net.Broken.Tools.Command; - -import net.Broken.Commande; -import net.Broken.MainBot; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.reflections.Reflections; -import org.reflections.util.ClasspathHelper; -import org.reflections.util.ConfigurationBuilder; - -import java.util.Set; - - -/** - * Find and load bot's command - */ -public class CommandLoader { - private static Logger logger = LogManager.getLogger(); - - /** - * Search all implemented Command interface class and add it to MainBot.commands HashMap - */ - public static void load() { - logger.info("Loading Command..."); - Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage( - "net.Broken.Commands", - ClasspathHelper.contextClassLoader(), - ClasspathHelper.staticClassLoader())) - ); - Set> modules = reflections.getSubTypesOf(Commande.class); - - logger.info("Find " + modules.size() + " Command:"); - for (Class command : modules) { - - String reference = command.getName(); - String[] splited = reference.split("\\."); - String name = splited[splited.length - 1].toLowerCase(); - if (!command.isAnnotationPresent(Ignore.class)) { - logger.info("..." + name); - - if (command.isAnnotationPresent(NoDev.class) && MainBot.dev) { - logger.warn("Command disabled in dev mode"); - } else { - try { - MainBot.commandes.put(name, command.newInstance()); - } catch (InstantiationException | IllegalAccessException e) { - logger.error("Failed to load " + name + "!"); - } - - } - - } else { - logger.trace("Ignored command: " + name); - } - - } - } -} diff --git a/src/main/java/net/Broken/Tools/Command/SlashCommandLoader.java b/src/main/java/net/Broken/Tools/Command/SlashCommandLoader.java index 2af7628..35152ea 100644 --- a/src/main/java/net/Broken/Tools/Command/SlashCommandLoader.java +++ b/src/main/java/net/Broken/Tools/Command/SlashCommandLoader.java @@ -1,5 +1,6 @@ package net.Broken.Tools.Command; +import net.Broken.BotConfigLoader; import net.Broken.MainBot; import net.Broken.SlashCommand; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -23,7 +24,7 @@ public class SlashCommandLoader { /** * Search all implemented Command interface class and add it to MainBot.commands HashMap */ - public static void load() { + public static void load(BotConfigLoader config) { logger.info("Loading Slash Command..."); Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage( "net.Broken.SlashCommands", @@ -41,7 +42,7 @@ public class SlashCommandLoader { if (!command.isAnnotationPresent(Ignore.class)) { logger.info("..." + name); - if (command.isAnnotationPresent(NoDev.class) && MainBot.dev) { + if (command.isAnnotationPresent(NoDev.class) && config.mode().equals("DEV")) { logger.warn("Command disabled in dev mode"); } else { try { diff --git a/src/main/java/net/Broken/Tools/EmbedMessageUtils.java b/src/main/java/net/Broken/Tools/EmbedMessageUtils.java index b0a98f5..fa81434 100644 --- a/src/main/java/net/Broken/Tools/EmbedMessageUtils.java +++ b/src/main/java/net/Broken/Tools/EmbedMessageUtils.java @@ -1,13 +1,16 @@ package net.Broken.Tools; import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; +import net.Broken.BotConfigLoader; import net.Broken.MainBot; +import net.Broken.SpringContext; import net.Broken.audio.UserAudioTrack; import net.Broken.audio.Youtube.SearchResult; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.User; +import org.springframework.context.ApplicationContext; import java.awt.*; import java.io.FileNotFoundException; @@ -21,18 +24,26 @@ import java.util.Map; public class EmbedMessageUtils { public static EmbedBuilder getError(String message) { - EmbedBuilder temp = new EmbedBuilder().setTitle(":warning: Error!").setColor(Color.red).setDescription(message); + EmbedBuilder temp = new EmbedBuilder() + .setTitle(":warning: Error!") + .setColor(Color.red) + .setDescription(message); return temp; } public static MessageEmbed getMusicError(String message) { - return new EmbedBuilder().setTitle(":warning: Musique Error").setDescription(":arrow_right: " + message).setFooter("'//help music' for more info.", MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).setColor(Color.red).setFooter(MainBot.url, MainBot.jda.getSelfUser().getAvatarUrl()).build(); + return buildStandar(new EmbedBuilder() + .setTitle(":warning: Musique Error") + .setDescription(":arrow_right: " + message) + .setColor(Color.red)); } public static MessageEmbed getMusicOk(String message) { // TODO better display for different action (add icon ?) - EmbedBuilder temp = new EmbedBuilder().setTitle(":loud_sound: " + message).setColor(Color.green); + EmbedBuilder temp = new EmbedBuilder() + .setTitle(":loud_sound: " + message) + .setColor(Color.green); return buildStandar(temp); } @@ -66,16 +77,25 @@ public class EmbedMessageUtils { } public static MessageEmbed getFlushError(String message) { - return buildStandar(new EmbedBuilder().setTitle(":warning: Flush Error").setDescription(message).setColor(Color.red)); + return buildStandar(new EmbedBuilder() + .setTitle(":warning: Flush Error") + .setDescription(message) + .setColor(Color.red)); } public static MessageEmbed getInternalError() { - return buildStandar(getError("I... I... I don't feel so good ~~mr stark~~... :thermometer_face: \nPlease contact my developer!").setImage("https://i.imgur.com/anKv8U5.gif")); + return buildStandar( + getError("I... I... I don't feel so good ~~mr stark~~... :thermometer_face: \nPlease contact my developer!") + .setImage("https://i.imgur.com/anKv8U5.gif")); } public static MessageEmbed buildStandar(EmbedBuilder embedBuilder) { - return embedBuilder.setFooter(MainBot.url, MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).build(); + BotConfigLoader config = SpringContext.getAppContext().getBean(BotConfigLoader.class); + return embedBuilder + .setFooter(config.url(), MainBot.jda.getSelfUser().getAvatarUrl()) + .setTimestamp(Instant.now()) + .build(); } public static MessageEmbed getUnautorized() { @@ -83,7 +103,10 @@ public class EmbedMessageUtils { } public static MessageEmbed getLastMessageFromTextChannel(HashMap message) { - EmbedBuilder temp = new EmbedBuilder().setTitle("Channel uses checker").setDescription("Last message date for channels:").setColor(Color.green); + EmbedBuilder temp = new EmbedBuilder() + .setTitle("Channel uses checker") + .setDescription("Last message date for channels:") + .setColor(Color.green); for (Map.Entry entry : message.entrySet()) { temp.addField(entry.getKey(), entry.getValue(), false); } @@ -91,7 +114,13 @@ public class EmbedMessageUtils { } public static MessageEmbed getReportUsersError() { - return new EmbedBuilder().setTitle(":warning: Command error").setDescription("").setColor(Color.red).setFooter("'//help move' for more info.", MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).build(); + return new EmbedBuilder() + .setTitle(":warning: Command error") + .setDescription("") + .setColor(Color.red) + .setFooter("'//help move' for more info.", MainBot.jda.getSelfUser().getAvatarUrl()) + .setTimestamp(Instant.now()) + .build(); } diff --git a/src/main/java/net/Broken/Tools/TrueRandom.java b/src/main/java/net/Broken/Tools/TrueRandom.java index 5a2b52a..96c30c5 100644 --- a/src/main/java/net/Broken/Tools/TrueRandom.java +++ b/src/main/java/net/Broken/Tools/TrueRandom.java @@ -1,5 +1,7 @@ package net.Broken.Tools; +import net.Broken.BotConfigLoader; +import net.Broken.SpringContext; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; @@ -18,11 +20,11 @@ import java.util.List; public class TrueRandom { - private static TrueRandom INSTANCE = new TrueRandom(); - private Logger logger = LogManager.getLogger(); - private String url = "https://api.random.org/json-rpc/2/invoke"; - private String apiKey = System.getenv("RANDOM_API_KEY"); + private static final TrueRandom INSTANCE = new TrueRandom(); + private final Logger logger = LogManager.getLogger(); + private final String apiKey; private TrueRandom() { + apiKey = SpringContext.getAppContext().getBean(BotConfigLoader.class).randomApiKey(); } public static TrueRandom getINSTANCE() { @@ -30,10 +32,13 @@ public class TrueRandom { } public ArrayList getNumbers(int min, int max) throws IOException { + +// TODO Migrate to native http client HttpClient httpClient = HttpClientBuilder.create().build(); String postVal = "{\"jsonrpc\":\"2.0\",\"method\":\"generateIntegers\",\"params\":{\"apiKey\":\"" + apiKey + "\",\"n\":50,\"min\":" + min + ",\"max\":" + max + ",\"replacement\":" + (((max - min) >= 50) ? "false" : "true") + "},\"id\":41}"; StringEntity entity = new StringEntity(postVal, ContentType.APPLICATION_JSON); + String url = "https://api.random.org/json-rpc/2/invoke"; HttpPost request = new HttpPost(url); request.setEntity(entity); request.setHeader("Accept", "application/json"); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 71dc6a1..04f3f7b 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -9,21 +9,22 @@ server: compression: enabled: true mime-types: application/json,application/xml,text/html,text/xml,text/plain,application/javascript,text/css - port: ${PORT} + port: 8080 http2: enabled: true -security: - jwt: - secret: ${JWT_SECRET} - discord: oauth: - client-id: ${CLIENT_ID} - client-secret: ${CLIENT_SECRET} + client-id: ${OAUTH_CLIENT_ID} + client-secret: ${OAUTH_CLIENT_SECRET} token-endpoint: https://discord.com/api/oauth2/token tokenRevokeEndpoint: https://discord.com/api/oauth2/token/revoke userInfoEnpoint: https://discord.com/api/users/@me + bot: + token: ${BOT_TOKEN} + url: "claptrapbot.com" + mode: ${APP_MODE} + randomApiKey: ${RANDOM_API_KEY} springdoc: paths-to-match: /api/v2/** \ No newline at end of file