Compare commits

..

10 Commits

Author SHA1 Message Date
renovate[bot]
7c41e0bf43
⬆️ Update dependency org.springdoc:springdoc-openapi-security to v1.7.0 2023-12-14 14:07:45 +00:00
b8099a1dd3
Merge pull request #219 from Sebclem/renovate/org.springdoc-springdoc-openapi-ui-1.x
⬆️ Update dependency org.springdoc:springdoc-openapi-ui to v1.7.0
2023-12-14 15:06:54 +01:00
342a587e18
Merge pull request #220 from Sebclem/renovate/spring-boot
⬆️ Update plugin org.springframework.boot to v2.7.18
2023-12-14 15:06:35 +01:00
f4f8c49846
Merge pull request #212 from Sebclem/renovate/hibernate-core
⬆️ Update dependency org.hibernate:hibernate-validator to v7.0.5.Final
2023-12-14 15:06:19 +01:00
79e35e1512
Feature/jda 5 (#223)
* Fist pass

* All easyfix done

* Fix slash command permission

* Fix Auth manager

---------

Co-authored-by: sclement <sebastien.clement@asso-cocktail.fr>
2023-12-14 15:05:21 +01:00
renovate[bot]
9741f851a5
⬆️ Update plugin org.springframework.boot to v2.7.18 2023-11-23 09:39:09 +00:00
55c5e54e0a
Merge branch 'hotfix/2.0.4' 2023-04-14 19:37:34 +02:00
f483b19b2d
Quick fix startup 2023-04-14 19:37:14 +02:00
renovate[bot]
7f8c31ece2
⬆️ Update dependency org.springdoc:springdoc-openapi-ui to v1.7.0 2023-04-02 10:58:05 +00:00
renovate[bot]
86a439c98b
⬆️ Update dependency org.hibernate:hibernate-validator to v7.0.5.Final 2022-08-03 13:44:06 +00:00
29 changed files with 375 additions and 627 deletions

View File

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

View File

@ -1,5 +1,5 @@
plugins { plugins {
id 'org.springframework.boot' version '2.7.2' id 'org.springframework.boot' version '2.7.18'
id 'io.spring.dependency-management' version '1.0.12.RELEASE' id 'io.spring.dependency-management' version '1.0.12.RELEASE'
id 'java' id 'java'
id 'groovy' id 'groovy'
@ -35,7 +35,7 @@ dependencies {
implementation('org.springframework.boot:spring-boot-starter-actuator') implementation('org.springframework.boot:spring-boot-starter-actuator')
implementation('io.micrometer:micrometer-registry-prometheus:1.9.2') implementation('io.micrometer:micrometer-registry-prometheus:1.9.2')
implementation('org.springdoc:springdoc-openapi-ui:1.6.9') implementation('org.springdoc:springdoc-openapi-ui:1.7.0')
implementation('org.springdoc:springdoc-openapi-security:1.7.0') implementation('org.springdoc:springdoc-openapi-security:1.7.0')
implementation('org.liquibase:liquibase-core') implementation('org.liquibase:liquibase-core')
@ -45,10 +45,10 @@ dependencies {
implementation('io.jsonwebtoken:jjwt-jackson:0.11.5') implementation('io.jsonwebtoken:jjwt-jackson:0.11.5')
implementation('com.sedmelluq:lavaplayer:1.3.78') implementation('com.sedmelluq:lavaplayer:1.3.78')
implementation('net.dv8tion:JDA:4.4.1_353') implementation('net.dv8tion:JDA:5.0.0-beta.18')
implementation(platform("org.apache.logging.log4j:log4j-bom:2.18.0")) implementation(platform("org.apache.logging.log4j:log4j-bom:2.18.0"))
implementation group: 'org.hibernate', name: 'hibernate-validator', version: '7.0.4.Final' implementation group: 'org.hibernate', name: 'hibernate-validator', version: '7.0.5.Final'
// Use MySQL Connector-J // Use MySQL Connector-J
implementation('mysql:mysql-connector-java:8.0.30') implementation('mysql:mysql-connector-java:8.0.30')

View File

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

View File

@ -1,40 +1,45 @@
package net.Broken.Api.Security; package net.Broken.Api.Security;
import net.Broken.Api.Security.Components.UnauthorizedHandler; import static org.springframework.security.config.Customizer.withDefaults;
import net.Broken.Api.Security.Filters.JwtFilter;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import net.Broken.Api.Security.Components.UnauthorizedHandler;
import net.Broken.Api.Security.Filters.JwtFilter;
@EnableWebSecurity @EnableWebSecurity
@Configuration @Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter { public class SecurityConfig {
private final UnauthorizedHandler unauthorizedHandler; private final UnauthorizedHandler unauthorizedHandler;
public SecurityConfig(UnauthorizedHandler unauthorizedHandler) { public SecurityConfig(UnauthorizedHandler unauthorizedHandler) {
this.unauthorizedHandler = unauthorizedHandler; this.unauthorizedHandler = unauthorizedHandler;
} }
@Override @Bean
protected void configure(HttpSecurity http) throws Exception { public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable() http.cors(withDefaults()).csrf(csrf -> csrf.disable())
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() .exceptionHandling(handling -> handling.authenticationEntryPoint(unauthorizedHandler))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .sessionManagement(management -> management.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeRequests() .authorizeHttpRequests(requests -> requests
.antMatchers("/api/v2/auth/**").permitAll() .antMatchers("/api/v2/auth/**").permitAll()
.antMatchers("/api/v2/guild/inviteLink").permitAll() .antMatchers("/api/v2/guild/inviteLink").permitAll()
.antMatchers("/swagger-ui/**").permitAll() .antMatchers("/swagger-ui/**").permitAll()
.antMatchers("/swagger-ui.html").permitAll() .antMatchers("/swagger-ui.html").permitAll()
.antMatchers("/v3/api-docs/**").permitAll() .antMatchers("/v3/api-docs/**").permitAll()
.antMatchers("/actuator/**").permitAll() .antMatchers("/actuator/**").permitAll()
.anyRequest().authenticated(); .anyRequest().authenticated());
http.addFilterBefore(jwtFilter(), UsernamePasswordAuthenticationFilter.class); http.addFilterBefore(jwtFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
} }
@Bean @Bean
@ -42,10 +47,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
return new JwtFilter(); return new JwtFilter();
} }
@Bean @Bean
@Override public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
public AuthenticationManager authenticationManagerBean() throws Exception { return http.getSharedObject(AuthenticationManagerBuilder.class)
return super.authenticationManagerBean(); .build();
} }
} }

View File

@ -58,11 +58,13 @@ public class DiscordOauthService {
try { try {
HttpResponse<String> response = makeFormPost(this.tokenEndpoint, data); HttpResponse<String> response = makeFormPost(this.tokenEndpoint, data);
if (response.statusCode() != 200) { if (response.statusCode() != 200) {
logger.warn("[OAUTH] Invalid response while getting AccessToken: Status Code: " + response.statusCode() + " Body:" + response.body()); logger.warn("[OAUTH] Invalid response while getting AccessToken: Status Code: " + response.statusCode()
+ " Body:" + response.body());
throw new OAuthLoginFail(); throw new OAuthLoginFail();
} }
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
AccessTokenResponse accessTokenResponse = objectMapper.readValue(response.body(), AccessTokenResponse.class); AccessTokenResponse accessTokenResponse = objectMapper.readValue(response.body(),
AccessTokenResponse.class);
return accessTokenResponse.access_token(); return accessTokenResponse.access_token();
} catch (IOException | InterruptedException e) { } catch (IOException | InterruptedException e) {
logger.catching(e); logger.catching(e);
@ -81,7 +83,8 @@ public class DiscordOauthService {
HttpClient client = HttpClient.newHttpClient(); HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) { if (response.statusCode() != 200) {
logger.warn("[OAUTH] Invalid response while getting UserInfo: Status Code: " + response.statusCode() + " Body:" + response.body()); logger.warn("[OAUTH] Invalid response while getting UserInfo: Status Code: " + response.statusCode()
+ " Body:" + response.body());
throw new OAuthLoginFail(); throw new OAuthLoginFail();
} }
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
@ -99,14 +102,14 @@ public class DiscordOauthService {
try { try {
HttpResponse<String> response = makeFormPost(this.tokenRevokeEndpoint, data); HttpResponse<String> response = makeFormPost(this.tokenRevokeEndpoint, data);
if (response.statusCode() != 200) { if (response.statusCode() != 200) {
logger.warn("[OAUTH] Invalid response while token revocation: Status Code: " + response.statusCode() + " Body:" + response.body()); logger.warn("[OAUTH] Invalid response while token revocation: Status Code: " + response.statusCode()
+ " Body:" + response.body());
} }
} catch (IOException | InterruptedException e) { } catch (IOException | InterruptedException e) {
logger.catching(e); logger.catching(e);
} }
} }
public record LoginOrRegisterResponse<T>(T response, boolean created) { public record LoginOrRegisterResponse<T>(T response, boolean created) {
} }
@ -126,7 +129,8 @@ public class DiscordOauthService {
userEntity.setUsername(discordOauthUserInfo.username()); userEntity.setUsername(discordOauthUserInfo.username());
updated = true; updated = true;
} }
if(userEntity.getDiscriminator() == null || !userEntity.getDiscriminator().equals(discordOauthUserInfo.discriminator())){ if (userEntity.getDiscriminator() == null
|| !userEntity.getDiscriminator().equals(discordOauthUserInfo.discriminator())) {
userEntity.setDiscriminator(discordOauthUserInfo.discriminator()); userEntity.setDiscriminator(discordOauthUserInfo.discriminator());
updated = true; updated = true;
} }
@ -141,7 +145,6 @@ public class DiscordOauthService {
return userEntity; return userEntity;
} }
private String getFormString(HashMap<String, String> params) { private String getFormString(HashMap<String, String> params) {
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
boolean first = true; boolean first = true;
@ -157,7 +160,8 @@ public class DiscordOauthService {
return result.toString(); return result.toString();
} }
private HttpResponse<String> makeFormPost(String endpoint, HashMap<String, String> data) throws IOException, InterruptedException { private HttpResponse<String> makeFormPost(String endpoint, HashMap<String, String> data)
throws IOException, InterruptedException {
HttpRequest.BodyPublisher body = HttpRequest.BodyPublishers.ofString(getFormString(data)); HttpRequest.BodyPublisher body = HttpRequest.BodyPublishers.ofString(getFormString(data));
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(tokenEndpoint)) .uri(URI.create(tokenEndpoint))
@ -168,5 +172,4 @@ public class DiscordOauthService {
return client.send(request, HttpResponse.BodyHandlers.ofString()); return client.send(request, HttpResponse.BodyHandlers.ofString());
} }
} }

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.audio.hooks.ConnectionStatus;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member; 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.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
@ -28,7 +30,7 @@ public class AudioService {
Member member = guild.getMemberById(userId); Member member = guild.getMemberById(userId);
VoiceChannel channel = guild.getAudioManager().getConnectedChannel(); AudioChannelUnion channel = guild.getAudioManager().getConnectedChannel();
ConnectionStatus status = guild.getAudioManager().getConnectionStatus(); ConnectionStatus status = guild.getAudioManager().getConnectionStatus();
if (channel != null) { if (channel != null) {
// The user can view the audio status if: // 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.Permission;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.User; 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 org.springframework.stereotype.Service;
import java.util.ArrayList; import java.util.ArrayList;
@ -35,7 +38,7 @@ public class GuildService {
net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId); net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId);
Member member = guild.getMemberById(userId); Member member = guild.getMemberById(userId);
List<Channel> voiceChannels = new ArrayList<>(); 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)) { if (member.hasPermission(voiceChannel, Permission.VIEW_CHANNEL)) {
voiceChannels.add(new Channel(voiceChannel.getId(), voiceChannel.getName())); 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); net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId);
Member member = guild.getMemberById(userId); Member member = guild.getMemberById(userId);
List<Channel> voiceChannels = new ArrayList<>(); 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)) { if (member.hasPermission(textChannel, Permission.VIEW_CHANNEL)) {
voiceChannels.add(new Channel(textChannel.getId(), textChannel.getName())); voiceChannels.add(new Channel(textChannel.getId(), textChannel.getName()));
} }

View File

@ -24,17 +24,19 @@ import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.EmbedMessageUtils;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.Emoji;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.VoiceChannel; import net.dv8tion.jda.api.entities.channel.middleman.AudioChannel;
import net.dv8tion.jda.api.events.interaction.GenericInteractionCreateEvent; import net.dv8tion.jda.api.entities.channel.unions.AudioChannelUnion;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.entities.emoji.Emoji;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.InteractionHook;
import net.dv8tion.jda.api.interactions.components.ActionRow; import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.Button; import net.dv8tion.jda.api.interactions.components.buttons.Button;
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;
import net.dv8tion.jda.api.utils.messages.MessageCreateData;
public class GuildAudioBotService { public class GuildAudioBotService {
@ -47,7 +49,7 @@ public class GuildAudioBotService {
/** /**
* Extrem limit for playlist * Extrem limit for playlist
*/ */
private final int listExtremLimit = 300; private static final int LIST_EXTREM_LIMIT = 300;
private final Guild guild; private final Guild guild;
private final Logger logger = LogManager.getLogger(); private final Logger logger = LogManager.getLogger();
@ -66,9 +68,7 @@ public class GuildAudioBotService {
} }
public static GuildAudioBotService getInstance(Guild guild) { public static GuildAudioBotService getInstance(Guild guild) {
if (!INSTANCES.containsKey(guild)) { INSTANCES.computeIfAbsent(guild, k -> new GuildAudioBotService(guild));
INSTANCES.put(guild, new GuildAudioBotService(guild));
}
return INSTANCES.get(guild); return INSTANCES.get(guild);
} }
@ -80,13 +80,13 @@ public class GuildAudioBotService {
* @param playlistLimit Limit of playlist * @param playlistLimit Limit of playlist
* @param onHead True for adding audio track on top of playlist * @param onHead True for adding audio track on top of playlist
*/ */
public void loadAndPlay(SlashCommandEvent event, VoiceChannel voiceChannel, final String trackUrl, int playlistLimit, boolean onHead) { public void loadAndPlay(SlashCommandInteractionEvent event, AudioChannel voiceChannel, final String trackUrl, int playlistLimit, boolean onHead) {
audioPlayerManager.loadItemOrdered(guildAudioManager, trackUrl, new AudioLoadResultHandler() { audioPlayerManager.loadItemOrdered(guildAudioManager, trackUrl, new AudioLoadResultHandler() {
@Override @Override
public void trackLoaded(AudioTrack track) { public void trackLoaded(AudioTrack track) {
logger.info("[" + guild + "] Single Track detected!"); logger.info("[{}] Single Track detected!", guild.getName());
UserAudioTrack uat = new UserAudioTrack(event.getUser(), track); UserAudioTrack uat = new UserAudioTrack(event.getUser(), track);
Message message = new MessageBuilder() MessageCreateData message = new MessageCreateBuilder()
.setEmbeds(EmbedMessageUtils.getMusicAdded(track.getInfo(), event.getMember(), -1)) .setEmbeds(EmbedMessageUtils.getMusicAdded(track.getInfo(), event.getMember(), -1))
.build(); .build();
clearLastButton(); clearLastButton();
@ -96,10 +96,10 @@ public class GuildAudioBotService {
@Override @Override
public void playlistLoaded(AudioPlaylist playlist) { public void playlistLoaded(AudioPlaylist playlist) {
logger.info("[" + guild + "] Playlist detected! Limit: " + playlistLimit); logger.info("[{}] Playlist detected! Limit: {}", guild, playlistLimit);
AudioTrack firstTrack = playlist.getSelectedTrack(); AudioTrack firstTrack = playlist.getSelectedTrack();
int size = Math.min(playlist.getTracks().size(), playlistLimit); int size = Math.min(playlist.getTracks().size(), playlistLimit);
Message message = new MessageBuilder() MessageCreateData message = new MessageCreateBuilder()
.setEmbeds(EmbedMessageUtils.getMusicAdded(firstTrack.getInfo(), event.getMember(), size)) .setEmbeds(EmbedMessageUtils.getMusicAdded(firstTrack.getInfo(), event.getMember(), size))
.build(); .build();
clearLastButton(); clearLastButton();
@ -109,16 +109,16 @@ public class GuildAudioBotService {
@Override @Override
public void noMatches() { public void noMatches() {
logger.warn("[" + guild + "] Cant find media!"); logger.warn("[{}] Cant find media!", guild);
Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicError("Video not found !")).build(); MessageCreateData message = new MessageCreateBuilder().setEmbeds(EmbedMessageUtils.getMusicError("Video not found !")).build();
event.getHook().setEphemeral(true).sendMessage(message).queue(); event.getHook().setEphemeral(true).sendMessage(message).queue();
} }
@Override @Override
public void loadFailed(FriendlyException exception) { public void loadFailed(FriendlyException exception) {
logger.error("[" + guild + "] Can't load media!"); logger.error("[{}] Can't load media!", guild);
logger.error(exception.getMessage()); logger.error(exception.getMessage());
Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicError("Playback error !")).build(); MessageCreateData message = new MessageCreateBuilder().setEmbeds(EmbedMessageUtils.getMusicError("Playback error !")).build();
event.getHook().setEphemeral(true).sendMessage(message).queue(); event.getHook().setEphemeral(true).sendMessage(message).queue();
} }
}); });
@ -126,12 +126,12 @@ public class GuildAudioBotService {
public boolean loadAndPlaySync(String trackUrl, String userId) throws ExecutionException, InterruptedException { public boolean loadAndPlaySync(String trackUrl, String userId) throws ExecutionException, InterruptedException {
Member member = guild.getMemberById(userId); Member member = guild.getMemberById(userId);
VoiceChannel playedChanel = guild.getAudioManager().getConnectedChannel(); AudioChannelUnion playedChanel = guild.getAudioManager().getConnectedChannel();
final String uuid = UUID.randomUUID().toString(); final String uuid = UUID.randomUUID().toString();
Future<Void> future = audioPlayerManager.loadItemOrdered(guildAudioManager, trackUrl, new AudioLoadResultHandler() { Future<Void> future = audioPlayerManager.loadItemOrdered(guildAudioManager, trackUrl, new AudioLoadResultHandler() {
@Override @Override
public void trackLoaded(AudioTrack track) { public void trackLoaded(AudioTrack track) {
logger.info("[" + guild + "] Auto add " + track.getInfo().title + " to playlist."); logger.info("[{}] Auto add {} to playlist.", guild, track.getInfo().title);
UserAudioTrack userAudioTrack = new UserAudioTrack(member.getUser(), track); UserAudioTrack userAudioTrack = new UserAudioTrack(member.getUser(), track);
play(guild, playedChanel, guildAudioManager, userAudioTrack, true); play(guild, playedChanel, guildAudioManager, userAudioTrack, true);
addStatus.put(uuid, true); addStatus.put(uuid, true);
@ -140,7 +140,7 @@ public class GuildAudioBotService {
@Override @Override
public void playlistLoaded(AudioPlaylist playlist) { public void playlistLoaded(AudioPlaylist playlist) {
AudioTrack track = playlist.getTracks().get(0); AudioTrack track = playlist.getTracks().get(0);
logger.info("[" + guild + "] Auto add " + track.getInfo().title + " to playlist."); logger.info("[{}] Auto add {} to playlist.", guild, track.getInfo().title);
UserAudioTrack userAudioTrack = new UserAudioTrack(member.getUser(), track); UserAudioTrack userAudioTrack = new UserAudioTrack(member.getUser(), track);
play(guild, playedChanel, guildAudioManager, userAudioTrack, true); play(guild, playedChanel, guildAudioManager, userAudioTrack, true);
addStatus.put(uuid, true); addStatus.put(uuid, true);
@ -148,13 +148,13 @@ public class GuildAudioBotService {
@Override @Override
public void noMatches() { public void noMatches() {
logger.warn("[" + guild + "] Track not found: " + trackUrl); logger.warn("[{}] Track not found: {}", guild, trackUrl);
addStatus.put(uuid, false); addStatus.put(uuid, false);
} }
@Override @Override
public void loadFailed(FriendlyException exception) { public void loadFailed(FriendlyException exception) {
logger.error("[" + guild + "] Cant load media!"); logger.error("[{}] Cant load media!", guild);
logger.error(exception.getMessage()); logger.error(exception.getMessage());
addStatus.put(uuid, false); addStatus.put(uuid, false);
} }
@ -174,7 +174,7 @@ public class GuildAudioBotService {
*/ */
public void playListLoader(AudioPlaylist playlist, int playlistLimit, User user, boolean onHead) { public void playListLoader(AudioPlaylist playlist, int playlistLimit, User user, boolean onHead) {
VoiceChannel playedChanel = guild.getAudioManager().getConnectedChannel(); AudioChannelUnion playedChanel = guild.getAudioManager().getConnectedChannel();
List<AudioTrack> tracks = playlist.getTracks(); List<AudioTrack> tracks = playlist.getTracks();
if (onHead) if (onHead)
Collections.reverse(tracks); Collections.reverse(tracks);
@ -183,7 +183,7 @@ public class GuildAudioBotService {
for (AudioTrack track : playlist.getTracks()) { for (AudioTrack track : playlist.getTracks()) {
UserAudioTrack uat = new UserAudioTrack(user, track); UserAudioTrack uat = new UserAudioTrack(user, track);
play(guild, playedChanel, guildAudioManager, uat, onHead); play(guild, playedChanel, guildAudioManager, uat, onHead);
if ((playlistLimit != -1 && i >= playlistLimit) || i > listExtremLimit) if ((playlistLimit != -1 && i >= playlistLimit) || i > LIST_EXTREM_LIMIT)
break; break;
i++; i++;
} }
@ -199,7 +199,7 @@ public class GuildAudioBotService {
* @param track Track to add to playlist * @param track Track to add to playlist
* @param onHead True for adding audio track on top of playlist * @param onHead True for adding audio track on top of playlist
*/ */
public void play(Guild guild, VoiceChannel channel, GuildAudioManager musicManager, UserAudioTrack track, boolean onHead) { public void play(Guild guild, AudioChannel channel, GuildAudioManager musicManager, UserAudioTrack track, boolean onHead) {
if (!guild.getAudioManager().isConnected()) if (!guild.getAudioManager().isConnected())
guild.getAudioManager().openAudioConnection(channel); guild.getAudioManager().openAudioConnection(channel);
if (!onHead) if (!onHead)
@ -208,39 +208,39 @@ public class GuildAudioBotService {
musicManager.scheduler.addNext(track); musicManager.scheduler.addNext(track);
} }
public void add(SlashCommandEvent event, String url, int playListLimit, boolean onHead) { public void add(SlashCommandInteractionEvent event, String url, int playListLimit, boolean onHead) {
if (guild.getAudioManager().isConnected()) { if (guild.getAudioManager().isConnected()) {
loadAndPlay(event, guild.getAudioManager().getConnectedChannel(), url, playListLimit, onHead); loadAndPlay(event, guild.getAudioManager().getConnectedChannel(), url, playListLimit, onHead);
} else { } else {
Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicError("Not connected to vocal chanel !")).build(); MessageCreateData message = new MessageCreateBuilder().setEmbeds(EmbedMessageUtils.getMusicError("Not connected to vocal chanel !")).build();
event.getHook().setEphemeral(true).sendMessage(message).queue(); event.getHook().setEphemeral(true).sendMessage(message).queue();
} }
} }
public void connect(VoiceChannel voiceChannel) { public void connect(AudioChannel voiceChannel) {
guild.getAudioManager().openAudioConnection(voiceChannel); guild.getAudioManager().openAudioConnection(voiceChannel);
} }
public void pause(GenericInteractionCreateEvent event) { public void pause(InteractionHook hook) {
pause(); pause();
Message message = new MessageBuilder().setEmbeds( MessageCreateData message = new MessageCreateBuilder().setEmbeds(
EmbedMessageUtils.buildStandar( EmbedMessageUtils.buildStandar(
new EmbedBuilder() new EmbedBuilder()
.setTitle(":pause_button: Playback paused") .setTitle(":pause_button: Playback paused")
.setColor(Color.green) .setColor(Color.green)
)).build(); )).build();
clearLastButton(); clearLastButton();
lastMessageWithButton = event.getHook().sendMessage(message).addActionRow(getActionButton()).complete(); lastMessageWithButton = hook.sendMessage(message).addActionRow(getActionButton()).complete();
} }
public void pause() { public void pause() {
guildAudioManager.scheduler.pause(); guildAudioManager.scheduler.pause();
} }
public void resume(GenericInteractionCreateEvent event) { public void resume(InteractionHook hook) {
Message message; MessageCreateData message;
if (guildAudioManager.player.getPlayingTrack() == null) { if (guildAudioManager.player.getPlayingTrack() == null) {
message = new MessageBuilder().setEmbeds( message = new MessageCreateBuilder().setEmbeds(
EmbedMessageUtils.buildStandar( EmbedMessageUtils.buildStandar(
new EmbedBuilder() new EmbedBuilder()
.setTitle(":warning: Nothing to play, playlist is empty !") .setTitle(":warning: Nothing to play, playlist is empty !")
@ -248,7 +248,7 @@ public class GuildAudioBotService {
)).build(); )).build();
} else { } else {
resume(); resume();
message = new MessageBuilder().setEmbeds( message = new MessageCreateBuilder().setEmbeds(
EmbedMessageUtils.buildStandar( EmbedMessageUtils.buildStandar(
new EmbedBuilder() new EmbedBuilder()
.setTitle(":arrow_forward: Playback resumed") .setTitle(":arrow_forward: Playback resumed")
@ -256,39 +256,39 @@ public class GuildAudioBotService {
)).build(); )).build();
} }
clearLastButton(); clearLastButton();
lastMessageWithButton = event.getHook().sendMessage(message).addActionRow(getActionButton()).complete(); lastMessageWithButton = hook.sendMessage(message).addActionRow(getActionButton()).complete();
} }
public void resume() { public void resume() {
guildAudioManager.scheduler.resume(); guildAudioManager.scheduler.resume();
} }
public void skipTrack(GenericInteractionCreateEvent event) { public void skipTrack(InteractionHook hook) {
skipTrack(); skipTrack();
Message message = new MessageBuilder().setEmbeds( MessageCreateData message = new MessageCreateBuilder().setEmbeds(
EmbedMessageUtils.buildStandar( EmbedMessageUtils.buildStandar(
new EmbedBuilder() new EmbedBuilder()
.setTitle(":track_next: Next Track") .setTitle(":track_next: Next Track")
.setColor(Color.green) .setColor(Color.green)
)).build(); )).build();
clearLastButton(); clearLastButton();
lastMessageWithButton = event.getHook().sendMessage(message).addActionRow(getActionButton()).complete(); lastMessageWithButton = hook.sendMessage(message).addActionRow(getActionButton()).complete();
} }
public void skipTrack() { public void skipTrack() {
guildAudioManager.scheduler.nextTrack(); guildAudioManager.scheduler.nextTrack();
} }
public void stop(GenericInteractionCreateEvent event) { public void stop(InteractionHook hook) {
stop(); stop();
Message message = new MessageBuilder().setEmbeds( MessageCreateData message = new MessageCreateBuilder().setEmbeds(
EmbedMessageUtils.buildStandar( EmbedMessageUtils.buildStandar(
new EmbedBuilder() new EmbedBuilder()
.setTitle(":stop_button: Playback stopped") .setTitle(":stop_button: Playback stopped")
.setColor(Color.green) .setColor(Color.green)
)).build(); )).build();
clearLastButton(); clearLastButton();
lastMessageWithButton = event.getHook().sendMessage(message).addActionRow(getActionButton()).complete(); lastMessageWithButton = hook.sendMessage(message).addActionRow(getActionButton()).complete();
} }
@ -298,16 +298,16 @@ public class GuildAudioBotService {
clearLastButton(); clearLastButton();
} }
public void disconnect(GenericInteractionCreateEvent event) { public void disconnect(InteractionHook hook) {
disconnect(); disconnect();
Message message = new MessageBuilder().setEmbeds( MessageCreateData message = new MessageCreateBuilder().setEmbeds(
EmbedMessageUtils.buildStandar( EmbedMessageUtils.buildStandar(
new EmbedBuilder() new EmbedBuilder()
.setTitle(":eject: Disconnected") .setTitle(":eject: Disconnected")
.setColor(Color.green) .setColor(Color.green)
)).build(); )).build();
clearLastButton(); clearLastButton();
event.getHook().sendMessage(message).queue(); hook.sendMessage(message).queue();
} }
public void disconnect() { public void disconnect() {
@ -316,24 +316,24 @@ public class GuildAudioBotService {
guild.getAudioManager().closeAudioConnection(); guild.getAudioManager().closeAudioConnection();
clearLastButton(); clearLastButton();
} }
public void info(GenericInteractionCreateEvent event) { public void info(InteractionHook hook) {
AudioTrackInfo info = guildAudioManager.scheduler.getInfo(); AudioTrackInfo info = guildAudioManager.scheduler.getInfo();
UserAudioTrack userAudioTrack = guildAudioManager.scheduler.getCurrentPlayingTrack(); UserAudioTrack userAudioTrack = guildAudioManager.scheduler.getCurrentPlayingTrack();
Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicInfo(info, userAudioTrack)).build(); MessageCreateData message = new MessageCreateBuilder().setEmbeds(EmbedMessageUtils.getMusicInfo(info, userAudioTrack)).build();
clearLastButton(); clearLastButton();
lastMessageWithButton = event.getHook().sendMessage(message).addActionRow(getActionButton()).complete(); lastMessageWithButton = hook.sendMessage(message).addActionRow(getActionButton()).complete();
} }
public void flush(GenericInteractionCreateEvent event) { public void flush(InteractionHook hook) {
guildAudioManager.scheduler.flush(); guildAudioManager.scheduler.flush();
Message message = new MessageBuilder().setEmbeds( MessageCreateData message = new MessageCreateBuilder().setEmbeds(
EmbedMessageUtils.buildStandar( EmbedMessageUtils.buildStandar(
new EmbedBuilder() new EmbedBuilder()
.setTitle(":wastebasket: Playlist flushed") .setTitle(":wastebasket: Playlist flushed")
.setColor(Color.green) .setColor(Color.green)
)).build(); )).build();
clearLastButton(); clearLastButton();
lastMessageWithButton = event.getHook().sendMessage(message).addActionRow(getActionButton()).complete(); lastMessageWithButton = hook.sendMessage(message).addActionRow(getActionButton()).complete();
} }
/** /**
@ -341,18 +341,18 @@ public class GuildAudioBotService {
* *
* @param event * @param event
*/ */
public void list(GenericInteractionCreateEvent event) { public void list(InteractionHook hook) {
List<UserAudioTrack> list = guildAudioManager.scheduler.getList(); List<UserAudioTrack> list = guildAudioManager.scheduler.getList();
if (list.size() == 0) { if (list.isEmpty()) {
Message message = new MessageBuilder().setEmbeds( MessageCreateData message = new MessageCreateBuilder().setEmbeds(
EmbedMessageUtils.buildStandar( EmbedMessageUtils.buildStandar(
new EmbedBuilder() new EmbedBuilder()
.setTitle(":scroll: Playlist") .setTitle(":scroll: Playlist")
.setColor(Color.green) .setColor(Color.green)
.setDescription("Oh no ! The playlist is empty !") .setDescription("Oh no ! The playlist is empty !")
)).build(); )).build();
event.getHook().sendMessage(message).queue(); hook.sendMessage(message).queue();
} else { } else {
StringBuilder resp = new StringBuilder(); StringBuilder resp = new StringBuilder();
int i = 0; int i = 0;
@ -370,14 +370,14 @@ public class GuildAudioBotService {
} }
i++; i++;
} }
Message message = new MessageBuilder().setEmbeds( MessageCreateData message = new MessageCreateBuilder().setEmbeds(
EmbedMessageUtils.buildStandar( EmbedMessageUtils.buildStandar(
new EmbedBuilder() new EmbedBuilder()
.setTitle(":scroll: Playlist") .setTitle(":scroll: Playlist")
.setColor(Color.green) .setColor(Color.green)
.setDescription(resp.toString()) .setDescription(resp.toString())
)).build(); )).build();
event.getHook().sendMessage(message).queue(); hook.sendMessage(message).queue();
} }
} }

View File

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

View File

@ -1,132 +0,0 @@
package net.Broken.Commands;
import net.Broken.Commande;
import net.Broken.Tools.EmbedMessageUtils;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
public class ChannelsReview implements Commande {
final Logger logger = LogManager.getLogger();
@Override
public void action(String[] args, MessageReceivedEvent event) {
DateFormat format = new SimpleDateFormat("dd.MM.yyyy");
event.getTextChannel().sendMessage("Number of channels found in total : " + event.getGuild().getTextChannels().size()).queue();
if (args.length >= 1) {
try {
SendBackBefore(format.parse(args[0]), event, format);
} catch (ParseException e) {
logger.warn("Can't parse date : " + e.getMessage());
}
} else {
SendBack(event);
}
}
private void SendBackBefore(Date beforeDate, MessageReceivedEvent event, DateFormat format) {
HashMap<String, String> result = new HashMap<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy").withLocale(Locale.ENGLISH);
int charCtl = 0;
for (TextChannel textChannel : event.getGuild().getTextChannels()) {
if (textChannel.hasLatestMessage()) {
String lastMessageId = textChannel.getLatestMessageId();
try {
Message lastMessage = textChannel.retrieveMessageById(lastMessageId).complete();
if (beforeDate.compareTo(format.parse(lastMessage.getTimeCreated().format(formatter))) > 0) {
logger.debug("Last message in channel " + textChannel + " is " + lastMessageId);
String date = lastMessage.getTimeCreated().format(formatter);
charCtl += textChannel.getName().length() + date.length();
result.put(textChannel.getName(), date);
}
} catch (RuntimeException | ParseException e) {
logger.warn("Can't find message with id: " + lastMessageId);
result.put(textChannel.getName(), "ERROR");
charCtl += textChannel.getName().length() + 5;
}
} else {
result.put(textChannel.getName(), "No message or access denied.");
charCtl += textChannel.getName().length() + 30;
}
if (charCtl > 3000) {
event.getTextChannel().sendMessage(EmbedMessageUtils.getLastMessageFromTextChannel(result)).complete();
result = new HashMap<>();
charCtl = 0;
}
}
if (charCtl != 0)
event.getTextChannel().sendMessage(EmbedMessageUtils.getLastMessageFromTextChannel(result)).queue();
}
private void SendBack(MessageReceivedEvent event) {
HashMap<String, String> result = new HashMap<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy").withLocale(Locale.ENGLISH);
int charCtl = 0;
for (TextChannel textChannel : event.getGuild().getTextChannels()) {
if (textChannel.hasLatestMessage()) {
String lastMessageId = textChannel.getLatestMessageId();
logger.debug("Last message in channel " + textChannel + " is " + lastMessageId);
try {
Message lastMessage = textChannel.retrieveMessageById(lastMessageId).complete();
String date = lastMessage.getTimeCreated().format(formatter);
charCtl += textChannel.getName().length() + date.length();
result.put(textChannel.getName(), date);
} catch (RuntimeException e) {
logger.warn("Can't find message with id: " + lastMessageId);
result.put(textChannel.getName(), "ERROR");
charCtl += textChannel.getName().length() + 5;
}
} else {
result.put(textChannel.getName(), "No message or access denied.");
charCtl += textChannel.getName().length() + 30;
}
if (charCtl > 3000) {
event.getTextChannel().sendMessage(EmbedMessageUtils.getLastMessageFromTextChannel(result)).queue();
event.getTextChannel().sendTyping().queue();
result = new HashMap<>();
charCtl = 0;
}
}
if (charCtl != 0)
event.getTextChannel().sendMessage(EmbedMessageUtils.getLastMessageFromTextChannel(result)).queue();
}
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isAdminCmd() {
return true;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

@ -1,39 +0,0 @@
package net.Broken.Commands;
import net.Broken.Commande;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
public class Ordre66 implements Commande {
@Override
public void action(String[] args, MessageReceivedEvent event) {
Message rest = event.getTextChannel().sendMessage("Très bien maître " + event.getAuthor().getAsMention() + ". J'arrive ! ").complete();
Message reste = event.getTextChannel().sendMessage("https://media2.giphy.com/media/UfzTayIyH7g5hk2BA2/giphy.gif\n").complete();
}
@Override
public boolean isPrivateUsable() {
return true;
}
@Override
public boolean isAdminCmd() {
return true;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

@ -1,69 +0,0 @@
package net.Broken.Commands;
import net.Broken.Commande;
import net.Broken.Tools.EmbedMessageUtils;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.requests.RestAction;
import java.util.Objects;
public class ReportUsers implements Commande {
@Override
public void action(String[] args, MessageReceivedEvent event) {
event.getGuild().loadMembers().onSuccess(members -> {
if (event.getMessage().getMentionedRoles().size() == 1 && args.length == 1) {
RestAction<Void> restAction = null;
for (Member member : members) {
if (member.getRoles().size() == 1) { //check if the member has a role
if (member.getRoles().contains(event.getMessage().getMentionedRoles().get(0))) { //check if the mentioned role is the same as the member's role
restAction = Objects.requireNonNullElseGet(restAction, () -> event.getTextChannel().sendMessage("List des membres : "))
.and(event.getTextChannel().sendMessage(member.getEffectiveName()));
}
}
}
if (restAction != null)
restAction.queue();
} else if (args.length == 0) {
for (Member member : members) {
if (member.getRoles().size() == 0) {
event.getTextChannel().sendMessage(member.getEffectiveName()).complete();
}
}
} else {
event.getTextChannel().sendMessage(EmbedMessageUtils.getReportUsersError()).complete();
}
});
}
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isAdminCmd() {
return true;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

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

View File

@ -1,6 +1,7 @@
package net.Broken; 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.DefaultMemberPermissions;
import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
@ -10,7 +11,7 @@ import java.util.List;
* Interface that define command structure. * Interface that define command structure.
*/ */
public interface SlashCommand { public interface SlashCommand {
void action(SlashCommandEvent event); void action(SlashCommandInteractionEvent event);
String getDescription(); String getDescription();
@ -34,7 +35,5 @@ public interface SlashCommand {
boolean isPrivateUsable(); boolean isPrivateUsable();
DefaultMemberPermissions getDefaultPermissions();
boolean isDisableByDefault();
} }

View File

@ -1,11 +1,11 @@
package net.Broken.SlashCommands; package net.Broken.SlashCommands;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.net.http.HttpClient; import java.net.http.HttpClient;
import java.net.http.HttpRequest; import java.net.http.HttpRequest;
import java.net.http.HttpResponse; import java.net.http.HttpResponse;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -17,10 +17,12 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import net.Broken.SlashCommand; import net.Broken.SlashCommand;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.EmbedMessageUtils;
import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions;
import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; 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. * Command that return a random picture of cat.
@ -29,32 +31,33 @@ public class Cat implements SlashCommand {
private final Logger logger = LogManager.getLogger(); private final Logger logger = LogManager.getLogger();
@Override @Override
public void action(SlashCommandEvent event) { public void action(SlashCommandInteractionEvent event) {
try { try {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://aws.random.cat/meow")) .uri(URI.create("https://aws.random.cat/meow"))
.GET() .GET()
.build(); .build();
HttpClient client = HttpClient.newHttpClient(); HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) { 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(); throw new IOException();
} }
TypeReference<HashMap<String, String>> typeRef = new TypeReference<>() {}; TypeReference<HashMap<String, String>> typeRef = new TypeReference<>() {
};
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
HashMap<String, String> json = mapper.readValue(response.body(), typeRef); HashMap<String, String> json = mapper.readValue(response.body(), typeRef);
event.reply(json.get("file")).queue(); event.reply(json.get("file")).queue();
} catch (InterruptedException | IOException e) { } catch (InterruptedException | IOException e) {
logger.catching(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 @Override
@ -64,15 +67,14 @@ public class Cat implements SlashCommand {
@Override @Override
public List<OptionData> getOptions() { public List<OptionData> getOptions() {
return null; return Collections.emptyList();
} }
@Override @Override
public List<SubcommandData> getSubcommands() { public List<SubcommandData> getSubcommands() {
return null; return Collections.emptyList();
} }
/** /**
* Determines if the command is usable only by bot level admin user * Determines if the command is usable only by bot level admin user
* *
@ -94,7 +96,8 @@ public class Cat implements SlashCommand {
} }
@Override @Override
public boolean isDisableByDefault() { public DefaultMemberPermissions getDefaultPermissions(){
return false; return DefaultMemberPermissions.enabledFor(Permission.MESSAGE_SEND);
} }
} }

View File

@ -1,29 +1,32 @@
package net.Broken.SlashCommands; package net.Broken.SlashCommands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.Broken.SlashCommand; import net.Broken.SlashCommand;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.EmbedMessageUtils;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel;
import net.dv8tion.jda.api.entities.MessageChannel; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions;
import net.dv8tion.jda.api.interactions.commands.OptionType; 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.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; 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 { public class Clear implements SlashCommand {
@Override @Override
public void action(SlashCommandEvent event) { public void action(SlashCommandInteractionEvent event) {
if (event.getMember().hasPermission(Permission.MESSAGE_MANAGE)) { if (event.getMember().hasPermission(Permission.MESSAGE_MANAGE)) {
event.reply(":white_check_mark: Done").setEphemeral(true).queue(); event.reply(":white_check_mark: Done").setEphemeral(true).queue();
long n = event.getOption("n").getAsLong(); long n = event.getOption("n").getAsLong();
MessageChannel chanel = event.getChannel(); MessageChannel chanel = event.getChannel();
chanel.getIterableHistory().takeAsync((int) n).thenAccept(chanel::purgeMessages); chanel.getIterableHistory().takeAsync((int) n).thenAccept(chanel::purgeMessages);
} else { } 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(); event.reply(message).setEphemeral(true).queue();
} }
} }
@ -42,7 +45,7 @@ public class Clear implements SlashCommand {
@Override @Override
public List<SubcommandData> getSubcommands() { public List<SubcommandData> getSubcommands() {
return null; return Collections.emptyList();
} }
@Override @Override
@ -61,7 +64,9 @@ public class Clear implements SlashCommand {
} }
@Override @Override
public boolean isDisableByDefault() { public DefaultMemberPermissions getDefaultPermissions() {
return true; return DefaultMemberPermissions.enabledFor(Permission.MESSAGE_MANAGE);
} }
} }

View File

@ -1,48 +1,52 @@
package net.Broken.SlashCommands; 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.SlashCommand;
import net.Broken.Audio.GuildAudioBotService;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.EmbedMessageUtils;
import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.entities.channel.unions.AudioChannelUnion;
import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.entities.VoiceChannel; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.dv8tion.jda.api.interactions.commands.OptionType; 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.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
import org.apache.logging.log4j.LogManager; import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;
import org.apache.logging.log4j.Logger; import net.dv8tion.jda.api.utils.messages.MessageCreateData;
import java.util.ArrayList;
import java.util.List;
/** /**
* Command that return a random picture of cat. * Command that return a random picture of cat.
*/ */
public class Music implements SlashCommand { public class Music implements SlashCommand {
private static final String PLAYLIST_LIMIT = "playlist-limit";
private final Logger logger = LogManager.getLogger(); private final Logger logger = LogManager.getLogger();
@Override @Override
public void action(SlashCommandEvent event) { public void action(SlashCommandInteractionEvent event) {
GuildAudioBotService audio = GuildAudioBotService.getInstance(event.getGuild()); GuildAudioBotService audio = GuildAudioBotService.getInstance(event.getGuild());
String action = event.getSubcommandName(); String action = event.getSubcommandName();
event.deferReply().queue(); event.deferReply().queue();
switch (action) { switch (action) {
case "play": case "play":
if (event.getMember().getVoiceState().inVoiceChannel()) { if (event.getMember().getVoiceState().inAudioChannel()) {
VoiceChannel voiceChanel = event.getMember().getVoiceState().getChannel(); AudioChannelUnion voiceChanel = event.getMember().getVoiceState().getChannel();
logger.info("Connecting to " + voiceChanel.getName() + "..."); logger.info("Connecting to {}...", voiceChanel.getName());
OptionMapping url = event.getOption("url"); 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); audio.loadAndPlay(event, voiceChanel, url.getAsString(), 30, false);
} else { } else {
long limit = event.getOption("playlist-limit").getAsLong(); long limit = event.getOption(PLAYLIST_LIMIT).getAsLong();
audio.loadAndPlay(event, voiceChanel, url.getAsString(), (int) limit, false); audio.loadAndPlay(event, voiceChanel, url.getAsString(), (int) limit, false);
} }
} else { } 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(); event.getHook().setEphemeral(true).sendMessage(message).queue();
} }
break; break;
@ -52,34 +56,34 @@ public class Music implements SlashCommand {
if (event.getOption("next") != null) { if (event.getOption("next") != null) {
next = event.getOption("next").getAsBoolean(); next = event.getOption("next").getAsBoolean();
} }
if (event.getOption("playlist-limit") == null) { if (event.getOption(PLAYLIST_LIMIT) == null) {
audio.add(event, url.getAsString(), 30, next); audio.add(event, url.getAsString(), 30, next);
} else { } else {
long limit = event.getOption("playlist-limit").getAsLong(); long limit = event.getOption(PLAYLIST_LIMIT).getAsLong();
audio.add(event, url.getAsString(), (int) limit, next); audio.add(event, url.getAsString(), (int) limit, next);
} }
break; break;
case "pause": case "pause":
audio.pause(event); audio.pause(event.getHook());
break; break;
case "resume": case "resume":
audio.resume(event); audio.resume(event.getHook());
break; break;
case "next": case "next":
audio.skipTrack(event); audio.skipTrack(event.getHook());
break; break;
case "stop": case "stop":
case "disconnect": case "disconnect":
audio.stop(event); audio.stop(event.getHook());
break; break;
case "info": case "info":
audio.info(event); audio.info(event.getHook());
break; break;
case "flush": case "flush":
audio.flush(event); audio.flush(event.getHook());
break; break;
case "list": case "list":
audio.list(event); audio.list(event.getHook());
break; break;
} }
} }
@ -91,7 +95,7 @@ public class Music implements SlashCommand {
@Override @Override
public List<OptionData> getOptions() { public List<OptionData> getOptions() {
return null; return Collections.emptyList();
} }
@Override @Override
@ -99,11 +103,11 @@ public class Music implements SlashCommand {
ArrayList<SubcommandData> subCommandList = new ArrayList<>(); ArrayList<SubcommandData> subCommandList = new ArrayList<>();
subCommandList.add(new SubcommandData("play", "Play music") subCommandList.add(new SubcommandData("play", "Play music")
.addOption(OptionType.STRING, "url", "The URL of the video to play", true) .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") subCommandList.add(new SubcommandData("add", "Add track to queue")
.addOption(OptionType.STRING, "url", " The URL of the video to play", true) .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.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("pause", "Pause playback"));
subCommandList.add(new SubcommandData("resume", "Resume playback")); subCommandList.add(new SubcommandData("resume", "Resume playback"));
subCommandList.add(new SubcommandData("stop", "Stop playback")); subCommandList.add(new SubcommandData("stop", "Stop playback"));
@ -136,7 +140,9 @@ public class Music implements SlashCommand {
} }
@Override @Override
public boolean isDisableByDefault() { public DefaultMemberPermissions getDefaultPermissions() {
return false; return DefaultMemberPermissions.ENABLED;
} }
} }

View File

@ -3,6 +3,9 @@ package net.Broken.SlashCommands.Over18;
import net.Broken.Tools.Command.Ignore; import net.Broken.Tools.Command.Ignore;
import net.Broken.Tools.Command.NoDev; import net.Broken.Tools.Command.NoDev;
import net.Broken.Tools.Command.NumberedSlashCommand; import net.Broken.Tools.Command.NumberedSlashCommand;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
@NoDev @NoDev
@ -35,7 +38,7 @@ public class Ass extends NumberedSlashCommand {
} }
@Override @Override
public boolean isDisableByDefault() { public DefaultMemberPermissions getDefaultPermissions() {
return true; return DefaultMemberPermissions.enabledFor(Permission.MESSAGE_SEND);
} }
} }

View File

@ -3,6 +3,10 @@ package net.Broken.SlashCommands.Over18;
import net.Broken.Tools.Command.Ignore; import net.Broken.Tools.Command.Ignore;
import net.Broken.Tools.Command.NoDev; import net.Broken.Tools.Command.NoDev;
import net.Broken.Tools.Command.NumberedSlashCommand; import net.Broken.Tools.Command.NumberedSlashCommand;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@ -37,7 +41,7 @@ public class Boobs extends NumberedSlashCommand {
} }
@Override @Override
public boolean isDisableByDefault() { public DefaultMemberPermissions getDefaultPermissions() {
return true; return DefaultMemberPermissions.enabledFor(Permission.MESSAGE_SEND);
} }
} }

View File

@ -2,6 +2,8 @@ package net.Broken.SlashCommands.Over18;
import net.Broken.Tools.Command.NoDev; import net.Broken.Tools.Command.NoDev;
import net.Broken.Tools.Command.NumberedSlashCommand; import net.Broken.Tools.Command.NumberedSlashCommand;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions;
import net.Broken.Tools.FindContentOnWebPage; import net.Broken.Tools.FindContentOnWebPage;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@ -57,11 +59,11 @@ public class Madame extends NumberedSlashCommand {
int randomResult = randomQueue.poll(); int randomResult = randomQueue.poll();
String url = baseURL + randomResult + urlSuffix; String url = baseURL + randomResult + urlSuffix;
logger.debug("URL: " + url); logger.debug("URL: {}",url);
if (scanPageForTipeee(url, logger)) { if (scanPageForTipeee(url, logger)) {
logger.debug("Advertisement detected! Retry! (" + url + ")"); logger.debug("Advertisement detected! Retry! ({})", url);
} else { } else {
imgUrl = FindContentOnWebPage.doYourJob(url, "post-content", "img"); imgUrl = FindContentOnWebPage.doYourJob(url, "post-content", "img");
@ -94,7 +96,7 @@ public class Madame extends NumberedSlashCommand {
} }
@Override @Override
public boolean isDisableByDefault() { public DefaultMemberPermissions getDefaultPermissions() {
return true; return DefaultMemberPermissions.enabledFor(Permission.MESSAGE_SEND);
} }
} }

View File

@ -5,16 +5,18 @@ import net.Broken.SlashCommand;
import net.Broken.SpringContext; import net.Broken.SpringContext;
import net.Broken.Tools.UserManager.Stats.UserStatsUtils; import net.Broken.Tools.UserManager.Stats.UserStatsUtils;
import net.dv8tion.jda.api.entities.MessageEmbed; 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.DefaultMemberPermissions;
import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; 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; import java.util.List;
public class Rank implements SlashCommand { public class Rank implements SlashCommand {
@Override @Override
public void action(SlashCommandEvent event) { public void action(SlashCommandInteractionEvent event) {
String url = SpringContext.getAppContext().getBean(BotConfigLoader.class).url(); String url = SpringContext.getAppContext().getBean(BotConfigLoader.class).url();
event.deferReply().queue(); event.deferReply().queue();
UserStatsUtils userStats = UserStatsUtils.getINSTANCE(); UserStatsUtils userStats = UserStatsUtils.getINSTANCE();
@ -31,12 +33,12 @@ public class Rank implements SlashCommand {
@Override @Override
public List<OptionData> getOptions() { public List<OptionData> getOptions() {
return null; return Collections.emptyList();
} }
@Override @Override
public List<SubcommandData> getSubcommands() { public List<SubcommandData> getSubcommands() {
return null; return Collections.emptyList();
} }
@Override @Override
@ -55,7 +57,7 @@ public class Rank implements SlashCommand {
} }
@Override @Override
public boolean isDisableByDefault() { public DefaultMemberPermissions getDefaultPermissions() {
return false; return DefaultMemberPermissions.ENABLED;
} }
} }

View File

@ -1,20 +1,21 @@
package net.Broken.Tools; package net.Broken.Tools;
import net.Broken.DB.Entity.GuildPreferenceEntity; import static net.Broken.MainBot.jda;
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.requests.RestAction;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import static net.Broken.MainBot.jda; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.channel.middleman.AudioChannel;
import net.dv8tion.jda.api.requests.RestAction;
public class AutoVoiceChannel { public class AutoVoiceChannel {
private static final HashMap<String, AutoVoiceChannel> INSTANCE_MAP = new HashMap<>(); private static final HashMap<String, AutoVoiceChannel> INSTANCE_MAP = new HashMap<>();
@ -34,14 +35,14 @@ public class AutoVoiceChannel {
return INSTANCE_MAP.get(guild.getId()); return INSTANCE_MAP.get(guild.getId());
} }
public void join(VoiceChannel voiceChannel) { public void join(AudioChannel voiceChannel) {
Guild guild = jda.getGuildById(guildID); Guild guild = jda.getGuildById(guildID);
if (guild == null) if (guild == null)
return; return;
GuildPreferenceEntity pref = SettingsUtils.getInstance().getPreference(guild); GuildPreferenceEntity pref = SettingsUtils.getInstance().getPreference(guild);
if (pref.isAutoVoice() && voiceChannel.getId().equals(pref.getAutoVoiceChannelID())) { 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(); AudioChannel newChannel = (AudioChannel) voiceChannel.createCopy().complete();
int next = getNextNumber(); int next = getNextNumber();
String title = pref.getAutoVoiceChannelTitle(); String title = pref.getAutoVoiceChannelTitle();
if (title.isEmpty()) { if (title.isEmpty()) {
@ -56,7 +57,7 @@ public class AutoVoiceChannel {
} }
public void leave(VoiceChannel voiceChannel) { public void leave(AudioChannel voiceChannel) {
if (voiceChannel.getMembers().isEmpty()) { if (voiceChannel.getMembers().isEmpty()) {
String id = voiceChannel.getId(); String id = voiceChannel.getId();
for (Map.Entry<Integer, String> entry : createdChannels.entrySet()) { for (Map.Entry<Integer, String> entry : createdChannels.entrySet()) {
@ -79,7 +80,7 @@ public class AutoVoiceChannel {
return 999; return 999;
} }
private void moveMembers(List<Member> members, VoiceChannel destination) { private void moveMembers(List<Member> members, AudioChannel destination) {
logger.debug("Moving Members to new voice channel..."); logger.debug("Moving Members to new voice channel...");
RestAction<Void> restAction = null; RestAction<Void> restAction = null;
for (Member member : members) { for (Member member : members) {

View File

@ -39,7 +39,7 @@ public class CommandParser {
args[i] = args[i].replace('$', ' '); args[i] = args[i].replace('$', ' ');
logger.info("Author: " + e.getAuthor().getName() + ", Command: " + commande + ", args: " + Arrays.toString(args)); logger.info("Author: {}, Command: {}, args: {}", e.getAuthor().getName(), commande, Arrays.toString(args));
return new CommandContainer(brt, sansTete, splitSansTete, commande, args, e); return new CommandContainer(brt, sansTete, splitSansTete, commande, args, e);

View File

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

View File

@ -1,18 +1,20 @@
package net.Broken.Tools.Command; package net.Broken.Tools.Command;
import net.Broken.BotConfigLoader; import java.lang.reflect.InvocationTargetException;
import net.Broken.MainBot; import java.util.Set;
import net.Broken.SlashCommand;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction;
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.reflections.Reflections; import org.reflections.Reflections;
import org.reflections.util.ClasspathHelper; import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder; import org.reflections.util.ConfigurationBuilder;
import java.lang.reflect.InvocationTargetException; import net.Broken.BotConfigLoader;
import java.util.Set; import net.Broken.MainBot;
import net.Broken.SlashCommand;
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;
/** /**
@ -21,6 +23,8 @@ import java.util.Set;
public class SlashCommandLoader { public class SlashCommandLoader {
private static final Logger logger = LogManager.getLogger(); private static final Logger logger = LogManager.getLogger();
private 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
*/ */
@ -33,14 +37,14 @@ public class SlashCommandLoader {
); );
Set<Class<? extends SlashCommand>> modules = reflections.getSubTypesOf(SlashCommand.class); 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) { for (Class<? extends SlashCommand> command : modules) {
String reference = command.getName(); String reference = command.getName();
String[] splited = reference.split("\\."); String[] splited = reference.split("\\.");
String name = splited[splited.length - 1].toLowerCase(); String name = splited[splited.length - 1].toLowerCase();
if (!command.isAnnotationPresent(Ignore.class)) { if (!command.isAnnotationPresent(Ignore.class)) {
logger.info("..." + name); logger.info("...{}", name);
if (command.isAnnotationPresent(NoDev.class) && config.mode().equals("DEV")) { if (command.isAnnotationPresent(NoDev.class) && config.mode().equals("DEV")) {
logger.warn("Command disabled in dev mode"); logger.warn("Command disabled in dev mode");
@ -49,24 +53,25 @@ public class SlashCommandLoader {
MainBot.slashCommands.put(name, command.getDeclaredConstructor().newInstance()); MainBot.slashCommands.put(name, command.getDeclaredConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
NoSuchMethodException e) { NoSuchMethodException e) {
logger.error("Failed to load " + name + "!"); logger.error("Failed to load {} !", name);
} }
} }
} else { } else {
logger.trace("Ignored command: " + name); logger.trace("Ignored command: {}", name);
} }
} }
} }
public static void registerSlashCommands(CommandListUpdateAction commandListUpdateAction) { public static void registerSlashCommands(CommandListUpdateAction commandListUpdateAction) {
MainBot.slashCommands.forEach((k, v) -> { MainBot.slashCommands.forEach((k, v) -> {
CommandData command = new CommandData(k, v.getDescription()); SlashCommandData command = Commands.slash(k, v.getDescription());
if (v.getOptions() != null) if (v.getOptions() != null)
command.addOptions(v.getOptions()); command.addOptions(v.getOptions());
if (v.getSubcommands() != null) { if (v.getSubcommands() != null) {
command.addSubcommands(v.getSubcommands()); command.addSubcommands(v.getSubcommands());
} }
command.setDefaultEnabled(!v.isDisableByDefault()); command.setDefaultPermissions(v.getDefaultPermissions());
commandListUpdateAction.addCommands(command); commandListUpdateAction.addCommands(command);
}); });
commandListUpdateAction.queue(); commandListUpdateAction.queue();

View File

@ -8,7 +8,8 @@ import net.Broken.SpringContext;
import net.Broken.Tools.DayListener.NewDayListener; import net.Broken.Tools.DayListener.NewDayListener;
import net.Broken.Tools.FindContentOnWebPage; import net.Broken.Tools.FindContentOnWebPage;
import net.dv8tion.jda.api.entities.Guild; 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.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
@ -44,12 +45,8 @@ public class DailyMadame implements NewDayListener {
if (day != Calendar.MONDAY && day != Calendar.SUNDAY) { if (day != Calendar.MONDAY && day != Calendar.SUNDAY) {
LocalDate now = LocalDate.now().minusDays(1); LocalDate now = LocalDate.now().minusDays(1);
String date = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(now); String date = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(now);
String url = "https://www.bonjourmadame.fr/" + date + "/"; String url = "https://www.bonjourmadame.fr/" + date + "/";
imgUrl = FindContentOnWebPage.doYourJob(url, "post-content", "img"); imgUrl = FindContentOnWebPage.doYourJob(url, "post-content", "img");
} else { } else {
Madame command = (Madame) MainBot.slashCommands.get("madame"); Madame command = (Madame) MainBot.slashCommands.get("madame");
imgUrl = command.poll(); imgUrl = command.poll();
@ -64,17 +61,14 @@ public class DailyMadame implements NewDayListener {
for (TextChannel iterator : guild.getTextChannels()) { for (TextChannel iterator : guild.getTextChannels()) {
if (iterator.isNSFW() && iterator.canTalk()) { if (iterator.isNSFW() && iterator.canTalk()) {
chanel = iterator; chanel = iterator;
logger.debug("break: " + chanel.getName()); logger.debug("break: {}", chanel.getName());
break; break;
} }
} }
if (chanel != null) { if (chanel != null) {
chanel.sendMessage("Madame of the day :kissing_heart: \n" + imgUrl).queue(); chanel.sendMessage("Madame of the day :kissing_heart: \n" + imgUrl).queue();
} else { } 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.Entity.GuildPreferenceEntity;
import net.Broken.DB.Repository.GuildPreferenceRepository; import net.Broken.DB.Repository.GuildPreferenceRepository;
import net.Broken.DB.Repository.UserRepository;
import net.Broken.SpringContext; import net.Broken.SpringContext;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
@ -14,13 +13,10 @@ public class SettingsUtils {
private static SettingsUtils INSTANCE; private static SettingsUtils INSTANCE;
private final Logger logger = LogManager.getLogger(); private final Logger logger = LogManager.getLogger();
private final GuildPreferenceRepository guildPreferenceRepository; private final GuildPreferenceRepository guildPreferenceRepository;
private final UserRepository userRepository;
private SettingsUtils() { private SettingsUtils() {
ApplicationContext context = SpringContext.getAppContext(); ApplicationContext context = SpringContext.getAppContext();
guildPreferenceRepository = (GuildPreferenceRepository) context.getBean("guildPreferenceRepository"); guildPreferenceRepository = (GuildPreferenceRepository) context.getBean("guildPreferenceRepository");
userRepository = (UserRepository) context.getBean("userRepository");
} }
public static SettingsUtils getInstance() { public static SettingsUtils getInstance() {
@ -29,7 +25,7 @@ public class SettingsUtils {
public GuildPreferenceEntity getPreference(Guild guild) { public GuildPreferenceEntity getPreference(Guild guild) {
return guildPreferenceRepository.findByGuildId(guild.getId()).orElseGet(()->{ 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())); return guildPreferenceRepository.save(GuildPreferenceEntity.getDefault(guild.getId()));
}); });
} }

View File

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

View File

@ -1,26 +0,0 @@
package net.Broken.Tools.UserManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class UserUtils {
private static final UserUtils INSTANCE = new UserUtils();
private final Logger logger = LogManager.getLogger();
/**
* Private default constructor
*/
private UserUtils() {
}
/**
* Singleton
*
* @return Unique UserUtils instance
*/
public static UserUtils getInstance() {
return INSTANCE;
}
}