Compare commits

...

1 Commits

Author SHA1 Message Date
43949e2b35
🔨 migrate env to config prop 2022-06-10 13:15:32 +02:00
10 changed files with 99 additions and 202 deletions

View File

@ -2,7 +2,6 @@ package net.Broken.Api.Services;
import net.Broken.Api.Data.Guild; import net.Broken.Api.Data.Guild;
import net.Broken.DB.Entity.UserEntity; import net.Broken.DB.Entity.UserEntity;
import net.Broken.MainBot;
import net.Broken.Tools.CacheTools; import net.Broken.Tools.CacheTools;
import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.User;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;

View File

@ -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
){}

View File

@ -35,12 +35,14 @@ import java.util.List;
*/ */
public class BotListener extends ListenerAdapter { public class BotListener extends ListenerAdapter {
private final GuildPreferenceRepository guildPreferenceRepository; private final GuildPreferenceRepository guildPreferenceRepository;
private final BotConfigLoader botConfig;
private final Logger logger = LogManager.getLogger(); private final Logger logger = LogManager.getLogger();
public BotListener() { public BotListener() {
ApplicationContext context = SpringContext.getAppContext(); ApplicationContext context = SpringContext.getAppContext();
guildPreferenceRepository = (GuildPreferenceRepository) context.getBean("guildPreferenceRepository"); guildPreferenceRepository = context.getBean(GuildPreferenceRepository.class);
botConfig = context.getBean(BotConfigLoader.class);
} }
@Override @Override
@ -194,7 +196,7 @@ public class BotListener extends ListenerAdapter {
EmbedBuilder eb = new EmbedBuilder().setColor(Color.GREEN) EmbedBuilder eb = new EmbedBuilder().setColor(Color.GREEN)
.setTitle("Hello there !") .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" + .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"); .setImage("https://i.imgur.com/Anf1Srg.gif");
Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.buildStandar(eb)).build(); Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.buildStandar(eb)).build();

View File

@ -3,7 +3,6 @@ package net.Broken;
import net.Broken.DB.Entity.UserEntity; import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.UserRepository; import net.Broken.DB.Repository.UserRepository;
import net.Broken.RestApi.ApiCommandLoader; import net.Broken.RestApi.ApiCommandLoader;
import net.Broken.Tools.Command.CommandLoader;
import net.Broken.Tools.Command.SlashCommandLoader; import net.Broken.Tools.Command.SlashCommandLoader;
import net.Broken.Tools.DayListener.DayListener; import net.Broken.Tools.DayListener.DayListener;
import net.Broken.Tools.DayListener.Listeners.DailyMadame; import net.Broken.Tools.DayListener.Listeners.DailyMadame;
@ -24,78 +23,56 @@ import java.util.List;
public class Init { public class Init {
static private Logger logger = LogManager.getLogger(); static private final Logger logger = LogManager.getLogger();
/** static JDA initJda(BotConfigLoader config) {
* Initialize all bot functionality
*
* @param token bot user token
* @return JDA object
*/
static JDA initJda(String token) {
JDA jda = null;
logger.info("-----------------------INIT-----------------------"); logger.info("-----------------------INIT-----------------------");
if (config == null) {
//Bot démarrer sans token
if (token == null) {
logger.fatal("Please enter bot token as an argument."); logger.fatal("Please enter bot token as an argument.");
return null;
} else { } else {
//Token présent
try { try {
logger.info("Connecting to Discord api..."); 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();
/************************************* jda.awaitReady()
* Definition des commande * .setAutoReconnect(true);
*************************************/
jda.getPresence().setPresence(OnlineStatus.DO_NOT_DISTURB, Activity.playing("Loading...")); jda.getPresence().setPresence(OnlineStatus.DO_NOT_DISTURB, Activity.playing("Loading..."));
//On recupere le l'id serveur
logger.info("Connected on " + jda.getGuilds().size() + " Guilds:"); logger.info("Connected on " + jda.getGuilds().size() + " Guilds:");
for (Guild server : jda.getGuilds()) { for (Guild server : jda.getGuilds()) {
server.loadMembers().get(); server.loadMembers().get();
//on recupere les utilisateur
logger.info("... " + server.getName() + " " + server.getMembers().size() + " Members"); logger.info("... " + server.getName() + " " + server.getMembers().size() + " Members");
} }
return jda;
} catch (LoginException | InterruptedException e) { } catch (LoginException | InterruptedException e) {
logger.catching(e); logger.catching(e);
return null;
} }
} }
return jda;
} }
static void polish(JDA jda) { static void polish(JDA jda, BotConfigLoader config) {
logger.info("Check database..."); logger.info("Check database...");
checkDatabase(); checkDatabase();
CommandLoader.load(); logger.info("Loading commands");
SlashCommandLoader.load(); SlashCommandLoader.load(config);
SlashCommandLoader.registerSlashCommands(jda.updateCommands()); SlashCommandLoader.registerSlashCommands(jda.updateCommands());
ApiCommandLoader.load(); ApiCommandLoader.load();
DayListener dayListener = DayListener.getInstance(); DayListener dayListener = DayListener.getInstance();
dayListener.addListener(new DailyMadame()); dayListener.addListener(new DailyMadame());
dayListener.start(); dayListener.start();
jda.addEventListener(new BotListener()); 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-----------------------"); 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;
}
} }

View File

@ -1,24 +1,21 @@
package net.Broken; package net.Broken;
import net.dv8tion.jda.api.JDA; 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.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.springframework.boot.ExitCodeGenerator; import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Controller;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
/** /**
* Main Class * Main Class
*/ */
@SpringBootApplication @SpringBootApplication
@Controller @ConfigurationPropertiesScan
public class MainBot { public class MainBot {
public static HashMap<String, Commande> commandes = new HashMap<>(); public static HashMap<String, Commande> commandes = new HashMap<>();
@ -27,37 +24,23 @@ public class MainBot {
public static boolean roleFlag = false; public static boolean roleFlag = false;
public static JDA jda; public static JDA jda;
public static boolean ready = false; public static boolean ready = false;
public static boolean dev = false;
public static String url = "claptrapbot.com";
public static int messageTimeOut = 10; public static int messageTimeOut = 10;
public static int gifMessageTimeOut = 30; public static int gifMessageTimeOut = 30;
private static Logger logger = LogManager.getLogger(); private static final Logger logger = LogManager.getLogger();
public static void main(String[] args) { public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(MainBot.class, args);
if (!Init.checkEnv()) BotConfigLoader config = ctx.getBean(BotConfigLoader.class);
System.exit(1);
logger.info("======================================="); logger.info("=======================================");
logger.info("--------------Starting Bot-------------"); logger.info("--------------Starting Bot-------------");
logger.info("======================================="); logger.info("=======================================");
if (System.getenv("DEV") != null) {
dev = Boolean.parseBoolean(System.getenv("DEV"));
}
jda = Init.initJda(config);
String token = System.getenv("DISCORD_TOKEN");
jda = Init.initJda(token);
ConfigurableApplicationContext ctx = SpringApplication.run(MainBot.class, args);
if (jda == null) { if (jda == null) {
System.exit(SpringApplication.exit(ctx, (ExitCodeGenerator) () -> { System.exit(SpringApplication.exit(ctx, (ExitCodeGenerator) () -> {
logger.fatal("Init error! Close application!"); logger.fatal("Init error! Close application!");
@ -65,8 +48,7 @@ public class MainBot {
})); }));
} }
Init.polish(jda); Init.polish(jda, config);
ready = true; ready = true;
} }
} }

View File

@ -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<Class<? extends Commande>> modules = reflections.getSubTypesOf(Commande.class);
logger.info("Find " + modules.size() + " Command:");
for (Class<? extends Commande> 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);
}
}
}
}

View File

@ -1,5 +1,6 @@
package net.Broken.Tools.Command; package net.Broken.Tools.Command;
import net.Broken.BotConfigLoader;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.SlashCommand; import net.Broken.SlashCommand;
import net.dv8tion.jda.api.interactions.commands.build.CommandData; 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 * 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..."); logger.info("Loading Slash Command...");
Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage( Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(
"net.Broken.SlashCommands", "net.Broken.SlashCommands",
@ -41,7 +42,7 @@ public class SlashCommandLoader {
if (!command.isAnnotationPresent(Ignore.class)) { if (!command.isAnnotationPresent(Ignore.class)) {
logger.info("..." + name); 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"); logger.warn("Command disabled in dev mode");
} else { } else {
try { try {

View File

@ -1,13 +1,16 @@
package net.Broken.Tools; package net.Broken.Tools;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;
import net.Broken.BotConfigLoader;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.SpringContext;
import net.Broken.audio.UserAudioTrack; import net.Broken.audio.UserAudioTrack;
import net.Broken.audio.Youtube.SearchResult; import net.Broken.audio.Youtube.SearchResult;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.User;
import org.springframework.context.ApplicationContext;
import java.awt.*; import java.awt.*;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@ -21,18 +24,26 @@ import java.util.Map;
public class EmbedMessageUtils { public class EmbedMessageUtils {
public static EmbedBuilder getError(String message) { 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; return temp;
} }
public static MessageEmbed getMusicError(String message) { 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) { public static MessageEmbed getMusicOk(String message) {
// TODO better display for different action (add icon ?) // 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); return buildStandar(temp);
} }
@ -66,16 +77,25 @@ public class EmbedMessageUtils {
} }
public static MessageEmbed getFlushError(String message) { 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() { 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) { 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() { public static MessageEmbed getUnautorized() {
@ -83,7 +103,10 @@ public class EmbedMessageUtils {
} }
public static MessageEmbed getLastMessageFromTextChannel(HashMap<String, String> message) { public static MessageEmbed getLastMessageFromTextChannel(HashMap<String, String> 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<String, String> entry : message.entrySet()) { for (Map.Entry<String, String> entry : message.entrySet()) {
temp.addField(entry.getKey(), entry.getValue(), false); temp.addField(entry.getKey(), entry.getValue(), false);
} }
@ -91,7 +114,13 @@ public class EmbedMessageUtils {
} }
public static MessageEmbed getReportUsersError() { 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();
} }

View File

@ -1,5 +1,7 @@
package net.Broken.Tools; package net.Broken.Tools;
import net.Broken.BotConfigLoader;
import net.Broken.SpringContext;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
@ -18,11 +20,11 @@ import java.util.List;
public class TrueRandom { public class TrueRandom {
private static TrueRandom INSTANCE = new TrueRandom(); private static final TrueRandom INSTANCE = new TrueRandom();
private Logger logger = LogManager.getLogger(); private final Logger logger = LogManager.getLogger();
private String url = "https://api.random.org/json-rpc/2/invoke"; private final String apiKey;
private String apiKey = System.getenv("RANDOM_API_KEY");
private TrueRandom() { private TrueRandom() {
apiKey = SpringContext.getAppContext().getBean(BotConfigLoader.class).randomApiKey();
} }
public static TrueRandom getINSTANCE() { public static TrueRandom getINSTANCE() {
@ -30,10 +32,13 @@ public class TrueRandom {
} }
public ArrayList<Integer> getNumbers(int min, int max) throws IOException { public ArrayList<Integer> getNumbers(int min, int max) throws IOException {
// TODO Migrate to native http client
HttpClient httpClient = HttpClientBuilder.create().build(); 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}"; 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); StringEntity entity = new StringEntity(postVal, ContentType.APPLICATION_JSON);
String url = "https://api.random.org/json-rpc/2/invoke";
HttpPost request = new HttpPost(url); HttpPost request = new HttpPost(url);
request.setEntity(entity); request.setEntity(entity);
request.setHeader("Accept", "application/json"); request.setHeader("Accept", "application/json");

View File

@ -9,21 +9,22 @@ server:
compression: compression:
enabled: true enabled: true
mime-types: application/json,application/xml,text/html,text/xml,text/plain,application/javascript,text/css mime-types: application/json,application/xml,text/html,text/xml,text/plain,application/javascript,text/css
port: ${PORT} port: 8080
http2: http2:
enabled: true enabled: true
security:
jwt:
secret: ${JWT_SECRET}
discord: discord:
oauth: oauth:
client-id: ${CLIENT_ID} client-id: ${OAUTH_CLIENT_ID}
client-secret: ${CLIENT_SECRET} client-secret: ${OAUTH_CLIENT_SECRET}
token-endpoint: https://discord.com/api/oauth2/token token-endpoint: https://discord.com/api/oauth2/token
tokenRevokeEndpoint: https://discord.com/api/oauth2/token/revoke tokenRevokeEndpoint: https://discord.com/api/oauth2/token/revoke
userInfoEnpoint: https://discord.com/api/users/@me userInfoEnpoint: https://discord.com/api/users/@me
bot:
token: ${BOT_TOKEN}
url: "claptrapbot.com"
mode: ${APP_MODE}
randomApiKey: ${RANDOM_API_KEY}
springdoc: springdoc:
paths-to-match: /api/v2/** paths-to-match: /api/v2/**