Compare commits

...

6 Commits

Author SHA1 Message Date
0255cac542
🔨 Add getRole endpoint 2022-06-10 21:25:12 +02:00
2cd22ab2db
🔨 Add setting description endpoint 2022-06-10 17:24:20 +02:00
3f5225bef1
🔨 Add textchannel and voicechannel endpoint 2022-06-10 16:55:31 +02:00
47fa3ae2bf
🔒 Add dev mode to auth 2022-06-10 16:55:05 +02:00
cb0c916196
🔒 Add security expression for guild 2022-06-10 16:54:52 +02:00
9a8a7693ae
🔨 migrate env to config prop 2022-06-10 16:53:56 +02:00
25 changed files with 454 additions and 213 deletions

View File

@ -1,16 +1,16 @@
package net.Broken.Api.Controllers;
import net.Broken.Api.Data.Guild;
import net.Broken.Api.Data.Guild.Guild;
import net.Broken.Api.Data.Guild.Role;
import net.Broken.Api.Data.InviteLink;
import net.Broken.Api.Data.Guild.Channel;
import net.Broken.Api.Security.Data.JwtPrincipal;
import net.Broken.Api.Services.GuildService;
import net.Broken.MainBot;
import net.dv8tion.jda.api.Permission;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@ -36,4 +36,23 @@ public class GuildController {
String link = MainBot.jda.getInviteUrl(Permission.ADMINISTRATOR);
return new InviteLink(link);
}
@GetMapping("/{guildId}/voiceChannels")
@PreAuthorize("isInGuild(#guildId)")
public List<Channel> getVoiceChannels(@PathVariable String guildId){
return guildService.getVoiceChannel(guildId);
}
@GetMapping("/{guildId}/textChannels")
@PreAuthorize("isInGuild(#guildId)")
public List<Channel> getTextChannels(@PathVariable String guildId){
return guildService.getTextChannel(guildId);
}
@GetMapping("/{guildId}/roles")
@PreAuthorize("isInGuild(#guildId)")
public List<Role> getRoles(@PathVariable String guildId){
return guildService.getRole(guildId);
}
}

View File

@ -5,6 +5,7 @@ import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.security.SecurityRequirements;
import net.Broken.Api.Security.Data.JwtPrincipal;
import net.Broken.DB.Entity.UserEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;

View File

@ -0,0 +1,26 @@
package net.Broken.Api.Controllers;
import net.Broken.Api.Data.Settings.SettingGroup;
import net.Broken.Api.Services.SettingService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/v2/setting")
@CrossOrigin(origins = "*", maxAge = 3600)
public class SettingController {
public final SettingService settingService;
public SettingController(SettingService settingService) {
this.settingService = settingService;
}
@GetMapping("description")
public List<SettingGroup> getSettingDescription(){
return settingService.getSettingDescription();
}
}

View File

@ -0,0 +1,4 @@
package net.Broken.Api.Data.Guild;
public record Channel(String id, String name) {
}

View File

@ -1,4 +1,4 @@
package net.Broken.Api.Data;
package net.Broken.Api.Data.Guild;
public record Guild(String id, String name, String iconUrl) {
}

View File

@ -0,0 +1,4 @@
package net.Broken.Api.Data.Guild;
public record Role(String id, String name) {
}

View File

@ -0,0 +1,16 @@
package net.Broken.Api.Data.Settings;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public record SettingDescriber(
String id,
String name,
String description,
TYPE type
) {
public enum TYPE {
BOOL, LIST, STRING, ROLE, TEXT_CHANNEL, VOICE_CHANNEL
}
}

View File

@ -0,0 +1,13 @@
package net.Broken.Api.Data.Settings;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL)
public record SettingGroup(
String name,
SettingDescriber mainField,
List<SettingDescriber> fields
) {
}

View File

@ -0,0 +1,26 @@
package net.Broken.Api.Security.Expression;
import net.Broken.Api.Security.Expression.CustomMethodSecurityExpressionRoot;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
public class CustomMethodSecurityExpressionHandler
extends DefaultMethodSecurityExpressionHandler {
private AuthenticationTrustResolver trustResolver =
new AuthenticationTrustResolverImpl();
@Override
protected MethodSecurityExpressionOperations createSecurityExpressionRoot(
Authentication authentication, MethodInvocation invocation) {
CustomMethodSecurityExpressionRoot root =
new CustomMethodSecurityExpressionRoot(authentication);
root.setPermissionEvaluator(getPermissionEvaluator());
root.setTrustResolver(this.trustResolver);
root.setRoleHierarchy(getRoleHierarchy());
return root;
}
}

View File

@ -0,0 +1,56 @@
package net.Broken.Api.Security.Expression;
import net.Broken.Api.Security.Data.JwtPrincipal;
import net.Broken.MainBot;
import net.Broken.Tools.CacheTools;
import net.dv8tion.jda.api.entities.Guild;
import okhttp3.Cache;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations;
import org.springframework.security.core.Authentication;
public class CustomMethodSecurityExpressionRoot
extends SecurityExpressionRoot
implements MethodSecurityExpressionOperations {
private Object filterObject;
private Object returnObject;
/**
* Creates a new instance
*
* @param authentication the {@link Authentication} to use. Cannot be null.
*/
public CustomMethodSecurityExpressionRoot(Authentication authentication) {
super(authentication);
}
public boolean isInGuild(String guildId){
JwtPrincipal jwtPrincipal = (JwtPrincipal) authentication.getPrincipal();
Guild guild = MainBot.jda.getGuildById(guildId);
return CacheTools.getJdaUser(jwtPrincipal.user()).getMutualGuilds().contains(guild);
}
@Override
public void setFilterObject(Object filterObject) {
this.filterObject = filterObject;
}
@Override
public Object getFilterObject() {
return this.filterObject;
}
@Override
public void setReturnObject(Object returnObject) {
this.returnObject = returnObject;
}
@Override
public Object getReturnObject() {
return this.returnObject;
}
@Override
public Object getThis() {
return this;
}
}

View File

@ -4,7 +4,9 @@ import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import net.Broken.Api.Security.Data.JwtPrincipal;
import net.Broken.Api.Security.Services.JwtService;
import net.Broken.BotConfigLoader;
import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.UserRepository;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
@ -23,6 +25,10 @@ import java.util.ArrayList;
public class JwtFilter extends OncePerRequestFilter {
@Autowired
private JwtService jwtService;
@Autowired
private BotConfigLoader config;
@Autowired
private UserRepository userRepository;
private final Logger logger = LogManager.getLogger();
@Override
@ -31,9 +37,17 @@ public class JwtFilter extends OncePerRequestFilter {
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.replace("Bearer ", "");
try {
UserEntity user;
JwtPrincipal principal;
if(config.mode().equals("DEV")){
user = userRepository.findByDiscordId(token).orElseThrow();
principal = new JwtPrincipal("DEV", user);
}
else {
Jws<Claims> jwt = jwtService.verifyAndParseJwt(token);
UserEntity user = jwtService.getUserWithJwt(jwt);
JwtPrincipal principal = new JwtPrincipal(jwt.getBody().getId(), user);
user = jwtService.getUserWithJwt(jwt);
principal = new JwtPrincipal(jwt.getBody().getId(), user);
}
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(principal, null, new ArrayList<>());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);

View File

@ -0,0 +1,16 @@
package net.Broken.Api.Security;
import net.Broken.Api.Security.Expression.CustomMethodSecurityExpressionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new CustomMethodSecurityExpressionHandler();
}
}

View File

@ -1,6 +1,8 @@
package net.Broken.Api.Services;
import net.Broken.Api.Data.Guild;
import net.Broken.Api.Data.Guild.Guild;
import net.Broken.Api.Data.Guild.Channel;
import net.Broken.Api.Data.Guild.Role;
import net.Broken.DB.Entity.UserEntity;
import net.Broken.MainBot;
import net.Broken.Tools.CacheTools;
@ -23,4 +25,32 @@ public class GuildService {
return guildList;
}
public List<Channel> getVoiceChannel(String guildId){
net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId);
List<Channel> voiceChannels = new ArrayList<>();
for(net.dv8tion.jda.api.entities.VoiceChannel voiceChannel : guild.getVoiceChannels()){
voiceChannels.add(new Channel(voiceChannel.getId(), voiceChannel.getName()));
}
return voiceChannels;
}
public List<Channel> getTextChannel(String guildId){
net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId);
List<Channel> voiceChannels = new ArrayList<>();
for(net.dv8tion.jda.api.entities.TextChannel textChannel : guild.getTextChannels()){
voiceChannels.add(new Channel(textChannel.getId(), textChannel.getName()));
}
return voiceChannels;
}
public List<Role> getRole(String guildId){
net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId);
List<Role> roles = new ArrayList<>();
for(net.dv8tion.jda.api.entities.Role role : guild.getRoles()){
roles.add(new Role(role.getId(), role.getName()));
}
return roles;
}
}

View File

@ -0,0 +1,115 @@
package net.Broken.Api.Services;
import net.Broken.Api.Data.Settings.SettingDescriber;
import net.Broken.Api.Data.Settings.SettingGroup;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class SettingService {
public List<SettingGroup> getSettingDescription() {
List<SettingGroup> toReturn = new ArrayList<>();
toReturn.add(getWelcomeGroup());
toReturn.add(getDefaultRoleGroup());
toReturn.add(getDailyGroup());
toReturn.add(getAutoVoiceChannelGroup());
return toReturn;
}
private SettingGroup getWelcomeGroup() {
SettingDescriber mainField = new SettingDescriber(
"welcome_enable",
"Enable Welcome Message",
null,
SettingDescriber.TYPE.BOOL
);
List<SettingDescriber> fields = new ArrayList<>();
fields.add(new SettingDescriber(
"welcome_chanel_id",
"Welcome Message chanel",
null,
SettingDescriber.TYPE.TEXT_CHANNEL
));
fields.add(new SettingDescriber(
"welcome_message",
"Welcome Message",
null,
SettingDescriber.TYPE.STRING
));
return new SettingGroup(
"Welcome Message",
mainField,
fields);
}
private SettingGroup getDefaultRoleGroup() {
SettingDescriber mainField = new SettingDescriber(
"default_role",
"Enable Default Role",
null,
SettingDescriber.TYPE.BOOL
);
List<SettingDescriber> fields = new ArrayList<>();
fields.add(new SettingDescriber(
"default_role_id",
"Default Role",
null,
SettingDescriber.TYPE.ROLE
));
return new SettingGroup(
"Default Role",
mainField,
fields);
}
private SettingGroup getDailyGroup() {
List<SettingDescriber> fields = new ArrayList<>();
fields.add(new SettingDescriber(
"daily_madame",
"[NSFW] Enable Daily Madame Message",
null,
SettingDescriber.TYPE.BOOL
));
return new SettingGroup(
"Daily",
null,
fields);
}
private SettingGroup getAutoVoiceChannelGroup() {
SettingDescriber mainField = new SettingDescriber(
"auto_voice",
"Enable Auto Create Voice Chanel",
"Auto create voice channel on join.",
SettingDescriber.TYPE.BOOL
);
List<SettingDescriber> fields = new ArrayList<>();
fields.add(new SettingDescriber(
"auto_voice_base_channel",
"Base Voice Channel For Auto Create",
"If someone joint this channel, a new voice channel will be created with the same settings.",
SettingDescriber.TYPE.VOICE_CHANNEL
));
fields.add(new SettingDescriber(
"auto_voice_channel_title",
"Auto Created Voice Channel title",
"Auto created voice channel will use this title, @count will be replaced by the channel count.",
SettingDescriber.TYPE.VOICE_CHANNEL
));
return new SettingGroup(
"Auto Voice Channel",
mainField,
fields);
}
}

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 {
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();

View File

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

View File

@ -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<String, Commande> 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;
}
}

View File

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

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;
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 {

View File

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

View File

@ -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<Integer> 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");

View File

@ -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/**

View File

@ -2,7 +2,7 @@
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<!--<PatternLayout pattern="[%d{HH:mm:ss.SSS}][%-5level][%-30.30c{1.}]: %msg%n" />-->
<PatternLayout>
<PatternLayout disableAnsi="false">
<Pattern>[%d{HH:mm:ss.SSS}]%highlight{[%-5level]}{FATAL=red blink, ERROR=red, WARN=bright yellow ,
INFO=blue, DEBUG=bright black, TRACE=cyan}[%-30.30c{1.}]: %highlight{%msg%n}{FATAL=red blink,
ERROR=red, WARN=bright yellow , INFO=blue, DEBUG=bright black, TRACE=cyan}