diff --git a/Dockerfile-dev b/Dockerfile-dev deleted file mode 100644 index 2ac4374d3..000000000 --- a/Dockerfile-dev +++ /dev/null @@ -1,6 +0,0 @@ -FROM gradle:6.6.1-jdk11 - -WORKDIR /home/kittybot - -COPY ./src ./home/kittybot/src - diff --git a/build.gradle b/build.gradle index a4709db95..6d5a5f9d3 100644 --- a/build.gradle +++ b/build.gradle @@ -1,93 +1,91 @@ plugins { - id 'java' - id 'application' - id 'com.github.johnrengelman.shadow' version '7.1.0' - id 'nu.studer.jooq' version '6.0.1' + id "java" + id "application" + id "com.github.johnrengelman.shadow" version "7.1.2" + id "nu.studer.jooq" version "6.0.1" } -group 'de.kittybot' -mainClassName = 'de.kittybot.kittybot.main.Main' +group "de.kittybot" +mainClassName = "de.kittybot.kittybot.main.Main" +sourceCompatibility = 1.11 +compileJava.options.encoding = "UTF-8" + repositories { - maven { url 'https://m2.dv8tion.net/releases' } - maven { url 'https://jitpack.io' } + maven { url "https://m2.dv8tion.net/releases" } + maven { url "https://jitpack.io" } mavenCentral() jcenter() // this is still required because of jda utilities } dependencies { // discord/jda related - implementation('net.dv8tion:JDA:4.3.0_339') { - exclude group: 'club.minnced', module: 'opus-java' + implementation("net.dv8tion:JDA:4.4.0_352") { + exclude group: "club.minnced", module: "opus-java" } - implementation 'com.jagrosh:jda-utilities:3.0.5' - implementation 'club.minnced:discord-webhooks:0.7.2' - implementation 'dev.mlnr:BotListHandler-jda:2.0.0_11' + implementation "com.jagrosh:jda-utilities:3.0.5" + implementation "club.minnced:discord-webhooks:0.7.5" + implementation "dev.mlnr:BotListHandler-jda:2.0.0_11" // audio - implementation('com.github.KittyBot-Org:Lavalink-Client:d48f1a6') { - exclude group: 'com.sedmelluq', module: 'lavaplayer' - } - implementation 'com.sedmelluq:lavaplayer:1.3.78' - implementation 'se.michaelthelin.spotify:spotify-web-api-java:6.5.4' + implementation "com.github.KittyBot-Org:Lavalink-Client:1.0.0" // database - implementation 'com.zaxxer:HikariCP:5.0.0' - implementation 'org.jooq:jooq:3.15.4' - implementation 'org.postgresql:postgresql:42.3.0' - jooqGenerator 'org.postgresql:postgresql:42.3.0' - + implementation "com.zaxxer:HikariCP:5.0.0" + implementation "org.jooq:jooq:3.16.0" + implementation "org.postgresql:postgresql:42.3.1" + jooqGenerator "org.postgresql:postgresql:42.3.1" // logging - implementation 'ch.qos.logback:logback-classic:1.3.0-alpha10' - implementation 'io.sentry:sentry-logback:5.2.4' + implementation "ch.qos.logback:logback-classic:1.2.8" + implementation "io.sentry:sentry-logback:5.5.2" // eval - implementation 'org.codehaus.groovy:groovy-jsr223:3.0.9' + implementation "org.codehaus.groovy:groovy-jsr223:3.0.9" // jjwt - implementation 'io.jsonwebtoken:jjwt-api:0.11.2' - implementation 'io.jsonwebtoken:jjwt-impl:0.11.2' - implementation 'io.jsonwebtoken:jjwt-jackson:0.11.2' + implementation "io.jsonwebtoken:jjwt-api:0.11.2" + implementation "io.jsonwebtoken:jjwt-impl:0.11.2" + implementation "io.jsonwebtoken:jjwt-jackson:0.11.2" // Prometheus - implementation 'io.prometheus:simpleclient:0.12.0' - implementation 'io.prometheus:simpleclient_hotspot:0.12.0' - implementation 'io.prometheus:simpleclient_httpserver:0.12.0' + implementation "io.prometheus:simpleclient:0.14.1" + implementation "io.prometheus:simpleclient_hotspot:0.14.1" + implementation "io.prometheus:simpleclient_httpserver:0.14.1" // other - implementation 'io.javalin:javalin:4.1.1' - implementation 'io.github.classgraph:classgraph:4.8.129' - implementation 'com.github.ben-manes.caffeine:caffeine:3.0.4' - implementation 'com.squareup.okhttp3:okhttp:4.9.2' + implementation "io.javalin:javalin:4.2.0" + implementation "io.github.classgraph:classgraph:4.8.138" + implementation "com.github.ben-manes.caffeine:caffeine:3.0.5" + implementation "com.squareup.okhttp3:okhttp:4.9.3" } jooq { - version = '3.15.2' + version = "3.15.2" configurations { main { generateSchemaSourceOnCompilation = false generationTool { logging = org.jooq.meta.jaxb.Logging.WARN jdbc { - driver = 'org.postgresql.Driver' + driver = "org.postgresql.Driver" url = "jdbc:postgresql://${KITTYBOT_DB_HOST}:${KITTYBOT_DB_PORT}/${KITTYBOT_DB_DATABASE}" user = KITTYBOT_DB_USER password = KITTYBOT_DB_PASSWORD } generator { - name = 'org.jooq.codegen.DefaultGenerator' + name = "org.jooq.codegen.DefaultGenerator" database { - name = 'org.jooq.meta.postgres.PostgresDatabase' - inputSchema = 'public' - includes = '.*' - excludes = '' + name = "org.jooq.meta.postgres.PostgresDatabase" + inputSchema = "public" + includes = ".*" + excludes = "" } generate { records = true fluentSetters = true } target { - packageName = 'de.kittybot.kittybot.jooq' + packageName = "de.kittybot.kittybot.jooq" directory = "src/main/jooq" } strategy.name = "org.jooq.codegen.DefaultGeneratorStrategy" @@ -98,8 +96,5 @@ jooq { } ext { - moduleName = 'KittyBot' + moduleName = "KittyBot" } - -sourceCompatibility = 1.11 -compileJava.options.encoding = 'UTF-8' diff --git a/src/main/java/de/kittybot/kittybot/commands/music/ForwardCommand.java b/src/main/java/de/kittybot/kittybot/commands/music/ForwardCommand.java index 6aea7c8b2..2627930f1 100644 --- a/src/main/java/de/kittybot/kittybot/commands/music/ForwardCommand.java +++ b/src/main/java/de/kittybot/kittybot/commands/music/ForwardCommand.java @@ -32,7 +32,7 @@ public void run(Options options, GuildInteraction ia){ var lavalinkPlayer = scheduler.getPlayer(); var position = lavalinkPlayer.getTrackPosition(); var newPos = position + forward; - if(newPos > scheduler.getPlayingTrack().getDuration()){ + if(newPos > scheduler.getPlayingTrack().getInfo().getLength()){ scheduler.next(true); ia.reply("Skipped to next track"); return; diff --git a/src/main/java/de/kittybot/kittybot/commands/music/SeekCommand.java b/src/main/java/de/kittybot/kittybot/commands/music/SeekCommand.java index b0da4127c..a23c13bce 100644 --- a/src/main/java/de/kittybot/kittybot/commands/music/SeekCommand.java +++ b/src/main/java/de/kittybot/kittybot/commands/music/SeekCommand.java @@ -30,7 +30,7 @@ public void run(Options options, GuildInteraction ia){ } var newPos = options.getLong("seconds") * 1000; var lavalinkPlayer = scheduler.getPlayer(); - if(newPos > scheduler.getPlayingTrack().getDuration()){ + if(newPos > scheduler.getPlayingTrack().getInfo().getLength()){ scheduler.next(true); ia.reply("Skipped to next track"); return; diff --git a/src/main/java/de/kittybot/kittybot/commands/roles/roles/ListCommand.java b/src/main/java/de/kittybot/kittybot/commands/roles/roles/ListCommand.java index bb571928c..d3d8249cf 100644 --- a/src/main/java/de/kittybot/kittybot/commands/roles/roles/ListCommand.java +++ b/src/main/java/de/kittybot/kittybot/commands/roles/roles/ListCommand.java @@ -53,7 +53,7 @@ public void run(Options options, GuildInteraction ia){ return; } ia.acknowledge().queue(success -> - ia.getChannel().sendMessage(embed).queue(message -> { + ia.getChannel().sendMessageEmbeds(embed).queue(message -> { ia.get(ReactionRoleModule.class).add(message.getGuild().getIdLong(), message.getIdLong()); sortedRoles.forEach(role -> message.addReaction("test:" + role.getEmoteId()).queue()); }) diff --git a/src/main/java/de/kittybot/kittybot/main/KittyBot.java b/src/main/java/de/kittybot/kittybot/main/KittyBot.java index 480310474..a21b9908c 100644 --- a/src/main/java/de/kittybot/kittybot/main/KittyBot.java +++ b/src/main/java/de/kittybot/kittybot/main/KittyBot.java @@ -58,8 +58,7 @@ public KittyBot() throws IOException, MissingConfigValuesException, LoginExcepti .disableCache( CacheFlag.MEMBER_OVERRIDES, CacheFlag.ACTIVITY, - CacheFlag.CLIENT_STATUS, - CacheFlag.ROLE_TAGS + CacheFlag.CLIENT_STATUS ) .setMemberCachePolicy(MemberCachePolicy.VOICE) .setChunkingFilter(ChunkingFilter.NONE) diff --git a/src/main/java/de/kittybot/kittybot/modules/AnnouncementModule.java b/src/main/java/de/kittybot/kittybot/modules/AnnouncementModule.java index fc930a8a5..9246ec9fa 100644 --- a/src/main/java/de/kittybot/kittybot/modules/AnnouncementModule.java +++ b/src/main/java/de/kittybot/kittybot/modules/AnnouncementModule.java @@ -53,7 +53,7 @@ public void onGuildMessageReceived(@NotNull GuildMessageReceivedEvent event){ return; } if((msg.contains("<@" + Config.BOT_ID + ">") || msg.contains("<@!" + Config.BOT_ID + ">")) && msg.contains("help")){ - event.getChannel().sendMessage(new EmbedBuilder() + event.getChannel().sendMessageEmbeds(new EmbedBuilder() .setColor(Colors.KITTYBOT_BLUE) .setAuthor("KittyBot Slash Commands Update", event.getJDA().getSelfUser().getEffectiveAvatarUrl(), Config.ORIGIN_URL) .setDescription("KittyBot now uses the new slash commands.\n" + @@ -92,7 +92,7 @@ public void onGuildJoin(@Nonnull GuildJoinEvent event){ if(channel == null || !channel.canTalk()){ return; } - channel.sendMessage(embed).queue(); + channel.sendMessageEmbeds(embed).queue(); return; } guild.retrieveAuditLogs().type(ActionType.BOT_ADD).limit(1).cache(false).queue(entries -> { @@ -105,14 +105,14 @@ public void onGuildJoin(@Nonnull GuildJoinEvent event){ return; } - user.openPrivateChannel().flatMap(channel -> channel.sendMessage(embed)).queue( + user.openPrivateChannel().flatMap(channel -> channel.sendMessageEmbeds(embed)).queue( null, error -> { var channel = guild.getDefaultChannel(); if(channel == null || !channel.canTalk()){ return; } - channel.sendMessage(embed).queue(); + channel.sendMessageEmbeds(embed).queue(); } ); }); diff --git a/src/main/java/de/kittybot/kittybot/modules/CommandsModule.java b/src/main/java/de/kittybot/kittybot/modules/CommandsModule.java index 4e5420b62..819ce3b27 100644 --- a/src/main/java/de/kittybot/kittybot/modules/CommandsModule.java +++ b/src/main/java/de/kittybot/kittybot/modules/CommandsModule.java @@ -88,15 +88,15 @@ public void deployCommands(long guildId, Map commands){ LOG.info("Registering commands {}...", guildId == -1 ? "global" : "for guild " + guildId); var rqBody = RequestBody.create( - DataArray.fromCollection(commands.values().stream().map(Command::toJSON).collect(Collectors.toList())).toJson(), - MediaType.parse("application/json") + MediaType.parse("application/json"), + DataArray.fromCollection(commands.values().stream().map(Command::toJSON).collect(Collectors.toList())).toJson() ); var route = guildId == -1L ? COMMANDS_CREATE.compile(String.valueOf(Config.BOT_ID)) : GUILD_COMMANDS_CREATE.compile(String.valueOf(Config.BOT_ID), String.valueOf(guildId)); try(var resp = newCall(route, rqBody).execute()){ if(!resp.isSuccessful()){ var body = resp.body(); - LOG.error("Registering commands failed. Request Body: {}, Response Body: {}", commands.toString(), body == null ? "null" : body.string()); + LOG.error("Registering commands failed. Request Body: {}, Response Body: {}", commands, body == null ? "null" : body.string()); } var body = resp.body(); if(body == null){ @@ -142,13 +142,13 @@ public Map getCommands(){ } public long registerGuildCommand(long guildId, DataObject command){ - var rqBody = RequestBody.create(command.toJson(), MediaType.parse("application/json")); + var rqBody = RequestBody.create(MediaType.parse("application/json"), command.toJson()); var route = GUILD_COMMAND_CREATE.compile(String.valueOf(Config.BOT_ID), String.valueOf(guildId)); try(var resp = newCall(route, rqBody).execute()){ if(!resp.isSuccessful()){ var body = resp.body(); - LOG.error("Registering command failed. Request Body: {}, Response Body: {}", command.toString(), body == null ? "null" : body.string()); + LOG.error("Registering command failed. Request Body: {}, Response Body: {}", command, body == null ? "null" : body.string()); return -1L; } var body = resp.body(); @@ -182,7 +182,7 @@ public boolean deleteGuildCommand(long guildId, long commandId){ } public boolean editGuildCommand(long guildId, long commandId, DataObject command){ - var rqBody = RequestBody.create(command.toJson(), MediaType.parse("application/json")); + var rqBody = RequestBody.create(MediaType.parse("application/json"), command.toJson()); var route = GUILD_COMMAND_EDIT.compile(String.valueOf(Config.BOT_ID), String.valueOf(guildId), String.valueOf(commandId)); try(var resp = newCall(route, rqBody).execute()){ @@ -220,7 +220,7 @@ public DataArray getGuildCommands(long guildId){ public void deleteAllCommands(long guildId){ LOG.info("Deleting commands {}...", guildId == -1 ? "global" : "for guild " + guildId); - var rqBody = RequestBody.create(DataArray.empty().toString(), MediaType.parse("application/json")); + var rqBody = RequestBody.create(MediaType.parse("application/json"), DataArray.empty().toString()); var route = guildId == -1L ? COMMANDS_CREATE.compile(String.valueOf(Config.BOT_ID)) : GUILD_COMMANDS_CREATE.compile(String.valueOf(Config.BOT_ID), String.valueOf(guildId)); try(var resp = newCall(route, rqBody).execute()){ diff --git a/src/main/java/de/kittybot/kittybot/modules/GuildLoggingModule.java b/src/main/java/de/kittybot/kittybot/modules/GuildLoggingModule.java index a295a9f0b..c1304e8e1 100644 --- a/src/main/java/de/kittybot/kittybot/modules/GuildLoggingModule.java +++ b/src/main/java/de/kittybot/kittybot/modules/GuildLoggingModule.java @@ -120,7 +120,7 @@ private void logEvent(GenericGuildEvent event, Color color, User user, String ev if(channel == null){ return; } - channel.sendMessage(new EmbedBuilder() + channel.sendMessageEmbeds(new EmbedBuilder() .setColor(color) .setDescription(String.format(message, args)) .setFooter(eventName, user == null ? null : user.getEffectiveAvatarUrl()) diff --git a/src/main/java/de/kittybot/kittybot/modules/InteractionsModule.java b/src/main/java/de/kittybot/kittybot/modules/InteractionsModule.java index 270408607..370246d97 100644 --- a/src/main/java/de/kittybot/kittybot/modules/InteractionsModule.java +++ b/src/main/java/de/kittybot/kittybot/modules/InteractionsModule.java @@ -123,6 +123,7 @@ else if(interaction.isFromGuild()){ } } catch(Exception e){ + LOG.error("Error while executing command", e); interaction.error(e.getMessage()); } return; diff --git a/src/main/java/de/kittybot/kittybot/modules/MusicModule.java b/src/main/java/de/kittybot/kittybot/modules/MusicModule.java index 55bb8e9f4..a53b4ecc8 100644 --- a/src/main/java/de/kittybot/kittybot/modules/MusicModule.java +++ b/src/main/java/de/kittybot/kittybot/modules/MusicModule.java @@ -30,7 +30,6 @@ public class MusicModule extends Module implements Serializable{ public static final Pattern URL_PATTERN = Pattern.compile("^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]?"); - public static final Pattern SPOTIFY_URL_PATTERN = Pattern.compile("(https?://)?(www\\.)?open\\.spotify\\.com/(user/[a-zA-Z0-9-_]+/)?(?track|album|playlist)/(?[a-zA-Z0-9-_]+)"); private Map musicPlayers; @@ -66,7 +65,7 @@ public void onGuildMessageReactionAdd(@NotNull GuildMessageReactionAddEvent even var messageId = event.getMessageIdLong(); var currentTrack = scheduler.getPlayingTrack(); var userId = event.getUserIdLong(); - var requesterId = currentTrack == null ? -1L : currentTrack.getUserData(Long.class); + var requesterId = currentTrack == null ? -1L : currentTrack.getUserData(Long.class) == null ? -1L : currentTrack.getUserData(Long.class); var settings = this.modules.get(SettingsModule.class).getSettings(event.getGuild().getIdLong()); if(messageId != scheduler.getControllerMessageId()){ @@ -202,12 +201,6 @@ public void play(GuildInteraction ia, String query, SearchProvider searchProvide ia.acknowledge().queue(); var manager = this.musicPlayers.computeIfAbsent(ia.getGuildId(), guildId -> new MusicManager(this.modules, guildId, ia.getChannelId())); - var matcher = SPOTIFY_URL_PATTERN.matcher(query); - if(matcher.find()){ - this.modules.get(SpotifyModule.class).load(ia, manager, matcher); - return; - } - if(!URL_PATTERN.matcher(query).matches()){ switch(searchProvider){ case YOUTUBE: diff --git a/src/main/java/de/kittybot/kittybot/modules/NotificationModule.java b/src/main/java/de/kittybot/kittybot/modules/NotificationModule.java index 77c036f4b..c107f2b53 100644 --- a/src/main/java/de/kittybot/kittybot/modules/NotificationModule.java +++ b/src/main/java/de/kittybot/kittybot/modules/NotificationModule.java @@ -63,7 +63,7 @@ private void schedule(Set notifs){ return; } guild.retrieveMemberById(notification.getUserId()).flatMap(member -> - channel.sendMessage(member.getAsMention()).embed( + channel.sendMessage(member.getAsMention()).setEmbeds( new EmbedBuilder() .setAuthor("Notification", Category.NOTIFICATION.getUrl(), Category.NOTIFICATION.getEmoteUrl()) .setColor(Colors.NOTIFICATION) diff --git a/src/main/java/de/kittybot/kittybot/modules/PaginatorModule.java b/src/main/java/de/kittybot/kittybot/modules/PaginatorModule.java index 48d80f872..0b5e9ae37 100644 --- a/src/main/java/de/kittybot/kittybot/modules/PaginatorModule.java +++ b/src/main/java/de/kittybot/kittybot/modules/PaginatorModule.java @@ -59,13 +59,13 @@ public void onGuildMessageReactionAdd(@NotNull GuildMessageReactionAddEvent even if(Emoji.ARROW_LEFT.get().equals(code)){ if(currentPage != 0){ paginator.previousPage(); - event.getChannel().editMessageById(event.getMessageIdLong(), paginator.constructEmbed()).queue(); + event.getChannel().editMessageEmbedsById(event.getMessageIdLong(), paginator.constructEmbed()).queue(); } } else if(Emoji.ARROW_RIGHT.get().equals(code)){ if(currentPage != maxPages - 1){ paginator.nextPage(); - event.getChannel().editMessageById(event.getMessageIdLong(), paginator.constructEmbed()).queue(); + event.getChannel().editMessageEmbedsById(event.getMessageIdLong(), paginator.constructEmbed()).queue(); } } else if(Emoji.WASTEBASKET.get().equals(code)){ @@ -84,7 +84,7 @@ public void create(TextChannel channel, long authorId, int maxPages, BiFunction< } public void create(int maxPages, BiFunction embedFunction, MessageEmbed embedBuilder, MessageChannel channel, long userId){ - channel.sendMessage(embedBuilder).queue(message -> { + channel.sendMessageEmbeds(embedBuilder).queue(message -> { var paginator = new Paginator(message, userId, maxPages, embedFunction); this.paginators.put(paginator.getMessageId(), paginator); if(channel instanceof GuildChannel && !((GuildChannel) channel).getGuild().getSelfMember().hasPermission(Permission.MESSAGE_HISTORY, Permission.MESSAGE_ADD_REACTION)){ diff --git a/src/main/java/de/kittybot/kittybot/modules/RequestModule.java b/src/main/java/de/kittybot/kittybot/modules/RequestModule.java index f710a0a24..fe3e3ab7e 100644 --- a/src/main/java/de/kittybot/kittybot/modules/RequestModule.java +++ b/src/main/java/de/kittybot/kittybot/modules/RequestModule.java @@ -126,7 +126,7 @@ public String executeRequest(Request request, API api){ public void postToHastebin(String content, Consumer callback){ this.requestBuilder.url(API.HASTEBIN.getUrl() + "/documents"); - this.requestBuilder.post(RequestBody.create(content, MediaType.parse("text/html; charset=utf-8"))); + this.requestBuilder.post(RequestBody.create(MediaType.parse("text/html; charset=utf-8"), content)); executeAsync(this.requestBuilder.build(), (call, response) -> { var body = response.body(); String key = null; @@ -155,7 +155,7 @@ public void uploadCommands(Collection commands){ var json = DataArray.fromCollection(commands.stream().map(Command::toDiscordServicesJSON).collect(Collectors.toList())); this.requestBuilder.url("https://api.discordservices.net/bot/" + Config.BOT_ID + "/commands"); - this.requestBuilder.post(RequestBody.create(json.toJson(), MediaType.parse("application/json"))); + this.requestBuilder.post(RequestBody.create(MediaType.parse("application/json"), json.toJson())); this.requestBuilder.header("Authorization", Config.DISCORD_SERVICES_TOKEN); executeAsync(this.requestBuilder.build(), (call, response) -> {}, (call, response) -> { var body = response.body(); diff --git a/src/main/java/de/kittybot/kittybot/modules/SpotifyModule.java b/src/main/java/de/kittybot/kittybot/modules/SpotifyModule.java deleted file mode 100644 index dfff41c2f..000000000 --- a/src/main/java/de/kittybot/kittybot/modules/SpotifyModule.java +++ /dev/null @@ -1,135 +0,0 @@ -package de.kittybot.kittybot.modules; - -import com.wrapper.spotify.SpotifyApi; -import com.wrapper.spotify.model_objects.specification.Track; -import com.wrapper.spotify.requests.authorization.client_credentials.ClientCredentialsRequest; -import de.kittybot.kittybot.objects.module.Module; -import de.kittybot.kittybot.objects.music.MusicManager; -import de.kittybot.kittybot.objects.music.SearchProvider; -import de.kittybot.kittybot.slashcommands.interaction.GuildInteraction; -import de.kittybot.kittybot.utils.Config; -import de.kittybot.kittybot.utils.Utils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.stream.Collectors; - -@SuppressWarnings("unused") -public class SpotifyModule extends Module{ - - private static final Logger LOG = LoggerFactory.getLogger(SpotifyModule.class); - - private SpotifyApi spotify; - private ClientCredentialsRequest clientCredentialsRequest; - private int hits; - - @Override - protected void onEnable(){ - this.spotify = new SpotifyApi.Builder().setClientId(Config.SPOTIFY_CLIENT_ID).setClientSecret(Config.SPOTIFY_CLIENT_SECRET).build(); - this.clientCredentialsRequest = this.spotify.clientCredentials().build(); - this.modules.scheduleAtFixedRate(this::refreshAccessToken, 0, 1, TimeUnit.HOURS); - this.hits = 0; - } - - private void refreshAccessToken(){ - try{ - this.spotify.setAccessToken(this.clientCredentialsRequest.execute().getAccessToken()); - this.hits = 0; - } - catch(Exception e){ - this.hits++; - if(this.hits < 10){ - LOG.warn("Updating the access token failed. Retrying in 10 seconds", e); - this.modules.schedule(this::refreshAccessToken, 10, TimeUnit.SECONDS); - return; - } - LOG.error("Updating the access token failed. Retrying in 20 seconds", e); - this.modules.schedule(this::refreshAccessToken, 20, TimeUnit.SECONDS); - } - } - - public void load(GuildInteraction ia, MusicManager manager, Matcher matcher){ - var identifier = matcher.group("identifier"); - switch(matcher.group("type")){ - case "album": - loadAlbum(identifier, ia, manager); - break; - case "track": - loadTrack(identifier, ia, manager); - break; - case "playlist": - loadPlaylist(identifier, ia, manager); - break; - } - } - - private void loadAlbum(String id, GuildInteraction ia, MusicManager manager){ - this.spotify.getAlbumsTracks(id).build().executeAsync().thenAcceptAsync(tracks -> { - var items = tracks.getItems(); - var toLoad = new ArrayList(); - for(var track : items){ - toLoad.add(track.getArtists()[0].getName() + " " + track.getName()); - } - loadTracks(id, ia, manager, toLoad); - }).exceptionally(throwable -> { - ia.editError(throwable.getMessage().contains("invalid id") ? "Album not found" : "There was an error while loading the album").queue(); - return null; - }); - } - - private void loadTrack(String id, GuildInteraction ia, MusicManager manager){ - this.spotify.getTrack(id).build().executeAsync().thenAcceptAsync(track -> - this.modules.get(MusicModule.class).play(ia, track.getArtists()[0].getName() + " " + track.getName(), SearchProvider.YOUTUBE) - ).exceptionally(throwable -> { - ia.editError(throwable.getMessage().contains("invalid id") ? "Track not found" : "There was an error while loading the track").queue(); - return null; - }); - } - - private void loadPlaylist(String id, GuildInteraction ia, MusicManager manager){ - this.spotify.getPlaylistsItems(id).build().executeAsync().thenAcceptAsync(tracks -> { - var items = tracks.getItems(); - var toLoad = new ArrayList(); - for(var item : items){ - var track = (Track) item.getTrack(); - toLoad.add(track.getArtists()[0].getName() + " " + track.getName()); - } - loadTracks(id, ia, manager, toLoad); - }).exceptionally(throwable -> { - ia.editError(throwable.getMessage().contains("Invalid playlist Id") ? "Playlist not found" : "There was an error while loading the playlist").queue(); - return null; - }); - } - - private void loadTracks(String id, GuildInteraction ia, MusicManager manager, List toLoad){ - var restClient = manager.getScheduler().getLink().getRestClient(); - Utils.all(toLoad.stream().map(restClient::getYoutubeSearchResult).collect(Collectors.toList())) - .thenAcceptAsync(results -> { - var tracks = results.stream().map(result -> { - if(result.isEmpty()){ - return null; - } - var track = result.get(0); - track.setUserData(ia.getUserId()); - return track; - }).filter(Objects::nonNull).collect(Collectors.toList()); - - if(tracks.isEmpty()){ - ia.followupError("No tracks on youtube found"); - return; - } - manager.connectToChannel(ia); - manager.getScheduler().queue(ia, tracks.remove(0), tracks); - }) - .exceptionally(error -> { - ia.editError("Something went wrong while fetching your tracks: \n" + error.getMessage()).queue(); - return null; - }); - } - -} diff --git a/src/main/java/de/kittybot/kittybot/objects/module/Modules.java b/src/main/java/de/kittybot/kittybot/objects/module/Modules.java index 05465471e..704149fd9 100644 --- a/src/main/java/de/kittybot/kittybot/objects/module/Modules.java +++ b/src/main/java/de/kittybot/kittybot/objects/module/Modules.java @@ -64,7 +64,7 @@ private void loadModules(){ var dependencies = instance.getDependencies(); if(dependencies != null && !dependencies.stream().allMatch(this.modules::containsKey)){ queue.add(instance); - LOG.info("Added '{}' back to the queue. Dependencies: {} (Dependency circle jerk incoming!)", instance.getClass().getSimpleName(), dependencies.toString()); + LOG.info("Added '{}' back to the queue. Dependencies: {} (Dependency circle jerk incoming!)", instance.getClass().getSimpleName(), dependencies); continue; } instance.onEnable(); diff --git a/src/main/java/de/kittybot/kittybot/objects/music/AudioLoader.java b/src/main/java/de/kittybot/kittybot/objects/music/AudioLoader.java index 139f8ad42..9936b4c5f 100644 --- a/src/main/java/de/kittybot/kittybot/objects/music/AudioLoader.java +++ b/src/main/java/de/kittybot/kittybot/objects/music/AudioLoader.java @@ -1,17 +1,18 @@ package de.kittybot.kittybot.objects.music; -import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler; -import com.sedmelluq.discord.lavaplayer.tools.FriendlyException; -import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist; -import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import de.kittybot.kittybot.slashcommands.interaction.GuildInteraction; +import lavalink.client.io.FriendlyException; +import lavalink.client.io.LoadResultHandler; +import lavalink.client.player.track.AudioPlaylist; +import lavalink.client.player.track.AudioTrack; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; +import java.util.List; import java.util.stream.Collectors; -public class AudioLoader implements AudioLoadResultHandler{ +public class AudioLoader implements LoadResultHandler{ private static final Logger LOG = LoggerFactory.getLogger(AudioLoader.class); @@ -37,15 +38,19 @@ public void playlistLoaded(AudioPlaylist playlist){ track.setUserData(this.ia.getUserId()); } var firstTrack = playlist.getTracks().get(0); - if(playlist.isSearchResult()){ - this.manager.getScheduler().queue(this.ia, firstTrack, Collections.emptyList()); - return; - } var toPlay = playlist.getSelectedTrack() == null ? firstTrack : playlist.getSelectedTrack(); this.manager.getScheduler().queue(this.ia, toPlay, playlist.getTracks().stream().filter(track -> !track.equals(toPlay)).collect(Collectors.toList())); } + @Override + public void searchResultLoaded(List tracks){ + this.manager.connectToChannel(this.ia); + var track = tracks.get(0); + track.setUserData(this.ia.getUserId()); + this.manager.getScheduler().queue(this.ia, track, Collections.emptyList()); + } + @Override public void noMatches(){ this.ia.reply("No track found"); diff --git a/src/main/java/de/kittybot/kittybot/objects/music/MusicManager.java b/src/main/java/de/kittybot/kittybot/objects/music/MusicManager.java index 37d35f06e..bb96bf906 100644 --- a/src/main/java/de/kittybot/kittybot/objects/music/MusicManager.java +++ b/src/main/java/de/kittybot/kittybot/objects/music/MusicManager.java @@ -1,7 +1,5 @@ package de.kittybot.kittybot.objects.music; -import com.sedmelluq.discord.lavaplayer.source.AudioSourceManager; -import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import de.kittybot.kittybot.modules.LavalinkModule; import de.kittybot.kittybot.modules.MusicModule; import de.kittybot.kittybot.objects.enums.Emoji; @@ -13,6 +11,7 @@ import lavalink.client.io.Link; import lavalink.client.io.jda.JdaLink; import lavalink.client.player.event.PlayerEventListenerAdapter; +import lavalink.client.player.track.AudioTrack; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.Permission; @@ -91,13 +90,13 @@ else if(track == null){ embed.setColor(Color.GREEN) .addField("Playing", Emoji.FORWARD.get() + " " + MusicUtils.formatTrack(track), false); } - embed.setThumbnail(getThumbnail(track.getIdentifier(), track.getSourceManager())) - .addField("Author", info.author, true) - .addField("Length", TimeUtils.formatDuration(track.getDuration()), true) + embed.setThumbnail(getThumbnail(info.getIdentifier(), info.getSourceName())) + .addField("Author", info.getAuthor(), true) + .addField("Length", TimeUtils.formatDuration(info.getLength()), true) .addField("Requested by", MessageUtils.getUserMention(track.getUserData(Long.class)), true); } embed - .addField("Volume", (int) (this.scheduler.getFilters().getVolume() * 100) + "%", true) + .addField("Volume", this.scheduler.getVolume() + "%", true) .addField("Repeat Mode", this.scheduler.getRepeatMode().getName(), true) .setTimestamp(Instant.now()); return embed; @@ -117,7 +116,7 @@ public void sendMusicController(){ if(!channel.canTalk()){ return; } - channel.sendMessage(embed.build()).queue(message -> { + channel.sendMessageEmbeds(embed.build()).queue(message -> { this.scheduler.setControllerId(message.getIdLong()); if(!channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_ADD_REACTION)){ return; @@ -140,14 +139,10 @@ public void updateMusicController(){ if(!channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_HISTORY)){ return; } - channel.editMessageById(this.scheduler.getControllerMessageId(), new MessageBuilder().setEmbed(buildMusicController().build()).build()).override(true).queue(); + channel.editMessageById(this.scheduler.getControllerMessageId(), new MessageBuilder().setEmbeds(buildMusicController().build()).build()).override(true).queue(); } - public String getThumbnail(String identifier, AudioSourceManager source){ - if(source == null){ - return null; - } - var sourceName = source.getSourceName(); + public String getThumbnail(String identifier, String sourceName){ String thumbnail; switch(sourceName){ case "youtube": @@ -178,13 +173,13 @@ private DataArray tracksToJSON(List tracks){ private DataObject trackToJSON(AudioTrack track){ var info = track.getInfo(); return DataObject.empty() - .put("identifier", info.identifier) - .put("uri", info.uri) - .put("title", info.title) - .put("author", info.author) - .put("length", info.length) - .put("source_name", track.getSourceManager().getSourceName()) - .put("is_stream", info.isStream); + .put("identifier", info.getIdentifier()) + .put("uri", info.getUri()) + .put("title", info.getTitle()) + .put("author", info.getAuthor()) + .put("length", info.getLength()) + .put("source_name", info.getSourceName()) + .put("is_stream", info.isStream()); } public TrackScheduler getScheduler(){ diff --git a/src/main/java/de/kittybot/kittybot/objects/music/TrackScheduler.java b/src/main/java/de/kittybot/kittybot/objects/music/TrackScheduler.java index c2e59dc28..5313dc2ac 100644 --- a/src/main/java/de/kittybot/kittybot/objects/music/TrackScheduler.java +++ b/src/main/java/de/kittybot/kittybot/objects/music/TrackScheduler.java @@ -1,7 +1,5 @@ package de.kittybot.kittybot.objects.music; -import com.sedmelluq.discord.lavaplayer.track.AudioTrack; -import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason; import de.kittybot.kittybot.modules.SettingsModule; import de.kittybot.kittybot.objects.module.Modules; import de.kittybot.kittybot.slashcommands.interaction.GuildInteraction; @@ -14,9 +12,13 @@ import lavalink.client.player.IPlayer; import lavalink.client.player.LavalinkPlayer; import lavalink.client.player.event.PlayerEventListenerAdapter; +import lavalink.client.player.track.AudioTrack; +import lavalink.client.player.track.AudioTrackEndReason; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.TextChannel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.time.Instant; import java.util.Collections; @@ -69,7 +71,7 @@ public void onTrackStart(IPlayer player, AudioTrack track){ @Override public void onTrackEnd(IPlayer player, AudioTrack track, AudioTrackEndReason endReason){ - this.history.push(track.makeClone()); + this.history.push(track); if(!endReason.mayStartNext){ this.manager.updateMusicController(); return; @@ -80,7 +82,7 @@ public void onTrackEnd(IPlayer player, AudioTrack track, AudioTrackEndReason end public void next(boolean force, AudioTrack track){ if(this.repeatMode == RepeatMode.SONG && !force){ if(track != null){ - this.player.playTrack(track.makeClone()); + this.player.playTrack(track); } return; } @@ -92,7 +94,7 @@ public void next(boolean force, AudioTrack track){ } this.player.playTrack(next); if(this.repeatMode == RepeatMode.QUEUE && track != null){ - this.queue.offer(track.makeClone()); + this.queue.offer(track); } } @@ -171,7 +173,7 @@ public boolean shuffle(){ } public void increaseVolume(int volumeStep){ - var newVol = ((int) this.player.getFilters().getVolume()) * 100 + volumeStep; + var newVol = this.player.getVolume() + volumeStep; if(newVol <= 0){ newVol = 10; } @@ -183,10 +185,14 @@ public void increaseVolume(int volumeStep){ } public void setVolume(int volume){ - this.player.getFilters().setVolume(volume / 100.0f).commit(); + this.player.setVolume(volume); this.manager.updateMusicController(); } + public int getVolume(){ + return this.player.getVolume(); + } + public long getControllerMessageId(){ return this.controllerMessageId; } diff --git a/src/main/java/de/kittybot/kittybot/slashcommands/application/Category.java b/src/main/java/de/kittybot/kittybot/slashcommands/application/Category.java index f88e21f85..5cc5cda81 100644 --- a/src/main/java/de/kittybot/kittybot/slashcommands/application/Category.java +++ b/src/main/java/de/kittybot/kittybot/slashcommands/application/Category.java @@ -42,7 +42,7 @@ public DataObject toJSON(){ } public String getUrl(){ - return "http://" + Config.ORIGIN_URL + "/commands#" + this.name.toLowerCase(); + return "https://" + Config.ORIGIN_URL + "/commands#" + this.name.toLowerCase(); } public String getEmoteUrl(){ diff --git a/src/main/java/de/kittybot/kittybot/slashcommands/interaction/response/InteractionRespondAction.java b/src/main/java/de/kittybot/kittybot/slashcommands/interaction/response/InteractionRespondAction.java index c95a57f8b..e2bf3039f 100644 --- a/src/main/java/de/kittybot/kittybot/slashcommands/interaction/response/InteractionRespondAction.java +++ b/src/main/java/de/kittybot/kittybot/slashcommands/interaction/response/InteractionRespondAction.java @@ -72,7 +72,7 @@ public RequestBody finalizeData(){ } protected RequestBody asJSON(){ - return RequestBody.create(getJSON().toJson(), Requester.MEDIA_TYPE_JSON); + return RequestBody.create(Requester.MEDIA_TYPE_JSON, getJSON().toJson()); } protected DataObject getJSON(){ diff --git a/src/main/java/de/kittybot/kittybot/utils/Config.java b/src/main/java/de/kittybot/kittybot/utils/Config.java index bb29e14b4..eede6b5f5 100644 --- a/src/main/java/de/kittybot/kittybot/utils/Config.java +++ b/src/main/java/de/kittybot/kittybot/utils/Config.java @@ -37,9 +37,6 @@ public class Config{ public static String SIGNING_KEY; - public static String SPOTIFY_CLIENT_ID; - public static String SPOTIFY_CLIENT_SECRET; - public static String TOP_GG_TOKEN; public static String DISCORD_EXTREME_LIST_TOKEN; public static String DISCORD_BOATS_TOKEN; @@ -106,9 +103,6 @@ public static void init(String path) throws IOException, MissingConfigValuesExce SIGNING_KEY = json.getString("signing_key", ""); - SPOTIFY_CLIENT_ID = json.getString("spotify_client_id", ""); - SPOTIFY_CLIENT_SECRET = json.getString("spotify_client_secret", ""); - DISCORD_BOTS_TOKEN = getBotListToken(json, "discord_bots_token"); TOP_GG_TOKEN = getBotListToken(json, "top_gg_token"); DISCORD_EXTREME_LIST_TOKEN = getBotListToken(json, "discord_extreme_list_token"); diff --git a/src/main/java/de/kittybot/kittybot/utils/MusicUtils.java b/src/main/java/de/kittybot/kittybot/utils/MusicUtils.java index 0764e31ac..c5270403b 100644 --- a/src/main/java/de/kittybot/kittybot/utils/MusicUtils.java +++ b/src/main/java/de/kittybot/kittybot/utils/MusicUtils.java @@ -1,11 +1,11 @@ package de.kittybot.kittybot.utils; -import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import de.kittybot.kittybot.modules.PaginatorModule; import de.kittybot.kittybot.modules.SettingsModule; import de.kittybot.kittybot.objects.module.Modules; import de.kittybot.kittybot.objects.music.TrackScheduler; import de.kittybot.kittybot.slashcommands.interaction.GuildInteraction; +import lavalink.client.player.track.AudioTrack; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.TextChannel; @@ -31,12 +31,12 @@ public static String formatTracks(String message, Collection tracks) public static String formatTrackWithInfo(AudioTrack track){ var info = track.getInfo(); - return formatTrack(track) + " - " + TimeUtils.formatDuration(info.length) + " [" + MessageUtils.getUserMention(track.getUserData(Long.class)) + "]"; + return formatTrack(track) + " - " + TimeUtils.formatDuration(info.getLength()) + " [" + MessageUtils.getUserMention(track.getUserData(Long.class)) + "]"; } public static String formatTrack(AudioTrack track){ var info = track.getInfo(); - return MessageUtils.maskLink("`" + info.title + "`", info.uri); + return MessageUtils.maskLink("`" + info.getTitle() + "`", info.getUri()); } public static boolean checkCommandRequirements(GuildInteraction ia, TrackScheduler scheduler){ diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml index e32dc0046..3fd501101 100644 --- a/src/main/resources/logback.xml +++ b/src/main/resources/logback.xml @@ -1,6 +1,8 @@ + + INFO @@ -19,14 +21,6 @@ - - - - - - - -