Fist pass

This commit is contained in:
SebClem 2023-03-29 23:58:13 +02:00
parent ded6513a02
commit fbeb9b18fe
Signed by: sebclem
GPG Key ID: 5A4308F6A359EA50
18 changed files with 187 additions and 196 deletions

View File

@ -1,3 +1,4 @@
{
"java.configuration.updateBuildConfiguration": "automatic"
"java.configuration.updateBuildConfiguration": "automatic",
"java.compile.nullAnalysis.mode": "disabled"
}

View File

@ -45,7 +45,7 @@ dependencies {
implementation('io.jsonwebtoken:jjwt-jackson:0.11.5')
implementation('com.sedmelluq:lavaplayer:1.3.78')
implementation('net.dv8tion:JDA:4.4.1_353')
implementation('net.dv8tion:JDA:5.0.0-beta.6')
implementation(platform("org.apache.logging.log4j:log4j-bom:2.18.0"))
implementation group: 'org.hibernate', name: 'hibernate-validator', version: '7.0.4.Final'

View File

@ -2,13 +2,14 @@ package net.Broken.Api.Security.Expression;
import net.Broken.Api.Data.Music.Connect;
import net.Broken.Api.Security.Data.JwtPrincipal;
import net.Broken.Audio.GuildAudioBotService;
import net.Broken.MainBot;
import net.Broken.Tools.CacheTools;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel;
import net.dv8tion.jda.api.entities.channel.unions.AudioChannelUnion;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations;
import org.springframework.security.core.Authentication;
@ -61,8 +62,7 @@ public class CustomMethodSecurityExpressionRoot
public boolean canInteractWithVoiceChannel(String guildId) {
JwtPrincipal jwtPrincipal = (JwtPrincipal) authentication.getPrincipal();
Guild guild = MainBot.jda.getGuildById(guildId);
GuildAudioBotService guildAudioBotService = GuildAudioBotService.getInstance(guild);
VoiceChannel channel = guild.getAudioManager().getConnectedChannel();
AudioChannelUnion channel = guild.getAudioManager().getConnectedChannel();
if (channel == null) {
return false;

View File

@ -9,7 +9,9 @@ import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.audio.hooks.ConnectionStatus;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel;
import net.dv8tion.jda.api.entities.channel.unions.AudioChannelUnion;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
@ -28,7 +30,7 @@ public class AudioService {
Member member = guild.getMemberById(userId);
VoiceChannel channel = guild.getAudioManager().getConnectedChannel();
AudioChannelUnion channel = guild.getAudioManager().getConnectedChannel();
ConnectionStatus status = guild.getAudioManager().getConnectionStatus();
if (channel != null) {
// The user can view the audio status if:

View File

@ -8,6 +8,9 @@ import net.Broken.MainBot;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@ -35,7 +38,7 @@ public class GuildService {
net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId);
Member member = guild.getMemberById(userId);
List<Channel> voiceChannels = new ArrayList<>();
for (net.dv8tion.jda.api.entities.VoiceChannel voiceChannel : guild.getVoiceChannels()) {
for (VoiceChannel voiceChannel : guild.getVoiceChannels()) {
if (member.hasPermission(voiceChannel, Permission.VIEW_CHANNEL)) {
voiceChannels.add(new Channel(voiceChannel.getId(), voiceChannel.getName()));
}
@ -47,7 +50,7 @@ public class GuildService {
net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId);
Member member = guild.getMemberById(userId);
List<Channel> voiceChannels = new ArrayList<>();
for (net.dv8tion.jda.api.entities.TextChannel textChannel : guild.getTextChannels()) {
for (TextChannel textChannel : guild.getTextChannels()) {
if (member.hasPermission(textChannel, Permission.VIEW_CHANNEL)) {
voiceChannels.add(new Channel(textChannel.getId(), textChannel.getName()));
}

View File

@ -7,19 +7,21 @@ import net.Broken.Tools.AutoVoiceChannel;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.UserManager.Stats.UserStatsUtils;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.events.guild.GuildJoinEvent;
import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent;
import net.dv8tion.jda.api.events.guild.member.GuildMemberRoleRemoveEvent;
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceJoinEvent;
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceLeaveEvent;
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceMoveEvent;
import net.dv8tion.jda.api.events.interaction.ButtonClickEvent;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.events.guild.voice.GenericGuildVoiceEvent;
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceUpdateEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.events.session.ReadyEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;
import net.dv8tion.jda.api.utils.messages.MessageCreateData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
@ -29,7 +31,6 @@ import java.awt.*;
import java.util.HashMap;
import java.util.Optional;
/**
* Bot Listener
*/
@ -50,27 +51,27 @@ public class BotListener extends ListenerAdapter {
logger.info("Connection success");
}
@Override
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
GuildPreferenceEntity guildPref = getPreference(event.getGuild());
if (guildPref.isDefaultRole()) {
logger.info("[" + event.getGuild().getName() + "] : " + event.getUser().getName() + " join the guild, adding default role !");
logger.info("[{}] : {} join the guild, adding default role !", event.getGuild().getName(),
event.getUser().getName());
Role default_role = event.getGuild().getRoleById(guildPref.getDefaultRoleId());
if (default_role != null) {
event.getGuild().addRoleToMember(event.getMember(), default_role).queue();
} else {
logger.fatal("[" + event.getGuild().getName() + "] : Default role is null !");
logger.fatal("[{}] : Default role is null !", event.getGuild().getName());
}
}
if (guildPref.isWelcome()) {
TextChannel chanel = event.getGuild().getTextChannelById(guildPref.getWelcomeChanelID());
if (chanel != null) {
String message = guildPref.getWelcomeMessage().replaceAll("@name", event.getMember().getAsMention());
String message = guildPref.getWelcomeMessage().replace("@name", event.getMember().getAsMention());
logger.debug(message);
chanel.sendMessage(message).queue();
} else {
logger.fatal("[" + event.getGuild().getName() + "] : Welcome chanel is null !");
logger.fatal("[{}] : Welcome chanel is null !", event.getGuild().getName());
}
}
@ -79,41 +80,24 @@ public class BotListener extends ListenerAdapter {
@Override
public void onGuildMemberRoleRemove(GuildMemberRoleRemoveEvent event) {
GuildPreferenceEntity guildPref = getPreference(event.getGuild());
if (guildPref.isDefaultRole()) {
if (event.getMember().getRoles().size() == 0) {
logger.info("[" + event.getGuild().getName() + "] : " + event.getUser().getName() + " have no roles, reset to default !");
Role default_role = event.getGuild().getRoleById(guildPref.getDefaultRoleId());
if (default_role == null) {
logger.fatal("[" + event.getGuild().getName() + "] : Default role is null !");
if (guildPref.isDefaultRole() && event.getMember().getRoles().isEmpty()) {
logger.info("[{}] : {} have no roles, reset to default !", event.getGuild().getName(),
event.getUser().getName());
Role defaultRole = event.getGuild().getRoleById(guildPref.getDefaultRoleId());
if (defaultRole == null) {
logger.fatal("[{}] : Default role is null !", event.getGuild().getName());
return;
}
event.getGuild().addRoleToMember(event.getMember(), default_role).queue();
}
event.getGuild().addRoleToMember(event.getMember(), defaultRole).queue();
}
}
@Override
public void onGuildVoiceJoin(GuildVoiceJoinEvent event) {
super.onGuildVoiceJoin(event);
if (!event.getMember().getUser().isBot()) {
UserStatsUtils userStatsUtils = UserStatsUtils.getINSTANCE();
if (!userStatsUtils.runningCounters.containsKey(event.getMember().getId())) {
UserStatsUtils.VoicePresenceCounter temp = new UserStatsUtils.VoicePresenceCounter(event.getMember());
temp.start();
userStatsUtils.runningCounters.put(event.getMember().getId(), temp);
}
AutoVoiceChannel autoVoiceChannel = AutoVoiceChannel.getInstance(event.getGuild());
autoVoiceChannel.join(event.getChannelJoined());
}
}
@Override
public void onGuildVoiceLeave(GuildVoiceLeaveEvent event) {
super.onGuildVoiceLeave(event);
public void onGuildVoiceUpdate(GuildVoiceUpdateEvent event) {
super.onGuildVoiceUpdate(event);
// Disconnect
if (event.getChannelJoined() == null) {
if (event.getGuild().getAudioManager().isConnected()) {
logger.trace("User disconnected from voice channel.");
@ -127,14 +111,25 @@ public class BotListener extends ListenerAdapter {
AutoVoiceChannel autoVoiceChannel = AutoVoiceChannel.getInstance(event.getGuild());
autoVoiceChannel.leave(event.getChannelLeft());
}
@Override
public void onGuildVoiceMove(@NotNull GuildVoiceMoveEvent event) {
super.onGuildVoiceMove(event);
// Connect
else if (event.getChannelLeft() == null && !event.getMember().getUser().isBot()) {
UserStatsUtils userStatsUtils = UserStatsUtils.getINSTANCE();
if (!userStatsUtils.runningCounters.containsKey(event.getMember().getId())) {
UserStatsUtils.VoicePresenceCounter temp = new UserStatsUtils.VoicePresenceCounter(
event.getMember());
temp.start();
userStatsUtils.runningCounters.put(event.getMember().getId(), temp);
}
AutoVoiceChannel autoVoiceChannel = AutoVoiceChannel.getInstance(event.getGuild());
autoVoiceChannel.join(event.getChannelJoined());
}
// Move
else {
AutoVoiceChannel autoVoiceChannel = AutoVoiceChannel.getInstance(event.getGuild());
autoVoiceChannel.leave(event.getChannelLeft());
autoVoiceChannel.join(event.getChannelJoined());
}
}
@Override
public void onMessageReceived(MessageReceivedEvent event) {
@ -144,8 +139,8 @@ public class BotListener extends ListenerAdapter {
}
@Override
public void onButtonClick(@NotNull ButtonClickEvent event) {
super.onButtonClick(event);
public void onButtonInteraction(ButtonInteractionEvent event) {
super.onButtonInteraction(event);
event.deferReply().queue();
GuildAudioBotService guildAudioBotService = GuildAudioBotService.getInstance(event.getGuild());
switch (event.getComponentId()) {
@ -158,9 +153,9 @@ public class BotListener extends ListenerAdapter {
}
@Override
public void onSlashCommand(@NotNull SlashCommandEvent event) {
public void onSlashCommandInteraction(SlashCommandInteractionEvent event) {
super.onSlashCommandInteraction(event);
HashMap<String, SlashCommand> commands = MainBot.slashCommands;
super.onSlashCommand(event);
if (commands.containsKey(event.getName())) {
SlashCommand commandRunner = commands.get(event.getName());
// It's form private message
@ -170,18 +165,16 @@ public class BotListener extends ListenerAdapter {
} else {
MessageEmbed message = EmbedMessageUtils.buildStandar(new EmbedBuilder()
.setTitle(":no_entry_sign: This command is not usable in private message")
.setColor(Color.red)
);
.setColor(Color.red));
event.replyEmbeds(message).setEphemeral(true).queue();
}
} else {
if (!commandRunner.isNSFW() || event.getTextChannel().isNSFW()) {
if (!commandRunner.isNSFW() || event.getChannel().asTextChannel().isNSFW()) {
commandRunner.action(event);
} else {
MessageEmbed message = EmbedMessageUtils.buildStandar(new EmbedBuilder()
.setTitle(":underage: This command is only usable in NSFW channels")
.setColor(Color.red)
);
.setColor(Color.red));
event.replyEmbeds(message).setEphemeral(true).queue();
}
}
@ -190,19 +183,23 @@ public class BotListener extends ListenerAdapter {
@Override
public void onGuildJoin(GuildJoinEvent event) {
logger.info("Join new guild! (" + event.getGuild().getName() + " " + event.getGuild().getMembers().size() + " Members)");
logger.info("Join new guild! ({} {} Members)", event.getGuild().getName(),
event.getGuild().getMembers().size());
super.onGuildJoin(event);
getPreference(event.getGuild());
event.getGuild().loadMembers().onSuccess((members -> logger.debug("[" + event.getGuild().getName() + "] Members loaded")));
event.getGuild().loadMembers()
.onSuccess((members -> logger.debug("[{}] Members loaded", event.getGuild().getName())));
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" +
.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: " + botConfig.url())
.setImage("https://i.imgur.com/Anf1Srg.gif");
Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.buildStandar(eb)).build();
MessageCreateData message = new MessageCreateBuilder().setEmbeds(EmbedMessageUtils.buildStandar(eb)).build();
TextChannel defaultChan = event.getGuild().getDefaultChannel();
if (defaultChan != null && defaultChan.canTalk()) {
TextChannel defaultChan = event.getGuild().getDefaultChannel().asTextChannel();
if (defaultChan.canTalk()) {
defaultChan.sendMessage(message).queue();
} else {
for (TextChannel chan : event.getGuild().getTextChannels()) {
@ -217,12 +214,10 @@ public class BotListener extends ListenerAdapter {
private GuildPreferenceEntity getPreference(Guild guild) {
Optional<GuildPreferenceEntity> guildPref = guildPreferenceRepository.findByGuildId(guild.getId());
if (guildPref.isEmpty()) {
logger.info("[" + guild.getName() + "] : Generate default pref");
logger.info("[{}] : Generate default pref", guild.getName());
return guildPreferenceRepository.save(GuildPreferenceEntity.getDefault(guild.getId()));
} else{
} else {
return guildPref.get();
}
}
}

View File

@ -1,13 +1,10 @@
package net.Broken;
import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.GuildPreferenceRepository;
import net.Broken.DB.Repository.UserRepository;
import net.Broken.Tools.Command.SlashCommandLoader;
import net.Broken.Tools.DayListener.DayListener;
import net.Broken.Tools.DayListener.Listeners.DailyMadame;
import net.Broken.Tools.UserManager.Stats.UserStatsUtils;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
@ -19,14 +16,13 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import javax.security.auth.login.LoginException;
import java.util.List;
public class Init {
static private final Logger logger = LogManager.getLogger();
private Init() {}
static JDA initJda(BotConfigLoader config) {
logger.info("-----------------------INIT-----------------------");
if (config == null) {
@ -47,13 +43,13 @@ public class Init {
.setAutoReconnect(true);
jda.getPresence().setPresence(OnlineStatus.DO_NOT_DISTURB, Activity.playing("Loading..."));
logger.info("Connected on " + jda.getGuilds().size() + " Guilds:");
logger.info("Connected on {} Guilds:", jda.getGuilds().size());
for (Guild server : jda.getGuilds()) {
server.loadMembers().get();
logger.info("... " + server.getName() + " " + server.getMembers().size() + " Members");
logger.info("... {} {} Members", server.getName(), server.getMembers().size());
}
return jda;
} catch (LoginException | InterruptedException e) {
} catch (InterruptedException e) {
logger.catching(e);
return null;
}
@ -79,17 +75,8 @@ public class Init {
private static void checkDatabase() {
ApplicationContext context = SpringContext.getAppContext();
UserRepository userRepository = (UserRepository) context.getBean("userRepository");
List<UserEntity> users = (List<UserEntity>) userRepository.findAll();
UserStatsUtils userStatsUtils = UserStatsUtils.getINSTANCE();
logger.debug("Stats...");
// for (UserEntity userEntity : users) {
// logger.debug("..." + userEntity.getName());
// userStatsUtils.getUserStats(userEntity);
//
// }
logger.debug("Guild Prefs...");
GuildPreferenceRepository guildPreference = context.getBean(GuildPreferenceRepository.class);
for(GuildPreferenceEntity pref :guildPreference.findAll()){

View File

@ -1,6 +1,6 @@
package net.Broken;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
@ -10,7 +10,7 @@ import java.util.List;
* Interface that define command structure.
*/
public interface SlashCommand {
void action(SlashCommandEvent event);
void action(SlashCommandInteractionEvent event);
String getDescription();

View File

@ -1,11 +1,11 @@
package net.Broken.SlashCommands;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@ -17,10 +17,10 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import net.Broken.SlashCommand;
import net.Broken.Tools.EmbedMessageUtils;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;
/**
* Command that return a random picture of cat.
@ -29,32 +29,33 @@ public class Cat implements SlashCommand {
private final Logger logger = LogManager.getLogger();
@Override
public void action(SlashCommandEvent event) {
public void action(SlashCommandInteractionEvent event) {
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://aws.random.cat/meow"))
.GET()
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
logger.warn("[CAT] Fail to fetch cat: Status Code: " + response.statusCode() + " Body:" + response.body());
logger.warn("[CAT] Fail to fetch cat: Status Code: {} Body: {}", response.statusCode(),
response.body());
throw new IOException();
}
TypeReference<HashMap<String, String>> typeRef = new TypeReference<>() {};
TypeReference<HashMap<String, String>> typeRef = new TypeReference<>() {
};
ObjectMapper mapper = new ObjectMapper();
HashMap<String, String> json = mapper.readValue(response.body(), typeRef);
event.reply(json.get("file")).queue();
} catch (InterruptedException | IOException e) {
logger.catching(e);
event.reply(new MessageBuilder().setEmbeds(EmbedMessageUtils.getInternalError()).build()).setEphemeral(true).queue();
event.reply(new MessageCreateBuilder().setEmbeds(EmbedMessageUtils.getInternalError()).build()).setEphemeral(true)
.queue();
}
}
@Override
@ -64,15 +65,14 @@ public class Cat implements SlashCommand {
@Override
public List<OptionData> getOptions() {
return null;
return Collections.emptyList();
}
@Override
public List<SubcommandData> getSubcommands() {
return null;
return Collections.emptyList();
}
/**
* Determines if the command is usable only by bot level admin user
*

View File

@ -1,29 +1,31 @@
package net.Broken.SlashCommands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.Broken.SlashCommand;
import net.Broken.Tools.EmbedMessageUtils;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageChannel;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;
import net.dv8tion.jda.api.utils.messages.MessageCreateData;
import java.util.ArrayList;
import java.util.List;
public class Clear implements SlashCommand {
@Override
public void action(SlashCommandEvent event) {
public void action(SlashCommandInteractionEvent event) {
if (event.getMember().hasPermission(Permission.MESSAGE_MANAGE)) {
event.reply(":white_check_mark: Done").setEphemeral(true).queue();
long n = event.getOption("n").getAsLong();
MessageChannel chanel = event.getChannel();
chanel.getIterableHistory().takeAsync((int) n).thenAccept(chanel::purgeMessages);
} else {
Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getFlushError("You are not a supreme being, you cannot do that !")).build();
MessageCreateData message = new MessageCreateBuilder().setEmbeds(EmbedMessageUtils.getFlushError("You are not a supreme being, you cannot do that !")).build();
event.reply(message).setEphemeral(true).queue();
}
}
@ -42,7 +44,7 @@ public class Clear implements SlashCommand {
@Override
public List<SubcommandData> getSubcommands() {
return null;
return Collections.emptyList();
}
@Override

View File

@ -1,48 +1,53 @@
package net.Broken.SlashCommands;
import net.Broken.Audio.GuildAudioBotService;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.Broken.SlashCommand;
import net.Broken.Audio.GuildAudioBotService;
import net.Broken.Tools.EmbedMessageUtils;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel;
import net.dv8tion.jda.api.entities.channel.unions.AudioChannelUnion;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;
import net.dv8tion.jda.api.utils.messages.MessageCreateData;
/**
* Command that return a random picture of cat.
*/
public class Music implements SlashCommand {
private static final String PLAYLIST_LIMIT = "playlist-limit";
private final Logger logger = LogManager.getLogger();
@Override
public void action(SlashCommandEvent event) {
public void action(SlashCommandInteractionEvent event) {
GuildAudioBotService audio = GuildAudioBotService.getInstance(event.getGuild());
String action = event.getSubcommandName();
event.deferReply().queue();
switch (action) {
case "play":
if (event.getMember().getVoiceState().inVoiceChannel()) {
VoiceChannel voiceChanel = event.getMember().getVoiceState().getChannel();
logger.info("Connecting to " + voiceChanel.getName() + "...");
if (event.getMember().getVoiceState().inAudioChannel()) {
AudioChannelUnion voiceChanel = event.getMember().getVoiceState().getChannel();
logger.info("Connecting to {}...", voiceChanel.getName());
OptionMapping url = event.getOption("url");
if (event.getOption("playlist-limit") == null) {
if (event.getOption(PLAYLIST_LIMIT) == null) {
audio.loadAndPlay(event, voiceChanel, url.getAsString(), 30, false);
} else {
long limit = event.getOption("playlist-limit").getAsLong();
long limit = event.getOption(PLAYLIST_LIMIT).getAsLong();
audio.loadAndPlay(event, voiceChanel, url.getAsString(), (int) limit, false);
}
} else {
Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicError("You are not in a voice channel !")).build();
MessageCreateData message = new MessageCreateBuilder().setEmbeds(EmbedMessageUtils.getMusicError("You are not in a voice channel !")).build();
event.getHook().setEphemeral(true).sendMessage(message).queue();
}
break;
@ -52,10 +57,10 @@ public class Music implements SlashCommand {
if (event.getOption("next") != null) {
next = event.getOption("next").getAsBoolean();
}
if (event.getOption("playlist-limit") == null) {
if (event.getOption(PLAYLIST_LIMIT) == null) {
audio.add(event, url.getAsString(), 30, next);
} else {
long limit = event.getOption("playlist-limit").getAsLong();
long limit = event.getOption(PLAYLIST_LIMIT).getAsLong();
audio.add(event, url.getAsString(), (int) limit, next);
}
break;
@ -91,7 +96,7 @@ public class Music implements SlashCommand {
@Override
public List<OptionData> getOptions() {
return null;
return Collections.emptyList();
}
@Override
@ -99,11 +104,11 @@ public class Music implements SlashCommand {
ArrayList<SubcommandData> subCommandList = new ArrayList<>();
subCommandList.add(new SubcommandData("play", "Play music")
.addOption(OptionType.STRING, "url", "The URL of the video to play", true)
.addOption(OptionType.INTEGER, "playlist-limit", "If a playlist is loaded, enter the max number of loaded tracks (default to 30)"));
.addOption(OptionType.INTEGER, PLAYLIST_LIMIT, "If a playlist is loaded, enter the max number of loaded tracks (default to 30)"));
subCommandList.add(new SubcommandData("add", "Add track to queue")
.addOption(OptionType.STRING, "url", " The URL of the video to play", true)
.addOption(OptionType.BOOLEAN, "next", "If true, track will be added on top of the playlist and will be the next to play")
.addOption(OptionType.INTEGER, "playlist-limit", "If a playlist is loaded, enter the max number of loaded tracks (default to 30)"));
.addOption(OptionType.INTEGER, PLAYLIST_LIMIT, "If a playlist is loaded, enter the max number of loaded tracks (default to 30)"));
subCommandList.add(new SubcommandData("pause", "Pause playback"));
subCommandList.add(new SubcommandData("resume", "Resume playback"));
subCommandList.add(new SubcommandData("stop", "Stop playback"));

View File

@ -5,16 +5,17 @@ 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;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
import net.dv8tion.jda.api.interactions.components.Button;
import net.dv8tion.jda.api.interactions.components.buttons.Button;
import java.util.Collections;
import java.util.List;
public class Rank implements SlashCommand {
@Override
public void action(SlashCommandEvent event) {
public void action(SlashCommandInteractionEvent event) {
String url = SpringContext.getAppContext().getBean(BotConfigLoader.class).url();
event.deferReply().queue();
UserStatsUtils userStats = UserStatsUtils.getINSTANCE();
@ -31,12 +32,12 @@ public class Rank implements SlashCommand {
@Override
public List<OptionData> getOptions() {
return null;
return Collections.emptyList();
}
@Override
public List<SubcommandData> getSubcommands() {
return null;
return Collections.emptyList();
}
@Override

View File

@ -4,7 +4,7 @@ package net.Broken.Tools;
import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel;
import net.dv8tion.jda.api.requests.RestAction;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@ -40,7 +40,7 @@ public class AutoVoiceChannel {
return;
GuildPreferenceEntity pref = SettingsUtils.getInstance().getPreference(guild);
if (pref.isAutoVoice() && voiceChannel.getId().equals(pref.getAutoVoiceChannelID())) {
logger.info("Creating new voice channel for Guild : " + guild.getName());
logger.info("Creating new voice channel for Guild : {}", guild.getName());
VoiceChannel newChannel = voiceChannel.createCopy().complete();
int next = getNextNumber();
String title = pref.getAutoVoiceChannelTitle();

View File

@ -1,6 +1,7 @@
package net.Broken.Tools.Command;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
@ -13,7 +14,7 @@ import net.Broken.Tools.FindContentOnWebPage;
import net.Broken.Tools.LimitChecker;
import net.Broken.Tools.Random.TrueRandom;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
@ -39,7 +40,7 @@ public abstract class NumberedSlashCommand implements SlashCommand {
* @param divClass DivClass to search to extract image
* @param htmlType HTML tag to extract image (img)
*/
public NumberedSlashCommand(Logger logger, String baseURL, String urlSuffix, String divClass, String htmlType) {
protected NumberedSlashCommand(Logger logger, String baseURL, String urlSuffix, String divClass, String htmlType) {
this.logger = logger;
this.baseURL = baseURL;
this.divClass = divClass;
@ -48,19 +49,19 @@ public abstract class NumberedSlashCommand implements SlashCommand {
try {
logger.debug("Checking max...");
maxNumber = LimitChecker.doYourJob(baseURL, 2, urlSuffix);
logger.info("Limit is " + maxNumber);
logger.info("Limit is {}",maxNumber);
} catch (IOException e) {
logger.catching(e);
}
}
public NumberedSlashCommand(Logger logger, String baseURL, String urlSuffix) {
protected NumberedSlashCommand(Logger logger, String baseURL, String urlSuffix) {
this(logger, baseURL, urlSuffix, null, null);
}
@Override
public void action(SlashCommandEvent event) {
public void action(SlashCommandInteractionEvent event) {
event.deferReply().queue();
try {
String result = poll();
@ -82,7 +83,7 @@ public abstract class NumberedSlashCommand implements SlashCommand {
}
protected void checkRandom() throws IOException {
logger.trace("Queue size: " + randomQueue.size());
logger.trace("Queue size: {}", randomQueue.size());
if (randomQueue.isEmpty()) {
logger.debug("Queue empty, update it.");
fillRandomQueue();
@ -97,12 +98,12 @@ public abstract class NumberedSlashCommand implements SlashCommand {
@Override
public List<OptionData> getOptions() {
return null;
return Collections.emptyList();
}
@Override
public List<SubcommandData> getSubcommands() {
return null;
return Collections.emptyList();
}
}

View File

@ -4,6 +4,8 @@ import net.Broken.BotConfigLoader;
import net.Broken.MainBot;
import net.Broken.SlashCommand;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.interactions.commands.build.Commands;
import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData;
import net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@ -21,6 +23,8 @@ import java.util.Set;
public class SlashCommandLoader {
private static final Logger logger = LogManager.getLogger();
private SlashCommandLoader() {}
/**
* Search all implemented Command interface class and add it to MainBot.commands HashMap
*/
@ -33,14 +37,14 @@ public class SlashCommandLoader {
);
Set<Class<? extends SlashCommand>> modules = reflections.getSubTypesOf(SlashCommand.class);
logger.info("Find " + modules.size() + " Command:");
logger.info("Find {} Command:", modules.size());
for (Class<? extends SlashCommand> 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);
logger.info("...{}", name);
if (command.isAnnotationPresent(NoDev.class) && config.mode().equals("DEV")) {
logger.warn("Command disabled in dev mode");
@ -49,23 +53,24 @@ public class SlashCommandLoader {
MainBot.slashCommands.put(name, command.getDeclaredConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException | InvocationTargetException |
NoSuchMethodException e) {
logger.error("Failed to load " + name + "!");
logger.error("Failed to load {} !", name);
}
}
} else {
logger.trace("Ignored command: " + name);
logger.trace("Ignored command: {}", name);
}
}
}
public static void registerSlashCommands(CommandListUpdateAction commandListUpdateAction) {
MainBot.slashCommands.forEach((k, v) -> {
CommandData command = new CommandData(k, v.getDescription());
SlashCommandData command = Commands.slash(k, v.getDescription());
if (v.getOptions() != null)
command.addOptions(v.getOptions());
if (v.getSubcommands() != null) {
command.addSubcommands(v.getSubcommands());
}
// TODO Change slash command perm
command.setDefaultEnabled(!v.isDisableByDefault());
commandListUpdateAction.addCommands(command);
});

View File

@ -8,7 +8,8 @@ import net.Broken.SpringContext;
import net.Broken.Tools.DayListener.NewDayListener;
import net.Broken.Tools.FindContentOnWebPage;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
@ -44,12 +45,8 @@ public class DailyMadame implements NewDayListener {
if (day != Calendar.MONDAY && day != Calendar.SUNDAY) {
LocalDate now = LocalDate.now().minusDays(1);
String date = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(now);
String url = "https://www.bonjourmadame.fr/" + date + "/";
imgUrl = FindContentOnWebPage.doYourJob(url, "post-content", "img");
} else {
Madame command = (Madame) MainBot.slashCommands.get("madame");
imgUrl = command.poll();
@ -64,17 +61,14 @@ public class DailyMadame implements NewDayListener {
for (TextChannel iterator : guild.getTextChannels()) {
if (iterator.isNSFW() && iterator.canTalk()) {
chanel = iterator;
logger.debug("break: " + chanel.getName());
logger.debug("break: {}", chanel.getName());
break;
}
}
if (chanel != null) {
chanel.sendMessage("Madame of the day :kissing_heart: \n" + imgUrl).queue();
} else {
logger.info("No NSFW chanel found for " + guild.getName() + ", ignoring it!");
logger.info("No NSFW chanel found for {}, ignoring it!", guild.getName());
}
}
}

View File

@ -2,7 +2,6 @@ package net.Broken.Tools;
import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.Broken.DB.Repository.GuildPreferenceRepository;
import net.Broken.DB.Repository.UserRepository;
import net.Broken.SpringContext;
import net.dv8tion.jda.api.entities.Guild;
import org.apache.logging.log4j.LogManager;
@ -14,13 +13,10 @@ public class SettingsUtils {
private static SettingsUtils INSTANCE;
private final Logger logger = LogManager.getLogger();
private final GuildPreferenceRepository guildPreferenceRepository;
private final UserRepository userRepository;
private SettingsUtils() {
ApplicationContext context = SpringContext.getAppContext();
guildPreferenceRepository = (GuildPreferenceRepository) context.getBean("guildPreferenceRepository");
userRepository = (UserRepository) context.getBean("userRepository");
}
public static SettingsUtils getInstance() {
@ -29,7 +25,7 @@ public class SettingsUtils {
public GuildPreferenceEntity getPreference(Guild guild) {
return guildPreferenceRepository.findByGuildId(guild.getId()).orElseGet(()->{
logger.info("Generate default pref for " + guild.getName());
logger.info("Generate default pref for {}", guild.getName());
return guildPreferenceRepository.save(GuildPreferenceEntity.getDefault(guild.getId()));
});
}

View File

@ -60,16 +60,16 @@ public class UserStatsUtils {
logger.debug(userEntity);
logger.debug(userEntity.getUserStats());
if (userEntity.getUserStats() == null || userEntity.getUserStats().size() == 0 || userEntity.getUserStats().size() < jdaUser.getMutualGuilds().size()) {
logger.debug("Stats not found for " + userEntity.getUsername());
if (userEntity.getUserStats() == null || userEntity.getUserStats().isEmpty() || userEntity.getUserStats().size() < jdaUser.getMutualGuilds().size()) {
logger.debug("Stats not found for {}", userEntity.getUsername());
List<UserStats> stats;
if (userEntity.getUserStats() == null || userEntity.getUserStats().size() == 0) {
logger.debug("No stats found for user " + jdaUser.getName() + ", use blank.");
if (userEntity.getUserStats() == null || userEntity.getUserStats().isEmpty()) {
logger.debug("No stats found for user {}, use blank.", jdaUser.getName());
logger.debug("Creating stats for guilds: ");
stats = new ArrayList<>();
for (Guild guid : jdaUser.getMutualGuilds()) {
logger.debug("..." + guid.getName());
logger.debug("...{}", guid.getName());
stats.add(new UserStats(guid.getId(), userEntity));
}
} else {
@ -81,7 +81,7 @@ public class UserStatsUtils {
for (Guild guid : jdaUser.getMutualGuilds()) {
logger.debug(guid.getName());
if (!guildStat.contains(guid.getId())) {
logger.debug("Guild " + guid.getName() + " stats don't exist");
logger.debug("Guild {} stats don't exist", guid.getName());
stats.add(new UserStats(guid.getId(), userEntity));
}
}
@ -108,8 +108,8 @@ public class UserStatsUtils {
.orElseGet(() -> genUserEntity(member.getUser()));
List<UserStats> userStatsList = userStatsRepository.findByUserAndGuildId(userEntity, member.getGuild().getId());
if (userStatsList.size() == 0) {
logger.debug("User stats not found for user " + userEntity.getUsername() + " guild: " + member.getGuild().getId());
if (userStatsList.isEmpty()) {
logger.debug("User stats not found for user {} guild: {}", userEntity.getUsername(), member.getGuild().getId());
getUserStats(userEntity);
userStatsList = userStatsRepository.findByUserAndGuildId(userEntity, member.getGuild().getId());
}
@ -119,8 +119,8 @@ public class UserStatsUtils {
public UserStats getGuildUserStats(UserEntity userEntity, String guildId) {
List<UserStats> userStatsList = userStatsRepository.findByUserAndGuildId(userEntity, guildId);
if (userStatsRepository.findByUserAndGuildId(userEntity, guildId).size() == 0) {
logger.debug("User stats not found for user " + userEntity.getUsername() + " guild: " + guildId);
if (userStatsRepository.findByUserAndGuildId(userEntity, guildId).isEmpty()) {
logger.debug("User stats not found for user {} guild: {}", userEntity.getUsername(), guildId);
getUserStats(userEntity);
userStatsList = userStatsRepository.findByUserAndGuildId(userEntity, guildId);
}
@ -163,7 +163,6 @@ public class UserStatsUtils {
public GuildStatsPack getStatPack(UserEntity userEntity, String guildId) {
UserStats userStats = getGuildUserStats(userEntity, guildId);
GuildStats selfGuildStats = null;
List<UserStats> allStats = userStatsRepository.findByGuildId(guildId);
@ -183,13 +182,13 @@ public class UserStatsUtils {
}
ranked.add(temp);
}
if (needCache.size() != 0) {
if (!needCache.isEmpty()) {
logger.info("Cache mismatch, loading all guild");
MainBot.jda.getGuildById(guildId).loadMembers().get();
for (UserStats stats : needCache) {
Member member = guild.getMemberById(stats.getUser().getDiscordId());
if (member == null) {
logger.warn("Can't find member '" + stats.getUser().getUsername() + "'after load, User leave the guild ?");
logger.warn("Can't find member '{}'after load, User leave the guild ?", stats.getUser().getUsername());
continue;
}
String avatar = member.getUser().getAvatarUrl();
@ -253,10 +252,10 @@ public class UserStatsUtils {
@Override
public void run() {
while (member.getVoiceState().inVoiceChannel()) {
while (member.getVoiceState().inAudioChannel()) {
try {
Thread.sleep(10000);
if (member.getVoiceState().inVoiceChannel())
if (member.getVoiceState().inAudioChannel())
if (member.getGuild().getAfkChannel() != member.getVoiceState().getChannel())
UserStatsUtils.getINSTANCE().addVocalCount(member);