From fe3bdb4c1dc8b1c57fd8718658c423bb2ab34773 Mon Sep 17 00:00:00 2001 From: Presti Date: Tue, 23 Jan 2024 13:24:50 +0100 Subject: [PATCH 01/94] Start updating. --- pom.xml | 2 +- .../CustomEventContainerCreator.java | 9 ++- .../StreamActionContainerCreator.java | 5 +- .../commands/impl/community/Giveaway.java | 12 ++- .../impl/community/InstagramNotifier.java | 12 +-- .../commands/impl/community/Reactions.java | 16 ++-- .../ree6/commands/interfaces/ICommand.java | 30 ++++---- .../de/presti/ree6/events/CustomEvents.java | 23 +++--- .../de/presti/ree6/events/LoggingEvents.java | 75 +++++++++++-------- 9 files changed, 105 insertions(+), 79 deletions(-) diff --git a/pom.xml b/pom.xml index 572fbb907..fc3e6dcff 100644 --- a/pom.xml +++ b/pom.xml @@ -156,7 +156,7 @@ de.ree6 Ree6-SQL - 2.2.5 + a447cefa76 diff --git a/src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainerCreator.java b/src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainerCreator.java index e9265f891..5bfc1ac6b 100644 --- a/src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainerCreator.java +++ b/src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainerCreator.java @@ -13,6 +13,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.CompletableFuture; /** * A Utility class used to create CustomEventContainers. @@ -72,10 +73,10 @@ public static Class getAction(String action) { * @param typ The typ of the CustomEventAction. * @return A List of CustomEventContainer. */ - public static List getContainers(CustomEventTyp typ) { + public static CompletableFuture> getContainers(CustomEventTyp typ) { return SQLSession.getSqlConnector().getSqlWorker() .getEntityList(new CustomEventAction(), "FROM CustomEventAction WHERE event = :typ", Map.of("typ", typ.name())) - .stream().map(CustomEventContainer::new).toList(); + .thenApply(list -> list.stream().map(CustomEventContainer::new).toList()); } /** @@ -85,10 +86,10 @@ public static List getContainers(CustomEventTyp typ) { * @param typ The typ of the CustomEventAction. * @return A List of CustomEventContainer. */ - public static List getContainers(String guildId, CustomEventTyp typ) { + public static CompletableFuture> getContainers(String guildId, CustomEventTyp typ) { return SQLSession.getSqlConnector().getSqlWorker() .getEntityList(new CustomEventAction(), "FROM CustomEventAction WHERE guildId = :guild AND event = :typ", Map.of("guild", guildId, "typ", typ.name())) - .stream().map(CustomEventContainer::new).toList(); + .thenApply(list -> list.stream().map(CustomEventContainer::new).toList()); } } diff --git a/src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainerCreator.java b/src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainerCreator.java index e3d317cc5..1c7734c8e 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainerCreator.java +++ b/src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainerCreator.java @@ -13,6 +13,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.CompletableFuture; /** * A Utility class used to create StreamActionContainers. @@ -77,10 +78,10 @@ public static Class getAction(String action) { * @param listenerId The Listener to get the Containers for. * @return A List of StreamActionContainers. */ - public static List getContainers(int listenerId) { + public static CompletableFuture> getContainers(int listenerId) { return SQLSession.getSqlConnector().getSqlWorker() .getEntityList(new StreamAction(), "FROM StreamAction WHERE listener = :listener", Map.of("listener", listenerId)) - .stream().map(StreamActionContainer::new).toList(); + .thenApply(list -> list.stream().map(StreamActionContainer::new).toList()); } } diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java b/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java index 705cd12d2..f31827656 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java @@ -97,9 +97,15 @@ public void onPerform(CommandEvent commandEvent) { new de.presti.ree6.sql.entities.Giveaway(message.getIdLong(), commandEvent.getMember().getIdLong(), commandEvent.getGuild().getIdLong(), commandEvent.getChannel().getIdLong(), prize, winners, endTime); - giveaway = SQLSession.getSqlConnector().getSqlWorker().updateEntity(giveaway); - Main.getInstance().getGiveawayManager().add(giveaway); - commandEvent.reply(commandEvent.getResource("message.giveaway.created", message.getId())); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(giveaway).thenAccept(giveaway1 -> { + if (giveaway1 == null) { + commandEvent.reply(commandEvent.getResource("message.default.internalError")); + return; + } + + Main.getInstance().getGiveawayManager().add(giveaway1); + commandEvent.reply(commandEvent.getResource("message.giveaway.created", message.getId())); + }); }); } diff --git a/src/main/java/de/presti/ree6/commands/impl/community/InstagramNotifier.java b/src/main/java/de/presti/ree6/commands/impl/community/InstagramNotifier.java index f7b478aaa..405a514e6 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/InstagramNotifier.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/InstagramNotifier.java @@ -56,13 +56,15 @@ public void onPerform(CommandEvent commandEvent) { switch (command) { case "list" -> { - StringBuilder end = new StringBuilder(); + SQLSession.getSqlConnector().getSqlWorker().getAllInstagramUsers(commandEvent.getGuild().getIdLong()).thenAccept(strings -> { + StringBuilder end = new StringBuilder(); - for (String users : SQLSession.getSqlConnector().getSqlWorker().getAllInstagramUsers(commandEvent.getGuild().getIdLong())) { - end.append(users).append("\n"); - } + for (String users : strings) { + end.append(users).append("\n"); + } - commandEvent.reply(commandEvent.getResource("message.instagramNotifier.list", end.toString()), 10); + commandEvent.reply(commandEvent.getResource("message.instagramNotifier.list", end.toString()), 10); + }); } case "add" -> { if (nameMapping == null || channelMapping == null) { diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java b/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java index 7972fdf31..2583755ed 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java @@ -85,15 +85,15 @@ public void onPerform(CommandEvent commandEvent) { return; } - ReactionRole reactionRole = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ReactionRole(), + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ReactionRole(), "FROM ReactionRole WHERE guildRoleId.guildId=:gid AND guildRoleId.roleId=:roleId AND messageId=:messageId", - Map.of("gid", commandEvent.getGuild().getIdLong(), "roleId", role.getAsRole().getIdLong(), "messageId", messageId)); + Map.of("gid", commandEvent.getGuild().getIdLong(), "roleId", role.getAsRole().getIdLong(), "messageId", messageId)).thenAccept(reactionRole -> { + if (reactionRole != null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(reactionRole); - if (reactionRole != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(reactionRole); - - commandEvent.reply(commandEvent.getResource("message.reactions.removed", role.getAsRole().getIdLong()), 5); - } + commandEvent.reply(commandEvent.getResource("message.reactions.removed", role.getAsRole().getIdLong()), 5); + } + }); } default -> commandEvent.reply(commandEvent.getResource("message.default.invalidOption"), 5); @@ -107,7 +107,7 @@ public void onPerform(CommandEvent commandEvent) { public CommandData getCommandData() { return new CommandDataImpl("reactions", LanguageService.getDefault("command.description.reactions")) .addSubcommands(new SubcommandData("remove", "Remove a reaction role.") - .addOption(OptionType.STRING,"message", "The ID of the Message.", true) + .addOption(OptionType.STRING, "message", "The ID of the Message.", true) .addOption(OptionType.ROLE, "role", "The Role to be given.", true), new SubcommandData("add", "Add a reaction role.") .addOption(OptionType.STRING, "message", "The ID of the Message.", true) diff --git a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java index 94ae0e76d..9631a9d8d 100644 --- a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java +++ b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java @@ -40,22 +40,22 @@ default void onASyncPerform(CommandEvent commandEvent) { } return null; }); - ThreadUtil.createThread(y -> { - // Update Stats. - SQLSession.getSqlConnector().getSqlWorker().addStats(commandEvent.getGuild().getIdLong(), commandEvent.getCommand()); - if (SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").getBooleanValue()) { - AnnouncementManager.getAnnouncementList().forEach(a -> { - if (!AnnouncementManager.hasReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id())) { - Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder().setTitle(a.title()) - .setAuthor(BotConfig.getBotName() + "-Info") - .setDescription(a.content().replace("\\n", "\n") + "\n\n" + LanguageService.getByGuild(commandEvent.getGuild(), "message.news.notice")) - .setFooter(BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) - .setColor(BotWorker.randomEmbedColor()), 15, commandEvent.getChannel()); - AnnouncementManager.addReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id()); - } - }); - } + // Update Stats. + SQLSession.getSqlConnector().getSqlWorker().addStats(commandEvent.getGuild().getIdLong(), commandEvent.getCommand()); + SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").thenAccept(setting -> { + if (!setting.getBooleanValue()) return; + AnnouncementManager.getAnnouncementList().forEach(a -> { + if (!AnnouncementManager.hasReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id())) { + Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder().setTitle(a.title()) + .setAuthor(BotConfig.getBotName() + "-Info") + .setDescription(a.content().replace("\\n", "\n") + "\n\n" + LanguageService.getByGuild(commandEvent.getGuild(), "message.news.notice")) + .setFooter(BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) + .setColor(BotWorker.randomEmbedColor()), 15, commandEvent.getChannel()); + + AnnouncementManager.addReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id()); + } + }); }); } diff --git a/src/main/java/de/presti/ree6/events/CustomEvents.java b/src/main/java/de/presti/ree6/events/CustomEvents.java index d7713b11d..876cd38e9 100644 --- a/src/main/java/de/presti/ree6/events/CustomEvents.java +++ b/src/main/java/de/presti/ree6/events/CustomEvents.java @@ -32,6 +32,7 @@ public class CustomEvents implements EventListener { /** * Listens for all events. + * * @param event The event. */ @Override @@ -54,7 +55,8 @@ public void onEvent(@NotNull GenericEvent event) { /** * Run the cache entry for the given event. - * @param clazz The event class. + * + * @param clazz The event class. * @param guildId The guild id. */ public void runCacheEntry(Class clazz, long guildId) { @@ -67,29 +69,28 @@ public void runCacheEntry(Class clazz, long guildId) { /** * Check for new CustomEvents. - * @param clazz The event class. + * + * @param clazz The event class. * @param guildId The guild id. */ public void checkForNew(Class clazz, long guildId) { if (System.currentTimeMillis() - lastCheck < Duration.ofMinutes(1).toMillis()) return; lastCheck = System.currentTimeMillis(); - ThreadUtil.createThread(x -> { - List list = SQLSession.getSqlConnector().getSqlWorker().getEntityList(new CustomEventAction(), - "FROM CustomEventAction WHERE guildId=:gid", - Map.of("gid", guildId)).stream().map(CustomEventContainer::new).toList(); + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new CustomEventAction(), + "FROM CustomEventAction WHERE guildId=:gid", + Map.of("gid", guildId)).thenApply(x -> x.stream().map(CustomEventContainer::new).toList()).thenAccept(list -> { + CustomEventTyp typ = CustomEventMapper.getEventTyp(clazz); list.forEach(c -> { - - CustomEventTyp typ = CustomEventMapper.getEventTyp(clazz); - if (cache.containsKey(typ) && !cache.get(typ).contains(c)) { cache.get(typ).add(c); } else { cache.put(typ, List.of(c)); } - }); - cache.values().forEach(entries -> entries.removeIf(c -> !list.contains(c))); + cache.values().forEach(entries -> entries.removeIf(c -> !list.contains(c))); + }); }); + } } diff --git a/src/main/java/de/presti/ree6/events/LoggingEvents.java b/src/main/java/de/presti/ree6/events/LoggingEvents.java index 6f4ba1e38..9262bb39f 100644 --- a/src/main/java/de/presti/ree6/events/LoggingEvents.java +++ b/src/main/java/de/presti/ree6/events/LoggingEvents.java @@ -65,7 +65,7 @@ public class LoggingEvents extends ListenerAdapter { //region Guild /** - * @see ListenerAdapter#onGuildUpdateVanityCode(GuildUpdateVanityCodeEvent) + * @see ListenerAdapter#onGuildUpdateVanityCode(GuildUpdateVanityCodeEvent) */ @Override public void onGuildUpdateVanityCode(@NotNull GuildUpdateVanityCodeEvent event) { @@ -73,22 +73,20 @@ public void onGuildUpdateVanityCode(@NotNull GuildUpdateVanityCodeEvent event) { if (!event.getGuild().getSelfMember().hasPermission(Permission.MANAGE_SERVER)) return; - Invite invite = event.getOldVanityCode() != null ? - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Invite(), "FROM Invite WHERE guildAndCode.guild = :gid AND guildAndCode.code = :code", - Map.of("gid", event.getGuild().getIdLong(), "code", event.getOldVanityCode())) - : null; - - if (invite != null) { - invite.setCode(event.getNewVanityCode()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(invite); - } else { + if (event.getOldVanityCode() == null) { event.getGuild().retrieveVanityInvite().onErrorMap(throwable -> null).queue(vanityInvite -> SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Invite(event.getGuild().getIdLong(), event.getGuild().getOwnerIdLong(), vanityInvite.getUses(), event.getNewVanityCode()))); + } else { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Invite(), "FROM Invite WHERE guildAndCode.guild = :gid AND guildAndCode.code = :code", + Map.of("gid", event.getGuild().getIdLong(), "code", event.getOldVanityCode())).thenAccept(invite -> { + invite.setCode(event.getNewVanityCode()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(invite); + }); } } /** - * @see ListenerAdapter#onGuildBan(GuildBanEvent) + * @see ListenerAdapter#onGuildBan(GuildBanEvent) */ @Override public void onGuildBan(@Nonnull GuildBanEvent event) { @@ -113,7 +111,8 @@ public void onGuildBan(@Nonnull GuildBanEvent event) { AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.BAN).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -147,7 +146,8 @@ public void onGuildUnban(@Nonnull GuildUnbanEvent event) { AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.UNBAN).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -264,7 +264,8 @@ public void onGuildMemberRemove(@Nonnull GuildMemberRemoveEvent event) { AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.KICK).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -353,7 +354,8 @@ public void onGuildMemberUpdateNickname(@Nonnull GuildMemberUpdateNicknameEvent AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -414,7 +416,8 @@ public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_VOICE_KICK).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -440,7 +443,8 @@ public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_VOICE_MOVE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -497,7 +501,8 @@ public void onGenericChannel(@Nonnull GenericChannelEvent event) { return; } - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -547,7 +552,8 @@ public void onGenericChannel(@Nonnull GenericChannelEvent event) { return; } - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -589,13 +595,14 @@ public void onGuildMemberRoleAdd(@Nonnull GuildMemberRoleAddEvent event) { finalString.append(":white_check_mark: ").append(r.getName()).append("\n"); } - we.setDescription(LanguageService.getByGuild(event.getGuild(),"logging.member", event.getMember().getAsMention())); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.member", event.getMember().getAsMention())); we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.roles") + ":**", finalString.toString())); AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -629,13 +636,14 @@ public void onGuildMemberRoleRemove(@Nonnull GuildMemberRoleRemoveEvent event) { finalString.append(":no_entry: ").append(r.getName()).append("\n"); } - we.setDescription(LanguageService.getByGuild(event.getGuild(),"logging.member", event.getMember().getAsMention())); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.member", event.getMember().getAsMention())); we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.roles") + ":**", finalString.toString())); AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -667,7 +675,8 @@ public void onRoleCreate(@Nonnull RoleCreateEvent event) { AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_CREATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -699,7 +708,8 @@ public void onRoleDelete(@Nonnull RoleDeleteEvent event) { AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_DELETE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -733,7 +743,8 @@ public void onRoleUpdateName(@Nonnull RoleUpdateNameEvent event) { AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -767,7 +778,8 @@ public void onRoleUpdateMentionable(@Nonnull RoleUpdateMentionableEvent event) { AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -801,7 +813,8 @@ public void onRoleUpdateHoisted(@Nonnull RoleUpdateHoistedEvent event) { AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -860,7 +873,8 @@ public void onRoleUpdatePermissions(@Nonnull RoleUpdatePermissionsEvent event) { AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -895,7 +909,8 @@ public void onRoleUpdateColor(@Nonnull RoleUpdateColorEvent event) { AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); From 35b5b6ffd0037dc8a684d74a9df1adcf02ef3141 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 24 Jan 2024 12:43:16 +0100 Subject: [PATCH 02/94] Finishing up one Event class. --- .../de/presti/ree6/events/OtherEvents.java | 361 +++++++++--------- .../ree6/utils/others/ModerationUtil.java | 20 +- 2 files changed, 202 insertions(+), 179 deletions(-) diff --git a/src/main/java/de/presti/ree6/events/OtherEvents.java b/src/main/java/de/presti/ree6/events/OtherEvents.java index b6aa1b232..d30823e09 100644 --- a/src/main/java/de/presti/ree6/events/OtherEvents.java +++ b/src/main/java/de/presti/ree6/events/OtherEvents.java @@ -13,7 +13,6 @@ import de.presti.ree6.sql.entities.ReactionRole; import de.presti.ree6.sql.entities.TemporalVoicechannel; import de.presti.ree6.sql.entities.Tickets; -import de.presti.ree6.sql.entities.level.ChatUserLevel; import de.presti.ree6.sql.entities.level.VoiceUserLevel; import de.presti.ree6.sql.entities.stats.ChannelStats; import de.presti.ree6.utils.apis.ChatGPTAPI; @@ -59,6 +58,7 @@ import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.IntStream; /** @@ -102,9 +102,7 @@ public void onGuildLeave(@Nonnull GuildLeaveEvent event) { @Override public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { - ThreadUtil.createThread(x -> { - - ChannelStats channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getId())); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getId())).thenAccept(channelStats -> { if (channelStats != null) { if (channelStats.getMemberStatsChannelId() != null) { GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStats.getMemberStatsChannelId()); @@ -129,36 +127,45 @@ public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { } }); } + }); - UserUtil.handleMemberJoin(event.getGuild(), event.getMember()); - - if (!SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong())) return; + UserUtil.handleMemberJoin(event.getGuild(), event.getMember()); + + SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong()).thenAccept(x -> { + if (x) { + WebhookMessageBuilder wmb = new WebhookMessageBuilder(); + + wmb.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wmb.setUsername("Welcome!"); + + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join").thenAccept(messageSetting -> { + final String messageContent = messageSetting.getStringValue() + .replace("%user_name%", event.getMember().getUser().getName()) + .replace("%guild_name%", event.getGuild().getName()) + .replace("%guild_member_count%", String.valueOf(event.getGuild().getMemberCount())); + + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join_image").thenAccept(joinImage -> { + if (!joinImage.getStringValue().isBlank()) { + try { + wmb.addFile("welcome.png", ImageCreationUtility.createJoinImage(event.getUser(), joinImage.getStringValue(), + messageContent.replace("%user_mention%", event.getMember().getUser().getName()))); + } catch (IOException e) { + wmb.setContent(messageContent); + log.error("Error while creating join image!", e); + } + } else { + wmb.setContent(messageContent.replace("%user_mention%", event.getMember().getUser().getAsMention())); + } - WebhookMessageBuilder wmb = new WebhookMessageBuilder(); + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + if (webhook == null) return; - wmb.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wmb.setUsername("Welcome!"); + WebhookUtil.sendWebhook(wmb.build(), webhook); + }); + }); - String messageContent = SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join") - .getStringValue() - .replace("%user_name%", event.getMember().getUser().getName()) - .replace("%guild_name%", event.getGuild().getName()) - .replace("%guild_member_count%", String.valueOf(event.getGuild().getMemberCount())); - if (!SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join_image").getStringValue().isBlank()) { - try { - messageContent = messageContent.replace("%user_mention%", event.getMember().getUser().getName()); - wmb.addFile("welcome.png", ImageCreationUtility.createJoinImage(event.getUser(), - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join_image").getStringValue(), messageContent)); - } catch (IOException e) { - wmb.setContent(messageContent); - log.error("Error while creating join image!", e); - } - } else { - messageContent = messageContent.replace("%user_mention%", event.getMember().getUser().getAsMention()); - wmb.setContent(messageContent); + }); } - - WebhookUtil.sendWebhook(wmb.build(), SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong())); }); } @@ -169,8 +176,7 @@ public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) { super.onGuildMemberRemove(event); - ThreadUtil.createThread(x -> { - ChannelStats channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getId())); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getId())).thenAccept(channelStats -> { if (channelStats != null) { if (channelStats.getMemberStatsChannelId() != null) { GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStats.getMemberStatsChannelId()); @@ -198,64 +204,65 @@ public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) { }); if (BotConfig.isModuleActive("tickets")) { - Tickets tickets = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - if (tickets != null) { - Category category = event.getGuild().getCategoryById(tickets.getTicketCategory()); - - if (category != null) { - List channels = category.getTextChannels().stream().filter(c -> c.getTopic() != null && c.getTopic().equalsIgnoreCase(event.getUser().getId())).toList(); - if (!channels.isEmpty()) { - TextChannel channel = channels.get(0); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(BotConfig.getBotName()) - .append(" Ticket transcript") - .append(" ") - .append(ZonedDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG))) - .append("\n") - .append("\n"); - - - for (Message message : channel.getIterableHistory().reverse()) { - stringBuilder - .append("[") - .append(message.getTimeCreated().toZonedDateTime().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT))) - .append("]") - .append(" ") - .append(message.getAuthor().getAsTag()) + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(tickets -> { + if (tickets != null) { + Category category = event.getGuild().getCategoryById(tickets.getTicketCategory()); + + if (category != null) { + List channels = category.getTextChannels().stream().filter(c -> c.getTopic() != null && c.getTopic().equalsIgnoreCase(event.getUser().getId())).toList(); + if (!channels.isEmpty()) { + TextChannel channel = channels.get(0); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(BotConfig.getBotName()) + .append(" Ticket transcript") .append(" ") - .append("->") - .append(" ") - .append(message.getContentRaw()); - - if (!message.getAttachments().isEmpty()) { - for (Message.Attachment attachment : message.getAttachments()) { - stringBuilder.append("\n").append(attachment.getUrl()); + .append(ZonedDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG))) + .append("\n") + .append("\n"); + + + for (Message message : channel.getIterableHistory().reverse()) { + stringBuilder + .append("[") + .append(message.getTimeCreated().toZonedDateTime().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT))) + .append("]") + .append(" ") + .append(message.getAuthor().getAsTag()) + .append(" ") + .append("->") + .append(" ") + .append(message.getContentRaw()); + + if (!message.getAttachments().isEmpty()) { + for (Message.Attachment attachment : message.getAttachments()) { + stringBuilder.append("\n").append(attachment.getUrl()); + } } - } - stringBuilder.append("\n"); - } + stringBuilder.append("\n"); + } - stringBuilder.append("\n").append("Closed by").append(" ").append(event.getUser().getEffectiveName()); + stringBuilder.append("\n").append("Closed by").append(" ").append(event.getUser().getEffectiveName()); - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - webhookMessageBuilder.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName() + "-Tickets"); + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + webhookMessageBuilder.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName() + "-Tickets"); - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - webhookEmbedBuilder.setDescription("Here is the transcript of the ticket " + tickets.getTicketCount() + "!"); - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - webhookEmbedBuilder.setColor(BotWorker.randomEmbedColor().getRGB()); + webhookEmbedBuilder.setDescription("Here is the transcript of the ticket " + tickets.getTicketCount() + "!"); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + webhookEmbedBuilder.setColor(BotWorker.randomEmbedColor().getRGB()); - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - webhookMessageBuilder.addFile(tickets.getTicketCount() + "_transcript.txt", stringBuilder.toString().getBytes(StandardCharsets.UTF_8)); + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + webhookMessageBuilder.addFile(tickets.getTicketCount() + "_transcript.txt", stringBuilder.toString().getBytes(StandardCharsets.UTF_8)); - WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), tickets.getLogChannelId(), tickets.getLogChannelWebhookToken(), false); - channel.delete().queue(); + WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), tickets.getLogChannelId(), tickets.getLogChannelWebhookToken(), false); + channel.delete().queue(); + } } } - } + }); } } @@ -277,30 +284,31 @@ public void onGuildVoiceUpdate(@Nonnull GuildVoiceUpdateEvent event) { } if (BotConfig.isModuleActive("temporalvoice")) { - TemporalVoicechannel temporalVoicechannel = SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getId())); - - if (temporalVoicechannel != null) { - VoiceChannel voiceChannel = event.getGuild().getVoiceChannelById(event.getChannelJoined().getId()); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getId())) + .thenAccept(temporalVoicechannel -> { + if (temporalVoicechannel != null) { + VoiceChannel voiceChannel = event.getGuild().getVoiceChannelById(event.getChannelJoined().getId()); - if (voiceChannel == null) - return; + if (voiceChannel == null) + return; - if (temporalVoicechannel.getGuildChannelId().getChannelId() != voiceChannel.getIdLong()) { - return; - } + if (temporalVoicechannel.getGuildChannelId().getChannelId() != voiceChannel.getIdLong()) { + return; + } - if (voiceChannel.getParentCategory() != null) { - String preName = LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", "SPLIT"); - preName = preName.split("SPLIT")[0]; + if (voiceChannel.getParentCategory() != null) { + String preName = LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", "SPLIT"); + preName = preName.split("SPLIT")[0]; - String finalPreName = preName; - voiceChannel.getParentCategory().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", - event.getGuild().getVoiceChannels().stream().filter(c -> c.getName().startsWith(finalPreName)).count() + 1)).queue(channel -> { - event.getGuild().moveVoiceMember(event.getMember(), channel).queue(); - ArrayUtil.temporalVoicechannel.add(channel.getId()); + String finalPreName = preName; + voiceChannel.getParentCategory().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", + event.getGuild().getVoiceChannels().stream().filter(c -> c.getName().startsWith(finalPreName)).count() + 1)).queue(channel -> { + event.getGuild().moveVoiceMember(event.getMember(), channel).queue(); + ArrayUtil.temporalVoicechannel.add(channel.getId()); + }); + } + } }); - } - } } } else if (event.getChannelJoined() == null) { doVoiceXPStuff(event.getMember()); @@ -328,30 +336,31 @@ public void onGuildVoiceUpdate(@Nonnull GuildVoiceUpdateEvent event) { } } else { - TemporalVoicechannel temporalVoicechannel = SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getId())); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getId())) + .thenAccept(temporalVoicechannel -> { + if (temporalVoicechannel != null) { + VoiceChannel voiceChannel = event.getGuild().getVoiceChannelById(event.getChannelJoined().getId()); - if (temporalVoicechannel != null) { - VoiceChannel voiceChannel = event.getGuild().getVoiceChannelById(event.getChannelJoined().getId()); + if (voiceChannel == null) + return; - if (voiceChannel == null) - return; - - if (temporalVoicechannel.getGuildChannelId().getChannelId() != voiceChannel.getIdLong()) { - return; - } + if (temporalVoicechannel.getGuildChannelId().getChannelId() != voiceChannel.getIdLong()) { + return; + } - if (voiceChannel.getParentCategory() != null) { - String preName = LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", "SPLIT"); - preName = preName.split("SPLIT")[0]; + if (voiceChannel.getParentCategory() != null) { + String preName = LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", "SPLIT"); + preName = preName.split("SPLIT")[0]; - String finalPreName = preName; - voiceChannel.getParentCategory().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", - event.getGuild().getVoiceChannels().stream().filter(c -> c.getName().startsWith(finalPreName)).count() + 1)).queue(channel -> { - event.getGuild().moveVoiceMember(event.getMember(), channel).queue(); - ArrayUtil.temporalVoicechannel.add(channel.getId()); + String finalPreName = preName; + voiceChannel.getParentCategory().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", + event.getGuild().getVoiceChannels().stream().filter(c -> c.getName().startsWith(finalPreName)).count() + 1)).queue(channel -> { + event.getGuild().moveVoiceMember(event.getMember(), channel).queue(); + ArrayUtil.temporalVoicechannel.add(channel.getId()); + }); + } + } }); - } - } } } @@ -393,6 +402,7 @@ public void onGenericGuildVoice(@NotNull GenericGuildVoiceEvent event) { /** * Method used to do all the calculations for the Voice XP. + * * @param member the Member that should be checked. */ public void doVoiceXPStuff(Member member) { @@ -401,12 +411,10 @@ public void doVoiceXPStuff(Member member) { int addXP = IntStream.rangeClosed(1, min).map(i -> RandomUtils.random.nextInt(5, 11)).sum(); - // TODO:: await database future system. - ThreadUtil.createThread(x -> { - VoiceUserLevel newUserLevel = SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelData(member.getGuild().getIdLong(), member.getIdLong()); - newUserLevel.addExperience(addXP); + SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelData(member.getGuild().getIdLong(), member.getIdLong()).thenAccept(x -> { + x.addExperience(addXP); - SQLSession.getSqlConnector().getSqlWorker().addVoiceLevelData(member.getGuild().getIdLong(), newUserLevel); + SQLSession.getSqlConnector().getSqlWorker().addVoiceLevelData(member.getGuild().getIdLong(), x); UserUtil.handleVoiceLevelReward(member.getGuild(), member); }); @@ -438,9 +446,11 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { super.onMessageReceived(event); if (event.isFromType(ChannelType.NEWS) && - BotConfig.isModuleActive("autopublish") && - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "configuration_autopublish").getBooleanValue()) { - event.getMessage().crosspost().queue(c -> c.addReaction(Emoji.fromUnicode("U+1F4E2")).queue()); + BotConfig.isModuleActive("autopublish")) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "configuration_autopublish").thenAccept(x -> { + if (x.getBooleanValue()) + event.getMessage().crosspost().queue(c -> c.addReaction(Emoji.fromUnicode("U+1F4E2")).queue()); + }); } if (event.isFromGuild() && (event.isFromType(ChannelType.TEXT) || event.isFromType(ChannelType.VOICE)) && event.getMember() != null) { @@ -455,17 +465,20 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { ArrayUtil.messageIDwithUser.put(event.getMessageId(), event.getAuthor()); } - // TODO:: start working with futureComplete instead of creating a thread here. - ThreadUtil.createThread(x -> { - - if (ModerationUtil.shouldModerate(event.getGuild().getIdLong())) { - if (ModerationUtil.checkMessage(event.getGuild().getIdLong(), event.getMessage().getContentRaw())) { - Main.getInstance().getCommandManager().deleteMessage(event.getMessage(), null); - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.blacklisted"), event.getChannel(), null); - return; - } + ModerationUtil.shouldModerate(event.getGuild().getIdLong()).thenAccept(x -> { + AtomicBoolean moderated = new AtomicBoolean(false); + if (x) { + ModerationUtil.checkMessage(event.getGuild().getIdLong(), event.getMessage().getContentRaw()).thenAccept(y -> { + if (y) { + Main.getInstance().getCommandManager().deleteMessage(event.getMessage(), null); + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.blacklisted"), event.getChannel(), null); + moderated.set(true); + } + }); } + if (moderated.get()) return; + if (!Main.getInstance().getCommandManager().perform(event.getMember(), event.getGuild(), event.getMessage().getContentRaw(), event.getMessage(), event.getGuildChannel(), null)) { if (!event.getMessage().getMentions().getUsers().isEmpty() && event.getMessage().getMentions().getUsers().contains(event.getJDA().getSelfUser())) { @@ -485,19 +498,23 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { if (BotConfig.isModuleActive("level")) { if (!ArrayUtil.timeout.contains(event.getMember())) { - ChatUserLevel userLevel = SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(event.getGuild().getIdLong(), event.getMember().getIdLong()); - - if (userLevel.addExperience(RandomUtils.random.nextInt(15, 26)) && SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "level_message").getBooleanValue()) { - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), - "message.levelUp", userLevel.getLevel(), LanguageService.getByGuild(event.getGuild(), "label.chat") - , event.getMember().getAsMention()), event.getChannel()); - } + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(event.getGuild().getIdLong(), event.getMember().getIdLong()).thenAccept(userLevel -> { + if (userLevel.addExperience(RandomUtils.random.nextInt(15, 26))) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "level_message").thenAccept(z -> { + if (z.getBooleanValue()) { + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), + "message.levelUp", userLevel.getLevel(), LanguageService.getByGuild(event.getGuild(), "label.chat") + , event.getMember().getAsMention()), event.getChannel()); + } + }); + } - SQLSession.getSqlConnector().getSqlWorker().addChatLevelData(event.getGuild().getIdLong(), userLevel); + SQLSession.getSqlConnector().getSqlWorker().addChatLevelData(event.getGuild().getIdLong(), userLevel); - ArrayUtil.timeout.add(event.getMember()); + ArrayUtil.timeout.add(event.getMember()); - ThreadUtil.createThread(y -> ArrayUtil.timeout.remove(event.getMember()), Duration.ofSeconds(30), false, false); + ThreadUtil.createThread(y -> ArrayUtil.timeout.remove(event.getMember()), Duration.ofSeconds(30), false, false); + }); } UserUtil.handleChatLevelReward(event.getGuild(), event.getMember()); @@ -560,30 +577,32 @@ public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) { } } } else { - ReactionRole reactionRole = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ReactionRole(), "FROM ReactionRole WHERE guildRoleId.guildId=:gid AND emoteId=:emoteId AND messageId=:messageId", Map.of("gid", event.getGuild().getIdLong(), "emoteId", emojiId, "messageId", message.getIdLong())); - - if (reactionRole != null) { - Role role = event.getGuild().getRoleById(reactionRole.getId()); - - if (role != null) { - event.getGuild().addRoleToMember(event.getMember(), role).queue(); - } + SQLSession.getSqlConnector().getSqlWorker() + .getEntity(new ReactionRole(), "FROM ReactionRole WHERE guildRoleId.guildId=:gid AND emoteId=:emoteId AND messageId=:messageId", + Map.of("gid", event.getGuild().getIdLong(), "emoteId", emojiId, "messageId", message.getIdLong())).thenAccept(reactionRole -> { + if (reactionRole != null) { + Role role = event.getGuild().getRoleById(reactionRole.getId()); + + if (role != null) { + event.getGuild().addRoleToMember(event.getMember(), role).queue(); + } - boolean changes = false; + boolean changes = false; - if (reactionRole.getChannelId() == 0) { - reactionRole.setChannelId(event.getChannel().getIdLong()); - changes = true; - } + if (reactionRole.getChannelId() == 0) { + reactionRole.setChannelId(event.getChannel().getIdLong()); + changes = true; + } - if (reactionRole.getFormattedEmote().isBlank()) { - reactionRole.setFormattedEmote(emojiUnion.getFormatted()); - changes = true; - } + if (reactionRole.getFormattedEmote().isBlank()) { + reactionRole.setFormattedEmote(emojiUnion.getFormatted()); + changes = true; + } - if (changes) - SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRole); - } + if (changes) + SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRole); + } + }); } }); } @@ -605,17 +624,17 @@ public void onMessageReactionRemove(@NotNull MessageReactionRemoveEvent event) { emojiId = reactionCode.replace(":", "").hashCode(); } - ReactionRole reactionRole = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ReactionRole(), + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ReactionRole(), "FROM ReactionRole WHERE guildRoleId.guildId=:gid AND emoteId=:emoteId AND messageId=:messageId", - Map.of("gid", event.getGuild().getIdLong(), "emoteId", emojiId, "messageId", event.getMessageIdLong())); - - if (reactionRole != null) { - Role role = event.getGuild().getRoleById(reactionRole.getId()); + Map.of("gid", event.getGuild().getIdLong(), "emoteId", emojiId, "messageId", event.getMessageIdLong())).thenAccept(reactionRole -> { + if (reactionRole != null) { + Role role = event.getGuild().getRoleById(reactionRole.getId()); - if (role != null) { - event.getGuild().removeRoleFromMember(event.getMember(), role).queue(); + if (role != null) { + event.getGuild().removeRoleFromMember(event.getMember(), role).queue(); + } } - } + }); } /** diff --git a/src/main/java/de/presti/ree6/utils/others/ModerationUtil.java b/src/main/java/de/presti/ree6/utils/others/ModerationUtil.java index 05529c25d..9c0c003ce 100644 --- a/src/main/java/de/presti/ree6/utils/others/ModerationUtil.java +++ b/src/main/java/de/presti/ree6/utils/others/ModerationUtil.java @@ -6,6 +6,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Future; /** * Class to handle the moderation user behaviour. @@ -27,7 +29,7 @@ private ModerationUtil() { * @param guildId the ID of the Guild. * @return an {@link ArrayList} with every Blacklisted word from the Guild. */ - public static List getBlacklist(long guildId) { + public static CompletableFuture> getBlacklist(long guildId) { return SQLSession.getSqlConnector().getSqlWorker().getChatProtectorWords(guildId); } @@ -38,8 +40,9 @@ public static List getBlacklist(long guildId) { * @param message the Message-Content. * @return true, if there is a blacklisted for contained. */ - public static boolean checkMessage(long guildId, String message) { - return Arrays.stream(message.toLowerCase().split(" ")).anyMatch(word -> checkBlacklist(guildId, word)); + public static CompletableFuture checkMessage(long guildId, String message) { + return getBlacklist(guildId).thenApply(blacklist -> + Arrays.stream(message.toLowerCase().split(" ")).anyMatch(blacklist::contains)); } /** @@ -49,7 +52,7 @@ public static boolean checkMessage(long guildId, String message) { * @param word the word to check. * @return true, if there is a blacklisted for contained. */ - public static boolean checkBlacklist(long guildId, String word) { + public static CompletableFuture checkBlacklist(long guildId, String word) { return SQLSession.getSqlConnector().getSqlWorker().isChatProtectorSetup(guildId, word); } @@ -59,8 +62,8 @@ public static boolean checkBlacklist(long guildId, String word) { * @param guildId the ID of the Guild. * @return true, if the Server should be moderated. */ - public static boolean shouldModerate(long guildId) { - return BotConfig.isModuleActive("moderation") && SQLSession.getSqlConnector().getSqlWorker().isChatProtectorSetup(guildId); + public static CompletableFuture shouldModerate(long guildId) { + return SQLSession.getSqlConnector().getSqlWorker().isChatProtectorSetup(guildId).thenApply(x -> x && BotConfig.isModuleActive("moderation")); } /** @@ -70,9 +73,10 @@ public static boolean shouldModerate(long guildId) { * @param word the Word you want to blacklist. */ public static void blacklist(long guildId, String word) { - if (!checkBlacklist(guildId, word)) { + checkBlacklist(guildId, word).thenAccept(x -> { + if (x) return; SQLSession.getSqlConnector().getSqlWorker().addChatProtectorWord(guildId, word); - } + }); } /** From 0bce11cca6eff49828b67048293bf7bdfaed720c Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 24 Jan 2024 12:51:45 +0100 Subject: [PATCH 03/94] Finished WebhookUtil --- .../de/presti/ree6/bot/util/WebhookUtil.java | 141 +++++++++--------- 1 file changed, 72 insertions(+), 69 deletions(-) diff --git a/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java b/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java index 3015906ad..ae0306f6c 100644 --- a/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java +++ b/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java @@ -13,6 +13,7 @@ import net.dv8tion.jda.api.entities.Guild; import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; /** * Class to handle Webhook sends. @@ -89,15 +90,29 @@ public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, if (webhookToken.contains("Not setup!") || webhookId == 0) return; // Check if the given data is in the Database. - if (isLog && !SQLSession.getSqlConnector().getSqlWorker().existsLogData(webhookId, webhookToken)) return; + if (isLog) { + SQLSession.getSqlConnector().getSqlWorker().existsLogData(webhookId, webhookToken).thenAccept(x -> { + if (!x) { + // If not, inform about invalid send. + log.error("[Webhook] Invalid Webhook: {} - {}", webhookId, webhookToken); + return; + } else { + // Check if the LoggerMessage is canceled. + if ((loggerMessage == null || loggerMessage.isCanceled())) { + // If so, inform about invalid send. + log.error("[Webhook] Got a Invalid or canceled LoggerMessage!"); + return; + } - // Check if the LoggerMessage is canceled. - if (isLog && (loggerMessage == null || loggerMessage.isCanceled())) { - // If so, inform about invalid send. - log.error("[Webhook] Got a Invalid or canceled LoggerMessage!"); - return; + sendWebhookMessage(loggerMessage, message, webhookId, webhookToken, true); + } + }); + } else { + sendWebhookMessage(loggerMessage, message, webhookId, webhookToken, false); } + } + private static void sendWebhookMessage(LogMessage loggerMessage, WebhookMessage message, long webhookId, String webhookToken, boolean isLog) { // Try sending a Webhook to the given data. try (WebhookClient wcl = WebhookClient.withId(webhookId, webhookToken)) { // Send the message and handle exceptions. @@ -110,71 +125,59 @@ public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, SQLSession.getSqlConnector().getSqlWorker().deleteLogWebhook(webhookId, webhookToken); log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { - boolean deleted = false; - - WebhookWelcome welcome = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookWelcome(), "FROM WebhookWelcome WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)); - if (welcome != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(welcome); - log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - deleted = true; - } - - WebhookYouTube webhookYouTube = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookYouTube(), "FROM WebhookYouTube WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)); - - if (webhookYouTube != null && !deleted) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookYouTube); - log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - deleted = true; - } - - if (!deleted) { - WebhookTwitter webhookTwitter = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTwitter(), "FROM WebhookTwitter WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)); - - if (webhookTwitter != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTwitter); + // TODO:: this has become worst so please for the love of god find a better solution brain. + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookWelcome(), "FROM WebhookWelcome WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).thenAccept(welcome -> { + if (welcome != null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(welcome); log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - deleted = true; + } else { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookYouTube(), "FROM WebhookYouTube WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).thenAccept(webhookYouTube -> { + if (webhookYouTube != null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookYouTube); + log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); + } else { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTwitter(), "FROM WebhookTwitter WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).thenAccept(webhookTwitter -> { + if (webhookTwitter != null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTwitter); + log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); + } else { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTwitch(), "FROM WebhookTwitch WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).thenAccept(webhookTwitch -> { + + if (webhookTwitch != null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTwitch); + log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); + } else { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookReddit(), "FROM WebhookReddit WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).thenAccept(webhookReddit -> { + + if (webhookReddit != null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookReddit); + log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); + } else { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookInstagram(), "FROM WebhookInstagram WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).thenAccept(webhookInstagram -> { + + if (webhookInstagram != null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookInstagram); + log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); + } else { + log.error("[Webhook] Invalid Webhook: {} - {}, has not been deleted since it is not a Log-Webhook.", webhookId, webhookToken); + } + }); + } + }); + } + }); + } + }); + } + }); } - } - - if (!deleted) { - WebhookTwitch webhookTwitch = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTwitch(), "FROM WebhookTwitch WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)); - - if (webhookTwitch != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTwitch); - log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - deleted = true; - } - } - - if (!deleted) { - WebhookReddit webhookReddit = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookReddit(), "FROM WebhookReddit WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)); - - if (webhookReddit != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookReddit); - log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - deleted = true; - } - } - - if (!deleted) { - WebhookInstagram webhookInstagram = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookInstagram(), "FROM WebhookInstagram WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)); - - if (webhookInstagram != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookInstagram); - log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - deleted = true; - } - } - - if (!deleted) - log.error("[Webhook] Invalid Webhook: {} - {}, has not been deleted since it is not a Log-Webhook.", webhookId, webhookToken); + }); } } else if (throwable.getMessage().contains("failure 400")) { // If 404 inform that the Message had an invalid Body. From 0c2355f859f58d36be0f08087d816c646496c60f Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 12 Apr 2024 12:44:39 +0200 Subject: [PATCH 04/94] Fixing more internal code. --- pom.xml | 2 +- .../presti/ree6/commands/CommandManager.java | 170 +++++++++--------- .../commands/impl/community/Notifier.java | 136 +++++++------- .../commands/impl/community/Schedule.java | 82 ++++----- .../ree6/commands/impl/mod/Suggestion.java | 40 +++-- .../presti/ree6/commands/impl/mod/Warn.java | 133 +++++++------- .../de/presti/ree6/events/CustomEvents.java | 2 +- .../de/presti/ree6/events/OtherEvents.java | 81 +++++---- 8 files changed, 329 insertions(+), 317 deletions(-) diff --git a/pom.xml b/pom.xml index ae905019b..388a28aff 100644 --- a/pom.xml +++ b/pom.xml @@ -156,7 +156,7 @@ de.ree6 Ree6-SQL - 7902589483 + 17d32f2afd diff --git a/src/main/java/de/presti/ree6/commands/CommandManager.java b/src/main/java/de/presti/ree6/commands/CommandManager.java index 3894e4b59..303062ffb 100644 --- a/src/main/java/de/presti/ree6/commands/CommandManager.java +++ b/src/main/java/de/presti/ree6/commands/CommandManager.java @@ -43,6 +43,7 @@ import java.lang.reflect.InvocationTargetException; import java.time.Duration; import java.util.*; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; /** @@ -357,52 +358,53 @@ public void removeCommand(ICommand command) { * @param slashCommandInteractionEvent the Slash Command Event if it was a Slash Command. * @return true, if a command has been performed. */ - public boolean perform(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion messageChannel, SlashCommandInteractionEvent slashCommandInteractionEvent) { + public CompletableFuture perform(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion messageChannel, SlashCommandInteractionEvent slashCommandInteractionEvent) { + boolean isSlashCommand = slashCommandInteractionEvent != null; + // Check if the User is under Cooldown. if (isTimeout(member.getUser())) { // Check if it is a Slash Command or not. - if (slashCommandInteractionEvent != null) { + if (isSlashCommand) { sendMessage(LanguageService.getByGuild(guild, "command.perform.cooldown"), 5, messageChannel, slashCommandInteractionEvent.getHook().setEphemeral(true)); deleteMessage(message, slashCommandInteractionEvent.getHook().setEphemeral(true)); - } else if (messageContent.toLowerCase().startsWith(SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").getStringValue().toLowerCase())) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.cooldown"), 5, messageChannel, null); - deleteMessage(message, null); + } else { + SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").thenAccept(setting -> { + if (setting != null && messageContent.toLowerCase().startsWith(setting.getStringValue().toLowerCase())) { + sendMessage(LanguageService.getByGuild(guild, "command.perform.cooldown"), 5, messageChannel, null); + deleteMessage(message, null); + } + }); } // Return false. - return false; + return CompletableFuture.completedFuture(false); } // Check if it is a Slash Command. - if (slashCommandInteractionEvent != null) { - if (!BotConfig.isModuleActive("slashcommands")) return false; - if (!performSlashCommand(messageChannel, slashCommandInteractionEvent)) { - return false; - } + if (isSlashCommand) { + if (!BotConfig.isModuleActive("slashcommands")) return CompletableFuture.completedFuture(false); + return performSlashCommand(messageChannel, slashCommandInteractionEvent); } else { - if (!BotConfig.isModuleActive("messagecommands")) return false; - if (!performMessageCommand(member, guild, messageContent, message, messageChannel)) { - return false; - } + if (!BotConfig.isModuleActive("messagecommands")) return CompletableFuture.completedFuture(false); + return performMessageCommand(member, guild, messageContent, message, messageChannel); } + } + public void timeoutUser(User user) { // Check if this is a Developer build, if not then cooldown the User. - if (!BotConfig.isDebug()) { - ThreadUtil.createThread(x -> ArrayUtil.commandCooldown.remove(member.getUser().getId()), null, Duration.ofSeconds(5), false, false); - } + if (!BotConfig.isDebug()) return; + + ThreadUtil.createThread(x -> ArrayUtil.commandCooldown.remove(user.getId()), null, Duration.ofSeconds(5), false, false); // Add them to the Cooldown. - if (!ArrayUtil.commandCooldown.contains(member.getUser().getId()) && !BotConfig.isDebug()) { - ArrayUtil.commandCooldown.add(member.getUser().getId()); + if (!ArrayUtil.commandCooldown.contains(user.getId())) { + ArrayUtil.commandCooldown.add(user.getId()); } - - // Return that a command has been performed. - return true; } /** - * Perform a Message based Command. + * Perform a Message-based Command. * * @param member the Member that performed the command. * @param guild the Guild the Member is from. @@ -411,79 +413,79 @@ public boolean perform(Member member, Guild guild, String messageContent, Messag * @param textChannel the TextChannel where the command has been performed. * @return true, if a command has been performed. */ - private boolean performMessageCommand(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion textChannel) { + private CompletableFuture performMessageCommand(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion textChannel) { // Check if the Message is null. if (message == null) { sendMessage(LanguageService.getByGuild(guild, "command.perform.error"), 5, textChannel, null); - return false; + return CompletableFuture.completedFuture(false); } - String currentPrefix = SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").getStringValue().toLowerCase(); + return SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").thenApply(setting -> { - // Check if the message starts with the prefix. - if (!messageContent.toLowerCase().startsWith(currentPrefix)) - return false; + String currentPrefix = setting.getStringValue().toLowerCase(); - // Parse the Message and remove the prefix from it. - messageContent = messageContent.substring(currentPrefix.length()); + // Check if the message starts with the prefix. + if (!messageContent.toLowerCase().startsWith(currentPrefix)) + return false; - // Split all Arguments. - String[] arguments = messageContent.split("\\s+"); + // Split all Arguments. + String[] arguments = messageContent.substring(currentPrefix.length()).split("\\s+"); - if (arguments.length == 0 || arguments[0].isBlank()) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.missingCommand"), 5, textChannel, null); - return false; - } + if (arguments.length == 0 || arguments[0].isBlank()) { + sendMessage(LanguageService.getByGuild(guild, "command.perform.missingCommand"), 5, textChannel, null); + return false; + } - // Get the Command by the name. - ICommand command = getCommandByName(arguments[0]); + // Get the Command by the name. + ICommand command = getCommandByName(arguments[0]); - // Check if there is even a Command with that name. - if (command == null && BotConfig.isModuleActive("customcommands")) { - CustomCommand customCommand = SQLSession.getSqlConnector().getSqlWorker().getEntity(new CustomCommand(), "FROM CustomCommand WHERE guildId=:gid AND name=:command", Map.of("gid", guild.getIdLong(), "command", arguments[0].toLowerCase())); - if (customCommand != null) { - GuildMessageChannelUnion messageChannelUnion = textChannel; + // Check if there is even a Command with that name. + if (command == null && BotConfig.isModuleActive("customcommands")) { + CustomCommand customCommand = SQLSession.getSqlConnector().getSqlWorker().getEntity(new CustomCommand(), "FROM CustomCommand WHERE guildId=:gid AND name=:command", Map.of("gid", guild.getIdLong(), "command", arguments[0].toLowerCase())).join(); + if (customCommand != null) { + GuildMessageChannelUnion messageChannelUnion = textChannel; - if (customCommand.getChannelId() != -1) { - messageChannelUnion = guild.getChannelById(GuildMessageChannelUnion.class, customCommand.getChannelId()); - } + if (customCommand.getChannelId() != -1) { + messageChannelUnion = guild.getChannelById(GuildMessageChannelUnion.class, customCommand.getChannelId()); + } - if (customCommand.getMessageResponse() != null) { - sendMessage(customCommand.getMessageResponse(), 5, messageChannelUnion, null); - } + if (customCommand.getMessageResponse() != null) { + sendMessage(customCommand.getMessageResponse(), 5, messageChannelUnion, null); + } + + if (customCommand.getEmbedResponse() != null) { + EmbedBuilder embedBuilder = EmbedBuilder.fromData(DataObject.fromJson(customCommand.getEmbedResponse().toString())); + sendMessage(embedBuilder, 5, messageChannelUnion, null); + } - if (customCommand.getEmbedResponse() != null) { - EmbedBuilder embedBuilder = EmbedBuilder.fromData(DataObject.fromJson(customCommand.getEmbedResponse().toString())); - sendMessage(embedBuilder, 5, messageChannelUnion, null); + return true; } - return true; + sendMessage(LanguageService.getByGuild(guild, "command.perform.notFound"), 5, textChannel, null); + return false; + } else if (command == null) { + sendMessage(LanguageService.getByGuild(guild, "command.perform.notFound"), 5, textChannel, null); + return false; } - sendMessage(LanguageService.getByGuild(guild, "command.perform.notFound"), 5, textChannel, null); - return false; - } else if (command == null) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.notFound"), 5, textChannel, null); - return false; - } + if (command.getClass().getAnnotation(Command.class).category() != Category.HIDDEN) { + Setting blacklistSetting = SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()).join(); - if (command.getClass().getAnnotation(Command.class).category() != Category.HIDDEN) { - Setting blacklistSetting = SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()); - - // Check if the Command is blacklisted. - if (blacklistSetting != null && !blacklistSetting.getBooleanValue()) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.blocked"), 5, textChannel, null); - return false; + // Check if the Command is blacklisted. + if (blacklistSetting != null && !blacklistSetting.getBooleanValue()) { + sendMessage(LanguageService.getByGuild(guild, "command.perform.blocked"), 5, textChannel, null); + return false; + } } - } - // Parse the arguments. - String[] argumentsParsed = Arrays.copyOfRange(arguments, 1, arguments.length); + // Parse the arguments. + String[] argumentsParsed = Arrays.copyOfRange(arguments, 1, arguments.length); - // Perform the Command. - command.onASyncPerform(new CommandEvent(command.getClass().getAnnotation(Command.class).name(), member, guild, message, textChannel, argumentsParsed, null)); + // Perform the Command. + command.onASyncPerform(new CommandEvent(command.getClass().getAnnotation(Command.class).name(), member, guild, message, textChannel, argumentsParsed, null)); - return true; + return true; + }); } /** @@ -493,30 +495,26 @@ private boolean performMessageCommand(Member member, Guild guild, String message * @param slashCommandInteractionEvent the Slash-Command Event. * @return true, if a command has been performed. */ - private boolean performSlashCommand(GuildMessageChannelUnion messageChannel, SlashCommandInteractionEvent slashCommandInteractionEvent) { + private CompletableFuture performSlashCommand(GuildMessageChannelUnion messageChannel, SlashCommandInteractionEvent slashCommandInteractionEvent) { //Get the Command by the Slash Command Name. ICommand command = getCommandBySlashName(slashCommandInteractionEvent.getName()); // Check if there is a command with that Name. if (command == null || slashCommandInteractionEvent.getGuild() == null || slashCommandInteractionEvent.getMember() == null) { sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.notFound"), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); - return false; + return CompletableFuture.completedFuture(false); } - if (command.getClass().getAnnotation(Command.class).category() != Category.HIDDEN) { - Setting blacklistSetting = SQLSession.getSqlConnector().getSqlWorker().getSetting(slashCommandInteractionEvent.getGuild().getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()); - - // Check if the Command is blacklisted. - if (blacklistSetting != null && !blacklistSetting.getBooleanValue()) { + return SQLSession.getSqlConnector().getSqlWorker().getSetting(slashCommandInteractionEvent.getGuild().getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()).thenApply(setting -> { + if (command.getClass().getAnnotation(Command.class).category() != Category.HIDDEN && setting != null && !setting.getBooleanValue()) { sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.blocked"), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); return false; } - } - - // Perform the Command. - command.onASyncPerform(new CommandEvent(command.getClass().getAnnotation(Command.class).name(), slashCommandInteractionEvent.getMember(), slashCommandInteractionEvent.getGuild(), null, messageChannel, null, slashCommandInteractionEvent)); - return true; + // Perform the Command. + command.onASyncPerform(new CommandEvent(command.getClass().getAnnotation(Command.class).name(), slashCommandInteractionEvent.getMember(), slashCommandInteractionEvent.getGuild(), null, messageChannel, null, slashCommandInteractionEvent)); + return true; + }); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java b/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java index cdbf4a16a..e01adb97a 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java @@ -69,90 +69,90 @@ public void onPerform(CommandEvent commandEvent) { StringBuilder end = new StringBuilder("\n"); switch (command) { - case "instagram" -> { - - for (String users : SQLSession.getSqlConnector().getSqlWorker().getAllInstagramUsers(commandEvent.getGuild().getIdLong())) { - end.append(users).append("\n"); - } - - commandEvent.reply(commandEvent.getResource("message.instagramNotifier.list", end.toString()), 10); - } - - case "youtube" -> { - - for (String users : SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels(commandEvent.getGuild().getIdLong())) { - - ChannelResult channelResult = null; - - try { - channelResult = YouTubeAPIHandler.getInstance().isValidChannelId(users) ? - YouTubeAPIHandler.getInstance().getYouTubeChannelById(users) : - YouTubeAPIHandler.getInstance().getYouTubeChannelBySearch(users); - } catch (Exception ignore) { - } - - end.append(users); + case "instagram" -> + SQLSession.getSqlConnector().getSqlWorker().getAllInstagramUsers(commandEvent.getGuild().getIdLong()).thenAccept(users -> { + for (String user : users) { + end.append(user).append("\n"); + } - if (channelResult != null) { - end.append(" ").append("-").append(" ").append(channelResult.getTitle()); - } + commandEvent.reply(commandEvent.getResource("message.instagramNotifier.list", end.toString()), 10); + }); - end.append("\n"); - } + case "youtube" -> + SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels(commandEvent.getGuild().getIdLong()).thenAccept(userList -> { + for (String users : userList) { - commandEvent.reply(commandEvent.getResource("message.youtubeNotifier.list", end.toString()), 10); - } + ChannelResult channelResult = null; - case "twitch" -> { + try { + channelResult = YouTubeAPIHandler.getInstance().isValidChannelId(users) ? + YouTubeAPIHandler.getInstance().getYouTubeChannelById(users) : + YouTubeAPIHandler.getInstance().getYouTubeChannelBySearch(users); + } catch (Exception ignore) { + } - for (String users : SQLSession.getSqlConnector().getSqlWorker().getAllTwitchNames(commandEvent.getGuild().getIdLong())) { - end.append(users).append("\n"); - } + end.append(users); - commandEvent.reply(commandEvent.getResource("message.twitchNotifier.list", end.toString()), 10); - } + if (channelResult != null) { + end.append(" ").append("-").append(" ").append(channelResult.getTitle()); + } - case "twitter" -> { + end.append("\n"); + } - for (String users : SQLSession.getSqlConnector().getSqlWorker().getAllTwitterNames(commandEvent.getGuild().getIdLong())) { - end.append(users).append("\n"); - } + commandEvent.reply(commandEvent.getResource("message.youtubeNotifier.list", end.toString()), 10); + }); - commandEvent.reply(commandEvent.getResource("message.twitterNotifier.list", end.toString()), 10); - } + case "twitch" -> + SQLSession.getSqlConnector().getSqlWorker().getAllTwitchNames(commandEvent.getGuild().getIdLong()).thenAccept(users -> { + for (String user : users) { + end.append(user).append("\n"); + } - case "tiktok" -> { + commandEvent.reply(commandEvent.getResource("message.twitchNotifier.list", end.toString()), 10); + }); - for (String users : SQLSession.getSqlConnector().getSqlWorker().getAllTikTokNames(commandEvent.getGuild().getIdLong())) { - end.append(users); - try { - TikTokUser tikTokUser = TikTokWrapper.getUser(Long.parseLong(users), false); - end.append(" ").append("-").append(" ").append(tikTokUser.getName()); - } catch (Exception ignore) { - } - end.append("\n"); - } + case "twitter" -> + SQLSession.getSqlConnector().getSqlWorker().getAllTwitterNames(commandEvent.getGuild().getIdLong()).thenAccept(users -> { + for (String user : users) { + end.append(user).append("\n"); + } - commandEvent.reply(commandEvent.getResource("message.tiktokNotifier.list", end.toString()), 10); - } + commandEvent.reply(commandEvent.getResource("message.twitterNotifier.list", end.toString()), 10); + }); - case "reddit" -> { + case "tiktok" -> + SQLSession.getSqlConnector().getSqlWorker().getAllTikTokNames(commandEvent.getGuild().getIdLong()).thenAccept(users -> { + for (String user : users) { + end.append(user); + try { + TikTokUser tikTokUser = TikTokWrapper.getUser(Long.parseLong(user), false); + end.append(" ").append("-").append(" ").append(tikTokUser.getName()); + } catch (Exception ignore) { + } + end.append("\n"); + } - for (String users : SQLSession.getSqlConnector().getSqlWorker().getAllSubreddits(commandEvent.getGuild().getIdLong())) { - end.append(users).append("\n"); - } + commandEvent.reply(commandEvent.getResource("message.tiktokNotifier.list", end.toString()), 10); + }); - commandEvent.reply(commandEvent.getResource("message.redditNotifier.list", end.toString()), 10); - } + case "reddit" -> + SQLSession.getSqlConnector().getSqlWorker().getAllSubreddits(commandEvent.getGuild().getIdLong()).thenAccept(users -> { + for (String user : users) { + end.append(user).append("\n"); + } - case "rss" -> { + commandEvent.reply(commandEvent.getResource("message.redditNotifier.list", end.toString()), 10); + }); - for (String users : SQLSession.getSqlConnector().getSqlWorker().getAllRSSUrls(commandEvent.getGuild().getIdLong())) { - end.append(users).append("\n"); - } + case "rss" -> + SQLSession.getSqlConnector().getSqlWorker().getAllRSSUrls(commandEvent.getGuild().getIdLong()).thenAccept(users -> { + for (String user : users) { + end.append(user).append("\n"); + } - commandEvent.reply(commandEvent.getResource("message.rssNotifier.list", end.toString()), 10); - } + commandEvent.reply(commandEvent.getResource("message.rssNotifier.list", end.toString()), 10); + }); default -> commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); } @@ -161,7 +161,7 @@ public void onPerform(CommandEvent commandEvent) { switch (command) { case "instagram" -> { // Ignore this, because the Compiler would otherwise scream: - // "OMG YOU CAN NOT INITIALIZE THE VARIABLE BELOW BECAUSE YOU CANT REACH IT!!!!" + // "OMG YOU CANNOT INITIALIZE THE VARIABLE BELOW BECAUSE YOU CANT REACH IT!!!!" if (true) { commandEvent.reply("This feature is currently broken. Please wait for a fix.", 10); return; @@ -274,7 +274,7 @@ public void onPerform(CommandEvent commandEvent) { case "twitter" -> { // Ignore this, because the Compiler would otherwise scream: - // "OMG YOU CAN NOT INITIALIZE THE VARIABLE BELOW BECAUSE YOU CANT REACH IT!!!!" + // "OMG YOU CANNOT INITIALIZE THE VARIABLE BELOW BECAUSE YOU CANT REACH IT!!!!" if (true) { commandEvent.reply("This feature is currently broken. Please wait for a fix.", 10); return; diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java b/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java index 7f77745b9..64353babb 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java @@ -55,35 +55,34 @@ public void onPerform(CommandEvent commandEvent) { switch (subCommand) { - case "list" -> { - StringBuilder stringBuilder = new StringBuilder(); - - for (ScheduledMessage scheduledMessage : SQLSession.getSqlConnector().getSqlWorker() - .getEntityList(new ScheduledMessage(), "FROM ScheduledMessage WHERE guildAndId.guildId = :gid ", - Map.of("gid", commandEvent.getGuild().getIdLong()))) { - stringBuilder.append(scheduledMessage.getId()).append(" ").append("-").append(" ") - .append(scheduledMessage.getMessage()).append(" ") - .append("->").append(" ") - .append(Instant.ofEpochMilli(scheduledMessage.getDelayAmount()) - .atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH/mm"))); - } - - commandEvent.reply(commandEvent.getResource("message.schedule.list", stringBuilder.toString())); - } + case "list" -> SQLSession.getSqlConnector().getSqlWorker() + .getEntityList(new ScheduledMessage(), "FROM ScheduledMessage WHERE guildAndId.guildId = :gid ", + Map.of("gid", commandEvent.getGuild().getIdLong())).thenAccept(scheduledMessages -> { + StringBuilder stringBuilder = new StringBuilder(); + + for (ScheduledMessage scheduledMessage : scheduledMessages) { + stringBuilder.append(scheduledMessage.getId()).append(" ").append("-").append(" ") + .append(scheduledMessage.getMessage()).append(" ") + .append("->").append(" ") + .append(Instant.ofEpochMilli(scheduledMessage.getDelayAmount()) + .atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH/mm"))); + } + commandEvent.reply(commandEvent.getResource("message.schedule.list", stringBuilder.toString())); + }); case "delete" -> { OptionMapping id = commandEvent.getOption("id"); - ScheduledMessage scheduledMessage = SQLSession.getSqlConnector().getSqlWorker() + SQLSession.getSqlConnector().getSqlWorker() .getEntity(new ScheduledMessage(), "FROM ScheduledMessage WHERE guildAndId.guildId = :gid AND guildAndId.id = :id", - Map.of("gid", commandEvent.getGuild().getIdLong(), "id", id.getAsLong())); - - if (scheduledMessage != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage); - commandEvent.reply(commandEvent.getResource("message.schedule.delete.success")); - } else { - commandEvent.reply(commandEvent.getResource("message.schedule.delete.failed")); - } + Map.of("gid", commandEvent.getGuild().getIdLong(), "id", id.getAsLong())).thenAccept(scheduledMessage -> { + if (scheduledMessage != null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage); + commandEvent.reply(commandEvent.getResource("message.schedule.delete.success")); + } else { + commandEvent.reply(commandEvent.getResource("message.schedule.delete.failed")); + } + }); } case "create" -> { @@ -109,22 +108,23 @@ public void onPerform(CommandEvent commandEvent) { ScheduledMessage scheduledMessage = new ScheduledMessage(); - WebhookScheduledMessage webhookScheduledMessage = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookScheduledMessage(), + long finalFullTime = fullTime; + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookScheduledMessage(), "FROM WebhookScheduledMessage WHERE guildAndId.guildId = :gid AND channelId = :channel", - Map.of("gid", commandEvent.getGuild().getId(),"channel", guildChannel.getIdLong())); - - if (webhookScheduledMessage == null) { - Webhook webhook = guildChannel.asStandardGuildMessageChannel().createWebhook(BotConfig.getBotName() + "-Schedule").complete(); - - webhookScheduledMessage = SQLSession.getSqlConnector().getSqlWorker() - .updateEntity(new WebhookScheduledMessage(commandEvent.getGuild().getIdLong(), guildChannel.getIdLong(), webhook.getIdLong(), webhook.getToken())); - } - - scheduledMessage.setScheduledMessageWebhook(webhookScheduledMessage); - scheduledMessage.setDelayAmount(fullTime); - scheduledMessage.setRepeated(repeat.getAsBoolean()); - commandEvent.reply(commandEvent.getResource("message.schedule.added")); + Map.of("gid", commandEvent.getGuild().getId(), "channel", guildChannel.getIdLong())).thenAccept(webhookScheduledMessage -> { + if (webhookScheduledMessage == null) { + Webhook webhook = guildChannel.asStandardGuildMessageChannel().createWebhook(BotConfig.getBotName() + "-Schedule").complete(); + + webhookScheduledMessage = SQLSession.getSqlConnector().getSqlWorker() + .updateEntity(new WebhookScheduledMessage(commandEvent.getGuild().getIdLong(), guildChannel.getIdLong(), webhook.getIdLong(), webhook.getToken())).join(); + } + + scheduledMessage.setScheduledMessageWebhook(webhookScheduledMessage); + scheduledMessage.setDelayAmount(finalFullTime); + scheduledMessage.setRepeated(repeat.getAsBoolean()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage).join(); + commandEvent.reply(commandEvent.getResource("message.schedule.added")); + }); } default -> commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); @@ -138,8 +138,8 @@ public void onPerform(CommandEvent commandEvent) { public CommandData getCommandData() { return new CommandDataImpl("schedule", "command.description.schedule") .addSubcommands(new SubcommandData("create", "Create a new scheduled Message.") - .addOptions(new OptionData(OptionType.CHANNEL, "channel", "The channel it should be sent to.", true).setChannelTypes(ChannelType.NEWS, ChannelType.TEXT)) - .addOption(OptionType.BOOLEAN, "repeat", "If the schedule should be repeated.", true) + .addOptions(new OptionData(OptionType.CHANNEL, "channel", "The channel it should be sent to.", true).setChannelTypes(ChannelType.NEWS, ChannelType.TEXT)) + .addOption(OptionType.BOOLEAN, "repeat", "If the schedule should be repeated.", true) .addOption(OptionType.INTEGER, "month", "The months of the delay.", false) .addOption(OptionType.INTEGER, "day", "The days of the delay.", false) .addOption(OptionType.INTEGER, "hour", "The hours of the delay.", false) diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java b/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java index efa5f26f4..62f8822bc 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java @@ -73,30 +73,32 @@ public void onPerform(CommandEvent commandEvent) { * @param messageChannel the Channel for the Message. */ public void createSuggestions(CommandEvent commandEvent, MessageChannel channel, MessageChannel messageChannel) { - MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setTitle(commandEvent.getResource("label.suggestionMenu")); - embedBuilder.setColor(Color.ORANGE); - embedBuilder.setDescription(SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_suggestion_menu").getStringValue()); - embedBuilder.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); - messageCreateBuilder.setEmbeds(embedBuilder.build()); - messageCreateBuilder.setActionRow(Button.primary("re_suggestion", commandEvent.getResource("message.suggestion.suggestionMenuPlaceholder"))); - Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), messageChannel); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Suggestions(), "FROM Suggestions WHERE guildChannelId.guildId = :id", Map.of("id", commandEvent.getGuild().getIdLong())) + .thenApply(suggestions -> { + if (suggestions != null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(suggestions); - Suggestions suggestions = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Suggestions(), "FROM Suggestions WHERE guildChannelId.guildId = :id", Map.of("id", commandEvent.getGuild().getIdLong())); + suggestions.getGuildChannelId().setChannelId(channel.getIdLong()); + return SQLSession.getSqlConnector().getSqlWorker().updateEntity(suggestions); + } else { + return SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Suggestions(commandEvent.getGuild().getIdLong(), channel.getIdLong())); + } + }).thenAccept(suggestions -> SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_suggestion_menu").thenAccept(setting -> { + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setTitle(commandEvent.getResource("label.suggestionMenu")); + embedBuilder.setColor(Color.ORANGE); + embedBuilder.setDescription(setting.getStringValue()); + embedBuilder.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); + messageCreateBuilder.setEmbeds(embedBuilder.build()); + messageCreateBuilder.setActionRow(Button.primary("re_suggestion", commandEvent.getResource("message.suggestion.suggestionMenuPlaceholder"))); - if (suggestions != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(suggestions); + Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), messageChannel); - suggestions.getGuildChannelId().setChannelId(channel.getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(suggestions); - } else { - suggestions = new Suggestions(commandEvent.getGuild().getIdLong(), channel.getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(suggestions); - } + commandEvent.reply(commandEvent.getResource("message.suggestion.success"), 5); + })); - commandEvent.reply(commandEvent.getResource("message.suggestion.success"), 5); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java b/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java index cb4223fc1..c7c93a07d 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java @@ -116,38 +116,41 @@ public void onPerform(CommandEvent commandEvent) { } case "list" -> { - StringBuilder stringBuilder = new StringBuilder(); - for (Punishments punishments : SQLSession.getSqlConnector().getSqlWorker().getEntityList(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid", Map.of("gid", commandEvent.getGuild().getIdLong()))) { - int action = punishments.getAction(); - stringBuilder.append(punishments.getId()).append(" - ").append(punishments.getWarnings()).append(" -> "); - - switch (action) { - case 1 -> - stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.timeout", Duration.ofMillis(punishments.getTimeoutTime()).toSeconds())); - case 2 -> - stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.roleAdd", punishments.getRoleId())); - case 3 -> - stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.roleRemove", punishments.getRoleId())); - case 4 -> - stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.kick", punishments.getReason())); - case 5 -> - stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.ban", punishments.getReason())); - } + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid", Map.of("gid", commandEvent.getGuild().getIdLong())).thenAccept(punishmentsList -> { + StringBuilder stringBuilder = new StringBuilder(); + for (Punishments punishments : punishmentsList) { + int action = punishments.getAction(); + stringBuilder.append(punishments.getId()).append(" - ").append(punishments.getWarnings()).append(" -> "); + + switch (action) { + case 1 -> + stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.timeout", Duration.ofMillis(punishments.getTimeoutTime()).toSeconds())); + case 2 -> + stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.roleAdd", punishments.getRoleId())); + case 3 -> + stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.roleRemove", punishments.getRoleId())); + case 4 -> + stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.kick", punishments.getReason())); + case 5 -> + stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.ban", punishments.getReason())); + } - stringBuilder.append("\n"); - } - commandEvent.reply(commandEvent.getResource("message.warn.punishment.list", stringBuilder.toString())); + stringBuilder.append("\n"); + } + commandEvent.reply(commandEvent.getResource("message.warn.punishment.list", stringBuilder.toString())); + }); } case "delete" -> { int id = idMapping.getAsInt(); - Punishments punishment = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid AND guildAndId.id = :id", Map.of("gid", commandEvent.getGuild().getIdLong(), "id", id)); - if (punishment != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment); - commandEvent.reply(commandEvent.getResource("message.warn.punishment.deleted", id)); - } else { - commandEvent.reply(commandEvent.getResource("message.warn.punishment.notFound", id)); - } + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid AND guildAndId.id = :id", Map.of("gid", commandEvent.getGuild().getIdLong(), "id", id)).thenAccept(punishment -> { + if (punishment != null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment); + commandEvent.reply(commandEvent.getResource("message.warn.punishment.deleted", id)); + } else { + commandEvent.reply(commandEvent.getResource("message.warn.punishment.notFound", id)); + } + }); } } } @@ -155,46 +158,50 @@ public void onPerform(CommandEvent commandEvent) { default -> { Member member = userMapping.getAsMember(); if (commandEvent.getGuild().getSelfMember().canInteract(member) && commandEvent.getMember().canInteract(member)) { - Warning warning = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Warning(), "FROM Warning WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", Map.of("gid", commandEvent.getGuild().getIdLong(), "uid", member.getIdLong())); - int warnings = warning != null ? warning.getWarnings() + 1 : 1; - if (warning == null) { - warning = new Warning(); - warning.setUserId(member.getIdLong()); - warning.setGuildId(commandEvent.getGuild().getIdLong()); - } - - warning.setWarnings(warnings); - - SQLSession.getSqlConnector().getSqlWorker().updateEntity(warning); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Warning(), "FROM Warning WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", Map.of("gid", commandEvent.getGuild().getIdLong(), "uid", member.getIdLong())).thenApplyAsync(warning -> { + int warnings = warning != null ? warning.getWarnings() + 1 : 1; + if (warning == null) { + warning = new Warning(); + warning.setUserId(member.getIdLong()); + warning.setGuildId(commandEvent.getGuild().getIdLong()); + } - commandEvent.reply(commandEvent.getResource("message.warn.success", userMapping.getAsMember().getAsMention(), warnings)); - Punishments punishment = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid AND warnings = :amount", Map.of("gid", commandEvent.getGuild().getIdLong(), "amount", warnings)); - if (punishment != null) { - switch (punishment.getAction()) { - case 1 -> member.timeoutFor(Duration.ofMillis(punishment.getTimeoutTime())).reason(commandEvent.getResource("message.warn.reachedWarnings", warnings)).queue(); - case 2 -> { - Role role = commandEvent.getGuild().getRoleById(punishment.getRoleId()); - if (role == null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment); - return; + warning.setWarnings(warnings); + + return SQLSession.getSqlConnector().getSqlWorker().updateEntity(warning).join(); + }).thenAccept(warning -> { + commandEvent.reply(commandEvent.getResource("message.warn.success", member.getAsMention(), warning.getWarnings())); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid AND warnings = :amount", Map.of("gid", commandEvent.getGuild().getIdLong(), "amount", warning.getWarnings())).thenAccept(punishment -> { + if (punishment != null) { + switch (punishment.getAction()) { + case 1 -> + member.timeoutFor(Duration.ofMillis(punishment.getTimeoutTime())).reason(commandEvent.getResource("message.warn.reachedWarnings", warning.getWarnings())).queue(); + case 2 -> { + Role role = commandEvent.getGuild().getRoleById(punishment.getRoleId()); + if (role == null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment); + return; + } + + commandEvent.getGuild().addRoleToMember(member, role).reason(commandEvent.getResource("message.warn.reachedWarnings", warning.getWarnings())).queue(); + } + case 3 -> { + Role role = commandEvent.getGuild().getRoleById(punishment.getRoleId()); + if (role == null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment); + return; + } + + commandEvent.getGuild().removeRoleFromMember(member, role).reason(commandEvent.getResource("message.warn.reachedWarnings", warning.getWarnings())).queue(); + } + case 4 -> member.kick().reason(punishment.getReason()).queue(); + case 5 -> member.ban(0, TimeUnit.DAYS).reason(punishment.getReason()).queue(); + default -> log.error("Unhandled action! {}", punishment.getAction()); } - - commandEvent.getGuild().addRoleToMember(member, role).reason(commandEvent.getResource("message.warn.reachedWarnings", warnings)).queue(); } - case 3 -> { - Role role = commandEvent.getGuild().getRoleById(punishment.getRoleId()); - if (role == null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment); - return; - } + }); + }); - commandEvent.getGuild().removeRoleFromMember(member, role).reason(commandEvent.getResource("message.warn.reachedWarnings", warnings)).queue(); - } - case 4 -> member.kick().reason(punishment.getReason()).queue(); - case 5 -> member.ban(0, TimeUnit.DAYS).reason(punishment.getReason()).queue(); - default -> log.error("Unhandled action! {}", punishment.getAction()); - } - } } else { if (commandEvent.getGuild().getSelfMember().canInteract(member)) { commandEvent.reply(commandEvent.getResource("message.warn.hierarchySelfError"), 5); diff --git a/src/main/java/de/presti/ree6/events/CustomEvents.java b/src/main/java/de/presti/ree6/events/CustomEvents.java index 876cd38e9..536d5295f 100644 --- a/src/main/java/de/presti/ree6/events/CustomEvents.java +++ b/src/main/java/de/presti/ree6/events/CustomEvents.java @@ -88,7 +88,7 @@ public void checkForNew(Class clazz, long guildId) { cache.put(typ, List.of(c)); } - cache.values().forEach(entries -> entries.removeIf(c -> !list.contains(c))); + cache.values().forEach(entries -> entries.removeIf(z -> !list.contains(z))); }); }); diff --git a/src/main/java/de/presti/ree6/events/OtherEvents.java b/src/main/java/de/presti/ree6/events/OtherEvents.java index bf48f81e5..063194615 100644 --- a/src/main/java/de/presti/ree6/events/OtherEvents.java +++ b/src/main/java/de/presti/ree6/events/OtherEvents.java @@ -18,10 +18,7 @@ import de.presti.ree6.utils.apis.ChatGPTAPI; import de.presti.ree6.utils.data.ArrayUtil; import de.presti.ree6.utils.data.ImageCreationUtility; -import de.presti.ree6.utils.others.ModerationUtil; -import de.presti.ree6.utils.others.RandomUtils; -import de.presti.ree6.utils.others.ThreadUtil; -import de.presti.ree6.utils.others.TimeUtil; +import de.presti.ree6.utils.others.*; import io.sentry.Sentry; import lombok.extern.slf4j.Slf4j; import net.dv8tion.jda.api.Permission; @@ -131,7 +128,7 @@ public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { } }); - GuildUtil.handleMemberJoin(event.getGuild(), event.getMember()); + GuildUtil.handleMemberJoin(event.getGuild(), event.getMember()); SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong()).thenAccept(x -> { if (x) { @@ -412,6 +409,7 @@ public void onGenericGuildVoice(@NotNull GenericGuildVoiceEvent event) { /** * Method used to do all the calculations for the Voice XP. + * * @param member the Member that should be checked. */ public void doVoiceXPStuff(Member member) { @@ -488,47 +486,50 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { if (moderated.get()) return; - if (!Main.getInstance().getCommandManager().perform(event.getMember(), event.getGuild(), event.getMessage().getContentRaw(), event.getMessage(), event.getGuildChannel(), null)) { + Main.getInstance().getCommandManager().perform(event.getMember(), event.getGuild(), event.getMessage().getContentRaw(), event.getMessage(), event.getGuildChannel(), null).thenAccept(value -> { + if (!value) { + if (!event.getMessage().getMentions().getUsers().isEmpty() && event.getMessage().getMentions().getUsers().contains(event.getJDA().getSelfUser())) { + if (event.getMessage().getMessageReference() != null) return; - if (!event.getMessage().getMentions().getUsers().isEmpty() && event.getMessage().getMentions().getUsers().contains(event.getJDA().getSelfUser())) { - if (event.getMessage().getMessageReference() != null) return; - - try { - String response = ChatGPTAPI.getResponse(event.getMember(), event.getMessage().getContentDisplay()); + try { + String response = ChatGPTAPI.getResponse(event.getMember(), event.getMessage().getContentDisplay()); - if (response != null && !response.isBlank()) - Main.getInstance().getCommandManager().sendMessage(response, event.getChannel()); - } catch (Exception e) { - Sentry.captureException(e); - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError"), event.getChannel()); + if (response != null && !response.isBlank()) + Main.getInstance().getCommandManager().sendMessage(response, event.getChannel()); + } catch (Exception e) { + Sentry.captureException(e); + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError"), event.getChannel()); + } } - } - if (BotConfig.isModuleActive("level")) { - if (!ArrayUtil.timeout.contains(event.getMember())) { - - SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(event.getGuild().getIdLong(), event.getMember().getIdLong()).thenAccept(userLevel -> { - if (userLevel.addExperience(RandomUtils.random.nextInt(15, 26))) { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "level_message").thenAccept(z -> { - if (z.getBooleanValue()) { - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), - "message.levelUp", userLevel.getLevel(), LanguageService.getByGuild(event.getGuild(), "label.chat") - , event.getMember().getAsMention()), event.getChannel()); - } - }); - } + if (BotConfig.isModuleActive("level")) { + if (!ArrayUtil.timeout.contains(event.getMember())) { + + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(event.getGuild().getIdLong(), event.getMember().getIdLong()).thenAccept(userLevel -> { + if (userLevel.addExperience(RandomUtils.random.nextInt(15, 26))) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "level_message").thenAccept(z -> { + if (z.getBooleanValue()) { + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), + "message.levelUp", userLevel.getLevel(), LanguageService.getByGuild(event.getGuild(), "label.chat") + , event.getMember().getAsMention()), event.getChannel()); + } + }); + } - SQLSession.getSqlConnector().getSqlWorker().addChatLevelData(event.getGuild().getIdLong(), userLevel); + SQLSession.getSqlConnector().getSqlWorker().addChatLevelData(event.getGuild().getIdLong(), userLevel); - ArrayUtil.timeout.add(event.getMember()); + ArrayUtil.timeout.add(event.getMember()); - ThreadUtil.createThread(y -> ArrayUtil.timeout.remove(event.getMember()), Duration.ofSeconds(30), false, false); - }); - } + ThreadUtil.createThread(y -> ArrayUtil.timeout.remove(event.getMember()), Duration.ofSeconds(30), false, false); + }); + } - GuildUtil.handleChatLevelReward(event.getGuild(), event.getMember()); + GuildUtil.handleChatLevelReward(event.getGuild(), event.getMember()); + } + } else { + Main.getInstance().getCommandManager().timeoutUser(event.getAuthor()); } - } + }); }); } } @@ -658,6 +659,10 @@ public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent even event.deferReply(true).queue(); - Main.getInstance().getCommandManager().perform(Objects.requireNonNull(event.getMember()), event.getGuild(), null, null, event.getGuildChannel(), event); + Main.getInstance().getCommandManager().perform(Objects.requireNonNull(event.getMember()), event.getGuild(), null, null, event.getGuildChannel(), event).thenAccept(x -> { + if (x != null) { + Main.getInstance().getCommandManager().timeoutUser(event.getUser()); + } + }); } } From 9fe284e5f1ccd1ab4b58cc0e9ea2273f9f878637 Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 12 Apr 2024 12:57:17 +0200 Subject: [PATCH 05/94] Fixing more internal code. --- .../impl/community/StreamActionCommand.java | 276 ++++++++---------- .../ree6/commands/impl/community/Ticket.java | 73 ++--- .../ree6/commands/impl/info/Infractions.java | 14 +- .../ree6/commands/impl/info/Optout.java | 16 +- 4 files changed, 171 insertions(+), 208 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java index 843f26688..18249fec1 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java @@ -62,167 +62,146 @@ public void onPerform(CommandEvent commandEvent) { String subCommand = commandEvent.getSubcommand(); switch (subCommandGroup) { - case "manage" -> { - StreamAction streamAction = SQLSession.getSqlConnector().getSqlWorker() - .getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.name = :name AND guildAndName.guildId = :gid", - Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())); - - if (streamAction != null) { - switch (subCommand) { - case "create" -> { - OptionMapping action = commandEvent.getOption("action"); + case "manage" -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.name = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).thenAccept(streamAction -> { + if (streamAction != null) { + switch (subCommand) { + case "create" -> { + OptionMapping action = commandEvent.getOption("action"); - String[] values = action.getAsString().split("\\s+"); + String[] values = action.getAsString().split("\\s+"); - JsonObject jsonObject = new JsonObject(); - String actionName = values[0]; - jsonObject.addProperty("action", actionName); + JsonObject jsonObject = new JsonObject(); + String actionName = values[0]; + jsonObject.addProperty("action", actionName); - values = Arrays.stream(values).skip(1).toArray(String[]::new); + values = Arrays.stream(values).skip(1).toArray(String[]::new); - jsonObject.addProperty("value", String.join(" ", values)); + jsonObject.addProperty("value", String.join(" ", values)); - if (streamAction.getActions() == null || !streamAction.getActions().isJsonArray()) { - streamAction.setActions(new JsonArray()); - } + if (streamAction.getActions() == null || !streamAction.getActions().isJsonArray()) { + streamAction.setActions(new JsonArray()); + } - streamAction.getActions().getAsJsonArray().add(jsonObject); + streamAction.getActions().getAsJsonArray().add(jsonObject); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction).join(); - commandEvent.reply(commandEvent.getResource("message.stream-action.addedLine", actionName)); - } + commandEvent.reply(commandEvent.getResource("message.stream-action.addedLine", actionName)); + } - case "delete" -> { - try { - OptionMapping line = commandEvent.getOption("line"); - int value = line.getAsInt(); - if (streamAction.getActions().getAsJsonArray().size() >= value && value > 0) { - streamAction.getActions().getAsJsonArray().remove(value - 1); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction); - commandEvent.reply(commandEvent.getResource("message.stream-action.deletedLine", "" + value)); - } else { - commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); + case "delete" -> { + try { + OptionMapping line = commandEvent.getOption("line"); + int value = line.getAsInt(); + if (streamAction.getActions().getAsJsonArray().size() >= value && value > 0) { + streamAction.getActions().getAsJsonArray().remove(value - 1); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction).join(); + commandEvent.reply(commandEvent.getResource("message.stream-action.deletedLine", "" + value)); + } else { + commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); + } + } catch (Exception exception) { + commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); + } } - } catch (Exception exception) { - commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); - } - } - case "list" -> { - StreamActionContainer streamActionContainer = new StreamActionContainer(streamAction); + case "list" -> { + StreamActionContainer streamActionContainer = new StreamActionContainer(streamAction); - StringBuilder stringBuilder = new StringBuilder(); - streamActionContainer.getActions() - .forEach(actionRun -> - stringBuilder.append(actionRun.getAction().getClass().getAnnotation(ActionInfo.class).name()) - .append(" -> ") - .append(String.join(" ", actionRun.getArguments())).append("\n")); + StringBuilder stringBuilder = new StringBuilder(); + streamActionContainer.getActions().forEach(actionRun -> stringBuilder.append(actionRun.getAction().getClass().getAnnotation(ActionInfo.class).name()).append(" -> ").append(String.join(" ", actionRun.getArguments())).append("\n")); - commandEvent.reply(commandEvent.getResource("message.stream-action.actionList", stringBuilder.toString())); - } - - case "listener" -> { - OptionMapping listener = commandEvent.getOption("listener"); - String[] values = listener.getAsString().split("\\s+"); - - if (values.length >= 1) { - if (values[0].equalsIgnoreCase("redemption")) { - streamAction.setListener(0); - } else if (values[0].equalsIgnoreCase("follow")) { - streamAction.setListener(1); - } else if (values[0].equalsIgnoreCase("subscribe")) { - streamAction.setListener(2); - } else { - commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); - return; + commandEvent.reply(commandEvent.getResource("message.stream-action.actionList", stringBuilder.toString())); } - if (values.length >= 2) - streamAction.setArgument(values[1]); - - SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction); - if (values.length >= 2) { - commandEvent.reply(commandEvent.getResource("message.stream-action.listenerArgument", values[0], values[1])); - } else { - commandEvent.reply(commandEvent.getResource("message.stream-action.listener", values[0])); + case "listener" -> { + OptionMapping listener = commandEvent.getOption("listener"); + String[] values = listener.getAsString().split("\\s+"); + + if (values.length >= 1) { + if (values[0].equalsIgnoreCase("redemption")) { + streamAction.setListener(0); + } else if (values[0].equalsIgnoreCase("follow")) { + streamAction.setListener(1); + } else if (values[0].equalsIgnoreCase("subscribe")) { + streamAction.setListener(2); + } else { + commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); + return; + } + + if (values.length >= 2) streamAction.setArgument(values[1]); + + SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction).join(); + if (values.length >= 2) { + commandEvent.reply(commandEvent.getResource("message.stream-action.listenerArgument", values[0], values[1])); + } else { + commandEvent.reply(commandEvent.getResource("message.stream-action.listener", values[0])); + } + } else { + commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); + } } - } else { - commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); + + default -> commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); } + } else { + commandEvent.reply(commandEvent.getResource("message.stream-action.notFound", name.getAsString())); } - - default -> commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); - } - } else { - commandEvent.reply(commandEvent.getResource("message.stream-action.notFound", name.getAsString())); - } - } + }); default -> { switch (subCommand) { - case "create" -> { - StreamAction streamAction = SQLSession.getSqlConnector().getSqlWorker() - .getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.actionName = :name AND guildAndName.guildId = :gid", - Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())); - - if (streamAction == null) { - TwitchIntegration twitchIntegration = SQLSession.getSqlConnector().getSqlWorker() - .getEntity(new TwitchIntegration(),"FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())); - if (twitchIntegration != null) { - streamAction = new StreamAction(); - streamAction.setIntegration(twitchIntegration); - streamAction.setGuildId(commandEvent.getGuild().getIdLong()); - streamAction.setName(name.getAsString()); - - SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction); - commandEvent.reply(commandEvent.getResource("message.stream-action.added", name.getAsString())); - } else { - commandEvent.reply(commandEvent.getResource("message.stream-action.noTwitch", BotConfig.getTwitchAuth())); - } - } else { - commandEvent.reply(commandEvent.getResource("message.stream-action.alreadyExisting", name.getAsString())); - } - } + case "create" -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.actionName = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).thenAccept(streamAction -> { + if (streamAction == null) { + TwitchIntegration twitchIntegration = SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())).join(); + if (twitchIntegration != null) { + streamAction = new StreamAction(); + streamAction.setIntegration(twitchIntegration); + streamAction.setGuildId(commandEvent.getGuild().getIdLong()); + streamAction.setName(name.getAsString()); + + SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction); + commandEvent.reply(commandEvent.getResource("message.stream-action.added", name.getAsString())); + } else { + commandEvent.reply(commandEvent.getResource("message.stream-action.noTwitch", BotConfig.getTwitchAuth())); + } + } else { + commandEvent.reply(commandEvent.getResource("message.stream-action.alreadyExisting", name.getAsString())); + } + }); - case "delete" -> { - StreamAction streamAction = SQLSession.getSqlConnector().getSqlWorker() - .getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.actionName = :name AND guildAndName.guildId = :gid", - Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())); - if (streamAction != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(streamAction); - commandEvent.reply(commandEvent.getResource("message.stream-action.deleted", name.getAsString())); - } else { - commandEvent.reply(commandEvent.getResource("message.stream-action.notFound", name.getAsString())); - } - } - - case "list" -> { - List streamActions = SQLSession.getSqlConnector().getSqlWorker() - .getEntityList(new StreamAction(), "FROM StreamAction WHERE guildAndName.guildId = :gid", - Map.of("gid", commandEvent.getGuild().getIdLong())); - - commandEvent.reply(LanguageService.getByEvent(commandEvent, "message.stream-action.list", - String.join("\n", streamActions.stream().map(StreamAction::getName).toArray(String[]::new)))); - } - - case "points" -> { - TwitchIntegration twitchIntegration = SQLSession.getSqlConnector().getSqlWorker() - .getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())); - if (twitchIntegration != null) { - StringBuilder stringBuilder = new StringBuilder(); - Main.getInstance().getNotifier().getTwitchClient().getHelix() - .getCustomRewards(twitchIntegration.getToken(), twitchIntegration.getChannelId(), null, false) - .execute().getRewards().forEach(c -> stringBuilder.append(c.getId()).append(" - ").append(c.getTitle()).append("\n")); - MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); - messageCreateBuilder.setContent(commandEvent.getResource("message.stream-action.points")); - messageCreateBuilder.addFiles(FileUpload.fromData(stringBuilder.toString().getBytes(StandardCharsets.UTF_8), "points.txt")); - commandEvent.reply(messageCreateBuilder.build()); - } else { - commandEvent.reply(commandEvent.getResource("message.stream-action.noTwitch", BotConfig.getTwitchAuth())); - } - } + case "delete" -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.actionName = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).thenAccept(streamAction -> { + if (streamAction != null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(streamAction); + commandEvent.reply(commandEvent.getResource("message.stream-action.deleted", name.getAsString())); + } else { + commandEvent.reply(commandEvent.getResource("message.stream-action.notFound", name.getAsString())); + } + }); + + case "list" -> + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new StreamAction(), "FROM StreamAction WHERE guildAndName.guildId = :gid", Map.of("gid", commandEvent.getGuild().getIdLong())).thenAccept(streamActions -> { + commandEvent.reply(LanguageService.getByEvent(commandEvent, "message.stream-action.list", String.join("\n", streamActions.stream().map(StreamAction::getName).toArray(String[]::new)))); + }); + + case "points" -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())).thenAccept(twitchIntegration -> { + if (twitchIntegration != null) { + StringBuilder stringBuilder = new StringBuilder(); + Main.getInstance().getNotifier().getTwitchClient().getHelix().getCustomRewards(twitchIntegration.getToken(), twitchIntegration.getChannelId(), null, false).execute().getRewards().forEach(c -> stringBuilder.append(c.getId()).append(" - ").append(c.getTitle()).append("\n")); + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); + messageCreateBuilder.setContent(commandEvent.getResource("message.stream-action.points")); + messageCreateBuilder.addFiles(FileUpload.fromData(stringBuilder.toString().getBytes(StandardCharsets.UTF_8), "points.txt")); + commandEvent.reply(messageCreateBuilder.build()); + } else { + commandEvent.reply(commandEvent.getResource("message.stream-action.noTwitch", BotConfig.getTwitchAuth())); + } + }); default -> commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); } @@ -235,26 +214,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("stream-action", - LanguageService.getDefault("command.description.stream-action")) - .addSubcommands(new SubcommandData("create", "Create a new Stream-Action.") - .addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true)) - .addSubcommands(new SubcommandData("delete", "Delete a Stream-Action.") - .addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true)) - .addSubcommands(new SubcommandData("list", "List all Stream-Actions.")) - .addSubcommands(new SubcommandData("points", "List all your ChannelPoint Rewards.")) - .addSubcommandGroups(new SubcommandGroupData("manage", "Manage a existing Stream-action.") - .addSubcommands(new SubcommandData("listener", "Set the listener of the Stream-Action.") - .addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true) - .addOption(OptionType.STRING, "listener", "The listener of the Stream-Action.", true), - new SubcommandData("delete", "Delete a line of the Stream-Action.") - .addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true) - .addOptions(new OptionData(OptionType.INTEGER, "line", "The line of the Stream-Action.", true).setMinValue(1)), - new SubcommandData("create", "Create a action in the Stream-Action.") - .addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true) - .addOption(OptionType.STRING, "action", "The action of the Stream-Action.", true), - new SubcommandData("list", "List all actions of the Stream-Action.") - .addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true))); + return new CommandDataImpl("stream-action", LanguageService.getDefault("command.description.stream-action")).addSubcommands(new SubcommandData("create", "Create a new Stream-Action.").addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true)).addSubcommands(new SubcommandData("delete", "Delete a Stream-Action.").addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true)).addSubcommands(new SubcommandData("list", "List all Stream-Actions.")).addSubcommands(new SubcommandData("points", "List all your ChannelPoint Rewards.")).addSubcommandGroups(new SubcommandGroupData("manage", "Manage a existing Stream-action.").addSubcommands(new SubcommandData("listener", "Set the listener of the Stream-Action.").addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true).addOption(OptionType.STRING, "listener", "The listener of the Stream-Action.", true), new SubcommandData("delete", "Delete a line of the Stream-Action.").addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true).addOptions(new OptionData(OptionType.INTEGER, "line", "The line of the Stream-Action.", true).setMinValue(1)), new SubcommandData("create", "Create a action in the Stream-Action.").addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true).addOption(OptionType.STRING, "action", "The action of the Stream-Action.", true), new SubcommandData("list", "List all actions of the Stream-Action.").addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true))); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java b/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java index fd355f42d..b25c2cb3b 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java @@ -59,45 +59,46 @@ public void onPerform(CommandEvent commandEvent) { EmbedBuilder embedBuilder = new EmbedBuilder(); - Tickets tickets = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", commandEvent.getGuild().getId())); - - if (tickets != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(tickets); - } - - StandardGuildMessageChannel channel = logChannel.getAsChannel().asStandardGuildMessageChannel(); - - tickets = new Tickets(); - tickets.setChannelId(ticketChannel.getAsChannel().getIdLong()); - tickets.setGuildId(commandEvent.getGuild().getIdLong()); - tickets.setLogChannelId(logChannel.getAsChannel().getIdLong()); - - Tickets finalTickets = tickets; - - channel.createWebhook("Ticket-Log").queue(webhook -> { - finalTickets.setLogChannelWebhookId(webhook.getIdLong()); - finalTickets.setLogChannelWebhookToken(webhook.getToken()); - commandEvent.getGuild().createCategory("Tickets").addPermissionOverride(commandEvent.getGuild().getPublicRole(), null, EnumSet.of(Permission.VIEW_CHANNEL)).queue(category1 -> { - finalTickets.setTicketCategory(category1.getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(finalTickets); - - MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); - messageCreateBuilder.setEmbeds(new EmbedBuilder() - .setTitle(LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket")) - .setDescription(SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_ticket_menu").getStringValue()) - .setColor(0x55ff00) - .setThumbnail(commandEvent.getGuild().getIconUrl()) - .setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) - .build()); - messageCreateBuilder.setActionRow(Button.of(ButtonStyle.PRIMARY, "re_ticket_open", LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket"), Emoji.fromUnicode("U+1F4E9"))); - Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), ticketChannel.getAsChannel().asTextChannel()); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", commandEvent.getGuild().getId())).thenAccept(tickets -> { + + if (tickets != null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(tickets); + } + + StandardGuildMessageChannel channel = logChannel.getAsChannel().asStandardGuildMessageChannel(); + + tickets = new Tickets(); + tickets.setChannelId(ticketChannel.getAsChannel().getIdLong()); + tickets.setGuildId(commandEvent.getGuild().getIdLong()); + tickets.setLogChannelId(logChannel.getAsChannel().getIdLong()); + + Tickets finalTickets = tickets; + + channel.createWebhook("Ticket-Log").queue(webhook -> { + finalTickets.setLogChannelWebhookId(webhook.getIdLong()); + finalTickets.setLogChannelWebhookToken(webhook.getToken()); + commandEvent.getGuild().createCategory("Tickets").addPermissionOverride(commandEvent.getGuild().getPublicRole(), null, EnumSet.of(Permission.VIEW_CHANNEL)).queue(category1 -> { + finalTickets.setTicketCategory(category1.getIdLong()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(finalTickets); + + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); + messageCreateBuilder.setEmbeds(new EmbedBuilder() + .setTitle(LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket")) + .setDescription(SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_ticket_menu").join().getStringValue()) + .setColor(0x55ff00) + .setThumbnail(commandEvent.getGuild().getIconUrl()) + .setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) + .build()); + messageCreateBuilder.setActionRow(Button.of(ButtonStyle.PRIMARY, "re_ticket_open", LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket"), Emoji.fromUnicode("U+1F4E9"))); + Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), ticketChannel.getAsChannel().asTextChannel()); + }); }); - }); - embedBuilder.setDescription(LanguageService.getByGuild(commandEvent.getGuild(), "message.ticket.setupSuccess")); - embedBuilder.setColor(Color.GREEN); + embedBuilder.setDescription(LanguageService.getByGuild(commandEvent.getGuild(), "message.ticket.setupSuccess")); + embedBuilder.setColor(Color.GREEN); - commandEvent.reply(embedBuilder.build()); + commandEvent.reply(embedBuilder.build()); + }); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Infractions.java b/src/main/java/de/presti/ree6/commands/impl/info/Infractions.java index 0d08efa67..59e4281d3 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Infractions.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Infractions.java @@ -38,13 +38,13 @@ public void onPerform(CommandEvent commandEvent) { return; } - Warning warning = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Warning(), "FROM Warning WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", Map.of("gid", commandEvent.getGuild().getIdLong(), "uid", member.getIdLong())); - - if (warning != null) { - commandEvent.reply(commandEvent.getResource("message.infractions.success", member.getAsMention(), warning.getWarnings())); - } else { - commandEvent.reply(commandEvent.getResource("message.infractions.empty", member.getAsMention())); - } + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Warning(), "FROM Warning WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", Map.of("gid", commandEvent.getGuild().getIdLong(), "uid", member.getIdLong())).thenAccept(warning -> { + if (warning != null) { + commandEvent.reply(commandEvent.getResource("message.infractions.success", member.getAsMention(), warning.getWarnings())); + } else { + commandEvent.reply(commandEvent.getResource("message.infractions.empty", member.getAsMention())); + } + }); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Optout.java b/src/main/java/de/presti/ree6/commands/impl/info/Optout.java index 0d98e1ba6..12300c325 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Optout.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Optout.java @@ -18,13 +18,15 @@ public class Optout implements ICommand { */ @Override public void onPerform(CommandEvent commandEvent) { - if (SQLSession.getSqlConnector().getSqlWorker().isOptOut(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong())) { - SQLSession.getSqlConnector().getSqlWorker().optIn(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong()); - commandEvent.reply(commandEvent.getResource("message.optout.optedIn")); - } else { - SQLSession.getSqlConnector().getSqlWorker().optOut(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong()); - commandEvent.reply(commandEvent.getResource("message.optout.optedOut")); - } + SQLSession.getSqlConnector().getSqlWorker().isOptOut(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong()).thenAccept(value -> { + if (value) { + SQLSession.getSqlConnector().getSqlWorker().optIn(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong()); + commandEvent.reply(commandEvent.getResource("message.optout.optedIn")); + } else { + SQLSession.getSqlConnector().getSqlWorker().optOut(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong()); + commandEvent.reply(commandEvent.getResource("message.optout.optedOut")); + } + }); } /** From f2e7a9b395a2d51c44cfba3d051b32ae8f698b98 Mon Sep 17 00:00:00 2001 From: Presti Date: Tue, 16 Apr 2024 10:20:18 +0200 Subject: [PATCH 06/94] Continues work on updating the internals. --- .../ree6/commands/impl/economy/Steal.java | 92 ++++++++++--------- .../ree6/commands/impl/economy/Work.java | 40 ++++---- .../presti/ree6/commands/impl/info/Help.java | 71 +++++++------- .../ree6/commands/impl/level/Level.java | 16 ++-- .../ree6/commands/impl/level/LevelRole.java | 27 +++--- .../presti/ree6/commands/impl/mod/Import.java | 48 +++++----- .../presti/ree6/commands/impl/mod/News.java | 34 +++---- 7 files changed, 168 insertions(+), 160 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java b/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java index 4cb8a9747..ee5306a84 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java @@ -43,51 +43,53 @@ public void onPerform(CommandEvent commandEvent) { String entryString = commandEvent.getGuild().getIdLong() + "-" + commandEvent.getMember().getIdLong(); - long delay = Long.parseLong((String) SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_steal_delay")).getValue()); - - if (stealTimeout.contains(entryString)) { - commandEvent.reply(commandEvent.getResource("message.steal.cooldown", delay)); - return; - } - - OptionMapping user = commandEvent.getOption("user"); - - if (user == null) { - commandEvent.reply(commandEvent.getResource("message.default.invalidOption"), 5); - return; - } - - Member member = user.getAsMember(); - - if (member == null) { - commandEvent.reply(commandEvent.getResource("message.default.invalidOption"), 5); - return; - } - - if (member.getIdLong() == commandEvent.getMember().getIdLong()) { - commandEvent.reply(commandEvent.getResource("message.steal.self"), 5); - return; - } - - MoneyHolder targetHolder = EconomyUtil.getMoneyHolder(commandEvent.getGuild().getIdLong(), member.getIdLong(), false); - - // Leave them poor people alone ong. - if (!EconomyUtil.hasCash(targetHolder) || targetHolder.getAmount() <= 50) { - commandEvent.reply(commandEvent.getResource("message.steal.notEnoughMoney", member.getAsMention()), 5); - return; - } - - double stealAmount = RandomUtils.round(targetHolder.getAmount() * RandomUtils.nextDouble(0.01, 0.25), 2); - if (EconomyUtil.pay(targetHolder, EconomyUtil.getMoneyHolder(commandEvent.getMember()), stealAmount, false, false)) { - // TODO:: more variation in the messages. - commandEvent.reply(commandEvent.getResource("message.steal.success", EconomyUtil.formatMoney(stealAmount), member.getAsMention()), 5); - } else { - commandEvent.reply(commandEvent.getResource("message.steal.failed", EconomyUtil.formatMoney(stealAmount), member.getAsMention()), 5); - } - - stealTimeout.add(entryString); - ThreadUtil.createThread(x -> stealTimeout.remove(entryString), Duration.ofSeconds(delay), false, false); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", + Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_steal_delay")).thenAccept(value -> { + long delay = Long.parseLong(value.getStringValue()); + + if (stealTimeout.contains(entryString)) { + commandEvent.reply(commandEvent.getResource("message.steal.cooldown", delay)); + return; + } + + OptionMapping user = commandEvent.getOption("user"); + + if (user == null) { + commandEvent.reply(commandEvent.getResource("message.default.invalidOption"), 5); + return; + } + + Member member = user.getAsMember(); + + if (member == null) { + commandEvent.reply(commandEvent.getResource("message.default.invalidOption"), 5); + return; + } + + if (member.getIdLong() == commandEvent.getMember().getIdLong()) { + commandEvent.reply(commandEvent.getResource("message.steal.self"), 5); + return; + } + + MoneyHolder targetHolder = EconomyUtil.getMoneyHolder(commandEvent.getGuild().getIdLong(), member.getIdLong(), false); + + // Leave them poor people alone ong. + if (!EconomyUtil.hasCash(targetHolder) || targetHolder.getAmount() <= 50) { + commandEvent.reply(commandEvent.getResource("message.steal.notEnoughMoney", member.getAsMention()), 5); + return; + } + + double stealAmount = RandomUtils.round(targetHolder.getAmount() * RandomUtils.nextDouble(0.01, 0.25), 2); + if (EconomyUtil.pay(targetHolder, EconomyUtil.getMoneyHolder(commandEvent.getMember()), stealAmount, false, false)) { + // TODO:: more variation in the messages. + commandEvent.reply(commandEvent.getResource("message.steal.success", EconomyUtil.formatMoney(stealAmount), member.getAsMention()), 5); + } else { + commandEvent.reply(commandEvent.getResource("message.steal.failed", EconomyUtil.formatMoney(stealAmount), member.getAsMention()), 5); + } + + stealTimeout.add(entryString); + ThreadUtil.createThread(x -> stealTimeout.remove(entryString), Duration.ofSeconds(delay), false, false); + }); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Work.java b/src/main/java/de/presti/ree6/commands/impl/economy/Work.java index bb17b90e9..09991d2c0 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Work.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Work.java @@ -33,31 +33,33 @@ public class Work implements ICommand { public void onPerform(CommandEvent commandEvent) { String entryString = commandEvent.getGuild().getIdLong() + "-" + commandEvent.getMember().getIdLong(); - long delay = Long.parseLong((String) SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_delay")).getValue()); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", + Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_delay")).thenAccept(value -> { + long delay = Long.parseLong(value.getStringValue()); - if (workTimeout.contains(entryString)) { - commandEvent.reply(commandEvent.getResource("message.work.cooldown", delay)); - return; - } + if (workTimeout.contains(entryString)) { + commandEvent.reply(commandEvent.getResource("message.work.cooldown", delay)); + return; + } - double min = Double.parseDouble((String) SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_min")).getValue()); + double min = Double.parseDouble((String) SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", + Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_min")).join().getStringValue()); - double max = Double.parseDouble((String) SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_max")).getValue()); + double max = Double.parseDouble((String) SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", + Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_max")).join().getStringValue()); - double amount = RandomUtils.round(RandomUtils.nextDouble(min, max), 2); + double amount = RandomUtils.round(RandomUtils.nextDouble(min, max), 2); - if (EconomyUtil.pay(null, EconomyUtil.getMoneyHolder(commandEvent.getMember()), amount, false, false, true)) { - // TODO:: add more variation messages. - commandEvent.reply(commandEvent.getResource("message.work.success", EconomyUtil.formatMoney(amount))); - } else { - commandEvent.reply(commandEvent.getResource("message.work.fail")); - } + if (EconomyUtil.pay(null, EconomyUtil.getMoneyHolder(commandEvent.getMember()), amount, false, false, true)) { + // TODO:: add more variation messages. + commandEvent.reply(commandEvent.getResource("message.work.success", EconomyUtil.formatMoney(amount))); + } else { + commandEvent.reply(commandEvent.getResource("message.work.fail")); + } - workTimeout.add(entryString); - ThreadUtil.createThread(x -> workTimeout.remove(entryString), Duration.ofSeconds(delay), false, false); + workTimeout.add(entryString); + ThreadUtil.createThread(x -> workTimeout.remove(entryString), Duration.ofSeconds(delay), false, false); + }); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Help.java b/src/main/java/de/presti/ree6/commands/impl/info/Help.java index 91cf59e14..c2b0886e0 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Help.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Help.java @@ -65,39 +65,6 @@ public void sendHelpInformation(String categoryString, CommandEvent commandEvent em.setTitle("Help Center"); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); - if (categoryString == null) { - String prefix = SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "chatprefix").getStringValue(); - for (Category cat : Category.values()) { - if (cat != Category.HIDDEN) { - if (!BotConfig.isModuleActive(cat.name().toLowerCase())) continue; - - String formattedName = cat.name().toUpperCase().charAt(0) + cat.name().substring(1).toLowerCase(); - em.addField("**" + formattedName + "**", prefix + "help " + cat.name().toLowerCase(), true); - } - } - } else { - if (isValid(categoryString)) { - StringBuilder end = new StringBuilder(); - - Category category = getCategoryFromString(categoryString); - - String prefix = SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "chatprefix").getStringValue(); - - for (ICommand cmd : Main.getInstance().getCommandManager().getCommands().stream().filter(command -> command.getClass().getAnnotation(Command.class).category() == category).toList()) { - end.append("``") - .append(prefix) - .append(cmd.getClass().getAnnotation(Command.class).name()) - .append("``\n") - .append(commandEvent.getResource(cmd.getClass().getAnnotation(Command.class).description())) - .append("\n\n"); - } - - em.setDescription(end.toString()); - } else { - sendHelpInformation(null, commandEvent); - return; - } - } messageCreateBuilder .addActionRow( @@ -111,7 +78,43 @@ public void sendHelpInformation(String categoryString, CommandEvent commandEvent Emoji.fromCustom("kiss", 1012765976951009361L, true)) ); - commandEvent.reply(messageCreateBuilder.setEmbeds(em.build()).build()); + if (categoryString == null) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "chatprefix").thenAccept(setting -> { + for (Category cat : Category.values()) { + if (cat != Category.HIDDEN) { + if (!BotConfig.isModuleActive(cat.name().toLowerCase())) continue; + + String formattedName = cat.name().toUpperCase().charAt(0) + cat.name().substring(1).toLowerCase(); + em.addField("**" + formattedName + "**", setting.getStringValue() + "help " + cat.name().toLowerCase(), true); + } + } + + commandEvent.reply(messageCreateBuilder.setEmbeds(em.build()).build()); + }); + } else { + if (isValid(categoryString)) { + StringBuilder end = new StringBuilder(); + + Category category = getCategoryFromString(categoryString); + + SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "chatprefix").thenAccept(setting -> { + for (ICommand cmd : Main.getInstance().getCommandManager().getCommands().stream().filter(command -> command.getClass().getAnnotation(Command.class).category() == category).toList()) { + end.append("``") + .append(setting.getStringValue()) + .append(cmd.getClass().getAnnotation(Command.class).name()) + .append("``\n") + .append(commandEvent.getResource(cmd.getClass().getAnnotation(Command.class).description())) + .append("\n\n"); + } + + em.setDescription(end.toString()); + commandEvent.reply(messageCreateBuilder.setEmbeds(em.build()).build()); + }); + } else { + sendHelpInformation(null, commandEvent); + } + } + } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/level/Level.java b/src/main/java/de/presti/ree6/commands/impl/level/Level.java index 5fa3696c2..1cb9441d3 100644 --- a/src/main/java/de/presti/ree6/commands/impl/level/Level.java +++ b/src/main/java/de/presti/ree6/commands/impl/level/Level.java @@ -49,7 +49,7 @@ public void onPerform(CommandEvent commandEvent) { sendLevel(commandEvent.getMessage().getMentions().getMembers().get(0), commandEvent, typ); } } else { - commandEvent.reply(commandEvent.getResource("message.default.usage","level chat/voice [@user]")); + commandEvent.reply(commandEvent.getResource("message.default.usage", "level chat/voice [@user]")); } } } @@ -68,21 +68,20 @@ public CommandData getCommandData() { */ @Override public String[] getAlias() { - return new String[] {"lvl", "xp", "rank"}; + return new String[]{"lvl", "xp", "rank"}; } /** * Sends the Level of the User. - * @param member The Member to get the Level of. + * + * @param member The Member to get the Level of. * @param commandEvent The CommandEvent. - * @param type The Type of the Level. + * @param type The Type of the Level. */ public void sendLevel(Member member, CommandEvent commandEvent, String type) { - - UserLevel userLevel = type.equalsIgnoreCase("voice") ? + (type.equalsIgnoreCase("voice") ? SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelData(commandEvent.getGuild().getIdLong(), member.getIdLong()) : - SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), member.getIdLong()); - + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), member.getIdLong())).thenAccept(userLevel -> { try { MessageCreateBuilder createBuilder = new MessageCreateBuilder(); createBuilder.addFiles(FileUpload.fromData(ImageCreationUtility.createRankImage(userLevel), "rank.png")); @@ -92,5 +91,6 @@ public void sendLevel(Member member, CommandEvent commandEvent, String type) { commandEvent.reply(commandEvent.getResource("command.perform.error")); log.error("Couldn't generated Rank Image!", exception); } + }); } } diff --git a/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java b/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java index f3d8df18f..dde1a3512 100644 --- a/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java +++ b/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java @@ -75,22 +75,23 @@ public void onPerform(CommandEvent commandEvent) { } commandEvent.reply(commandEvent.getResource("message.levelRole.removed", role.getName(), level)); } - case "list" -> { - MessageCreateBuilder createBuilder = new MessageCreateBuilder(); - StringBuilder voiceStringBuilder = new StringBuilder(); - StringBuilder chatStringBuilder = new StringBuilder(); - createBuilder.setContent(commandEvent.getResource("message.levelRole.list")); + case "list" -> + SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelRewards(commandEvent.getGuild().getIdLong()).thenAccept(level -> { + MessageCreateBuilder createBuilder = new MessageCreateBuilder(); + StringBuilder voiceStringBuilder = new StringBuilder(); + StringBuilder chatStringBuilder = new StringBuilder(); + createBuilder.setContent(commandEvent.getResource("message.levelRole.list")); - SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelRewards(commandEvent.getGuild().getIdLong()) - .forEach((level1, role1) -> voiceStringBuilder.append(level1).append(" -> ").append(role1)); - SQLSession.getSqlConnector().getSqlWorker().getChatLevelRewards(commandEvent.getGuild().getIdLong()) - .forEach((level1, role1) -> chatStringBuilder.append(level1).append(" -> ").append(role1)); + level.forEach((level1, role1) -> voiceStringBuilder.append(level1).append(" -> ").append(role1)); - createBuilder.addFiles(FileUpload.fromData(voiceStringBuilder.toString().getBytes(StandardCharsets.UTF_8), "voice.txt"), - FileUpload.fromData(chatStringBuilder.toString().getBytes(StandardCharsets.UTF_8), "chat.txt")); + SQLSession.getSqlConnector().getSqlWorker().getChatLevelRewards(commandEvent.getGuild().getIdLong()).join() + .forEach((level2, role2) -> chatStringBuilder.append(level2).append(" -> ").append(role2)); - commandEvent.reply(createBuilder.build()); - } + createBuilder.addFiles(FileUpload.fromData(voiceStringBuilder.toString().getBytes(StandardCharsets.UTF_8), "voice.txt"), + FileUpload.fromData(chatStringBuilder.toString().getBytes(StandardCharsets.UTF_8), "chat.txt")); + + commandEvent.reply(createBuilder.build()); + }); default -> commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); } diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Import.java b/src/main/java/de/presti/ree6/commands/impl/mod/Import.java index 6239f6166..ebbc07799 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Import.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Import.java @@ -71,19 +71,19 @@ public void importFromMee6(CommandEvent commandEvent) { JsonElement xp = player.getAsJsonObject().get("xp"); if (id.isJsonPrimitive() && xp.isJsonPrimitive()) { - ChatUserLevel chatUserLevel = SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), id.getAsLong()); - - if (chatUserLevel != null && chatUserLevel.getExperience() > xp.getAsLong()) { - return; - } - - if (chatUserLevel == null) { - chatUserLevel = new ChatUserLevel(commandEvent.getGuild().getIdLong(), id.getAsLong(), xp.getAsLong()); - } else { - chatUserLevel.setExperience(xp.getAsLong()); - } - - SQLSession.getSqlConnector().getSqlWorker().updateEntity(chatUserLevel); + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), id.getAsLong()).thenAccept(chatUserLevel -> { + if (chatUserLevel != null && chatUserLevel.getExperience() > xp.getAsLong()) { + return; + } + + if (chatUserLevel == null) { + chatUserLevel = new ChatUserLevel(commandEvent.getGuild().getIdLong(), id.getAsLong(), xp.getAsLong()); + } else { + chatUserLevel.setExperience(xp.getAsLong()); + } + + SQLSession.getSqlConnector().getSqlWorker().updateEntity(chatUserLevel).join(); + }); } } }); @@ -122,19 +122,19 @@ public void importFromAmari(CommandEvent commandEvent) { Leaderboard leaderboard = AmariAPI.getAmari4J().getRawLeaderboard(commandEvent.getGuild().getId(), Integer.MAX_VALUE); leaderboard.getMembers().forEach(member -> { - ChatUserLevel chatUserLevel = SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), Long.parseLong(member.getUserid())); - - if (chatUserLevel != null && chatUserLevel.getExperience() > member.getExperience()) { - return; - } + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), Long.parseLong(member.getUserid())).thenAccept(chatUserLevel -> { + if (chatUserLevel != null && chatUserLevel.getExperience() > member.getExperience()) { + return; + } - if (chatUserLevel == null) { - chatUserLevel = new ChatUserLevel(commandEvent.getGuild().getIdLong(), Long.parseLong(member.getUserid()), member.getExperience()); - } else { - chatUserLevel.setExperience(member.getExperience()); - } + if (chatUserLevel == null) { + chatUserLevel = new ChatUserLevel(commandEvent.getGuild().getIdLong(), Long.parseLong(member.getUserid()), member.getExperience()); + } else { + chatUserLevel.setExperience(member.getExperience()); + } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(chatUserLevel); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(chatUserLevel).join(); + }); }); commandEvent.reply(commandEvent.getResource("message.import.success", leaderboard.getCount()), 5); } catch (InvalidAPIKeyException | InvalidServerResponseException | RateLimitException e) { diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/News.java b/src/main/java/de/presti/ree6/commands/impl/mod/News.java index b3a6fa630..8a3e1e256 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/News.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/News.java @@ -25,23 +25,23 @@ public void onPerform(CommandEvent commandEvent) { return; } - Setting setting = SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news"); - - if (setting == null) { - SQLSession.getSqlConnector().getSqlWorker().setSetting(commandEvent.getGuild().getIdLong(), "configuration_news", "Receive News", true); - commandEvent.reply(commandEvent.getResource("message.news.enabled"), 5); - return; - } - - if (setting.getBooleanValue()) { - setting.setValue(false); - commandEvent.reply(commandEvent.getResource("message.news.disabled"), 5); - } else { - setting.setValue(true); - commandEvent.reply(commandEvent.getResource("message.news.enabled"), 5); - } - - SQLSession.getSqlConnector().getSqlWorker().updateEntity(setting); + SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").thenAccept(setting -> { + if (setting == null) { + SQLSession.getSqlConnector().getSqlWorker().setSetting(commandEvent.getGuild().getIdLong(), "configuration_news", "Receive News", true); + commandEvent.reply(commandEvent.getResource("message.news.enabled"), 5); + return; + } + + if (setting.getBooleanValue()) { + setting.setValue(false); + commandEvent.reply(commandEvent.getResource("message.news.disabled"), 5); + } else { + setting.setValue(true); + commandEvent.reply(commandEvent.getResource("message.news.enabled"), 5); + } + + SQLSession.getSqlConnector().getSqlWorker().updateEntity(setting).join(); + }); } /** From 1d1a497e2344f3cc254a03ee639b078c2328de13 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 17 Apr 2024 11:44:26 +0200 Subject: [PATCH 07/94] Continues work. --- .../presti/ree6/commands/impl/info/Stats.java | 43 +++--- .../presti/ree6/commands/impl/mod/Setup.java | 134 +++++++++++------- 2 files changed, 102 insertions(+), 75 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java index 6f600b892..08668a3d3 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java @@ -37,12 +37,9 @@ public void onPerform(CommandEvent commandEvent) { long start = System.currentTimeMillis(); - Message message = null; - if (commandEvent.isSlashCommand()) { - message = commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("label.loading")).complete(); - } else { - message = commandEvent.getChannel().sendMessage(commandEvent.getResource("label.loading")).complete(); - } + Message message = commandEvent.isSlashCommand() + ? commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("label.loading")).complete() + : commandEvent.getChannel().sendMessage(commandEvent.getResource("label.loading")).complete(); long ping = System.currentTimeMillis() - start; @@ -76,28 +73,32 @@ public void onPerform(CommandEvent commandEvent) { StringBuilder end = new StringBuilder(); - for (GuildCommandStats values : SQLSession.getSqlConnector().getSqlWorker().getStats(commandEvent.getGuild().getIdLong())) { - end.append(values.getCommand()).append(" - ").append(values.getUses()).append("\n"); - } + SQLSession.getSqlConnector().getSqlWorker().getStats(commandEvent.getGuild().getIdLong()).thenAccept(stats -> { + for (GuildCommandStats values : stats) { + end.append(values.getCommand()).append(" - ").append(values.getUses()).append("\n"); + } - StringBuilder end2 = new StringBuilder(); + StringBuilder end2 = new StringBuilder(); - for (CommandStats values : SQLSession.getSqlConnector().getSqlWorker().getStatsGlobal()) { - end2.append(values.getCommand()).append(" - ").append(values.getUses()).append("\n"); - } + SQLSession.getSqlConnector().getSqlWorker().getStatsGlobal().thenAccept(statsGlobal -> { + for (CommandStats values : statsGlobal) { + end2.append(values.getCommand()).append(" - ").append(values.getUses()).append("\n"); + } - em.addField("**" + commandEvent.getResource("label.commandStats") + ":**", "", true); - em.addField("**" + commandEvent.getResource("label.topCommands") + "**", end.toString(), true); - em.addField("**" + commandEvent.getResource("label.overallTopCommands") + "**", end2.toString(), true); + em.addField("**" + commandEvent.getResource("label.commandStats") + ":**", "", true); + em.addField("**" + commandEvent.getResource("label.topCommands") + "**", end.toString(), true); + em.addField("**" + commandEvent.getResource("label.overallTopCommands") + "**", end2.toString(), true); - em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); + em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); - MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); + MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); - messageEditBuilder.setContent(""); - messageEditBuilder.setEmbeds(em.build()); + messageEditBuilder.setContent(""); + messageEditBuilder.setEmbeds(em.build()); - commandEvent.update(message, messageEditBuilder.build()); + commandEvent.update(message, messageEditBuilder.build()); + }); + }); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java index 9cb4dbd89..e09525f39 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java @@ -17,6 +17,7 @@ import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Message; +import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.channel.ChannelType; import net.dv8tion.jda.api.entities.channel.unions.GuildChannelUnion; @@ -39,6 +40,7 @@ import java.util.Base64; import java.util.List; import java.util.Map; +import java.util.concurrent.CompletableFuture; /** * A command to set Ree6 up. @@ -113,15 +115,20 @@ public void onPerform(CommandEvent commandEvent) { .addActionRow(selectMenu).queue(); } } else if (commandEvent.getSubcommand().equalsIgnoreCase("autorole")) { - if (commandEvent.isSlashCommand()) { - commandEvent.getInteractionHook().sendMessageEmbeds(createAutoRoleSetupMessage(commandEvent.getGuild(), commandEvent.getInteractionHook()).build()) - .addActionRow(createAutoRoleSetupSelectMenu(commandEvent.getGuild(), commandEvent.getInteractionHook())) - .addActionRow(Button.link(BotConfig.getWebinterface(), "Webinterface")).queue(); - } else { - commandEvent.getChannel().sendMessageEmbeds(createAutoRoleSetupMessage(commandEvent.getGuild(), commandEvent.getInteractionHook()).build()) - .addActionRow(createAutoRoleSetupSelectMenu(commandEvent.getGuild(), commandEvent.getInteractionHook())) - .addActionRow(Button.link(BotConfig.getWebinterface(), "Webinterface")).queue(); - } + createAutoRoleSetupSelectMenu(commandEvent.getGuild(), commandEvent.getInteractionHook()).thenAccept(menu -> { + MessageEmbed embed = createAutoRoleSetupMessage(commandEvent.getGuild(), commandEvent.getInteractionHook()).build(); + Button webinterface = Button.link(BotConfig.getWebinterface(), "Webinterface"); + + if (commandEvent.isSlashCommand()) { + commandEvent.getInteractionHook().sendMessageEmbeds(embed) + .addActionRow(menu) + .addActionRow(webinterface).queue(); + } else { + commandEvent.getChannel().sendMessageEmbeds(embed) + .addActionRow(menu) + .addActionRow(webinterface).queue(); + } + }); } } else { OptionMapping optionMapping = commandEvent.getOption("channel"); @@ -138,46 +145,59 @@ public void onPerform(CommandEvent commandEvent) { if (commandEvent.getSubcommand().equals("set")) { if (guildChannelUnion.getType() == ChannelType.TEXT) { guildChannelUnion.asTextChannel().createWebhook(BotConfig.getBotName() + "-Logs").queue(webhook -> { - if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong())) { - WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong())); - } - - SQLSession.getSqlConnector().getSqlWorker().setLogWebhook(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong(), webhook.getIdLong(), webhook.getToken()); - commandEvent.reply(commandEvent.getResource("message.auditLog.setupSuccess")); + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong()).thenAccept(aBoolean -> { + if (aBoolean) { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong()).thenAccept(webhookEntity -> { + WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), webhookEntity); + }); + } + + SQLSession.getSqlConnector().getSqlWorker().setLogWebhook(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong(), webhook.getIdLong(), webhook.getToken()); + commandEvent.reply(commandEvent.getResource("message.auditLog.setupSuccess")); + }); }); } else { commandEvent.reply(commandEvent.getResource("message.default.invalidOptionChannel")); } } else { - if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong())) { - WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong())); - commandEvent.reply(commandEvent.getResource("message.auditLog.deleted")); - } else { - commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); - } + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong()).thenAccept(aBoolean -> { + if (aBoolean) { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong()).thenAccept(webhookEntity -> { + WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), webhookEntity); + commandEvent.reply(commandEvent.getResource("message.auditLog.deleted")); + }); + } else { + commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); + } + }); } } case "welcome" -> { if (commandEvent.getSubcommand().equals("set")) { if (guildChannelUnion.getType() == ChannelType.TEXT) { guildChannelUnion.asTextChannel().createWebhook(BotConfig.getBotName() + "-Welcome").queue(webhook -> { - if (SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong())) { - WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong())); - } - - SQLSession.getSqlConnector().getSqlWorker().setWelcomeWebhook(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong(), webhook.getIdLong(), webhook.getToken()); - commandEvent.reply(commandEvent.getResource("message.welcome.setupSuccess")); + SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong()).thenAccept(aBoolean -> { + if (aBoolean) { + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong()).thenAccept(webhookEntity -> { + WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), webhookEntity); + }); + } + SQLSession.getSqlConnector().getSqlWorker().setWelcomeWebhook(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong(), webhook.getIdLong(), webhook.getToken()); + commandEvent.reply(commandEvent.getResource("message.welcome.setupSuccess")); + }); }); } else { commandEvent.reply(commandEvent.getResource("message.default.invalidOptionChannel")); } } else { - if (SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong())) { - WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong())); - commandEvent.reply(commandEvent.getResource("message.welcome.deleted")); - } else { + SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong()).thenAccept(aBoolean -> { + if (aBoolean) { + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong()).thenAccept(webhookEntity -> + WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), webhookEntity)); + commandEvent.reply(commandEvent.getResource("message.welcome.deleted")); + } commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); - } + }); } } case "tempvoice" -> { @@ -189,13 +209,14 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.default.invalidOptionChannel")); } } else { - TemporalVoicechannel temporalVoicechannel = SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", commandEvent.getGuild().getId())); - if (temporalVoicechannel != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel); - commandEvent.reply(commandEvent.getResource("message.temporalVoice.deleted")); - } else { - commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); - } + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", commandEvent.getGuild().getId())).thenAccept(temporalVoicechannel -> { + if (temporalVoicechannel != null) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel); + commandEvent.reply(commandEvent.getResource("message.temporalVoice.deleted")); + } else { + commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); + } + }); } } case "rewards" -> { @@ -250,30 +271,32 @@ public static EmbedBuilder createAutoRoleSetupMessage(Guild guild, InteractionHo boolean hasRoles = !GuildUtil.getManagableRoles(guild).isEmpty(); return new EmbedBuilder() - .setTitle(LanguageService.getByGuildOrInteractionHook(guild, interactionHook,"label.setup")) + .setTitle(LanguageService.getByGuildOrInteractionHook(guild, interactionHook, "label.setup")) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()) .setColor(hasRoles ? Color.cyan : Color.red) .setDescription(LanguageService.getByGuildOrInteractionHook(guild, interactionHook, hasRoles ? "message.autoRole.setupDescription" : "message.default.needPermission", (hasRoles ? null : Permission.MANAGE_ROLES.name()))); } - public static SelectMenu createAutoRoleSetupSelectMenu(Guild guild, InteractionHook interactionHook) { + public static CompletableFuture createAutoRoleSetupSelectMenu(Guild guild, InteractionHook interactionHook) { List optionList = new ArrayList<>(); for (Role role : GuildUtil.getManagableRoles(guild)) { optionList.add(SelectOption.of(role.getName(), role.getId())); } - SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(guild.getIdLong()).forEach(autoRole -> { - SelectOption option = optionList.stream().filter(selectOption -> selectOption.getValue().equals(String.valueOf(autoRole.getRoleId()))).findFirst().orElse(null); - if (option != null) { - optionList.remove(option); - optionList.add(option.withDefault(true)); - } - }); + return SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(guild.getIdLong()).thenApply(list -> { + list.forEach(autoRole -> { + SelectOption option = optionList.stream().filter(selectOption -> selectOption.getValue().equals(String.valueOf(autoRole.getRoleId()))).findFirst().orElse(null); + if (option != null) { + optionList.remove(option); + optionList.add(option.withDefault(true)); + } + }); - return new StringSelectMenuImpl("setupAutoRole", LanguageService.getByGuildOrInteractionHook(guild, interactionHook, - "message.autoRole.setupPlaceholder"), - 0, Math.min(10, Math.max(1, optionList.size())), optionList.isEmpty(), optionList); + return new StringSelectMenuImpl("setupAutoRole", LanguageService.getByGuildOrInteractionHook(guild, interactionHook, + "message.autoRole.setupPlaceholder"), + 0, Math.min(10, Math.max(1, optionList.size())), optionList.isEmpty(), optionList); + }); } /** @@ -287,15 +310,18 @@ public CommandData getCommandData() { .addSubcommandGroups( new SubcommandGroupData("auditlog", "Auditlog Setup") .addSubcommands(new SubcommandData("set", "Set the Auditlog channel.") - .addOptions(new OptionData(OptionType.CHANNEL, "channel", "The Welcome Channel.", true).setChannelTypes(ChannelType.TEXT))) + .addOptions(new OptionData(OptionType.CHANNEL, "channel", "The Welcome Channel.", true) + .setChannelTypes(ChannelType.TEXT))) .addSubcommands(new SubcommandData("remove", "Remove the Auditlog channel.")), new SubcommandGroupData("welcome", "Welcome Setup") .addSubcommands(new SubcommandData("set", "Set the Welcome channel.") - .addOptions(new OptionData(OptionType.CHANNEL, "channel", "The Auditlog Channel.", true).setChannelTypes(ChannelType.TEXT))) + .addOptions(new OptionData(OptionType.CHANNEL, "channel", "The Auditlog Channel.", true) + .setChannelTypes(ChannelType.TEXT))) .addSubcommands(new SubcommandData("remove", "Remove the Welcome channel.")), new SubcommandGroupData("tempvoice", "Temporal Voice Setup") .addSubcommands(new SubcommandData("set", "Set a Temporal Voice Channel.") - .addOptions(new OptionData(OptionType.CHANNEL, "channel", "The Temporal Voice Channel.", true).setChannelTypes(ChannelType.VOICE))) + .addOptions(new OptionData(OptionType.CHANNEL, "channel", "The Temporal Voice Channel.", true) + .setChannelTypes(ChannelType.VOICE))) .addSubcommands(new SubcommandData("remove", "Remove a Temporal Voice Channel.")), // TODO:: think about a better way to implement it. /*new SubcommandGroupData("statistics", "Statistics Setup") From 8178a778e792432525f858a960dbc1c4f53dab92 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 17 Apr 2024 11:49:57 +0200 Subject: [PATCH 08/94] Continues work. --- .../ree6/commands/impl/mod/Blacklist.java | 50 +++++++++++-------- .../de/presti/ree6/events/MenuEvents.java | 12 +++-- .../ree6/game/impl/blackjack/Blackjack.java | 6 ++- 3 files changed, 40 insertions(+), 28 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java b/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java index c95c61283..eed366720 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java @@ -59,18 +59,22 @@ public void onPerform(CommandEvent commandEvent) { } default -> { - if (ModerationUtil.shouldModerate(commandEvent.getGuild().getIdLong())) { - StringBuilder end = new StringBuilder(); + ModerationUtil.shouldModerate(commandEvent.getGuild().getIdLong()).thenAccept(aBoolean -> { + if (aBoolean) { + ModerationUtil.getBlacklist(commandEvent.getGuild().getIdLong()).thenAccept(blacklists -> { + StringBuilder end = new StringBuilder(); - for (String s : ModerationUtil.getBlacklist(commandEvent.getGuild().getIdLong())) { - end.append("\n").append(s); - } + for (String s : blacklists) { + end.append("\n").append(s); + } - commandEvent.reply("```" + end + "```"); - } else { - commandEvent.reply(commandEvent.getResource("message.blacklist.setupNeeded")); - commandEvent.reply(commandEvent.getResource("message.default.usage", "blacklist add [WORD...]"), 5); - } + commandEvent.reply("```" + end + "```"); + }); + } else { + commandEvent.reply(commandEvent.getResource("message.blacklist.setupNeeded")); + commandEvent.reply(commandEvent.getResource("message.default.usage", "blacklist add [WORD...]"), 5); + } + }); } } @@ -84,18 +88,22 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.default.invalidQuery"), 5); commandEvent.reply(commandEvent.getResource("message.default.usage", "blacklist remove WORD"), 5); } else if (commandEvent.getArguments()[0].equalsIgnoreCase("list")) { - if (ModerationUtil.shouldModerate(commandEvent.getGuild().getIdLong())) { - StringBuilder end = new StringBuilder(); - - for (String s : ModerationUtil.getBlacklist(commandEvent.getGuild().getIdLong())) { - end.append("\n").append(s); + ModerationUtil.shouldModerate(commandEvent.getGuild().getIdLong()).thenAccept(aBoolean -> { + if (aBoolean) { + ModerationUtil.getBlacklist(commandEvent.getGuild().getIdLong()).thenAccept(blacklists -> { + StringBuilder end = new StringBuilder(); + + for (String s : blacklists) { + end.append("\n").append(s); + } + + commandEvent.reply("```" + end + "```"); + }); + } else { + commandEvent.reply(commandEvent.getResource("message.blacklist.setupNeeded")); + commandEvent.reply(commandEvent.getResource("message.default.usage", "blacklist add [WORD...]"), 5); } - - commandEvent.reply("```" + end + "```"); - } else { - commandEvent.reply(commandEvent.getResource("message.blacklist.setupNeeded")); - commandEvent.reply(commandEvent.getResource("message.default.usage", "blacklist add [WORD...]"), 5); - } + }); } else { commandEvent.reply(commandEvent.getResource("message.blacklist.notFound", commandEvent.getArguments()[0]), 5); commandEvent.reply(commandEvent.getResource("message.default.usage", "blacklist add/remove/list"), 5); diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index 772892c88..c91b3454c 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -969,11 +969,13 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired"), 1, 1, false, optionList)).queue(); } - case "autorole" -> event.editMessageEmbeds(Setup.createAutoRoleSetupMessage(event.getGuild(), event.getHook()).build()) - .setComponents( - ActionRow.of(Setup.createAutoRoleSetupSelectMenu(event.getGuild(), event.getHook())), - ActionRow.of(Button.link(BotConfig.getWebinterface(), "Webinterface"))) - .queue(); + case "autorole" -> + Setup.createAutoRoleSetupSelectMenu(event.getGuild(), event.getHook()).thenAccept(selectMenu -> + event.editMessageEmbeds(Setup.createAutoRoleSetupMessage(event.getGuild(), event.getHook()).build()) + .setComponents( + ActionRow.of(selectMenu), + ActionRow.of(Button.link(BotConfig.getWebinterface(), "Webinterface"))) + .queue()); case "tempvoice" -> { optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setup"), "tempVoiceSetup")); diff --git a/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java b/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java index 4b6ba6a39..68c3f98e4 100644 --- a/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java +++ b/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java @@ -311,8 +311,10 @@ public void stopGame(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlayer) nextPlayer.getInteractionHook().editOriginalComponents(new ArrayList<>()).queue(); Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), session.getChannel()); - rewardPlayer(session, winner, SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_blackjack_win")).getValue()); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", + Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_blackjack_win")) + .thenAccept(setting -> rewardPlayer(session, winner, setting.getValue())); + stopGame(); } From 95f2f03734b6d04b66ef98d71e2f447143b5f330 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 17 Apr 2024 12:15:31 +0200 Subject: [PATCH 09/94] Continues work. --- .../ree6/game/impl/musicquiz/MusicQuiz.java | 23 +- src/main/java/de/presti/ree6/main/Main.java | 245 +++++++++--------- 2 files changed, 141 insertions(+), 127 deletions(-) diff --git a/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java b/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java index 124802f7a..cb16d7837 100644 --- a/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java +++ b/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java @@ -213,8 +213,10 @@ public void onMessageReceive(MessageReceivedEvent messageReceivedEvent) { if (currentEntry.checkTitle(messageContent)) { musicQuizPlayer.addPoints(1); - rewardPlayer(session, musicQuizPlayer,SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_title")).getValue()); + + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", + Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_title")) + .thenAccept(setting -> rewardPlayer(session, musicQuizPlayer, setting.getValue())); messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundTitle", currentEntry.getTitle())).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); messageReceivedEvent.getMessage().delete().queue(); @@ -222,8 +224,10 @@ public void onMessageReceive(MessageReceivedEvent messageReceivedEvent) { if (currentEntry.checkArtist(messageContent)) { musicQuizPlayer.addPoints(2); - rewardPlayer(session, musicQuizPlayer,SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_artist")).getValue()); + + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", + Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_artist")) + .thenAccept(setting -> rewardPlayer(session, musicQuizPlayer, setting.getValue())); messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundArtists", currentEntry.getArtist())).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); messageReceivedEvent.getMessage().delete().queue(); @@ -231,8 +235,10 @@ public void onMessageReceive(MessageReceivedEvent messageReceivedEvent) { if (currentEntry.checkFeatures(messageContent)) { musicQuizPlayer.addPoints(3); - rewardPlayer(session, musicQuizPlayer,SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_feature")).getValue()); + + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", + Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_feature")) + .thenAccept(setting -> rewardPlayer(session, musicQuizPlayer, setting.getValue())); messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundFeature", String.join(",", currentEntry.getFeatures()))).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); messageReceivedEvent.getMessage().delete().queue(); @@ -280,8 +286,9 @@ public void stopGame() { menuMessage.delete().queue(); session.getChannel().sendMessage(messageCreateBuilder.build()).queue(); - rewardPlayer(session, sortedList.get(0), SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_win")).getValue()); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", + Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_win")) + .thenAccept(setting -> rewardPlayer(session, sortedList.get(0), setting.getValue())); Main.getInstance().getMusicWorker().disconnect(session.getGuild()); } diff --git a/src/main/java/de/presti/ree6/main/Main.java b/src/main/java/de/presti/ree6/main/Main.java index 79e877b10..95d5c2e80 100644 --- a/src/main/java/de/presti/ree6/main/Main.java +++ b/src/main/java/de/presti/ree6/main/Main.java @@ -344,71 +344,72 @@ public static void main(String[] args) { if (BotConfig.isModuleActive("notifier")) { ThreadUtil.createThread(x -> { log.info("Loading Notifier data."); - List channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), "FROM ChannelStats", null); - - try { - // Register all Twitch Channels. - getInstance().getNotifier().registerTwitchChannel(SQLSession.getSqlConnector().getSqlWorker().getAllTwitchNames()); - getInstance().getNotifier().registerTwitchChannel(channelStats.stream().map(ChannelStats::getTwitchFollowerChannelUsername).filter(Objects::nonNull).toList()); + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), "FROM ChannelStats", null).thenAccept(channelStats -> { + try { + // Register all Twitch Channels. + SQLSession.getSqlConnector().getSqlWorker().getAllTwitchNames().thenAccept(getInstance().getNotifier()::registerTwitchChannel); + getInstance().getNotifier().registerTwitchChannel(channelStats.stream().map(ChannelStats::getTwitchFollowerChannelUsername).filter(Objects::nonNull).toList()); - // Register the Event-handler. - getInstance().getNotifier().registerTwitchEventHandler(); - } catch (Exception exception) { - log.error("Error while loading Twitch data: " + exception.getMessage()); - Sentry.captureException(exception); - } + // Register the Event-handler. + getInstance().getNotifier().registerTwitchEventHandler(); + } catch (Exception exception) { + log.error("Error while loading Twitch data: {}", exception.getMessage()); + Sentry.captureException(exception); + } - try { - // Register all Twitter Users. - getInstance().getNotifier().registerTwitterUser(SQLSession.getSqlConnector().getSqlWorker().getAllTwitterNames()); - getInstance().getNotifier().registerTwitterUser(channelStats.stream().map(ChannelStats::getTwitterFollowerChannelUsername).filter(Objects::nonNull).toList()); - } catch (Exception exception) { - log.error("Error while loading Twitter data: " + exception.getMessage()); - Sentry.captureException(exception); - } + try { + // Register all Twitter Users. + SQLSession.getSqlConnector().getSqlWorker().getAllTwitterNames().thenAccept(getInstance().getNotifier()::registerTwitterUser); + getInstance().getNotifier().registerTwitterUser(channelStats.stream().map(ChannelStats::getTwitterFollowerChannelUsername).filter(Objects::nonNull).toList()); + } catch (Exception exception) { + log.error("Error while loading Twitter data: {}", exception.getMessage()); + Sentry.captureException(exception); + } - try { - // Register all YouTube channels. - getInstance().getNotifier().registerYouTubeChannel(SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels()); - getInstance().getNotifier().registerYouTubeChannel(channelStats.stream().map(ChannelStats::getYoutubeSubscribersChannelUsername).filter(Objects::nonNull).toList()); - } catch (Exception exception) { - log.error("Error while loading YouTube data: " + exception.getMessage()); - Sentry.captureException(exception); - } + try { + // Register all YouTube channels. + SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels().thenAccept(getInstance().getNotifier()::registerYouTubeChannel); + getInstance().getNotifier().registerYouTubeChannel(channelStats.stream().map(ChannelStats::getYoutubeSubscribersChannelUsername).filter(Objects::nonNull).toList()); + } catch (Exception exception) { + log.error("Error while loading YouTube data: {}", exception.getMessage()); + Sentry.captureException(exception); + } - try { - // Register all Reddit Subreddits. - getInstance().getNotifier().registerSubreddit(SQLSession.getSqlConnector().getSqlWorker().getAllSubreddits()); - getInstance().getNotifier().registerSubreddit(channelStats.stream().map(ChannelStats::getSubredditMemberChannelSubredditName).filter(Objects::nonNull).toList()); - } catch (Exception exception) { - log.error("Error while loading Reddit data: " + exception.getMessage()); - Sentry.captureException(exception); - } + try { + // Register all Reddit Subreddits. + SQLSession.getSqlConnector().getSqlWorker().getAllSubreddits().thenAccept(getInstance().getNotifier()::registerSubreddit); + getInstance().getNotifier().registerSubreddit(channelStats.stream().map(ChannelStats::getSubredditMemberChannelSubredditName).filter(Objects::nonNull).toList()); + } catch (Exception exception) { + log.error("Error while loading Reddit data: {}", exception.getMessage()); + Sentry.captureException(exception); + } - try { - // Register all Instagram Users. - getInstance().getNotifier().registerInstagramUser(SQLSession.getSqlConnector().getSqlWorker().getAllInstagramUsers()); - getInstance().getNotifier().registerInstagramUser(channelStats.stream().map(ChannelStats::getInstagramFollowerChannelUsername).filter(Objects::nonNull).toList()); - } catch (Exception exception) { - log.error("Error while loading Instagram data: " + exception.getMessage()); - Sentry.captureException(exception); - } + try { + // Register all Instagram Users. + SQLSession.getSqlConnector().getSqlWorker().getAllInstagramUsers().thenAccept(getInstance().getNotifier()::registerInstagramUser); + getInstance().getNotifier().registerInstagramUser(channelStats.stream().map(ChannelStats::getInstagramFollowerChannelUsername).filter(Objects::nonNull).toList()); + } catch (Exception exception) { + log.error("Error while loading Instagram data: {}", exception.getMessage()); + Sentry.captureException(exception); + } - try { - // Register all TikTok Users. - getInstance().getNotifier().registerTikTokUser(SQLSession.getSqlConnector().getSqlWorker().getAllTikTokNames().stream().map(Long::parseLong).toList()); - } catch (Exception exception) { - log.error("Error while loading TikTok data: " + exception.getMessage()); - Sentry.captureException(exception); - } + try { + // Register all TikTok Users. + SQLSession.getSqlConnector().getSqlWorker().getAllTikTokNames().thenAccept(tiktokNames -> + tiktokNames.forEach(tikTokName -> getInstance().getNotifier().registerTikTokUser(Long.parseLong(tikTokName)))); + } catch (Exception exception) { + log.error("Error while loading TikTok data: {}", exception.getMessage()); + Sentry.captureException(exception); + } - try { - // Register all RSS-Feeds. - getInstance().getNotifier().registerRSS(SQLSession.getSqlConnector().getSqlWorker().getAllRSSUrls()); - } catch (Exception exception) { - log.error("Error while loading RSS data: " + exception.getMessage()); - Sentry.captureException(exception); - } + try { + // Register all RSS-Feeds. + SQLSession.getSqlConnector().getSqlWorker().getAllRSSUrls().thenAccept(getInstance().getNotifier()::registerRSS); + } catch (Exception exception) { + log.error("Error while loading RSS data: {}", exception.getMessage()); + Sentry.captureException(exception); + } + }); }, t -> Sentry.captureException(t.getCause())); } @@ -586,30 +587,33 @@ public void createCheckerThread() { log.info("[Stats] "); LocalDate yesterday = LocalDate.now().minusDays(1); - Statistics statistics = SQLSession.getSqlConnector().getSqlWorker().getStatistics(yesterday.getDayOfMonth(), yesterday.getMonthValue(), yesterday.getYear()); - JsonObject jsonObject = statistics != null ? statistics.getStatsObject() : new JsonObject(); - JsonObject guildStats = statistics != null && jsonObject.has("guild") ? jsonObject.getAsJsonObject("guild") : new JsonObject(); + SQLSession.getSqlConnector().getSqlWorker().getStatistics(yesterday.getDayOfMonth(), yesterday.getMonthValue(), yesterday.getYear()).thenAccept(statistics -> { + JsonObject jsonObject = statistics != null ? statistics.getStatsObject() : new JsonObject(); + JsonObject guildStats = statistics != null && jsonObject.has("guild") ? jsonObject.getAsJsonObject("guild") : new JsonObject(); - guildStats.addProperty("amount", guildSize); - guildStats.addProperty("users", userSize); + guildStats.addProperty("amount", guildSize); + guildStats.addProperty("users", userSize); - jsonObject.add("guild", guildStats); + jsonObject.add("guild", guildStats); - SQLSession.getSqlConnector().getSqlWorker().updateStatistic(jsonObject); - - Calendar currentCalendar = Calendar.getInstance(); + SQLSession.getSqlConnector().getSqlWorker().updateStatistic(jsonObject); + }); SQLSession.getSqlConnector().getSqlWorker() - .getBirthdays().stream().filter(birthday -> { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(birthday.getBirthdate()); - return calendar.get(Calendar.MONTH) == currentCalendar.get(Calendar.MONTH) && - calendar.get(Calendar.DAY_OF_MONTH) == currentCalendar.get(Calendar.DAY_OF_MONTH); - }).forEach(birthday -> { - TextChannel textChannel = BotWorker.getShardManager().getTextChannelById(birthday.getChannelId()); - - if (textChannel != null && textChannel.canTalk()) - textChannel.sendMessage(LanguageService.getByGuild(textChannel.getGuild(), "message.birthday.wish", birthday.getUserId())).queue(); + .getBirthdays().thenAccept(birthdayWishes -> { + Calendar currentCalendar = Calendar.getInstance(); + + birthdayWishes.stream().filter(birthday -> { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(birthday.getBirthdate()); + return calendar.get(Calendar.MONTH) == currentCalendar.get(Calendar.MONTH) && + calendar.get(Calendar.DAY_OF_MONTH) == currentCalendar.get(Calendar.DAY_OF_MONTH); + }).forEach(birthday -> { + TextChannel textChannel = BotWorker.getShardManager().getTextChannelById(birthday.getChannelId()); + + if (textChannel != null && textChannel.canTalk()) + textChannel.sendMessage(LanguageService.getByGuild(textChannel.getGuild(), "message.birthday.wish", birthday.getUserId())).queue(); + }); }); lastDay = new SimpleDateFormat("dd").format(new Date()); @@ -641,47 +645,49 @@ public void createCheckerThread() { //region Schedules Message sending. try { - for (ScheduledMessage scheduledMessage : SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ScheduledMessage(), "FROM ScheduledMessage", null)) { - if (!scheduledMessage.isRepeated()) { - if (scheduledMessage.getLastExecute() == null) { - if (Timestamp.from(Instant.now()).after(Timestamp.from(scheduledMessage.getCreated().toInstant().plusMillis(scheduledMessage.getDelayAmount())))) { - - WebhookUtil.sendWebhook(new WebhookMessageBuilder() - .setUsername(BotConfig.getBotName() + "-Scheduler") - .setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()) - .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); - + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ScheduledMessage(), "FROM ScheduledMessage", null).thenAccept(messages -> { + for (ScheduledMessage scheduledMessage : messages) { + if (!scheduledMessage.isRepeated()) { + if (scheduledMessage.getLastExecute() == null) { + if (Timestamp.from(Instant.now()).after(Timestamp.from(scheduledMessage.getCreated().toInstant().plusMillis(scheduledMessage.getDelayAmount())))) { + + WebhookUtil.sendWebhook(new WebhookMessageBuilder() + .setUsername(BotConfig.getBotName() + "-Scheduler") + .setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()) + .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); + + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage); + } + } else { SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage); } } else { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage); - } - } else { - if (scheduledMessage.getLastUpdated() == null) { - if (Timestamp.from(Instant.now()).after(Timestamp.from(scheduledMessage.getCreated().toInstant().plusMillis(scheduledMessage.getDelayAmount())))) { + if (scheduledMessage.getLastUpdated() == null) { + if (Timestamp.from(Instant.now()).after(Timestamp.from(scheduledMessage.getCreated().toInstant().plusMillis(scheduledMessage.getDelayAmount())))) { - WebhookUtil.sendWebhook(new WebhookMessageBuilder() - .setUsername(BotConfig.getBotName() + "-Scheduler") - .setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()) - .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); + WebhookUtil.sendWebhook(new WebhookMessageBuilder() + .setUsername(BotConfig.getBotName() + "-Scheduler") + .setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()) + .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); - scheduledMessage.setLastExecute(Timestamp.from(Instant.now())); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage); - } - } else { - if (Timestamp.from(Instant.now()).after(Timestamp.from(scheduledMessage.getLastUpdated().toInstant().plusMillis(scheduledMessage.getDelayAmount())))) { + scheduledMessage.setLastExecute(Timestamp.from(Instant.now())); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage); + } + } else { + if (Timestamp.from(Instant.now()).after(Timestamp.from(scheduledMessage.getLastUpdated().toInstant().plusMillis(scheduledMessage.getDelayAmount())))) { - WebhookUtil.sendWebhook(new WebhookMessageBuilder() - .setUsername(BotConfig.getBotName() + "-Scheduler") - .setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()) - .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); + WebhookUtil.sendWebhook(new WebhookMessageBuilder() + .setUsername(BotConfig.getBotName() + "-Scheduler") + .setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()) + .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); - scheduledMessage.setLastExecute(Timestamp.from(Instant.now())); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage); + scheduledMessage.setLastExecute(Timestamp.from(Instant.now())); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage); + } } } } - } + }); } catch (Exception exception) { log.error("Failed to run scheduled Messages.", exception); Sentry.captureException(exception); @@ -782,22 +788,23 @@ public void createCheckerThread() { if (BotConfig.isModuleActive("notifier")) Main.getInstance().getNotifier().getCredentialManager().load(); - for (TwitchIntegration twitchIntegrations : - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), "FROM TwitchIntegration", null)) { + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), "FROM TwitchIntegration", null).thenAccept(integrations -> { + for (TwitchIntegration twitchIntegrations : integrations) { - CustomOAuth2Credential credential = CustomOAuth2Util.convert(twitchIntegrations); + CustomOAuth2Credential credential = CustomOAuth2Util.convert(twitchIntegrations); - OAuth2Credential originalCredential = new OAuth2Credential("twitch", credential.getAccessToken(), credential.getRefreshToken(), credential.getUserId(), credential.getUserName(), credential.getExpiresIn(), credential.getScopes()); + OAuth2Credential originalCredential = new OAuth2Credential("twitch", credential.getAccessToken(), credential.getRefreshToken(), credential.getUserId(), credential.getUserName(), credential.getExpiresIn(), credential.getScopes()); - if (!Main.getInstance().getNotifier().getTwitchSubscription().containsKey(credential.getUserId())) { - PubSubSubscription[] subscriptions = new PubSubSubscription[3]; - subscriptions[0] = Main.getInstance().getNotifier().getTwitchClient().getPubSub().listenForChannelPointsRedemptionEvents(originalCredential, twitchIntegrations.getChannelId()); - subscriptions[1] = Main.getInstance().getNotifier().getTwitchClient().getPubSub().listenForSubscriptionEvents(originalCredential, twitchIntegrations.getChannelId()); - subscriptions[2] = Main.getInstance().getNotifier().getTwitchClient().getPubSub().listenForFollowingEvents(originalCredential, twitchIntegrations.getChannelId()); + if (!Main.getInstance().getNotifier().getTwitchSubscription().containsKey(credential.getUserId())) { + PubSubSubscription[] subscriptions = new PubSubSubscription[3]; + subscriptions[0] = Main.getInstance().getNotifier().getTwitchClient().getPubSub().listenForChannelPointsRedemptionEvents(originalCredential, twitchIntegrations.getChannelId()); + subscriptions[1] = Main.getInstance().getNotifier().getTwitchClient().getPubSub().listenForSubscriptionEvents(originalCredential, twitchIntegrations.getChannelId()); + subscriptions[2] = Main.getInstance().getNotifier().getTwitchClient().getPubSub().listenForFollowingEvents(originalCredential, twitchIntegrations.getChannelId()); - Main.getInstance().getNotifier().getTwitchSubscription().put(credential.getUserId(), subscriptions); + Main.getInstance().getNotifier().getTwitchSubscription().put(credential.getUserId(), subscriptions); + } } - } + }); } catch (Exception exception) { log.error("Failed to load Twitch Credentials.", exception); Sentry.captureException(exception); From 7f19271d194522756bc4b9d0d716812461f95f14 Mon Sep 17 00:00:00 2001 From: Presti Date: Tue, 21 May 2024 11:04:53 +0200 Subject: [PATCH 10/94] Fix formatting and stuff. --- .../de/presti/ree6/events/OtherEvents.java | 43 ++++++++++--------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/src/main/java/de/presti/ree6/events/OtherEvents.java b/src/main/java/de/presti/ree6/events/OtherEvents.java index 37b5cbaab..5ce7540c9 100644 --- a/src/main/java/de/presti/ree6/events/OtherEvents.java +++ b/src/main/java/de/presti/ree6/events/OtherEvents.java @@ -341,31 +341,31 @@ public void onGuildVoiceUpdate(@Nonnull GuildVoiceUpdateEvent event) { if (BotConfig.isModuleActive("temporalvoice")) { if (checkChannel(event.getChannelLeft(), event.getJDA())) return; - SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getId())) - .thenAccept(temporalVoicechannel -> { - if (temporalVoicechannel != null) { - VoiceChannel voiceChannel = event.getGuild().getVoiceChannelById(event.getChannelJoined().getId()); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getId())) + .thenAccept(temporalVoicechannel -> { + if (temporalVoicechannel != null) { + VoiceChannel voiceChannel = event.getGuild().getVoiceChannelById(event.getChannelJoined().getId()); - if (voiceChannel == null) - return; + if (voiceChannel == null) + return; - if (temporalVoicechannel.getGuildChannelId().getChannelId() != voiceChannel.getIdLong()) { - return; - } + if (temporalVoicechannel.getGuildChannelId().getChannelId() != voiceChannel.getIdLong()) { + return; + } - if (voiceChannel.getParentCategory() != null) { - String preName = LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", "SPLIT"); - preName = preName.split("SPLIT")[0]; + if (voiceChannel.getParentCategory() != null) { + String preName = LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", "SPLIT"); + preName = preName.split("SPLIT")[0]; - String finalPreName = preName; - voiceChannel.getParentCategory().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", - event.getGuild().getVoiceChannels().stream().filter(c -> c.getName().startsWith(finalPreName)).count() + 1)).queue(channel -> { - event.getGuild().moveVoiceMember(event.getMember(), channel).queue(); - ArrayUtil.temporalVoicechannel.add(channel.getId()); - }); + String finalPreName = preName; + voiceChannel.getParentCategory().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", + event.getGuild().getVoiceChannels().stream().filter(c -> c.getName().startsWith(finalPreName)).count() + 1)).queue(channel -> { + event.getGuild().moveVoiceMember(event.getMember(), channel).queue(); + ArrayUtil.temporalVoicechannel.add(channel.getId()); + }); + } } - } - }); + }); } } } @@ -421,6 +421,7 @@ public void onGenericGuildVoice(@NotNull GenericGuildVoiceEvent event) { /** * Method used to do all the calculations for the Voice XP. + * * @param member the Member that should be checked. */ public void doVoiceXPStuff(Member member) { @@ -645,7 +646,7 @@ public void onMessageReactionRemove(@NotNull MessageReactionRemoveEvent event) { emojiId = reactionCode.replace(":", "").hashCode(); } - ReactionRole reactionRole = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ReactionRole(), + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ReactionRole(), "FROM ReactionRole WHERE guildRoleId.guildId=:gid AND emoteId=:emoteId AND messageId=:messageId", Map.of("gid", event.getGuild().getIdLong(), "emoteId", emojiId, "messageId", event.getMessageIdLong())).thenAccept(reactionRole -> { if (reactionRole != null) { From 0782ba7ea3071d3784ccc925bc473602f69177b2 Mon Sep 17 00:00:00 2001 From: Presti Date: Tue, 21 May 2024 11:55:00 +0200 Subject: [PATCH 11/94] ASYNC LANGUAGES YEEEEEEEAH BABY Update to the latest SQL version and asynced the LanguageService class. --- pom.xml | 2 +- .../presti/ree6/language/LanguageService.java | 61 ++++++++++--------- 2 files changed, 33 insertions(+), 30 deletions(-) diff --git a/pom.xml b/pom.xml index 2d7032015..3d78c4e40 100644 --- a/pom.xml +++ b/pom.xml @@ -166,7 +166,7 @@ de.ree6 Ree6-SQL - 17d32f2afd + 8d0581e75e diff --git a/src/main/java/de/presti/ree6/language/LanguageService.java b/src/main/java/de/presti/ree6/language/LanguageService.java index 5c3fc9e13..be72d2dec 100644 --- a/src/main/java/de/presti/ree6/language/LanguageService.java +++ b/src/main/java/de/presti/ree6/language/LanguageService.java @@ -25,6 +25,7 @@ import java.util.HashMap; import java.util.Objects; import java.util.Set; +import java.util.concurrent.CompletableFuture; /** * Utility used to work with Languages. @@ -163,7 +164,7 @@ public static void downloadLanguages() { * @param parameter the parameter to replace. * @return the String. */ - public static @NotNull String getByEvent(@NotNull CommandEvent commandEvent, @NotNull String key, @Nullable Object... parameter) { + public static @NotNull CompletableFuture getByEvent(@NotNull CommandEvent commandEvent, @NotNull String key, @Nullable Object... parameter) { if (commandEvent.isSlashCommand()) { return getByInteraction(commandEvent.getInteractionHook().getInteraction(), key, parameter); } else { @@ -179,7 +180,7 @@ public static void downloadLanguages() { * @param parameter the parameter to replace. * @return the String. */ - public static @NotNull String getByEvent(@NotNull GenericGuildEvent commandEvent, @NotNull String key, @Nullable Object... parameter) { + public static @NotNull CompletableFuture getByEvent(@NotNull GenericGuildEvent commandEvent, @NotNull String key, @Nullable Object... parameter) { return getByGuild(commandEvent.getGuild(), key, parameter); } @@ -192,7 +193,7 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull String getByGuildOrInteractionHook(Guild guild, InteractionHook interaction, @NotNull String key, @Nullable Object... parameter) { + public static @NotNull CompletableFuture getByGuildOrInteractionHook(Guild guild, InteractionHook interaction, @NotNull String key, @Nullable Object... parameter) { return getByGuildOrInteraction(guild, interaction != null ? interaction.getInteraction() : null, key, parameter); } @@ -206,7 +207,7 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull String getByGuildOrInteraction(Guild guild, Interaction interaction, @NotNull String key, @Nullable Object... parameter) { + public static @NotNull CompletableFuture getByGuildOrInteraction(Guild guild, Interaction interaction, @NotNull String key, @Nullable Object... parameter) { if (interaction != null) { return getByInteraction(interaction, key, parameter); } else { @@ -222,7 +223,7 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull String getByGuild(Guild guild, @NotNull String key, @Nullable Object... parameter) { + public static @NotNull CompletableFuture getByGuild(Guild guild, @NotNull String key, @Nullable Object... parameter) { return getByGuild(guild != null ? guild.getIdLong() : -1, key, parameter); } @@ -234,20 +235,15 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull String getByGuild(long guildId, @NotNull String key, @Nullable Object... parameter) { - String resource; + public static @NotNull CompletableFuture getByGuild(long guildId, @NotNull String key, @Nullable Object... parameter) { if (guildId == -1) { - resource = getDefault(key, parameter); - } else { - resource = getByLocale(SQLSession.getSqlConnector().getSqlWorker().getSetting(guildId, "configuration_language").getStringValue(), key, parameter); - } - - if (guildId != -1 && resource.contains("{guild_prefix}")) { - resource = resource - .replace("{guild_prefix}", SQLSession.getSqlConnector().getSqlWorker().getSetting(guildId, "chatprefix").getStringValue()); + return getDefault(key, parameter); } - return resource; + return SQLSession.getSqlConnector().getSqlWorker().getSetting(guildId, "configuration_language") + .thenApply(setting -> getByLocale(setting.getStringValue(), key, parameter).join()) + .thenApply(resource -> SQLSession.getSqlConnector().getSqlWorker().getSetting(guildId, "chatprefix"). + thenApply(prefix -> resource.replace("{guild_prefix}", prefix.getStringValue())).join()); } /** @@ -258,14 +254,19 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull String getByInteraction(Interaction interaction, @NotNull String key, @Nullable Object... parameter) { - String resource = getByLocale(interaction.getUserLocale(), key, parameter); + public static @NotNull CompletableFuture getByInteraction(Interaction interaction, @NotNull String key, @Nullable Object... parameter) { + if (!interaction.isFromGuild()) { + return getByLocale(interaction.getUserLocale(), key, parameter); + } - if (interaction.getGuild() != null && resource.contains("{guild_prefix}")) - resource = resource - .replace("{guild_prefix}", SQLSession.getSqlConnector().getSqlWorker().getSetting(interaction.getGuild().getIdLong(), "chatprefix").getStringValue()); + return getByLocale(interaction.getUserLocale(), key, parameter).thenApply(resource -> { + if (resource.contains("{guild_prefix}")) { + return SQLSession.getSqlConnector().getSqlWorker().getSetting(interaction.getGuild().getIdLong(), "chatprefix") + .thenApply(prefix -> resource.replace("{guild_prefix}", prefix.getStringValue())).join(); + } - return resource; + return resource; + }); } /** @@ -275,7 +276,7 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull String getDefault(@NotNull String key, @Nullable Object... parameter) { + public static @NotNull CompletableFuture getDefault(@NotNull String key, @Nullable Object... parameter) { return getByLocale(DiscordLocale.from(BotConfig.getDefaultLanguage()), key, parameter); } @@ -287,7 +288,7 @@ public static void downloadLanguages() { * @param parameters The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull String getByLocale(@NotNull String locale, @NotNull String key, @Nullable Object... parameters) { + public static @NotNull CompletableFuture getByLocale(@NotNull String locale, @NotNull String key, @Nullable Object... parameters) { return getByLocale(DiscordLocale.from(locale), key, parameters); } @@ -299,13 +300,15 @@ public static void downloadLanguages() { * @param parameters The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull String getByLocale(@NotNull DiscordLocale discordLocale, @NotNull String key, @Nullable Object... parameters) { - if (discordLocale == DiscordLocale.UNKNOWN) return getDefault(key, parameters); + public static @NotNull CompletableFuture getByLocale(@NotNull DiscordLocale discordLocale, @NotNull String key, @Nullable Object... parameters) { + return CompletableFuture.supplyAsync(() -> { + if (discordLocale == DiscordLocale.UNKNOWN) return getDefault(key, parameters).join(); - Language language = languageResources.containsKey(discordLocale) ? languageResources.get(discordLocale) : - languageResources.get(DiscordLocale.from(BotConfig.getDefaultLanguage())); + Language language = languageResources.containsKey(discordLocale) ? languageResources.get(discordLocale) : + languageResources.get(DiscordLocale.from(BotConfig.getDefaultLanguage())); - return language != null ? language.getResource(key, parameters) : "Missing language resource!"; + return language != null ? language.getResource(key, parameters) : "Missing language resource!"; + }); } /** From abcd7eee5cf7a075a6ee05f22e983ebf52c9f9fb Mon Sep 17 00:00:00 2001 From: Presti Date: Tue, 21 May 2024 13:07:48 +0200 Subject: [PATCH 12/94] Fixing a few things that occurred during an old refactor. --- .../ree6/audio/AudioPlayerReceiveHandler.java | 70 +++++++++++-------- .../presti/ree6/audio/music/MusicWorker.java | 41 +++++------ .../ree6/audio/music/TrackScheduler.java | 41 +++++------ .../de/presti/ree6/commands/CommandEvent.java | 2 +- .../presti/ree6/commands/CommandManager.java | 60 ++++++++-------- .../commands/impl/community/Birthday.java | 2 +- .../commands/impl/community/Giveaway.java | 2 +- .../commands/impl/community/Reactions.java | 4 +- .../impl/community/StreamActionCommand.java | 23 +++++- .../ree6/commands/impl/community/Ticket.java | 8 +-- .../presti/ree6/commands/impl/fun/Anime.java | 2 +- .../presti/ree6/commands/impl/fun/Cringe.java | 2 +- .../presti/ree6/commands/impl/fun/Game.java | 6 +- .../ree6/commands/impl/fun/HornyJail.java | 3 +- .../de/presti/ree6/commands/impl/fun/Hug.java | 3 +- .../presti/ree6/commands/impl/fun/Kiss.java | 2 +- .../presti/ree6/commands/impl/fun/Manga.java | 2 +- .../presti/ree6/commands/impl/fun/Slap.java | 2 +- .../ree6/commands/impl/fun/Twitter.java | 2 +- .../commands/impl/hidden/Announcement.java | 2 +- .../ree6/commands/impl/info/Avatar.java | 2 +- .../presti/ree6/commands/impl/info/Help.java | 2 +- .../presti/ree6/commands/impl/info/Info.java | 2 +- .../ree6/commands/impl/level/Level.java | 3 +- .../ree6/commands/impl/level/LevelRole.java | 2 +- .../de/presti/ree6/commands/impl/mod/Ban.java | 2 +- .../presti/ree6/commands/impl/mod/Clear.java | 2 +- .../ree6/commands/impl/mod/EmbedSender.java | 2 +- .../presti/ree6/commands/impl/mod/Import.java | 3 +- .../presti/ree6/commands/impl/mod/Kick.java | 2 +- .../presti/ree6/commands/impl/mod/Mute.java | 2 +- .../presti/ree6/commands/impl/mod/Prefix.java | 2 +- .../presti/ree6/commands/impl/mod/Setup.java | 6 +- .../ree6/commands/impl/mod/Suggestion.java | 2 +- .../presti/ree6/commands/impl/mod/Unban.java | 2 +- .../presti/ree6/commands/impl/mod/Unmute.java | 2 +- .../presti/ree6/commands/impl/music/Play.java | 3 +- .../presti/ree6/commands/impl/music/Seek.java | 3 +- .../presti/ree6/commands/impl/music/Skip.java | 3 +- .../ree6/commands/impl/music/Volume.java | 3 +- .../ree6/commands/impl/nsfw/Rule34.java | 2 +- .../ree6/game/impl/blackjack/Blackjack.java | 58 +++++++-------- .../de/presti/ree6/utils/data/RegExUtil.java | 8 ++- 43 files changed, 223 insertions(+), 174 deletions(-) diff --git a/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java b/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java index 94a8509d9..46d24047b 100644 --- a/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java +++ b/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java @@ -68,39 +68,46 @@ public class AudioPlayerReceiveHandler implements AudioReceiveHandler { /** * The first sent message which should be edited. */ + // TODO:: make this async one day, and thread safe. Message message; /** * Constructor. * - * @param member The member who started the recording. + * @param member The member who started the recording. * @param audioChannelUnion The voice channel this handler should handle. */ public AudioPlayerReceiveHandler(Member member, AudioChannelUnion audioChannelUnion) { this.creatorId = member.getIdLong(); this.audioChannelUnion = audioChannelUnion; if (audioChannelUnion.getGuild().getSelfMember().hasPermission(Permission.NICKNAME_CHANGE)) { - audioChannelUnion.getGuild().getSelfMember().modifyNickname(LanguageService.getByGuild(member.getGuild(), "label.recording.name")).reason(LanguageService.getByGuild(member.getGuild(), "message.recording.startReason", member.getUser().getName())).onErrorMap(throwable -> { - - boolean canTalk = audioChannelUnion.getType() == ChannelType.STAGE ? - audioChannelUnion.asStageChannel().canTalk() : - audioChannelUnion.asVoiceChannel().canTalk(); - - if (canTalk) audioChannelUnion.asGuildMessageChannel().sendMessage(LanguageService.getByGuild(member.getGuild(), "message.default.nameChangeFailed")).queue(); - return null; - }).queue(); + LanguageService.getByGuild(member.getGuild(), "label.recording.name").thenAccept(name -> + LanguageService.getByGuild(member.getGuild(), "message.recording.startReason", member.getUser().getName()).thenAccept(reason -> + audioChannelUnion.getGuild().getSelfMember().modifyNickname(name).reason(reason).onErrorMap(throwable -> { + + boolean canTalk = audioChannelUnion.getType() == ChannelType.STAGE ? + audioChannelUnion.asStageChannel().canTalk() : + audioChannelUnion.asVoiceChannel().canTalk(); + + if (canTalk) { + LanguageService.getByGuild(member.getGuild(), "message.default.nameChangeFailed").thenAccept(message -> { + audioChannelUnion.asGuildMessageChannel().sendMessage(message).queue(); + }); + } + return null; + }).queue())); } message = audioChannelUnion.asGuildMessageChannel().sendMessageEmbeds(new EmbedBuilder() - .setDescription(LanguageService.getByGuild(member.getGuild(), "message.recording.started")) + .setDescription(LanguageService.getByGuild(member.getGuild(), "message.recording.started").join()) .setColor(Color.YELLOW) - .setFooter(LanguageService.getByGuild(member.getGuild(),"label.footerMessage", member.getEffectiveName(), BotConfig.getAdvertisement()), member.getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(member.getGuild(), "label.recording.start")) + .setFooter(LanguageService.getByGuild(member.getGuild(), "label.footerMessage", member.getEffectiveName(), BotConfig.getAdvertisement()).join(), member.getEffectiveAvatarUrl()) + .setTitle(LanguageService.getByGuild(member.getGuild(), "label.recording.start").join()) .build()).complete(); if (audioChannelUnion.getGuild().getSelfMember().hasPermission(Permission.VOICE_SET_STATUS)) { if (audioChannelUnion.getType() == ChannelType.VOICE) { - audioChannelUnion.asVoiceChannel().modifyStatus(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.recording.name")).queue(); + audioChannelUnion.asVoiceChannel().modifyStatus(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.recording.name").join()).queue(); } } } @@ -166,11 +173,14 @@ public void endReceiving() { audioChannelUnion.asVoiceChannel().canTalk(); if (audioChannelUnion.getGuild().getSelfMember().hasPermission(Permission.NICKNAME_CHANGE)) { - audioChannelUnion.getGuild().getSelfMember().modifyNickname(audioChannelUnion.getGuild().getSelfMember().getUser().getName()).reason(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.stopReason")).onErrorMap(throwable -> { - - if (canTalk) audioChannelUnion.asGuildMessageChannel().sendMessage(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.default.nameChangeFailed")).queue(); - return null; - }).queue(); + LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.stopReason").thenAccept(reason -> + audioChannelUnion.getGuild().getSelfMember().modifyNickname(audioChannelUnion.getGuild().getSelfMember().getUser().getName()).reason(reason).onErrorMap(throwable -> { + + if (canTalk) + LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.default.nameChangeFailed") + .thenAccept(message -> audioChannelUnion.asGuildMessageChannel().sendMessage(message).queue()); + return null; + }).queue()); } try { @@ -193,19 +203,19 @@ public void endReceiving() { if (canTalk) { message.editMessageEmbeds(new EmbedBuilder() - .setDescription(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.stopped")) - .setColor(Color.GREEN) - .setFooter(BotConfig.getAdvertisement(), audioChannelUnion.getGuild().getIconUrl()) - .setTitle(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.recording.finished")) - .build()) + .setDescription(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.stopped").join()) + .setColor(Color.GREEN) + .setFooter(BotConfig.getAdvertisement(), audioChannelUnion.getGuild().getIconUrl()) + .setTitle(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.recording.finished").join()) + .build()) .setActionRow( - new ButtonImpl("ree6RedirectButton", LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.download"), ButtonStyle.LINK, - BotConfig.getRecordingUrl() + "?id=" + recording.getIdentifier(), failedToUpload, Emoji.fromCustom("shiba", 941219375535509504L, true)), + new ButtonImpl("ree6RedirectButton", LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.download").join(), ButtonStyle.LINK, + BotConfig.getRecordingUrl() + "?id=" + recording.getIdentifier(), failedToUpload, Emoji.fromCustom("shiba", 941219375535509504L, true)), Button.primary("r_recordingDownload:" + recording.getIdentifier(), Emoji.fromCustom("sip", 1011956355810209852L, false)) - .withLabel(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.sendToChat")).withDisabled(!BotConfig.allowRecordingInChat() || failedToUpload)).complete(); + .withLabel(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.sendToChat").join()).withDisabled(!BotConfig.allowRecordingInChat() || failedToUpload)).complete(); if (failedToUpload) { - audioChannelUnion.asGuildMessageChannel().sendMessage(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.error", "Upload failed")).setFiles(FileUpload.fromData(recording.getRecording(), "recording.wav")); + audioChannelUnion.asGuildMessageChannel().sendMessage(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.error", "Upload failed").join()).setFiles(FileUpload.fromData(recording.getRecording(), "recording.wav")); } } // Find a way to still notify that the bot couldn't send the audio. @@ -213,10 +223,10 @@ public void endReceiving() { if (canTalk) { message.editMessageEmbeds(new EmbedBuilder() - .setDescription(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.error", ex.getMessage())) + .setDescription(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.error", ex.getMessage()).join()) .setColor(Color.RED) .setFooter(BotConfig.getAdvertisement(), audioChannelUnion.getGuild().getIconUrl()) - .setTitle(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.error")) + .setTitle(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.error").join()) .build()).complete(); } diff --git a/src/main/java/de/presti/ree6/audio/music/MusicWorker.java b/src/main/java/de/presti/ree6/audio/music/MusicWorker.java index 7b369e39a..dd7f3c8f4 100644 --- a/src/main/java/de/presti/ree6/audio/music/MusicWorker.java +++ b/src/main/java/de/presti/ree6/audio/music/MusicWorker.java @@ -47,6 +47,7 @@ /** * Wrapper class that handles most Music-related stuff. */ +// TODO:: async all these messages. @Slf4j public class MusicWorker { @@ -185,10 +186,10 @@ public void loadAndPlay(final Guild guild, GuildMessageChannelUnion channel, Aud Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").join()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guild, "message.music.notPlaying")) + .setDescription(LanguageService.getByGuild(guild, "message.music.notPlaying").join()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()) , channel, interactionHook); return; @@ -209,10 +210,10 @@ public void trackLoaded(AudioTrack track) { if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").join()) .setImage((track.getInfo().artworkUrl != null && track.getInfo().artworkUrl.isBlank()) ? guild.getJDA().getSelfUser().getEffectiveAvatarUrl() : track.getInfo().artworkUrl) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guild, "message.music.queueAdded.default", FormatUtil.filter(track.getInfo().title))) + .setDescription(LanguageService.getByGuild(guild, "message.music.queueAdded.default", FormatUtil.filter(track.getInfo().title)).join()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()), 5, messageChannel, interactionHook); play(finalAudioChannel, musicManager, track, force); @@ -234,10 +235,10 @@ public void playlistLoaded(AudioPlaylist playlist) { if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").join()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guild, "message.music.queueAdded.firstOfList", FormatUtil.filter(firstTrack.getInfo().title), FormatUtil.filter(playlist.getName()))) + .setDescription(LanguageService.getByGuild(guild, "message.music.queueAdded.firstOfList", FormatUtil.filter(firstTrack.getInfo().title), FormatUtil.filter(playlist.getName())).join()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()), 5, messageChannel, interactionHook); play(finalAudioChannel, musicManager, firstTrack, force); @@ -259,10 +260,10 @@ public void noMatches() { if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").join()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guild, "message.music.searchUrlFailed", FormatUtil.filter(trackUrl))) + .setDescription(LanguageService.getByGuild(guild, "message.music.searchUrlFailed", FormatUtil.filter(trackUrl)).join()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()), 5, messageChannel, interactionHook); } @@ -276,10 +277,10 @@ public void loadFailed(FriendlyException exception) { if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").join()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guild, "message.music.failedLoading", exception.getMessage())) + .setDescription(LanguageService.getByGuild(guild, "message.music.failedLoading", exception.getMessage()).join()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()), 5, messageChannel, interactionHook); } }); @@ -369,10 +370,10 @@ public void playSong(String value, Guild guild, Member member, GuildMessageChann EmbedBuilder em = new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer")) + .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").join()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFound", value)) + .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFound", value).join()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, 5, channel, interactionHook); return; @@ -406,10 +407,10 @@ public void playSong(String value, Guild guild, Member member, GuildMessageChann EmbedBuilder em = new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer")) + .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").join()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFoundMultiple", loadFailed.size())) + .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFoundMultiple", loadFailed.size()).join()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, 5, channel, interactionHook); } @@ -422,10 +423,10 @@ public void playSong(String value, Guild guild, Member member, GuildMessageChann } catch (Exception exception) { EmbedBuilder em = new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer")) + .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").join()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.searchFailed")) + .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.searchFailed").join()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, 5, channel, interactionHook); log.error("Error while searching for " + value + " on YouTube", exception); @@ -435,10 +436,10 @@ public void playSong(String value, Guild guild, Member member, GuildMessageChann if (ytResult == null) { EmbedBuilder em = new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer")) + .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").join()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.YELLOW) - .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFound", FormatUtil.filter(value))) + .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFound", FormatUtil.filter(value)).join()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, 5, channel, interactionHook); } else { @@ -469,10 +470,10 @@ public void skipTrack(GuildMessageChannelUnion channel, InteractionHook interact public void skipTrack(GuildMessageChannelUnion channel, InteractionHook interactionHook, int skipAmount, boolean silent) { if (!silent) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder().setAuthor(channel.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), channel.getJDA().getSelfUser().getAvatarUrl()) - .setTitle(LanguageService.getByGuild(channel.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(channel.getGuild(), "label.musicPlayer").join()) .setThumbnail(channel.getJDA().getSelfUser().getAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(channel.getGuild(), "message.music.skip")) + .setDescription(LanguageService.getByGuild(channel.getGuild(), "message.music.skip").join()) .setFooter(channel.getGuild().getName() + " - " + BotConfig.getAdvertisement(), channel.getGuild().getIconUrl()), 5, channel, interactionHook); } diff --git a/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java b/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java index f09272014..6426fefbc 100644 --- a/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java +++ b/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java @@ -29,6 +29,7 @@ * This class schedules tracks for the audio player. It contains the queue of * tracks. */ +// TODO:: async all these messages. @Slf4j @SuppressWarnings("ALL") public class TrackScheduler extends AudioEventAdapterWrapped { @@ -177,10 +178,10 @@ public void nextTrack(GuildMessageChannelUnion textChannel, int position, boolea if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.songNext", FormatUtil.filter(track.getInfo().title))) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.songNext", FormatUtil.filter(track.getInfo().title)).join()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); Main.getInstance().getEventBus().post(new MusicPlayerStateChangeEvent(guildMusicManager.getGuild(), MusicPlayerStateChangeEvent.State.PLAYING, track)); @@ -189,10 +190,10 @@ public void nextTrack(GuildMessageChannelUnion textChannel, int position, boolea if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.songQueueReachedEnd")) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.songQueueReachedEnd").join()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); Main.getInstance().getEventBus().post(new MusicPlayerStateChangeEvent(guildMusicManager.getGuild(), MusicPlayerStateChangeEvent.State.QUEUE_EMPTY, null)); @@ -209,10 +210,10 @@ public void seekPosition(GuildMessageChannelUnion channel, int seekAmountInSecon if (player.getPlayingTrack() == null) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.notPlaying")) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.notPlaying").join()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); return; } @@ -220,10 +221,10 @@ public void seekPosition(GuildMessageChannelUnion channel, int seekAmountInSecon if (player.getPlayingTrack().getPosition() / 1000 + seekAmountInSeconds > player.getPlayingTrack().getDuration() / 1000) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.seek.failed")) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.seek.failed").join()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); return; } @@ -237,10 +238,10 @@ public void seekPosition(GuildMessageChannelUnion channel, int seekAmountInSecon Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.seek.success", FormatUtil.formatTime(player.getPlayingTrack().getPosition()))) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.seek.success", FormatUtil.formatTime(player.getPlayingTrack().getPosition())).join()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); } @@ -276,10 +277,10 @@ public void onTrackEnd(IPlayer player, AudioTrack track, AudioTrackEndReason end if (getChannel() != null) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), "Track does not exist (Internally?)")) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), "Track does not exist (Internally?)").join()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); } @@ -292,10 +293,10 @@ public void onTrackEnd(IPlayer player, AudioTrack track, AudioTrackEndReason end if (getChannel() != null) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), endReason.name())) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), endReason.name()).join()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); } @@ -313,10 +314,10 @@ public void onTrackEnd(IPlayer player, AudioTrack track, AudioTrackEndReason end Main.getInstance().getEventBus().post(new MusicPlayerStateChangeEvent(guildMusicManager.getGuild(), MusicPlayerStateChangeEvent.State.ERROR, null)); Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), endReason.name())) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), endReason.name()).join()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); } nextTrack(getChannel(), track.getSourceManager() instanceof LocalAudioSourceManager); @@ -341,16 +342,16 @@ public void stopAll(InteractionHook interactionHook) { Main.getInstance().getMusicWorker().disconnect(guildMusicManager.getGuild()); em.setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()); - em.setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")); + em.setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()); em.setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()); em.setColor(Color.GREEN); - em.setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.stop")); + em.setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.stop").join()); } else { em.setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()); - em.setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer")); + em.setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()); em.setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()); em.setColor(Color.RED); - em.setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.notPlaying")); + em.setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.notPlaying").join()); } em.setFooter(BotConfig.getAdvertisement()); diff --git a/src/main/java/de/presti/ree6/commands/CommandEvent.java b/src/main/java/de/presti/ree6/commands/CommandEvent.java index 6c0118114..d5acd0ae6 100644 --- a/src/main/java/de/presti/ree6/commands/CommandEvent.java +++ b/src/main/java/de/presti/ree6/commands/CommandEvent.java @@ -183,7 +183,7 @@ public void setEphemeral(boolean ephemeral) { * @return the Message. */ public String getResource(String key, Object... parameters) { - return LanguageService.getByEvent(this, key, parameters); + return LanguageService.getByEvent(this, key, parameters).join(); } /** diff --git a/src/main/java/de/presti/ree6/commands/CommandManager.java b/src/main/java/de/presti/ree6/commands/CommandManager.java index 303062ffb..cf70c85d0 100644 --- a/src/main/java/de/presti/ree6/commands/CommandManager.java +++ b/src/main/java/de/presti/ree6/commands/CommandManager.java @@ -1,5 +1,6 @@ package de.presti.ree6.commands; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.exceptions.CommandInitializerException; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; @@ -10,7 +11,7 @@ import de.presti.ree6.sql.entities.custom.CustomCommand; import de.presti.ree6.sql.util.SettingsManager; import de.presti.ree6.utils.data.ArrayUtil; -import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.utils.data.RegExUtil; import de.presti.ree6.utils.others.ThreadUtil; import lombok.AccessLevel; import lombok.Getter; @@ -24,7 +25,6 @@ import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel; import net.dv8tion.jda.api.entities.channel.unions.GuildMessageChannelUnion; -import net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.DiscordLocale; import net.dv8tion.jda.api.interactions.InteractionHook; @@ -211,33 +211,35 @@ public void addSlashCommand(JDA jda) { if (commandData instanceof CommandDataImpl commandData1) { + boolean isValidDescription = commandAnnotation.description().matches(RegExUtil.ALLOWED_LANGUAGE_PATHS); + for (DiscordLocale discordLocale : DiscordLocale.values()) { if (!LanguageService.languageResources.containsKey(discordLocale)) continue; - if (commandAnnotation.description().endsWith(".") || !commandAnnotation.description().contains(".")) + if (!isValidDescription) continue; - String description = LanguageService.getByLocale(discordLocale, commandAnnotation.description()); + String localizedDescription = LanguageService.getByLocale(discordLocale, commandAnnotation.description()).join(); - if (description.equals("Missing language resource!")) { - description = LanguageService.getDefault(commandAnnotation.description()); + if (localizedDescription.equals("Missing language resource!")) { + localizedDescription = LanguageService.getDefault(commandAnnotation.description()).join(); } - if (!description.equals("Missing language resource!")) { - commandData1.setDescriptionLocalization(discordLocale, description); + if (!localizedDescription.equals("Missing language resource!")) { + commandData1.setDescriptionLocalization(discordLocale, localizedDescription); } commandData1.getSubcommandGroups().forEach(subcommandGroupData -> translateSubgroups(subcommandGroupData, discordLocale)); } - String description = LanguageService.getDefault(commandAnnotation.description()); + if (isValidDescription) { + String localizedDescription = LanguageService.getDefault(commandAnnotation.description()).join(); - if (!description.equals("Missing language resource!")) { - commandData1.setDescription(description); + if (!localizedDescription.equals("Missing language resource!")) { + commandData1.setDescription(localizedDescription); + } } - // TODO:: add the same language check to option names/description and add a translation to it. Also for the love of god Imma need to optimize this. - if (commandAnnotation.category() == Category.MOD && commandData.getDefaultPermissions() == DefaultMemberPermissions.ENABLED) { commandData1.setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.ADMINISTRATOR)); } @@ -262,13 +264,15 @@ public void addSlashCommand(JDA jda) { } public void translateSubgroups(SubcommandGroupData subcommandGroupData, DiscordLocale locale) { + // TODO:: add the same language check to option names/description and add a translation to it. + // Also for the love of god Imma need to optimize this. String groupDescription = subcommandGroupData.getDescription(); - if (groupDescription.contains(".") && !groupDescription.endsWith(".")) { - groupDescription = LanguageService.getByLocale(locale, groupDescription); + if (groupDescription.matches(RegExUtil.ALLOWED_LANGUAGE_PATHS)) { + groupDescription = LanguageService.getByLocale(locale, groupDescription).join(); if (groupDescription.equals("Missing language resource!")) { - groupDescription = LanguageService.getDefault(subcommandGroupData.getDescription()); + groupDescription = LanguageService.getDefault(subcommandGroupData.getDescription()).join(); } if (!groupDescription.equals("Missing language resource!")) { @@ -279,11 +283,11 @@ public void translateSubgroups(SubcommandGroupData subcommandGroupData, DiscordL for (SubcommandData subcommandData : subcommandGroupData.getSubcommands()) { String commandDescription = subcommandData.getDescription(); - if (commandDescription.contains(".") && !commandDescription.endsWith(".")) { - commandDescription = LanguageService.getByLocale(locale, commandDescription); + if (groupDescription.matches(RegExUtil.ALLOWED_LANGUAGE_PATHS)) { + commandDescription = LanguageService.getByLocale(locale, commandDescription).join(); if (commandDescription.equals("Missing language resource!")) { - commandDescription = LanguageService.getDefault(subcommandData.getDescription()); + commandDescription = LanguageService.getDefault(subcommandData.getDescription()).join(); } if (!commandDescription.equals("Missing language resource!")) { @@ -366,12 +370,12 @@ public CompletableFuture perform(Member member, Guild guild, String mes // Check if it is a Slash Command or not. if (isSlashCommand) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.cooldown"), 5, messageChannel, slashCommandInteractionEvent.getHook().setEphemeral(true)); + sendMessage(LanguageService.getByGuild(guild, "command.perform.cooldown").join(), 5, messageChannel, slashCommandInteractionEvent.getHook().setEphemeral(true)); deleteMessage(message, slashCommandInteractionEvent.getHook().setEphemeral(true)); } else { SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").thenAccept(setting -> { if (setting != null && messageContent.toLowerCase().startsWith(setting.getStringValue().toLowerCase())) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.cooldown"), 5, messageChannel, null); + sendMessage(LanguageService.getByGuild(guild, "command.perform.cooldown").join(), 5, messageChannel, null); deleteMessage(message, null); } }); @@ -416,7 +420,7 @@ public void timeoutUser(User user) { private CompletableFuture performMessageCommand(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion textChannel) { // Check if the Message is null. if (message == null) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.error"), 5, textChannel, null); + sendMessage(LanguageService.getByGuild(guild, "command.perform.error").join(), 5, textChannel, null); return CompletableFuture.completedFuture(false); } @@ -432,7 +436,7 @@ private CompletableFuture performMessageCommand(Member member, Guild gu String[] arguments = messageContent.substring(currentPrefix.length()).split("\\s+"); if (arguments.length == 0 || arguments[0].isBlank()) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.missingCommand"), 5, textChannel, null); + sendMessage(LanguageService.getByGuild(guild, "command.perform.missingCommand").join(), 5, textChannel, null); return false; } @@ -461,10 +465,10 @@ private CompletableFuture performMessageCommand(Member member, Guild gu return true; } - sendMessage(LanguageService.getByGuild(guild, "command.perform.notFound"), 5, textChannel, null); + sendMessage(LanguageService.getByGuild(guild, "command.perform.notFound").join(), 5, textChannel, null); return false; } else if (command == null) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.notFound"), 5, textChannel, null); + sendMessage(LanguageService.getByGuild(guild, "command.perform.notFound").join(), 5, textChannel, null); return false; } @@ -473,7 +477,7 @@ private CompletableFuture performMessageCommand(Member member, Guild gu // Check if the Command is blacklisted. if (blacklistSetting != null && !blacklistSetting.getBooleanValue()) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.blocked"), 5, textChannel, null); + sendMessage(LanguageService.getByGuild(guild, "command.perform.blocked").join(), 5, textChannel, null); return false; } } @@ -501,13 +505,13 @@ private CompletableFuture performSlashCommand(GuildMessageChannelUnion // Check if there is a command with that Name. if (command == null || slashCommandInteractionEvent.getGuild() == null || slashCommandInteractionEvent.getMember() == null) { - sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.notFound"), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); + sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.notFound").join(), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); return CompletableFuture.completedFuture(false); } return SQLSession.getSqlConnector().getSqlWorker().getSetting(slashCommandInteractionEvent.getGuild().getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()).thenApply(setting -> { if (command.getClass().getAnnotation(Command.class).category() != Category.HIDDEN && setting != null && !setting.getBooleanValue()) { - sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.blocked"), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); + sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.blocked").join(), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); return false; } diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java b/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java index 92fb46ade..832381114 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java @@ -93,7 +93,7 @@ public void onPerform(CommandEvent commandEvent) { @Override public CommandData getCommandData() { return new CommandDataImpl("birthday", - LanguageService.getDefault("command.description.birthday")) + "command.description.birthday") .addSubcommands(new SubcommandData("remove", "Remove a Birthday entry!") .addOptions(new OptionData(OptionType.USER, "user", "The User which should get their birthday entry removed.", false)), new SubcommandData("add", "Add a Birthday entry!") diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java b/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java index f31827656..6873b7ec4 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java @@ -304,7 +304,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("giveaway", LanguageService.getDefault("command.description.giveaway")) + return new CommandDataImpl("giveaway", "command.description.giveaway") .addSubcommands(new SubcommandData("create", "Create a Giveaway.") .addOption(OptionType.STRING, "prize", "The Prize of the Giveaway.", true) .addOption(OptionType.INTEGER, "winners", "The amount of winners.", true) diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java b/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java index 2583755ed..88201a925 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java @@ -63,7 +63,7 @@ public void onPerform(CommandEvent commandEvent) { }).queue(msg -> { if (msg == null) return; MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); - messageCreateBuilder.setContent(LanguageService.getByGuild(commandEvent.getGuild(), "message.reactions.reactionNeeded", role.getAsRole().getAsMention())); + messageCreateBuilder.setContent(LanguageService.getByGuild(commandEvent.getGuild(), "message.reactions.reactionNeeded", role.getAsRole().getAsMention()).join()); msg.reply(messageCreateBuilder.build()).queue(); }); @@ -105,7 +105,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("reactions", LanguageService.getDefault("command.description.reactions")) + return new CommandDataImpl("reactions", "command.description.reactions") .addSubcommands(new SubcommandData("remove", "Remove a reaction role.") .addOption(OptionType.STRING, "message", "The ID of the Message.", true) .addOption(OptionType.ROLE, "role", "The Role to be given.", true), diff --git a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java index 18249fec1..01002d15d 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java @@ -186,7 +186,7 @@ public void onPerform(CommandEvent commandEvent) { case "list" -> SQLSession.getSqlConnector().getSqlWorker().getEntityList(new StreamAction(), "FROM StreamAction WHERE guildAndName.guildId = :gid", Map.of("gid", commandEvent.getGuild().getIdLong())).thenAccept(streamActions -> { - commandEvent.reply(LanguageService.getByEvent(commandEvent, "message.stream-action.list", String.join("\n", streamActions.stream().map(StreamAction::getName).toArray(String[]::new)))); + commandEvent.reply(commandEvent.getResource("message.stream-action.list", String.join("\n", streamActions.stream().map(StreamAction::getName).toArray(String[]::new)))); }); case "points" -> @@ -214,7 +214,26 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("stream-action", LanguageService.getDefault("command.description.stream-action")).addSubcommands(new SubcommandData("create", "Create a new Stream-Action.").addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true)).addSubcommands(new SubcommandData("delete", "Delete a Stream-Action.").addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true)).addSubcommands(new SubcommandData("list", "List all Stream-Actions.")).addSubcommands(new SubcommandData("points", "List all your ChannelPoint Rewards.")).addSubcommandGroups(new SubcommandGroupData("manage", "Manage a existing Stream-action.").addSubcommands(new SubcommandData("listener", "Set the listener of the Stream-Action.").addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true).addOption(OptionType.STRING, "listener", "The listener of the Stream-Action.", true), new SubcommandData("delete", "Delete a line of the Stream-Action.").addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true).addOptions(new OptionData(OptionType.INTEGER, "line", "The line of the Stream-Action.", true).setMinValue(1)), new SubcommandData("create", "Create a action in the Stream-Action.").addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true).addOption(OptionType.STRING, "action", "The action of the Stream-Action.", true), new SubcommandData("list", "List all actions of the Stream-Action.").addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true))); + return new CommandDataImpl("stream-action", "command.description.stream-action") + .addSubcommands(new SubcommandData("create", "Create a new Stream-Action.") + .addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true)) + .addSubcommands(new SubcommandData("delete", "Delete a Stream-Action.") + .addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true)) + .addSubcommands(new SubcommandData("list", "List all Stream-Actions.")) + .addSubcommands(new SubcommandData("points", "List all your ChannelPoint Rewards.")) + .addSubcommandGroups(new SubcommandGroupData("manage", "Manage a existing Stream-action.") + .addSubcommands( + new SubcommandData("listener", "Set the listener of the Stream-Action.") + .addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true) + .addOption(OptionType.STRING, "listener", "The listener of the Stream-Action.", true), + new SubcommandData("delete", "Delete a line of the Stream-Action.") + .addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true) + .addOptions(new OptionData(OptionType.INTEGER, "line", "The line of the Stream-Action.", true).setMinValue(1)), + new SubcommandData("create", "Create a action in the Stream-Action.") + .addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true) + .addOption(OptionType.STRING, "action", "The action of the Stream-Action.", true), + new SubcommandData("list", "List all actions of the Stream-Action.") + .addOption(OptionType.STRING, "name", "The name of the Stream-Action.", true))); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java b/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java index b25c2cb3b..9925fcdf6 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java @@ -83,18 +83,18 @@ public void onPerform(CommandEvent commandEvent) { MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); messageCreateBuilder.setEmbeds(new EmbedBuilder() - .setTitle(LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket")) + .setTitle(LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket").join()) .setDescription(SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_ticket_menu").join().getStringValue()) .setColor(0x55ff00) .setThumbnail(commandEvent.getGuild().getIconUrl()) .setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) .build()); - messageCreateBuilder.setActionRow(Button.of(ButtonStyle.PRIMARY, "re_ticket_open", LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket"), Emoji.fromUnicode("U+1F4E9"))); + messageCreateBuilder.setActionRow(Button.of(ButtonStyle.PRIMARY, "re_ticket_open", LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket").join(), Emoji.fromUnicode("U+1F4E9"))); Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), ticketChannel.getAsChannel().asTextChannel()); }); }); - embedBuilder.setDescription(LanguageService.getByGuild(commandEvent.getGuild(), "message.ticket.setupSuccess")); + embedBuilder.setDescription(commandEvent.getResource("message.ticket.setupSuccess")); embedBuilder.setColor(Color.GREEN); commandEvent.reply(embedBuilder.build()); @@ -106,7 +106,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("tickets", LanguageService.getDefault("command.description.tickets")) + return new CommandDataImpl("tickets", "command.description.tickets") .addOptions(new OptionData(OptionType.CHANNEL, "supportchannel", "The channel that should have the ticket creation message.", true).setChannelTypes(ChannelType.NEWS, ChannelType.TEXT), new OptionData(OptionType.CHANNEL, "logchannel", "The channel that should receive the transcripts.", true).setChannelTypes(ChannelType.NEWS, ChannelType.TEXT)); } diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java b/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java index cdbc4bce1..1f77d24d6 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java @@ -157,7 +157,7 @@ public void sendAnime(CommandEvent commandEvent, Message message, String query) */ @Override public CommandData getCommandData() { - return new CommandDataImpl("anime", LanguageService.getDefault("command.description.anime")) + return new CommandDataImpl("anime", "command.description.anime") .addOption(OptionType.STRING, "search", "The search query to search for.", true); } diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Cringe.java b/src/main/java/de/presti/ree6/commands/impl/fun/Cringe.java index c895864da..9a6cdd7ab 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Cringe.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Cringe.java @@ -35,7 +35,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("shrekimage", LanguageService.getDefault("command.description.cringe_slash")); + return new CommandDataImpl("shrekimage", "command.description.cringe_slash"); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Game.java b/src/main/java/de/presti/ree6/commands/impl/fun/Game.java index c1aa3d446..6ce727f04 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Game.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Game.java @@ -52,7 +52,7 @@ public void onPerform(CommandEvent commandEvent) { if (GameManager.getGameNames().stream().noneMatch(c -> c.equalsIgnoreCase(nameMapping.getAsString().trim()))) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(commandEvent.getResource("message.game.availableGames")).append("```"); - GameManager.getGameCache().forEach((entry, entryValue) -> stringBuilder.append("\n").append(entry).append("- ").append(LanguageService.getByEvent(commandEvent,entryValue.getAnnotation(GameInfo.class).description()))); + GameManager.getGameCache().forEach((entry, entryValue) -> stringBuilder.append("\n").append(entry).append("- ").append(commandEvent.getResource(entryValue.getAnnotation(GameInfo.class).description()))); stringBuilder.append("```"); commandEvent.reply(stringBuilder.toString()); return; @@ -94,7 +94,7 @@ public void onPerform(CommandEvent commandEvent) { case "list" -> { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(commandEvent.getResource("message.game.availableGames")).append("```"); - GameManager.getGameCache().forEach((entry, entryValue) -> stringBuilder.append("\n").append(entry).append(" ").append("-").append(" ").append(LanguageService.getByEvent(commandEvent,entryValue.getAnnotation(GameInfo.class).description()))); + GameManager.getGameCache().forEach((entry, entryValue) -> stringBuilder.append("\n").append(entry).append(" ").append("-").append(" ").append(commandEvent.getResource(entryValue.getAnnotation(GameInfo.class).description()))); stringBuilder.append("```"); commandEvent.reply(stringBuilder.toString()); } @@ -108,7 +108,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("game", LanguageService.getDefault("command.description.game")) + return new CommandDataImpl("game", "command.description.game") .addSubcommands(new SubcommandData("create", "Create a new Game match.") .addOptions(new OptionData(OptionType.STRING, "name", "The Game name.", true).addChoice("Blackjack", "blackjack").addChoice("Music Quiz", "musicquiz")), new SubcommandData("join", "Join a Game match.") diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/HornyJail.java b/src/main/java/de/presti/ree6/commands/impl/fun/HornyJail.java index d47407f0f..4ed524cca 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/HornyJail.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/HornyJail.java @@ -53,7 +53,8 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("behave", LanguageService.getDefault("command.description.hornyjail_slash")).addOptions(new OptionData(OptionType.USER, "target", "The User that should be put into the Hornyjail!").setRequired(true)); + return new CommandDataImpl("behave", "command.description.hornyjail_slash") + .addOptions(new OptionData(OptionType.USER, "target", "The User that should be put into the Hornyjail!").setRequired(true)); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Hug.java b/src/main/java/de/presti/ree6/commands/impl/fun/Hug.java index 1985621f8..913c6f251 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Hug.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Hug.java @@ -54,7 +54,8 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("hug", LanguageService.getDefault("command.description.hug")).addOptions(new OptionData(OptionType.USER, "target", "The User that should be hugged!").setRequired(true)); + return new CommandDataImpl("hug", "command.description.hug") + .addOptions(new OptionData(OptionType.USER, "target", "The User that should be hugged!").setRequired(true)); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Kiss.java b/src/main/java/de/presti/ree6/commands/impl/fun/Kiss.java index 050a047a0..1da4e09ac 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Kiss.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Kiss.java @@ -54,7 +54,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("kiss", LanguageService.getDefault("command.description.kiss")) + return new CommandDataImpl("kiss", "command.description.kiss") .addOptions(new OptionData(OptionType.USER, "target", "The User that should be kissed!").setRequired(true)); } diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java b/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java index e62390981..e5cbadd06 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java @@ -203,7 +203,7 @@ public String tryResolvingGenres(JsonObject data) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("manga", LanguageService.getDefault("command.description.manga")) + return new CommandDataImpl("manga", "command.description.manga") .addOption(OptionType.STRING, "search", "The search query to search for.", true); } diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Slap.java b/src/main/java/de/presti/ree6/commands/impl/fun/Slap.java index 14a02c44e..898bbeb50 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Slap.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Slap.java @@ -54,7 +54,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("gracetheface", LanguageService.getDefault("command.description.slap")) + return new CommandDataImpl("gracetheface", "command.description.slap") .addOptions(new OptionData(OptionType.USER, "target", "The User that should be slapped!").setRequired(true)); } diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Twitter.java b/src/main/java/de/presti/ree6/commands/impl/fun/Twitter.java index 093e9dac3..19d2edc4a 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Twitter.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Twitter.java @@ -71,7 +71,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("twitter", LanguageService.getDefault("command.description.twitter")) + return new CommandDataImpl("twitter", "command.description.twitter") .addOptions(new OptionData(OptionType.USER, "target", "The User that should tweet something!").setRequired(true)) .addOptions(new OptionData(OptionType.STRING, "content", "The Tweet Content!").setRequired(true)); } diff --git a/src/main/java/de/presti/ree6/commands/impl/hidden/Announcement.java b/src/main/java/de/presti/ree6/commands/impl/hidden/Announcement.java index fe6dd6d0e..dca874b72 100644 --- a/src/main/java/de/presti/ree6/commands/impl/hidden/Announcement.java +++ b/src/main/java/de/presti/ree6/commands/impl/hidden/Announcement.java @@ -62,7 +62,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("announcement", LanguageService.getDefault("command.description.announcement")) + return new CommandDataImpl("announcement","command.description.announcement") .addOptions(new OptionData(OptionType.STRING, "title", "The title of the announcement.", false), new OptionData(OptionType.STRING, "content", "The content of the announcement.", false), new OptionData(OptionType.STRING, "id", "The to delete announcement id.", false)); diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java b/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java index 5bdb8fb0b..50e61f901 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java @@ -54,7 +54,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("avatar", LanguageService.getDefault("command.description.avatar")) + return new CommandDataImpl("avatar", "command.description.avatar") .addOptions(new OptionData(OptionType.USER, "target", "The User whose profile you want.").setRequired(true)); } diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Help.java b/src/main/java/de/presti/ree6/commands/impl/info/Help.java index c2b0886e0..6202341af 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Help.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Help.java @@ -130,7 +130,7 @@ public String[] getAlias() { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("help", LanguageService.getDefault("command.description.help")) + return new CommandDataImpl("help", "command.description.help") .addOptions(new OptionData(OptionType.STRING, "category", "Which Category you want to check out.")); } diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Info.java b/src/main/java/de/presti/ree6/commands/impl/info/Info.java index 2a42ea4b8..329de78e8 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Info.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Info.java @@ -57,7 +57,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("info", LanguageService.getDefault("command.description.info")) + return new CommandDataImpl("info", "command.description.info") .addOptions(new OptionData(OptionType.USER, "target", "The User whose profile Information you want.").setRequired(false)); } diff --git a/src/main/java/de/presti/ree6/commands/impl/level/Level.java b/src/main/java/de/presti/ree6/commands/impl/level/Level.java index 1cb9441d3..e10d7320a 100644 --- a/src/main/java/de/presti/ree6/commands/impl/level/Level.java +++ b/src/main/java/de/presti/ree6/commands/impl/level/Level.java @@ -59,7 +59,8 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("level", LanguageService.getDefault("command.description.level")).addOptions(new OptionData(OptionType.STRING, "typ", "Do you want to see chat or voice level?")) + return new CommandDataImpl("level", "command.description.level") + .addOptions(new OptionData(OptionType.STRING, "typ", "Do you want to see chat or voice level?")) .addOptions(new OptionData(OptionType.USER, "target", "Show the Level of the User.")); } diff --git a/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java b/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java index dde1a3512..e0ccc1aea 100644 --- a/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java +++ b/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java @@ -103,7 +103,7 @@ public void onPerform(CommandEvent commandEvent) { @Override public CommandData getCommandData() { return new CommandDataImpl("levelrole", - LanguageService.getDefault("command.description.levelrole")) + "command.description.levelrole") .addSubcommands(new SubcommandData("add", "Add a new Level-Role") .addOptions(new OptionData(OptionType.BOOLEAN, "voice", "True -> Voice-Level and False -> Text-Level").setRequired(true), new OptionData(OptionType.INTEGER, "level", "The level that needs to be reached to get the role.").setRequired(true).setMinValue(1), diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Ban.java b/src/main/java/de/presti/ree6/commands/impl/mod/Ban.java index f9431b3ab..3d1a749ff 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Ban.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Ban.java @@ -82,7 +82,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("ban", LanguageService.getDefault("command.description.ban")) + return new CommandDataImpl("ban", "command.description.ban") .addOptions(new OptionData(OptionType.USER, "target", "Which User should be banned.", true)) .addOptions(new OptionData(OptionType.INTEGER, "del_days", "Delete messages from the past days.") .setRequiredRange(0, 7)) diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Clear.java b/src/main/java/de/presti/ree6/commands/impl/mod/Clear.java index a13728d44..e887abe47 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Clear.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Clear.java @@ -67,7 +67,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("clear", LanguageService.getDefault("command.description.clear")) + return new CommandDataImpl("clear", "command.description.clear") .addOptions(new OptionData(OptionType.INTEGER, "amount", "How many messages should be removed.") .setRequired(true) .setMinValue(2) diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/EmbedSender.java b/src/main/java/de/presti/ree6/commands/impl/mod/EmbedSender.java index 5201a4446..9e85da08e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/EmbedSender.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/EmbedSender.java @@ -93,7 +93,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("embed", LanguageService.getDefault("command.description.embedSender")) + return new CommandDataImpl("embed", "command.description.embedSender") .addOption(OptionType.STRING, "title", "The title of the embed!", true) .addOption(OptionType.STRING, "description", "The description of the embed!", true) .addOption(OptionType.INTEGER, "color", "The color of the embed!", false) diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Import.java b/src/main/java/de/presti/ree6/commands/impl/mod/Import.java index ebbc07799..6e4e3c9f6 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Import.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Import.java @@ -151,7 +151,8 @@ public void importFromAmari(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("import", LanguageService.getDefault("command.description.import")).addOption(OptionType.STRING, "bot", "The Bot you want to import data from.", true); + return new CommandDataImpl("import", "command.description.import") + .addOption(OptionType.STRING, "bot", "The Bot you want to import data from.", true); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Kick.java b/src/main/java/de/presti/ree6/commands/impl/mod/Kick.java index fead46c39..1f2d51d26 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Kick.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Kick.java @@ -70,7 +70,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("kick", LanguageService.getDefault("command.description.kick")) + return new CommandDataImpl("kick", "command.description.kick") .addOptions(new OptionData(OptionType.USER, "target", "Which User should be kicked.").setRequired(true)) .addOptions(new OptionData(OptionType.STRING, "reason", "The Reason why the User should be kicked.").setRequired(false)) .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.KICK_MEMBERS)); diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Mute.java b/src/main/java/de/presti/ree6/commands/impl/mod/Mute.java index 7232325e4..a8a8e60e2 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Mute.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Mute.java @@ -88,7 +88,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("mute", LanguageService.getDefault("command.description.mute")) + return new CommandDataImpl("mute", "command.description.mute") .addOptions(new OptionData(OptionType.USER, "target", "Which User should be muted.").setRequired(true)) .addOptions(new OptionData(OptionType.INTEGER, "time", "How long the User should be muted for. (in minutes)").setRequired(true)) .addOptions(new OptionData(OptionType.STRING, "reason", "The Reason why the User should be muted.").setRequired(false)) diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Prefix.java b/src/main/java/de/presti/ree6/commands/impl/mod/Prefix.java index 70e502924..7644ab067 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Prefix.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Prefix.java @@ -56,7 +56,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("prefix", LanguageService.getDefault("command.description.prefix")) + return new CommandDataImpl("prefix", "command.description.prefix") .addOptions(new OptionData(OptionType.STRING, "new-prefix", "What should the new Prefix be?").setRequired(true)) .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.ADMINISTRATOR, Permission.MANAGE_SERVER)); } diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java index e09525f39..4aac1330e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java @@ -271,10 +271,10 @@ public static EmbedBuilder createAutoRoleSetupMessage(Guild guild, InteractionHo boolean hasRoles = !GuildUtil.getManagableRoles(guild).isEmpty(); return new EmbedBuilder() - .setTitle(LanguageService.getByGuildOrInteractionHook(guild, interactionHook, "label.setup")) + .setTitle(LanguageService.getByGuildOrInteractionHook(guild, interactionHook, "label.setup").join()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()) .setColor(hasRoles ? Color.cyan : Color.red) - .setDescription(LanguageService.getByGuildOrInteractionHook(guild, interactionHook, hasRoles ? "message.autoRole.setupDescription" : "message.default.needPermission", (hasRoles ? null : Permission.MANAGE_ROLES.name()))); + .setDescription(LanguageService.getByGuildOrInteractionHook(guild, interactionHook, hasRoles ? "message.autoRole.setupDescription" : "message.default.needPermission", (hasRoles ? null : Permission.MANAGE_ROLES.name())).join()); } public static CompletableFuture createAutoRoleSetupSelectMenu(Guild guild, InteractionHook interactionHook) { @@ -294,7 +294,7 @@ public static CompletableFuture createAutoRoleSetupSelectMenu(Guild }); return new StringSelectMenuImpl("setupAutoRole", LanguageService.getByGuildOrInteractionHook(guild, interactionHook, - "message.autoRole.setupPlaceholder"), + "message.autoRole.setupPlaceholder").join(), 0, Math.min(10, Math.max(1, optionList.size())), optionList.isEmpty(), optionList); }); } diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java b/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java index 62f8822bc..16617141c 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java @@ -106,7 +106,7 @@ public void createSuggestions(CommandEvent commandEvent, MessageChannel channel, */ @Override public CommandData getCommandData() { - return new CommandDataImpl("suggestion", LanguageService.getDefault("command.description.suggestion")) + return new CommandDataImpl("suggestion", "command.description.suggestion") .addOptions(new OptionData(OptionType.CHANNEL, "target", "The channel the suggestions should be shown in.").setChannelTypes(ChannelType.NEWS, ChannelType.TEXT).setRequired(true)) .addOptions(new OptionData(OptionType.CHANNEL, "messagetarget", "The channel the bot should send the suggestion message to.").setChannelTypes(ChannelType.NEWS, ChannelType.TEXT).setRequired(true)) .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.ADMINISTRATOR)); diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Unban.java b/src/main/java/de/presti/ree6/commands/impl/mod/Unban.java index dda750c37..48464732c 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Unban.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Unban.java @@ -70,7 +70,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("unban", LanguageService.getDefault("command.description.unban")) + return new CommandDataImpl("unban", "command.description.unban") .addOptions(new OptionData(OptionType.STRING, "id", "Which User should be unbanned.").setRequired(true)) .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.BAN_MEMBERS)); } diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Unmute.java b/src/main/java/de/presti/ree6/commands/impl/mod/Unmute.java index f82aae89c..ab84f3640 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Unmute.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Unmute.java @@ -68,7 +68,7 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("unmute", LanguageService.getDefault("command.description.unmute")) + return new CommandDataImpl("unmute", "command.description.unmute") .addOptions(new OptionData(OptionType.USER, "target", "Which User should be unmuted.").setRequired(true)) .setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.MODERATE_MEMBERS)); } diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Play.java b/src/main/java/de/presti/ree6/commands/impl/music/Play.java index ede205481..a76d13625 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Play.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Play.java @@ -73,7 +73,8 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("play", LanguageService.getDefault("command.description.play")).addOptions(new OptionData(OptionType.STRING, "name", "The YouTube URL, Song Name or the Spotify URL you want to play!").setRequired(true)); + return new CommandDataImpl("play", "command.description.play") + .addOptions(new OptionData(OptionType.STRING, "name", "The YouTube URL, Song Name or the Spotify URL you want to play!").setRequired(true)); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Seek.java b/src/main/java/de/presti/ree6/commands/impl/music/Seek.java index e2fceb04d..9410c764a 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Seek.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Seek.java @@ -54,7 +54,8 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("seek", LanguageService.getDefault("command.description.seek")).addOptions(new OptionData(OptionType.INTEGER, "seconds", "The seconds that should be seeked (negativ numbers work)").setRequired(true)); + return new CommandDataImpl("seek", "command.description.seek") + .addOptions(new OptionData(OptionType.INTEGER, "seconds", "The seconds that should be seeked (negativ numbers work)").setRequired(true)); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Skip.java b/src/main/java/de/presti/ree6/commands/impl/music/Skip.java index a6d7bb25f..7d68ed51f 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Skip.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Skip.java @@ -54,7 +54,8 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("skip", LanguageService.getDefault("command.description.skip")).addOptions(new OptionData(OptionType.INTEGER, "amount", "The amount of songs that should be skipped!").setRequired(false)); + return new CommandDataImpl("skip", "command.description.skip") + .addOptions(new OptionData(OptionType.INTEGER, "amount", "The amount of songs that should be skipped!").setRequired(false)); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Volume.java b/src/main/java/de/presti/ree6/commands/impl/music/Volume.java index 501b6c5e0..906b56a75 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Volume.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Volume.java @@ -105,7 +105,8 @@ public void onPerform(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("volume", LanguageService.getDefault("command.description.volume")).addOptions(new OptionData(OptionType.INTEGER, "amount", "The Volume that the Ree6 Music Player should be!").setRequired(true)); + return new CommandDataImpl("volume", "command.description.volume") + .addOptions(new OptionData(OptionType.INTEGER, "amount", "The Volume that the Ree6 Music Player should be!").setRequired(true)); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java b/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java index b4f8d0150..694fcb97d 100644 --- a/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java +++ b/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java @@ -136,7 +136,7 @@ public void sendImage(CommandEvent commandEvent, Message message, String tags) { */ @Override public CommandData getCommandData() { - return new CommandDataImpl("nsfw34", LanguageService.getDefault("command.description.rule34_slash")) + return new CommandDataImpl("nsfw34", "command.description.rule34_slash") .addOptions(new OptionData(OptionType.STRING, "tags", "Tags for the image search")); } diff --git a/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java b/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java index 68c3f98e4..c001139f7 100644 --- a/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java +++ b/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java @@ -77,20 +77,20 @@ public Blackjack(GameSession gameSession) { @Override public void createGame() { if (session.getParticipants().isEmpty() || session.getParticipants().size() > 2) { - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(session.getGuild(), "message.gameCore.needMore", 2), session.getChannel()); + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(session.getGuild(), "message.gameCore.needMore", 2).join(), session.getChannel()); stopGame(); } MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack")); + embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").join()); embedBuilder.setColor(BotWorker.randomEmbedColor()); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.welcome", session.getGameIdentifier())); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.welcome", session.getGameIdentifier()).join()); messageCreateBuilder.setEmbeds(embedBuilder.build()); - messageCreateBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame")).asDisabled(), - Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame")).asEnabled()); + messageCreateBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").join()).asDisabled(), + Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame").join()).asEnabled()); session.getChannel().sendMessage(messageCreateBuilder.build()).queue(message -> menuMessage = message); } @@ -127,17 +127,17 @@ public void startGame() { @Override public void joinGame(GamePlayer user) { if (session.getGameState() == GameState.STARTED) { - user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyStarted")).queue(); + user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyStarted").join()).queue(); return; } if (player != null && playerTwo != null) { - user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.full")).queue(); + user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.full").join()).queue(); return; } if ((player != null && user.getRelatedUserId() == player.getRelatedUserId()) || (playerTwo != null && user.getRelatedUserId() == playerTwo.getRelatedUserId())) { - user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyIn")).queue(); + user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyIn").join()).queue(); return; } @@ -151,18 +151,18 @@ public void joinGame(GamePlayer user) { MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); messageEditBuilder.applyMessage(menuMessage); EmbedBuilder embedBuilder = new EmbedBuilder(messageEditBuilder.getEmbeds().get(0)); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.minimalReached")); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.minimalReached").join()); messageEditBuilder.setEmbeds(embedBuilder.build()); - messageEditBuilder.setActionRow(Button.success("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame")).asEnabled()); + messageEditBuilder.setActionRow(Button.success("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").join()).asEnabled()); menuMessage.editMessage(messageEditBuilder.build()).queue(); messageEditBuilder.clear(); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined")); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined").join()); messageEditBuilder.setEmbeds(embedBuilder.build()); playerTwo.getInteractionHook().editOriginal(messageEditBuilder.build()).queue(); messageEditBuilder.clear(); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.minimalReachedHost")); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.minimalReachedHost").join()); messageEditBuilder.setEmbeds(embedBuilder.build()); player.getInteractionHook().editOriginal(messageEditBuilder.build()).queue(); } @@ -292,18 +292,18 @@ public void stand(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlayer) { public void stopGame(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlayer) { MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack")); + embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").join()); embedBuilder.setColor(BotWorker.randomEmbedColor()); BlackJackPlayer winner = findWinner(); if (winner == null) { - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.end.draw")); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.end.draw").join()); } else { - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.end.win", winner.getRelatedUser().getAsMention(), winner.getHandValue(true))); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.end.win", winner.getRelatedUser().getAsMention(), winner.getHandValue(true)).join()); } - embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", currentPlayer.getRelatedUser().getEffectiveName()), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", currentPlayer.getHandAsString(true), currentPlayer.getHandValue(true)), true); - embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", nextPlayer.getRelatedUser().getEffectiveName()), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", nextPlayer.getHandAsString(true), nextPlayer.getHandValue(true)), true); + embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", currentPlayer.getRelatedUser().getEffectiveName()).join(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", currentPlayer.getHandAsString(true), currentPlayer.getHandValue(true)).join(), true); + embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", nextPlayer.getRelatedUser().getEffectiveName()).join(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", nextPlayer.getHandAsString(true), nextPlayer.getHandValue(true)).join(), true); messageCreateBuilder.setEmbeds(embedBuilder.build()); messageCreateBuilder.setComponents(new ArrayList<>()); @@ -339,33 +339,33 @@ public void updateViews(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlaye MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); EmbedBuilder currentPlayerEmbed = new EmbedBuilder(); - currentPlayerEmbed.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack")); + currentPlayerEmbed.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").join()); currentPlayerEmbed.setColor(Color.GREEN); currentPlayerEmbed.setAuthor(currentPlayer.getRelatedUser().getEffectiveName(), null, currentPlayer.getRelatedUser().getEffectiveAvatarUrl()); - currentPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCardsSelf"), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", - currentPlayer.getHandAsString(true), currentPlayer.getHandValue(true)), true); - currentPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", nextPlayer.getRelatedUser().getEffectiveName()), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", - nextPlayer.getHandAsString(false), nextPlayer.getHandValue(false)), true); + currentPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCardsSelf").join(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", + currentPlayer.getHandAsString(true), currentPlayer.getHandValue(true)).join(), true); + currentPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", nextPlayer.getRelatedUser().getEffectiveName()).join(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", + nextPlayer.getHandAsString(false), nextPlayer.getHandValue(false)).join(), true); - currentPlayerEmbed.setFooter(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.turn.player")); + currentPlayerEmbed.setFooter(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.turn.player").join()); messageEditBuilder.setEmbeds(currentPlayerEmbed.build()); if (addButtons) { - messageEditBuilder.setActionRow(Button.primary("game_blackjack_hit", LanguageService.getByGuild(session.getGuild(), "label.hit")), - Button.success("game_blackjack_stand", LanguageService.getByGuild(session.getGuild(), "label.stand"))); + messageEditBuilder.setActionRow(Button.primary("game_blackjack_hit", LanguageService.getByGuild(session.getGuild(), "label.hit").join()), + Button.success("game_blackjack_stand", LanguageService.getByGuild(session.getGuild(), "label.stand").join())); } currentPlayer.getInteractionHook().editOriginal(messageEditBuilder.build()).queue(); EmbedBuilder nextPlayerEmbed = new EmbedBuilder(); - nextPlayerEmbed.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack")); + nextPlayerEmbed.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").join()); nextPlayerEmbed.setColor(Color.red); nextPlayerEmbed.setAuthor(nextPlayer.getRelatedUser().getEffectiveName(), null, nextPlayer.getRelatedUser().getEffectiveAvatarUrl()); - nextPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCardsSelf"), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", nextPlayer.getHandAsString(true), nextPlayer.getHandValue(true)), true); - nextPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", currentPlayer.getRelatedUser().getEffectiveName()), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", currentPlayer.getHandAsString(false), currentPlayer.getHandValue(false)), true); - nextPlayerEmbed.setFooter(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.turn.wait")); + nextPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCardsSelf").join(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", nextPlayer.getHandAsString(true), nextPlayer.getHandValue(true)).join(), true); + nextPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", currentPlayer.getRelatedUser().getEffectiveName()).join(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", currentPlayer.getHandAsString(false), currentPlayer.getHandValue(false)).join(), true); + nextPlayerEmbed.setFooter(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.turn.wait").join()); messageEditBuilder.setEmbeds(nextPlayerEmbed.build()); nextPlayer.getInteractionHook().editOriginal(messageEditBuilder.build()).queue(); diff --git a/src/main/java/de/presti/ree6/utils/data/RegExUtil.java b/src/main/java/de/presti/ree6/utils/data/RegExUtil.java index 1cadd5b9c..1bd7913c0 100644 --- a/src/main/java/de/presti/ree6/utils/data/RegExUtil.java +++ b/src/main/java/de/presti/ree6/utils/data/RegExUtil.java @@ -47,7 +47,13 @@ public class RegExUtil { /** * The Regex to detect any dhm based time input. - * For example 1d, 2h, 3m + * For example, 1d, 2h, 3m */ public static final String TIME_INPUT_REGEX = "\\d+[dhm]"; + + /** + * The Regex to detect if the given string is a valid language path. + * For example, message.kick.default + */ + public static final String ALLOWED_LANGUAGE_PATHS = "^(message\\.|label\\.|command\\.|game\\.|category\\.)\\S*"; } From fee18cad4257b3f9404babc66976374f21c90c86 Mon Sep 17 00:00:00 2001 From: Presti Date: Tue, 21 May 2024 13:50:52 +0200 Subject: [PATCH 13/94] Clean up work. --- .../presti/ree6/commands/CommandManager.java | 44 +++++++ .../de/presti/ree6/events/OtherEvents.java | 120 ++++++++---------- .../ree6/game/impl/musicquiz/MusicQuiz.java | 46 +++---- .../de/presti/ree6/logger/LoggerQueue.java | 23 ++-- src/main/java/de/presti/ree6/main/Main.java | 10 +- 5 files changed, 138 insertions(+), 105 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/CommandManager.java b/src/main/java/de/presti/ree6/commands/CommandManager.java index cf70c85d0..c6c5a365c 100644 --- a/src/main/java/de/presti/ree6/commands/CommandManager.java +++ b/src/main/java/de/presti/ree6/commands/CommandManager.java @@ -610,6 +610,50 @@ public void sendMessage(MessageCreateData messageCreateData, int deleteSecond, M } } + /** + * Send a message to a special Message-Channel. + * + * @param message the Message content as {@link CompletableFuture}. + * @param messageChannel the Message-Channel. + */ + public void sendMessage(CompletableFuture message, MessageChannel messageChannel) { + message.thenAccept(s -> sendMessage(s, messageChannel)); + } + + /** + * Send a message to a special Message-Channel, with a deletion delay. + * + * @param message the Message content as {@link CompletableFuture}. + * @param deleteSecond the delete delay + * @param messageChannel the Message-Channel. + */ + public void sendMessage(CompletableFuture message, int deleteSecond, MessageChannel messageChannel) { + message.thenAccept(s -> sendMessage(s, deleteSecond, messageChannel)); + } + + /** + * Send a message to a special Message-Channel. + * + * @param message the Message content as {@link CompletableFuture}. + * @param messageChannel the Message-Channel. + * @param interactionHook the Interaction-hook if it is a slash command. + */ + public void sendMessage(CompletableFuture message, MessageChannel messageChannel, InteractionHook interactionHook) { + message.thenAccept(s -> sendMessage(s, messageChannel, interactionHook)); + } + + /** + * Send a message to a special Message-Channel, with a deletion delay. + * + * @param messageContent the Message content as {@link CompletableFuture}. + * @param messageChannel the Message-Channel. + * @param interactionHook the Interaction-hook if it is a slash command. + * @param deleteSecond the delete delay + */ + public void sendMessage(CompletableFuture messageContent, int deleteSecond, MessageChannel messageChannel, InteractionHook interactionHook) { + messageContent.thenAccept(s -> sendMessage(s, deleteSecond, messageChannel, interactionHook)); + } + /** * Send a message to a special Message-Channel. * diff --git a/src/main/java/de/presti/ree6/events/OtherEvents.java b/src/main/java/de/presti/ree6/events/OtherEvents.java index 5ce7540c9..f006ebb60 100644 --- a/src/main/java/de/presti/ree6/events/OtherEvents.java +++ b/src/main/java/de/presti/ree6/events/OtherEvents.java @@ -45,6 +45,7 @@ import net.dv8tion.jda.api.events.session.ReadyEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.managers.AudioManager; +import net.dv8tion.jda.api.requests.restaction.MessageEditAction; import net.dv8tion.jda.internal.utils.PermissionUtil; import org.jetbrains.annotations.NotNull; @@ -291,31 +292,7 @@ public void onGuildVoiceUpdate(@Nonnull GuildVoiceUpdateEvent event) { } if (BotConfig.isModuleActive("temporalvoice")) { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getId())) - .thenAccept(temporalVoicechannel -> { - if (temporalVoicechannel != null) { - VoiceChannel voiceChannel = event.getGuild().getVoiceChannelById(event.getChannelJoined().getId()); - - if (voiceChannel == null) - return; - - if (temporalVoicechannel.getGuildChannelId().getChannelId() != voiceChannel.getIdLong()) { - return; - } - - if (voiceChannel.getParentCategory() != null) { - String preName = LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", "SPLIT"); - preName = preName.split("SPLIT")[0]; - - String finalPreName = preName; - voiceChannel.getParentCategory().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", - event.getGuild().getVoiceChannels().stream().filter(c -> c.getName().startsWith(finalPreName)).count() + 1)).queue(channel -> { - event.getGuild().moveVoiceMember(event.getMember(), channel).queue(); - ArrayUtil.temporalVoicechannel.add(channel.getId()); - }); - } - } - }); + checkCreationChannel(event.getGuild(), event.getMember(), event.getChannelJoined().getIdLong()); } } else if (event.getChannelJoined() == null) { doVoiceXPStuff(event.getMember()); @@ -341,33 +318,39 @@ public void onGuildVoiceUpdate(@Nonnull GuildVoiceUpdateEvent event) { if (BotConfig.isModuleActive("temporalvoice")) { if (checkChannel(event.getChannelLeft(), event.getJDA())) return; - SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getId())) - .thenAccept(temporalVoicechannel -> { - if (temporalVoicechannel != null) { - VoiceChannel voiceChannel = event.getGuild().getVoiceChannelById(event.getChannelJoined().getId()); + checkCreationChannel(event.getGuild(), event.getMember(), event.getChannelJoined().getIdLong()); + } + } + } - if (voiceChannel == null) - return; + private void checkCreationChannel(Guild guild, Member member, long channelId) { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", guild.getId())) + .thenAccept(temporalVoicechannel -> { + if (temporalVoicechannel != null) { + VoiceChannel voiceChannel = guild.getVoiceChannelById(channelId); - if (temporalVoicechannel.getGuildChannelId().getChannelId() != voiceChannel.getIdLong()) { - return; - } + if (voiceChannel == null) + return; - if (voiceChannel.getParentCategory() != null) { - String preName = LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", "SPLIT"); - preName = preName.split("SPLIT")[0]; + if (temporalVoicechannel.getGuildChannelId().getChannelId() != voiceChannel.getIdLong()) { + return; + } - String finalPreName = preName; - voiceChannel.getParentCategory().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.temporalVoiceName", - event.getGuild().getVoiceChannels().stream().filter(c -> c.getName().startsWith(finalPreName)).count() + 1)).queue(channel -> { - event.getGuild().moveVoiceMember(event.getMember(), channel).queue(); - ArrayUtil.temporalVoicechannel.add(channel.getId()); - }); - } - } - }); - } - } + if (voiceChannel.getParentCategory() != null) { + LanguageService.getByGuild(guild, "label.temporalVoiceName", "SPLIT").thenAccept(preName -> { + preName = preName.split("SPLIT")[0]; + String finalPreName = preName; + LanguageService.getByGuild(guild, "label.temporalVoiceName", + guild.getVoiceChannels().stream().filter(c -> c.getName().startsWith(finalPreName)).count() + 1) + .thenAccept(name -> voiceChannel.getParentCategory().createVoiceChannel(name) + .queue(channel -> { + guild.moveVoiceMember(member, channel).queue(); + ArrayUtil.temporalVoicechannel.add(channel.getId()); + })); + }); + } + } + }); } private boolean checkChannel(AudioChannelUnion channel, JDA instance) { @@ -490,6 +473,7 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { ModerationUtil.checkMessage(event.getGuild().getIdLong(), event.getMessage().getContentRaw()).thenAccept(y -> { if (y) { Main.getInstance().getCommandManager().deleteMessage(event.getMessage(), null); + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.blacklisted"), event.getChannel(), null); moderated.set(true); } @@ -573,31 +557,33 @@ public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) { if (message.getAuthor().getId().equalsIgnoreCase(event.getJDA().getSelfUser().getId())) { String messageContent = message.getContentRaw(); - if (messageContent.startsWith(LanguageService.getByGuild(event.getGuild(), "message.reactions.reactionNeeded", "SPLIT_HERE").split("SPLIT_HERE")[0])) { - if (event.getMember().hasPermission(Permission.ADMINISTRATOR) && message.getMessageReference() != null) { - if (message.getMentions().getRoles().isEmpty()) { - message.editMessage(LanguageService.getByGuild(event.getGuild(), "message.reactions.roleNotFound")).queue(); - return; - } + LanguageService.getByGuild(event.getGuild(), "message.reactions.reactionNeeded", "SPLIT_HERE").thenAccept(translation -> { + if (messageContent.startsWith(translation.split("SPLIT_HERE")[0])) { + if (event.getMember().hasPermission(Permission.ADMINISTRATOR) && message.getMessageReference() != null) { + if (message.getMentions().getRoles().isEmpty()) { + LanguageService.getByGuild(event.getGuild(), "message.reactions.roleNotFound").thenApply(message::editMessage).thenAccept(MessageEditAction::queue); + return; + } - Role role = message.getMentions().getRoles().get(0); + Role role = message.getMentions().getRoles().get(0); - if (role == null) { - message.editMessage(LanguageService.getByGuild(event.getGuild(), "message.reactions.roleNotFound")).queue(); - return; - } + if (role == null) { + LanguageService.getByGuild(event.getGuild(), "message.reactions.roleNotFound").thenApply(message::editMessage).thenAccept(MessageEditAction::queue); + return; + } - ReactionRole reactionRole = new ReactionRole(event.getGuild().getIdLong(), emojiId, emojiUnion.getFormatted(), role.getIdLong(), message.getMessageReference().getMessageIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRole); + ReactionRole reactionRole = new ReactionRole(event.getGuild().getIdLong(), emojiId, emojiUnion.getFormatted(), role.getIdLong(), message.getMessageReference().getMessageIdLong()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRole); - if (message.getMessageReference().getMessage() != null) { - message.getMessageReference().getMessage().addReaction(event.getEmoji()).queue(); - } + if (message.getMessageReference().getMessage() != null) { + message.getMessageReference().getMessage().addReaction(event.getEmoji()).queue(); + } - message.editMessage(LanguageService.getByGuild(event.getGuild(), "message.reactions.roleAssign", role.getAsMention())) - .delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); + LanguageService.getByGuild(event.getGuild(), "message.reactions.roleAssign", role.getAsMention()) + .thenAccept(x -> message.editMessage(x).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue()); + } } - } + }); } else { SQLSession.getSqlConnector().getSqlWorker() .getEntity(new ReactionRole(), "FROM ReactionRole WHERE guildRoleId.guildId=:gid AND emoteId=:emoteId AND messageId=:messageId", diff --git a/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java b/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java index cb16d7837..2fc6de6b4 100644 --- a/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java +++ b/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java @@ -105,20 +105,20 @@ public MusicQuiz(GameSession gameSession) { public void createGame() { if (session.getHost().getVoiceState() == null || session.getHost().getVoiceState().getChannel() == null) { - session.getChannel().sendMessage(LanguageService.getByGuild(session.getGuild(), "message.default.notInVoiceChannel")).queue(); + session.getChannel().sendMessage(LanguageService.getByGuild(session.getGuild(), "message.default.notInVoiceChannel").join()).queue(); return; } MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.musicQuiz")); + embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.musicQuiz").join()); embedBuilder.setColor(BotWorker.randomEmbedColor()); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.welcome", session.getGameIdentifier())); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.welcome", session.getGameIdentifier()).join()); messageCreateBuilder.setEmbeds(embedBuilder.build()); - messageCreateBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame")).asDisabled(), - Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame")).asEnabled()); + messageCreateBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").join()).asDisabled(), + Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame").join()).asEnabled()); menuMessage = session.getChannel().sendMessage(messageCreateBuilder.build()).complete(); } @@ -150,7 +150,7 @@ public void startGame() { public void joinGame(GamePlayer user) { if (participants.stream().anyMatch(c -> c.getRelatedUserId() == user.getRelatedUserId())) { - user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyJoined")).queue(); + user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyJoined").join()).queue(); return; } @@ -159,16 +159,16 @@ public void joinGame(GamePlayer user) { MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(menuMessage.getEmbeds().get(0)); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined")); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined").join()); messageEditBuilder.setEmbeds(embedBuilder.build()); - messageEditBuilder.setActionRow(Button.secondary("game_leave:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.leaveGame")).asEnabled()); + messageEditBuilder.setActionRow(Button.secondary("game_leave:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.leaveGame").join()).asEnabled()); user.getInteractionHook().editOriginal(messageEditBuilder.build()).queue(); if (participants.size() >= 2) { - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.welcome", session.getGameIdentifier())); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.welcome", session.getGameIdentifier()).join()); messageEditBuilder.setEmbeds(embedBuilder.build()); - messageEditBuilder.setActionRow(Button.success("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame")).asEnabled(), - Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame")).asEnabled()); + messageEditBuilder.setActionRow(Button.success("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").join()).asEnabled(), + Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame").join()).asEnabled()); menuMessage.editMessage(messageEditBuilder.build()).queue(); } } @@ -186,10 +186,10 @@ public void leaveGame(GamePlayer user) { messageEditBuilder.applyMessage(menuMessage); EmbedBuilder embedBuilder = new EmbedBuilder(messageEditBuilder.getEmbeds().get(0)); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined")); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined").join()); messageEditBuilder.setEmbeds(embedBuilder.build()); - messageEditBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame")).asDisabled(), - Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame")).asEnabled()); + messageEditBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").join()).asDisabled(), + Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame").join()).asEnabled()); menuMessage = menuMessage.editMessage(messageEditBuilder.build()).complete(); } } @@ -218,7 +218,7 @@ public void onMessageReceive(MessageReceivedEvent messageReceivedEvent) { Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_title")) .thenAccept(setting -> rewardPlayer(session, musicQuizPlayer, setting.getValue())); - messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundTitle", currentEntry.getTitle())).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); + messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundTitle", currentEntry.getTitle()).join()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); messageReceivedEvent.getMessage().delete().queue(); } @@ -229,7 +229,7 @@ public void onMessageReceive(MessageReceivedEvent messageReceivedEvent) { Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_artist")) .thenAccept(setting -> rewardPlayer(session, musicQuizPlayer, setting.getValue())); - messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundArtists", currentEntry.getArtist())).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); + messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundArtists", currentEntry.getArtist()).join()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); messageReceivedEvent.getMessage().delete().queue(); } @@ -240,12 +240,12 @@ public void onMessageReceive(MessageReceivedEvent messageReceivedEvent) { Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_feature")) .thenAccept(setting -> rewardPlayer(session, musicQuizPlayer, setting.getValue())); - messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundFeature", String.join(",", currentEntry.getFeatures()))).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); + messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundFeature", String.join(",", currentEntry.getFeatures())).join()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); messageReceivedEvent.getMessage().delete().queue(); } if (currentEntry.isTitleGuessed() && currentEntry.isArtistGuessed() && currentEntry.isFeaturesGuessed()) { - messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundAll")).queue(); + messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundAll").join()).queue(); selectNextSong(); } } @@ -272,14 +272,14 @@ public void stopGame() { MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(menuMessage.getEmbeds().get(0)); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.newSong")); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.newSong").join()); List sortedList = participants.stream().sorted(Comparator.comparingInt(MusicQuizPlayer::getPoints).reversed()).toList(); for (int i = 0; i < sortedList.size(); i++) { MusicQuizPlayer musicQuizPlayer = sortedList.get(i); - embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.position", i + 1), + embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.position", i + 1).join(), LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.points", musicQuizPlayer.getRelatedUser().getAsMention(), - musicQuizPlayer.getPoints()), false); + musicQuizPlayer.getPoints()).join(), false); } messageCreateBuilder.setEmbeds(embedBuilder.build()); @@ -324,9 +324,9 @@ public void selectNextSong() { messageEditBuilder.applyMessage(menuMessage); EmbedBuilder embedBuilder = new EmbedBuilder(messageEditBuilder.getEmbeds().get(0)); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.newSong")); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.newSong").join()); messageEditBuilder.setEmbeds(embedBuilder.build()); - messageEditBuilder.setActionRow(Button.success("game_musicquiz_skip", LanguageService.getByGuild(session.getGuild(), "label.skip")).asEnabled()); + messageEditBuilder.setActionRow(Button.success("game_musicquiz_skip", LanguageService.getByGuild(session.getGuild(), "label.skip").join()).asEnabled()); menuMessage.editMessage(messageEditBuilder.build()).queue(); AudioChannel audioChannel = session.getGuild().getMember(session.getHost()).getVoiceState().getChannel(); diff --git a/src/main/java/de/presti/ree6/logger/LoggerQueue.java b/src/main/java/de/presti/ree6/logger/LoggerQueue.java index 3071f27d1..6e2757d96 100644 --- a/src/main/java/de/presti/ree6/logger/LoggerQueue.java +++ b/src/main/java/de/presti/ree6/logger/LoggerQueue.java @@ -71,7 +71,8 @@ public void add(LogMessage loggerMessage) { // Set the new Webhook Message. webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(logMessageVoice.getMember().getUser().getEffectiveName(), logMessageVoice.getMember().getEffectiveAvatarUrl(), null)); - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.voicechannel.rejoin", logMessageVoice.getMember().getAsMention(), logMessageVoice.getCurrentVoiceChannel().getAsMention())); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.voicechannel.rejoin", + logMessageVoice.getMember().getAsMention(), logMessageVoice.getCurrentVoiceChannel().getAsMention()).join()); modified = true; } @@ -92,7 +93,8 @@ else if (loggerMessage.getType() == LogTyp.VC_MOVE && loggerMessage instanceof L // Set the new Webhook Message. webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(logMessageVoice.getMember().getUser().getEffectiveName(), logMessageVoice.getMember().getEffectiveAvatarUrl(), null)); - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.voicechannel.moveMany", logMessageVoice.getMember().getAsMention(), logMessageVoice.getCurrentVoiceChannel().getAsMention())); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.voicechannel.moveMany", + logMessageVoice.getMember().getAsMention(), logMessageVoice.getCurrentVoiceChannel().getAsMention()).join()); modified = true; } @@ -112,7 +114,8 @@ else if (loggerMessage.getType() == LogTyp.VC_LEAVE && loggerMessage instanceof // Set the new Webhook Message. webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(logMessageVoice.getMember().getUser().getEffectiveName(), logMessageVoice.getMember().getEffectiveAvatarUrl(), null)); - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.voicechannel.leaveInstant", logMessageVoice.getMember().getAsMention(), logMessageVoice.getPreviousVoiceChannel().getAsMention())); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.voicechannel.leaveInstant", + logMessageVoice.getMember().getAsMention(), logMessageVoice.getPreviousVoiceChannel().getAsMention()).join()); modified = true; } @@ -146,7 +149,7 @@ else if (loggerMessage.getType() == LogTyp.NICKNAME_CHANGE && loggerMessage inst webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.nickname.changed", logMessageMember.getMember().getAsMention(), logMessageMember.getPreviousName(), - memberData != null && memberData.getPreviousName() != null ? memberData.getPreviousName() : logMessageMember.getMember().getUser().getName())); + memberData != null && memberData.getPreviousName() != null ? memberData.getPreviousName() : logMessageMember.getMember().getUser().getName()).join()); modified = true; } @@ -216,7 +219,7 @@ else if (loggerMessage.getType() == LogTyp.MEMBERROLE_CHANGE && loggerMessage in logMessageMember.getMember().getEffectiveAvatarUrl(), null)); webhookEmbedBuilder.setThumbnailUrl(logMessageMember.getMember().getEffectiveAvatarUrl()); webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.member", - logMessageMember.getMember().getAsMention())); + logMessageMember.getMember().getAsMention()).join()); if (!logMessageMember.getAddedRoles().isEmpty() || !logMessageMember.getRemovedRoles().isEmpty()) webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.roles") + ":**", stringBuilder.toString())); @@ -312,7 +315,7 @@ else if (loggerMessage.getType() == LogTyp.ROLEDATA_CHANGE && loggerMessage inst if (!logMessageRole.isCreated() && !logMessageRole.isDeleted()) { // Set update as Description - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.update", logMessageRole.getCurrentName())); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.update", logMessageRole.getCurrentName()).join()); // Check if there is a previous and current Name. if (logMessageRole.getPreviousName() != null && logMessageRole.getCurrentName() != null) { @@ -392,10 +395,10 @@ else if (loggerMessage.getType() == LogTyp.ROLEDATA_CHANGE && loggerMessage inst if (logMessageRole.isCreated()) { // Set description to new Role created. - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.create", logMessageRole.getCurrentName())); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.create", logMessageRole.getCurrentName()).join()); } else { // Set description to Role deleted. - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.delete", logMessageRole.getCurrentName())); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.delete", logMessageRole.getCurrentName()).join()); } } @@ -425,12 +428,12 @@ else if (loggerMessage.getType() == LogTyp.SERVER_LEAVE && loggerMessage instanc loggerMessages instanceof LogMessageUser logMessageUser1 && logMessageUser1.getUser().getIdLong() == logMessageUser.getUser().getIdLong()) .anyMatch(loggerMessages -> loggerMessages.getType() == LogTyp.USER_BAN)) { - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.banned", logMessageUser.getUser().getAsMention())); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.banned", logMessageUser.getUser().getAsMention()).join()); logs.stream().filter(logMessage -> logMessage != loggerMessage && logMessage.getId() == loggerMessage.getId() && logMessage instanceof LogMessageUser logMessageUser1 && logMessageUser1.getUser().getIdLong() == logMessageUser.getUser().getIdLong()).forEach(LogMessage::cancel); } else { - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.joined.leave", logMessageUser.getUser().getAsMention())); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.joined.leave", logMessageUser.getUser().getAsMention()).join()); } modified = true; diff --git a/src/main/java/de/presti/ree6/main/Main.java b/src/main/java/de/presti/ree6/main/Main.java index 95d5c2e80..22bd2a6dc 100644 --- a/src/main/java/de/presti/ree6/main/Main.java +++ b/src/main/java/de/presti/ree6/main/Main.java @@ -612,7 +612,7 @@ public void createCheckerThread() { TextChannel textChannel = BotWorker.getShardManager().getTextChannelById(birthday.getChannelId()); if (textChannel != null && textChannel.canTalk()) - textChannel.sendMessage(LanguageService.getByGuild(textChannel.getGuild(), "message.birthday.wish", birthday.getUserId())).queue(); + textChannel.sendMessage(LanguageService.getByGuild(textChannel.getGuild(), "message.birthday.wish", birthday.getUserId()).join()).queue(); }); }); @@ -739,13 +739,13 @@ public void createCheckerThread() { MessageEditBuilder messageEditBuilder = MessageEditBuilder.fromMessage(message); reaction.retrieveUsers().mapToResult().onErrorMap(throwable -> { - messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.error")); + messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.error").join()); message.editMessage(messageEditBuilder.build()).queue(); toDelete.add(giveaway); return null; }).queue(users -> { if (users == null) { - messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.less")); + messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.less").join()); message.editMessage(messageEditBuilder.build()).queue(); return; } @@ -753,13 +753,13 @@ public void createCheckerThread() { users.onSuccess(userList -> { if (userList.isEmpty()) { - messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.none")); + messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.none").join()); message.editMessage(messageEditBuilder.build()).queue(); return; } if (userList.stream().filter(user -> !user.isBot()).count() < giveaway.getWinners()) { - messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.less")); + messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.less").join()); message.editMessage(messageEditBuilder.build()).queue(); return; } From f84a14671e5282f0ca0550d39b83daf1a8de17f4 Mon Sep 17 00:00:00 2001 From: Presti Date: Tue, 21 May 2024 17:05:49 +0200 Subject: [PATCH 14/94] Finishing up a bit more YAY! --- .../ree6/commands/impl/economy/Money.java | 87 +- .../ree6/commands/impl/economy/Steal.java | 50 +- .../ree6/commands/impl/economy/Work.java | 20 +- .../de/presti/ree6/events/LoggingEvents.java | 219 ++--- .../de/presti/ree6/game/core/base/IGame.java | 20 +- .../ree6/module/giveaway/GiveawayManager.java | 19 +- .../module/invite/InviteContainerManager.java | 7 +- .../de/presti/ree6/utils/apis/ChatGPTAPI.java | 2 +- .../de/presti/ree6/utils/apis/Notifier.java | 768 +++++++++--------- .../utils/data/DatabaseStorageBackend.java | 45 +- .../presti/ree6/utils/data/EconomyUtil.java | 33 +- .../presti/ree6/utils/others/GuildUtil.java | 234 +++--- 12 files changed, 793 insertions(+), 711 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Money.java b/src/main/java/de/presti/ree6/commands/impl/economy/Money.java index 876dcb65e..681614a20 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Money.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Money.java @@ -4,8 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.sql.entities.economy.MoneyHolder; import de.presti.ree6.utils.data.EconomyUtil; import de.presti.ree6.utils.others.RandomUtils; import net.dv8tion.jda.api.Permission; @@ -47,14 +45,14 @@ public void onPerform(CommandEvent commandEvent) { double withdrawAmount = RandomUtils.round(amount.getAsDouble(), 2); - MoneyHolder moneyHolder = EconomyUtil.getMoneyHolder(commandEvent.getMember()); - - if (EconomyUtil.hasEnoughMoney(moneyHolder, withdrawAmount, true)) { - EconomyUtil.pay(moneyHolder, moneyHolder, withdrawAmount, true, false); - commandEvent.reply(commandEvent.getResource("message.money.withdraw", EconomyUtil.formatMoney(withdrawAmount)), 5); - } else { - commandEvent.reply(commandEvent.getResource("message.money.notEnoughMoney"), 5); - } + EconomyUtil.getMoneyHolder(commandEvent.getMember()).thenAccept(moneyHolder -> { + if (EconomyUtil.hasEnoughMoney(moneyHolder, withdrawAmount, true)) { + EconomyUtil.pay(moneyHolder, moneyHolder, withdrawAmount, true, false); + commandEvent.reply(commandEvent.getResource("message.money.withdraw", EconomyUtil.formatMoney(withdrawAmount)), 5); + } else { + commandEvent.reply(commandEvent.getResource("message.money.notEnoughMoney"), 5); + } + }); } case "deposit" -> { if (amount == null) { @@ -64,14 +62,14 @@ public void onPerform(CommandEvent commandEvent) { double depositAmount = RandomUtils.round(amount.getAsDouble(), 2); - MoneyHolder moneyHolder = EconomyUtil.getMoneyHolder(commandEvent.getMember()); - - if (EconomyUtil.hasEnoughMoney(moneyHolder, depositAmount, false)) { - EconomyUtil.pay(moneyHolder, moneyHolder, depositAmount, false, true); - commandEvent.reply(commandEvent.getResource("message.money.deposit", EconomyUtil.formatMoney(depositAmount)), 5); - } else { - commandEvent.reply(commandEvent.getResource("message.money.notEnoughMoney"), 5); - } + EconomyUtil.getMoneyHolder(commandEvent.getMember()).thenAccept(moneyHolder -> { + if (EconomyUtil.hasEnoughMoney(moneyHolder, depositAmount, false)) { + EconomyUtil.pay(moneyHolder, moneyHolder, depositAmount, false, true); + commandEvent.reply(commandEvent.getResource("message.money.deposit", EconomyUtil.formatMoney(depositAmount)), 5); + } else { + commandEvent.reply(commandEvent.getResource("message.money.notEnoughMoney"), 5); + } + }); } case "send" -> { if (user == null || amount == null) { @@ -88,14 +86,15 @@ public void onPerform(CommandEvent commandEvent) { double sendAmount = RandomUtils.round(amount.getAsDouble(), 2); - MoneyHolder moneyHolder = EconomyUtil.getMoneyHolder(commandEvent.getMember()); - MoneyHolder target = EconomyUtil.getMoneyHolder(member); - - if (EconomyUtil.pay(moneyHolder, target, sendAmount, true, true)) { - commandEvent.reply(commandEvent.getResource("message.money.send", EconomyUtil.formatMoney(sendAmount), member.getAsMention())); - } else { - commandEvent.reply(commandEvent.getResource("message.money.notEnoughMoney"), 5); - } + EconomyUtil.getMoneyHolder(commandEvent.getMember()).thenAccept(moneyHolder -> { + EconomyUtil.getMoneyHolder(member).thenAccept(target -> { + if (EconomyUtil.pay(moneyHolder, target, sendAmount, true, true)) { + commandEvent.reply(commandEvent.getResource("message.money.send", EconomyUtil.formatMoney(sendAmount), member.getAsMention())); + } else { + commandEvent.reply(commandEvent.getResource("message.money.notEnoughMoney"), 5); + } + }); + }); } default -> { if (user != null) { @@ -106,11 +105,13 @@ public void onPerform(CommandEvent commandEvent) { return; } - MoneyHolder moneyHolder = EconomyUtil.getMoneyHolder(member); - commandEvent.reply(commandEvent.getResource("message.money.balance", member.getAsMention(), EconomyUtil.formatMoney(moneyHolder.getAmount()), EconomyUtil.formatMoney(moneyHolder.getBankAmount()))); + EconomyUtil.getMoneyHolder(member).thenAccept(moneyHolder -> + commandEvent.reply(commandEvent.getResource("message.money.balance", member.getAsMention(), + EconomyUtil.formatMoney(moneyHolder.getAmount()), EconomyUtil.formatMoney(moneyHolder.getBankAmount())))); } else { - MoneyHolder moneyHolder = EconomyUtil.getMoneyHolder(commandEvent.getMember()); - commandEvent.reply(commandEvent.getResource("message.money.balance", commandEvent.getMember().getAsMention(), EconomyUtil.formatMoney(moneyHolder.getAmount()), EconomyUtil.formatMoney(moneyHolder.getBankAmount()))); + EconomyUtil.getMoneyHolder(commandEvent.getMember()).thenAccept(moneyHolder -> + commandEvent.reply(commandEvent.getResource("message.money.balance", commandEvent.getMember().getAsMention(), + EconomyUtil.formatMoney(moneyHolder.getAmount()), EconomyUtil.formatMoney(moneyHolder.getBankAmount())))); } } } @@ -141,20 +142,26 @@ public void onPerform(CommandEvent commandEvent) { if (subcommandGroup.equals("admin")) { switch (subcommand) { case "add" -> { - EconomyUtil.pay(EconomyUtil.getMoneyHolder(commandEvent.getMember()), - EconomyUtil.getMoneyHolder(member), optionAmount, false, - transferToBank, true); - commandEvent.reply(commandEvent.getResource("message.money.add", EconomyUtil.formatMoney(optionAmount), member.getAsMention()), 5); + EconomyUtil.getMoneyHolder(commandEvent.getMember()).thenAccept(moneyHolder -> { + EconomyUtil.getMoneyHolder(member).thenAccept(target -> { + EconomyUtil.pay(moneyHolder, target, optionAmount, false, transferToBank, true); + commandEvent.reply(commandEvent.getResource("message.money.add", EconomyUtil.formatMoney(optionAmount), member.getAsMention()), 5); + }); + }); } case "set" -> { - EconomyUtil.set(EconomyUtil.getMoneyHolder(member), optionAmount, transferToBank); - commandEvent.reply(commandEvent.getResource("message.money.set", member.getAsMention(), EconomyUtil.formatMoney(optionAmount)), 5); + EconomyUtil.getMoneyHolder(member).thenAccept(moneyHolder -> { + EconomyUtil.set(moneyHolder, optionAmount, transferToBank); + commandEvent.reply(commandEvent.getResource("message.money.set", member.getAsMention(), EconomyUtil.formatMoney(optionAmount)), 5); + }); } case "remove" -> { - EconomyUtil.pay(EconomyUtil.getMoneyHolder(commandEvent.getMember()), - EconomyUtil.getMoneyHolder(member), -optionAmount, false, - transferToBank, true); - commandEvent.reply(commandEvent.getResource("message.money.remove", EconomyUtil.formatMoney(optionAmount), member.getAsMention()), 5); + EconomyUtil.getMoneyHolder(commandEvent.getMember()).thenAccept(moneyHolder -> { + EconomyUtil.getMoneyHolder(member).thenAccept(target -> { + EconomyUtil.pay(moneyHolder, target, -optionAmount, false, transferToBank, true); + commandEvent.reply(commandEvent.getResource("message.money.remove", EconomyUtil.formatMoney(optionAmount), member.getAsMention()), 5); + }); + }); } } } else { diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java b/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java index ee5306a84..ec323cf6f 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java @@ -6,7 +6,6 @@ import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Setting; -import de.presti.ree6.sql.entities.economy.MoneyHolder; import de.presti.ree6.utils.data.EconomyUtil; import de.presti.ree6.utils.others.RandomUtils; import de.presti.ree6.utils.others.ThreadUtil; @@ -71,24 +70,37 @@ public void onPerform(CommandEvent commandEvent) { return; } - MoneyHolder targetHolder = EconomyUtil.getMoneyHolder(commandEvent.getGuild().getIdLong(), member.getIdLong(), false); - - // Leave them poor people alone ong. - if (!EconomyUtil.hasCash(targetHolder) || targetHolder.getAmount() <= 50) { - commandEvent.reply(commandEvent.getResource("message.steal.notEnoughMoney", member.getAsMention()), 5); - return; - } - - double stealAmount = RandomUtils.round(targetHolder.getAmount() * RandomUtils.nextDouble(0.01, 0.25), 2); - if (EconomyUtil.pay(targetHolder, EconomyUtil.getMoneyHolder(commandEvent.getMember()), stealAmount, false, false)) { - // TODO:: more variation in the messages. - commandEvent.reply(commandEvent.getResource("message.steal.success", EconomyUtil.formatMoney(stealAmount), member.getAsMention()), 5); - } else { - commandEvent.reply(commandEvent.getResource("message.steal.failed", EconomyUtil.formatMoney(stealAmount), member.getAsMention()), 5); - } - - stealTimeout.add(entryString); - ThreadUtil.createThread(x -> stealTimeout.remove(entryString), Duration.ofSeconds(delay), false, false); + EconomyUtil.getMoneyHolder(commandEvent.getGuild().getIdLong(), member.getIdLong(), false).thenAccept(targetHolder -> { + if (targetHolder == null) { + commandEvent.reply(commandEvent.getResource("message.steal.notEnoughMoney", member.getAsMention()), 5); + return; + } + + // Leave them poor people alone ong. + if (!EconomyUtil.hasCash(targetHolder) || targetHolder.getAmount() <= 50) { + commandEvent.reply(commandEvent.getResource("message.steal.notEnoughMoney", member.getAsMention()), 5); + return; + } + + double stealAmount = RandomUtils.round(targetHolder.getAmount() * RandomUtils.nextDouble(0.01, 0.25), 2); + + EconomyUtil.getMoneyHolder(commandEvent.getMember()).thenAccept(holder -> { + if (holder == null) { + commandEvent.reply(commandEvent.getResource("message.steal.notEnoughMoney", member.getAsMention()), 5); + return; + } + + if (EconomyUtil.pay(targetHolder, holder, stealAmount, false, false)) { + // TODO:: more variation in the messages. + commandEvent.reply(commandEvent.getResource("message.steal.success", EconomyUtil.formatMoney(stealAmount), member.getAsMention()), 5); + } else { + commandEvent.reply(commandEvent.getResource("message.steal.failed", EconomyUtil.formatMoney(stealAmount), member.getAsMention()), 5); + } + + stealTimeout.add(entryString); + ThreadUtil.createThread(x -> stealTimeout.remove(entryString), Duration.ofSeconds(delay), false, false); + }); + }); }); } diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Work.java b/src/main/java/de/presti/ree6/commands/impl/economy/Work.java index 09991d2c0..623c3176f 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Work.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Work.java @@ -50,15 +50,19 @@ public void onPerform(CommandEvent commandEvent) { double amount = RandomUtils.round(RandomUtils.nextDouble(min, max), 2); - if (EconomyUtil.pay(null, EconomyUtil.getMoneyHolder(commandEvent.getMember()), amount, false, false, true)) { - // TODO:: add more variation messages. - commandEvent.reply(commandEvent.getResource("message.work.success", EconomyUtil.formatMoney(amount))); - } else { - commandEvent.reply(commandEvent.getResource("message.work.fail")); - } + EconomyUtil.getMoneyHolder(commandEvent.getMember()).thenAccept(moneyHolder -> { + if (moneyHolder == null) return; + + if (EconomyUtil.pay(null, moneyHolder, amount, false, false, true)) { + // TODO:: add more variation messages. + commandEvent.reply(commandEvent.getResource("message.work.success", EconomyUtil.formatMoney(amount))); + } else { + commandEvent.reply(commandEvent.getResource("message.work.fail")); + } - workTimeout.add(entryString); - ThreadUtil.createThread(x -> workTimeout.remove(entryString), Duration.ofSeconds(delay), false, false); + workTimeout.add(entryString); + ThreadUtil.createThread(x -> workTimeout.remove(entryString), Duration.ofSeconds(delay), false, false); + }); }); } diff --git a/src/main/java/de/presti/ree6/events/LoggingEvents.java b/src/main/java/de/presti/ree6/events/LoggingEvents.java index e38ad84f0..29bbd01c3 100644 --- a/src/main/java/de/presti/ree6/events/LoggingEvents.java +++ b/src/main/java/de/presti/ree6/events/LoggingEvents.java @@ -3,6 +3,7 @@ import club.minnced.discord.webhook.send.WebhookEmbed; import club.minnced.discord.webhook.send.WebhookEmbedBuilder; import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.language.LanguageService; import de.presti.ree6.logger.LogMessage; import de.presti.ree6.logger.LogTyp; @@ -10,14 +11,12 @@ import de.presti.ree6.logger.events.LogMessageRole; import de.presti.ree6.logger.events.LogMessageUser; import de.presti.ree6.logger.events.LogMessageVoice; -import de.presti.ree6.module.invite.InviteContainer; -import de.presti.ree6.module.invite.InviteContainerManager; import de.presti.ree6.main.Main; +import de.presti.ree6.module.invite.InviteContainer; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Invite; import de.presti.ree6.sql.entities.webhook.base.Webhook; import de.presti.ree6.utils.data.ArrayUtil; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.audit.ActionType; import net.dv8tion.jda.api.audit.AuditLogEntry; @@ -91,33 +90,36 @@ public void onGuildUpdateVanityCode(@NotNull GuildUpdateVanityCodeEvent event) { @Override public void onGuildBan(@Nonnull GuildBanEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberban").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberban").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.banned", event.getUser().getAsMention())); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByEvent(event, "logging.banned", event.getUser().getAsMention()).join()); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.BAN).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.BAN).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.USER_BAN, event.getUser())); + Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).join(); + Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.USER_BAN, event.getUser())); + }); + }); } /** @@ -126,33 +128,36 @@ public void onGuildBan(@Nonnull GuildBanEvent event) { @Override public void onGuildUnban(@Nonnull GuildUnbanEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberunban").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberunban").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.unbanned", event.getUser().getAsMention())); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByEvent(event, "logging.unbanned", event.getUser().getAsMention()).join()); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.UNBAN).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.UNBAN).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.USER_UNBAN, event.getUser())); + Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).join(); + Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.USER_UNBAN, event.getUser())); + }); + }); } //endregion @@ -165,72 +170,76 @@ public void onGuildUnban(@Nonnull GuildUnbanEvent event) { @Override public void onGuildMemberJoin(GuildMemberJoinEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong())) - return; - - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - - if (SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberjoin").getBooleanValue()) { - WebhookMessageBuilder wm = new WebhookMessageBuilder(); - - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); - - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.joined.default", event.getUser().getAsMention(), TimeFormat.DATE_TIME_SHORT.format(event.getUser().getTimeCreated()), TimeFormat.RELATIVE.format(event.getUser().getTimeCreated()))); - - wm.addEmbeds(we.build()); - Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.SERVER_JOIN, event.getUser())); - } - - if (event.getGuild().getSelfMember().hasPermission(Permission.MANAGE_SERVER) && SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_invite").getBooleanValue()) { - - WebhookMessageBuilder wm2 = new WebhookMessageBuilder(); - - wm2.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm2.setUsername(BotConfig.getBotName() + "-InviteLogs"); - - if (event.getUser().isBot()) { - event.getGuild().retrieveAuditLogs().type(ActionType.BOT_ADD).limit(1).queue(auditLogEntries -> { - if (auditLogEntries.isEmpty()) { - wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention())); - return; - } - AuditLogEntry entry = auditLogEntries.get(0); + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if(!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberjoin").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; + WebhookMessageBuilder wm = new WebhookMessageBuilder(); + + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); + + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByEvent(event, "logging.joined.default", event.getUser().getAsMention(), TimeFormat.DATE_TIME_SHORT.format(event.getUser().getTimeCreated()), TimeFormat.RELATIVE.format(event.getUser().getTimeCreated())).join()); + + wm.addEmbeds(we.build()); + Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.SERVER_JOIN, event.getUser())); + }); - if (entry.getUser() == null) { - wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention())); - return; - } + if (event.getGuild().getSelfMember().hasPermission(Permission.MANAGE_SERVER)) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_invite").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; + WebhookMessageBuilder wm2 = new WebhookMessageBuilder(); + + wm2.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm2.setUsername(BotConfig.getBotName() + "-InviteLogs"); + + if (event.getUser().isBot()) { + event.getGuild().retrieveAuditLogs().type(ActionType.BOT_ADD).limit(1).queue(auditLogEntries -> { + if (auditLogEntries.isEmpty()) { + wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention()).join()); + return; + } + AuditLogEntry entry = auditLogEntries.get(0); + + if (entry.getUser() == null) { + wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention()).join()); + return; + } + + if (entry.getTargetId().equals(event.getUser().getId())) { + wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.found", event.getUser().getAsMention(), entry.getUser().getAsMention()).join()); + } else { + wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention()).join()); + } + }); + } else { + InviteContainer inviteContainer = Main.getInstance().getInviteContainerManager().getRightInvite(event.getGuild()); + if (inviteContainer != null) { + inviteContainer.setUses(inviteContainer.getUses() + 1); + if (inviteContainer.isVanity()) { + wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.vanity", event.getUser().getAsMention()).join()); + } else { + wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.default", event.getUser().getAsMention(), "<@" + inviteContainer.getCreatorId() + ">", inviteContainer.getCode(), inviteContainer.getUses()).join()); + } + Main.getInstance().getInviteContainerManager().add(inviteContainer); + } else { + wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.notFound", event.getMember().getAsMention()).join()); + } + } - if (entry.getTargetId().equals(event.getUser().getId())) { - wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.found", event.getUser().getAsMention(), entry.getUser().getAsMention())); - } else { - wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention())); - } - }); - } else { - InviteContainer inviteContainer = Main.getInstance().getInviteContainerManager().getRightInvite(event.getGuild()); - if (inviteContainer != null) { - inviteContainer.setUses(inviteContainer.getUses() + 1); - if (inviteContainer.isVanity()) { - wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.vanity", event.getUser().getAsMention())); - } else { - wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.default", event.getUser().getAsMention(), "<@" + inviteContainer.getCreatorId() + ">", inviteContainer.getCode(), inviteContainer.getUses())); - } - Main.getInstance().getInviteContainerManager().add(inviteContainer); - } else { - wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.notFound", event.getMember().getAsMention())); + Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm2.build(), event.getGuild(), LogTyp.SERVER_INVITE, event.getUser())); + }); } - } + }); + }); - Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm2.build(), event.getGuild(), LogTyp.SERVER_INVITE, event.getUser())); - } } /** diff --git a/src/main/java/de/presti/ree6/game/core/base/IGame.java b/src/main/java/de/presti/ree6/game/core/base/IGame.java index 627915bf2..d499aac9e 100644 --- a/src/main/java/de/presti/ree6/game/core/base/IGame.java +++ b/src/main/java/de/presti/ree6/game/core/base/IGame.java @@ -1,15 +1,11 @@ package de.presti.ree6.game.core.base; import de.presti.ree6.game.core.GameSession; -import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.sql.entities.economy.MoneyHolder; import de.presti.ree6.utils.data.EconomyUtil; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.react.GenericMessageReactionEvent; -import java.util.Map; - /** * Interface for Games to implement. */ @@ -27,12 +23,14 @@ public interface IGame { /** * Called when a User wants to join the Game. + * * @param user The User who wants to join. */ void joinGame(GamePlayer user); /** * Called when a User wants to leave the Game. + * * @param user The User who wants to leave. */ void leaveGame(GamePlayer user); @@ -66,19 +64,23 @@ default void onButtonInteractionReceive(ButtonInteractionEvent buttonInteraction /** * Called when a User should be rewarded. + * * @param gameSession The current Session. - * @param player The Player who should be rewarded. - * @param parameter Any additional Parameter. + * @param player The Player who should be rewarded. + * @param parameter Any additional Parameter. */ default void rewardPlayer(GameSession gameSession, GamePlayer player, Object parameter) { if (parameter instanceof String parameterString) { try { parameter = Double.parseDouble(parameterString.replace(",", ".")); - } catch (Exception ignore) {} + } catch (Exception ignore) { + } } if (parameter instanceof Double money) { - EconomyUtil.pay(null, EconomyUtil.getMoneyHolder(gameSession.getGuild().getIdLong(), player.getRelatedUserId(), true), - money, false, false, true); + EconomyUtil.getMoneyHolder(gameSession.getGuild().getIdLong(), player.getRelatedUserId(), true).thenAccept(moneyHolder -> { + if (moneyHolder == null) return; + EconomyUtil.pay(null, moneyHolder, money, false, false, true); + }); } } diff --git a/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java b/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java index 7ae4d03d5..166e3971a 100644 --- a/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java +++ b/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java @@ -35,8 +35,9 @@ public GiveawayManager() { */ @Override public void load() { - replace(SQLSession.getSqlConnector().getSqlWorker() - .getEntityList(new Giveaway(), "FROM Giveaway", null)); + SQLSession.getSqlConnector().getSqlWorker() + .getEntityList(new Giveaway(), "FROM Giveaway", null) + .thenAccept(this::replace); } /** @@ -58,13 +59,13 @@ public Giveaway get(long value) { } } - Giveaway giveaway = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Giveaway(), "FROM Giveaway WHERE messageId = :id", Map.of("id", value)); - - if (giveaway != null) { - giveaways.add(giveaway); - return giveaway; - } - return null; + return SQLSession.getSqlConnector().getSqlWorker().getEntity(new Giveaway(), "FROM Giveaway WHERE messageId = :id", Map.of("id", value)).thenApply(giveaway -> { + if (giveaway != null) { + giveaways.add(giveaway); + return giveaway; + } + return null; + }).join(); } @Override diff --git a/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java b/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java index 8615ce955..dbc74fff2 100644 --- a/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java +++ b/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java @@ -43,7 +43,8 @@ public List getInvites(long guildId) { @Override public void load() { - replace(SQLSession.getSqlConnector().getSqlWorker().getEntityList(new de.presti.ree6.sql.entities.Invite(), "FROM Invite", null).stream().map(InviteContainer::new).toList()); + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new de.presti.ree6.sql.entities.Invite(), "FROM Invite", null) + .thenAccept(invites1 -> replace(invites1.stream().map(InviteContainer::new).toList())); } /** @@ -53,8 +54,8 @@ public void load() { */ public void refreshGuild(long guildId) { invites.removeIf(x -> x.guildId == guildId); - getList().addAll(SQLSession.getSqlConnector().getSqlWorker().getEntityList(new de.presti.ree6.sql.entities.Invite(), "FROM Invite WHERE guildAndCode.guildId = :gid", Map.of("gid", guildId)) - .stream().map(InviteContainer::new).toList()); + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new de.presti.ree6.sql.entities.Invite(), "FROM Invite WHERE guildAndCode.guildId = :gid", Map.of("gid", guildId)) + .thenAccept(invites1 -> replace(invites1.stream().map(InviteContainer::new).toList())); } /** diff --git a/src/main/java/de/presti/ree6/utils/apis/ChatGPTAPI.java b/src/main/java/de/presti/ree6/utils/apis/ChatGPTAPI.java index 4ac8f8b02..f6b10da93 100644 --- a/src/main/java/de/presti/ree6/utils/apis/ChatGPTAPI.java +++ b/src/main/java/de/presti/ree6/utils/apis/ChatGPTAPI.java @@ -79,7 +79,7 @@ public static String getResponse(Member member, String message) { response = getResponse(messages); } catch (BizException e) { Sentry.captureException(e); - return LanguageService.getByGuild(member.getGuild(), "message.default.retrievalError"); + return LanguageService.getByGuild(member.getGuild(), "message.default.retrievalError").join(); } messages.add(new Message("assistant", response)); diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index 2e76529ce..48601930c 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -30,7 +30,6 @@ import com.github.twitch4j.helix.domain.User; import com.github.twitch4j.pubsub.PubSubSubscription; import com.github.twitch4j.pubsub.events.RewardRedeemedEvent; -import de.presti.ree6.actions.streamtools.container.StreamActionContainer; import de.presti.ree6.actions.streamtools.container.StreamActionContainerCreator; import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; @@ -40,7 +39,6 @@ import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.TwitchIntegration; import de.presti.ree6.sql.entities.stats.ChannelStats; -import de.presti.ree6.sql.entities.webhook.*; import de.presti.ree6.utils.data.DatabaseStorageBackend; import de.presti.ree6.utils.others.ThreadUtil; import de.presti.wrapper.entities.VideoResult; @@ -186,46 +184,50 @@ public Notifier() { .withCredentialManager(credentialManager) .build(); - for (TwitchIntegration twitchIntegrations : - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), "FROM TwitchIntegration", null)) { + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), "FROM TwitchIntegration", null).thenAccept(twitchIntegrations -> { + for (TwitchIntegration twitchIntegration : twitchIntegrations) { + OAuth2Credential credential = new OAuth2Credential("twitch", twitchIntegration.getToken()); - OAuth2Credential credential = new OAuth2Credential("twitch", twitchIntegrations.getToken()); + PubSubSubscription[] subscriptions = new PubSubSubscription[2]; + subscriptions[0] = getTwitchClient().getPubSub().listenForChannelPointsRedemptionEvents(credential, twitchIntegration.getChannelId()); + subscriptions[1] = getTwitchClient().getPubSub().listenForSubscriptionEvents(credential, twitchIntegration.getChannelId()); - PubSubSubscription[] subscriptions = new PubSubSubscription[2]; - subscriptions[0] = getTwitchClient().getPubSub().listenForChannelPointsRedemptionEvents(credential, twitchIntegrations.getChannelId()); - subscriptions[1] = getTwitchClient().getPubSub().listenForSubscriptionEvents(credential, twitchIntegrations.getChannelId()); + getTwitchClient().getClientHelper().enableFollowEventListener(twitchIntegration.getChannelId()); - getTwitchClient().getClientHelper().enableFollowEventListener(twitchIntegrations.getChannelId()); - - twitchSubscription.put(credential.getUserId(), subscriptions); - } + twitchSubscription.put(credential.getUserId(), subscriptions); + } + }); twitchClient.getEventManager().onEvent(RewardRedeemedEvent.class, event -> { - List list = StreamActionContainerCreator.getContainers(0); - list.forEach(container -> { - if (!event.getRedemption().getChannelId().equalsIgnoreCase(container.getTwitchChannelId())) return; + StreamActionContainerCreator.getContainers(0).thenAccept(list -> { + list.forEach(container -> { + if (!event.getRedemption().getChannelId().equalsIgnoreCase(container.getTwitchChannelId())) + return; - if (container.getExtraArgument() == null || event.getRedemption().getReward().getId().equals(container.getExtraArgument())) { - container.runActions(event, event.getRedemption().getUserInput()); - } + if (container.getExtraArgument() == null || event.getRedemption().getReward().getId().equals(container.getExtraArgument())) { + container.runActions(event, event.getRedemption().getUserInput()); + } + }); }); }); twitchClient.getEventManager().onEvent(FollowEvent.class, event -> { - List list = StreamActionContainerCreator.getContainers(1); - list.forEach(container -> { - if (!event.getChannel().getId().equalsIgnoreCase(container.getTwitchChannelId())) return; + StreamActionContainerCreator.getContainers(1).thenAccept(list -> { + list.forEach(container -> { + if (!event.getChannel().getId().equalsIgnoreCase(container.getTwitchChannelId())) return; - container.runActions(event, event.getUser().getName()); + container.runActions(event, event.getUser().getName()); + }); }); }); twitchClient.getEventManager().onEvent(ChannelSubscribeEvent.class, event -> { - List list = StreamActionContainerCreator.getContainers(2); - list.forEach(container -> { - if (!event.getBroadcasterUserId().equalsIgnoreCase(container.getTwitchChannelId())) return; + StreamActionContainerCreator.getContainers(2).thenAccept(list -> { + list.forEach(container -> { + if (!event.getBroadcasterUserId().equalsIgnoreCase(container.getTwitchChannelId())) return; - container.runActions(null, event.getUserName()); + container.runActions(null, event.getUserName()); + }); }); }); } catch (Exception exception) { @@ -302,33 +304,35 @@ public Notifier() { log.info("Creating Twitter Streams..."); ThreadUtil.createThread(x -> { for (String twitterName : registeredTwitterUsers) { - List channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", Map.of("name", twitterName)); - if (!channelStats.isEmpty()) { - UserV2 twitterUser; - try { - twitterUser = Main.getInstance().getNotifier().getTwitterClient().getUserFromUserName(twitterName); - } catch (NoSuchElementException e) { - continue; - } + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), + "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", Map.of("name", twitterName)).thenAccept(channelStats -> { + if (!channelStats.isEmpty()) { + UserV2 twitterUser; + try { + twitterUser = Main.getInstance().getNotifier().getTwitterClient().getUserFromUserName(twitterName); + } catch (NoSuchElementException e) { + return; + } - if (twitterUser.getData() == null) continue; + if (twitterUser.getData() == null) return; - for (ChannelStats channelStat : channelStats) { - if (channelStat.getTwitterFollowerChannelUsername() != null) { - GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getTwitchFollowerChannelId()); - if (guildChannel == null) continue; - String newName = LanguageService.getByGuild(guildChannel.getGuild(), "label.twitterCountName", twitterUser.getFollowersCount()); + for (ChannelStats channelStat : channelStats) { + if (channelStat.getTwitterFollowerChannelUsername() != null) { + GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getTwitchFollowerChannelId()); + if (guildChannel == null) continue; - if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) - continue; + LanguageService.getByGuild(guildChannel.getGuild(), "label.twitterCountName", twitterUser.getFollowersCount()).thenAccept(newName -> { + if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) + return; - if (!guildChannel.getName().equalsIgnoreCase(newName)) { - guildChannel.getManager().setName(newName).queue(); + if (!guildChannel.getName().equalsIgnoreCase(newName)) { + guildChannel.getManager().setName(newName).queue(); + } + }); } } } - } + }); } }, x -> { log.error("Failed to run Twitter Follower count checker!", x); @@ -426,90 +430,91 @@ public void createRssStream() { if (typ.equals("tw")) { - List webhooks = SQLSession.getSqlConnector().getSqlWorker().getTwitterWebhooksByName(item.getChannel().getLink().replace("https://nitter.net/", "")); + SQLSession.getSqlConnector().getSqlWorker().getTwitterWebhooksByName(item.getChannel().getLink().replace("https://nitter.net/", "")).thenAccept(webhooks -> { - if (webhooks.isEmpty()) return; - - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + if (webhooks.isEmpty()) return; - webhookMessageBuilder.setUsername(BotConfig.getBotName()); - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); - item.getChannel().getImage().ifPresentOrElse(image -> - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), - URLDecoder.decode(image.getUrl().replace("nitter.net/pic/", ""), StandardCharsets.UTF_8), null)), - () -> webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), null, null))); + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + item.getChannel().getImage().ifPresentOrElse(image -> + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), + URLDecoder.decode(image.getUrl().replace("nitter.net/pic/", ""), StandardCharsets.UTF_8), null)), + () -> webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), null, null))); - webhookEmbedBuilder.setDescription(item.getTitle() + "\n"); - item.getDescription().ifPresent(description -> { - if (description.contains(" { + if (description.contains(" { - String message = webhook.getMessage() - .replace("%name%", item.getChannel().getTitle()); + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - if (item.getLink().isPresent()) { - message = message.replace("%url%", item.getLink().get() - .replace("nitter.net", "twitter.com")) - .replace("#m", ""); - } - webhookMessageBuilder.setContent(message); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); + webhooks.forEach(webhook -> { + String message = webhook.getMessage() + .replace("%name%", item.getChannel().getTitle()); + + if (item.getLink().isPresent()) { + message = message.replace("%url%", item.getLink().get() + .replace("nitter.net", "twitter.com")) + .replace("#m", ""); + } + webhookMessageBuilder.setContent(message); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); + }); }); } else { try { - List webhooks = SQLSession.getSqlConnector().getSqlWorker().getRSSWebhooksByUrl(id); + SQLSession.getSqlConnector().getSqlWorker().getRSSWebhooksByUrl(id).thenAccept(webhooks -> { + if (webhooks.isEmpty()) return; - if (webhooks.isEmpty()) return; + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName()); - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + item.getChannel().getImage().ifPresentOrElse(image -> + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), + URLDecoder.decode(image.getUrl(), StandardCharsets.UTF_8), null)), + () -> webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), null, null))); - item.getChannel().getImage().ifPresentOrElse(image -> - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), - URLDecoder.decode(image.getUrl(), StandardCharsets.UTF_8), null)), - () -> webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), null, null))); + item.getDescription().ifPresent(description -> webhookEmbedBuilder.setDescription(description + "\n")); - item.getDescription().ifPresent(description -> webhookEmbedBuilder.setDescription(description + "\n")); + if (item instanceof ItunesItem itunesItem) { + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(itunesItem.getItunesTitle().orElse("No Title"), item.getLink().orElse("No Link"))); + itunesItem.getItunesImage().ifPresent(webhookEmbedBuilder::setThumbnailUrl); + } else { - if (item instanceof ItunesItem itunesItem) { - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(itunesItem.getItunesTitle().orElse("No Title"), item.getLink().orElse("No Link"))); - itunesItem.getItunesImage().ifPresent(webhookEmbedBuilder::setThumbnailUrl); - } else { + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(item.getTitle().orElse("No Title"), item.getLink().orElse("No Link"))); + } - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(item.getTitle().orElse("No Title"), item.getLink().orElse("No Link"))); - } + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("RSS Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl(), null)); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("RSS Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl(), null)); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); + webhookEmbedBuilder.setTimestamp(Instant.now()); + webhookEmbedBuilder.setColor(Color.CYAN.getRGB()); - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); - webhookEmbedBuilder.setTimestamp(Instant.now()); - webhookEmbedBuilder.setColor(Color.CYAN.getRGB()); - - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook)); + webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook)); + }); } catch (Exception exception) { Sentry.captureException(exception); } @@ -529,67 +534,73 @@ public void createRssStream() { public void registerTwitchEventHandler() { getTwitchClient().getEventManager().onEvent(ChannelGoLiveEvent.class, channelGoLiveEvent -> { - List webhooks = SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(channelGoLiveEvent.getChannel().getName()); - if (webhooks.isEmpty()) { - return; - } + SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(channelGoLiveEvent.getChannel().getName()).thenAccept(webhooks -> { + if (webhooks.isEmpty()) { + return; + } - String twitchUrl = "https://twitch.tv/" + channelGoLiveEvent.getChannel().getName(); + String twitchUrl = "https://twitch.tv/" + channelGoLiveEvent.getChannel().getName(); - // Create a Webhook Message. - WebhookMessageBuilder wmb = new WebhookMessageBuilder(); + // Create a Webhook Message. + WebhookMessageBuilder wmb = new WebhookMessageBuilder(); - wmb.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); - wmb.setUsername(BotConfig.getBotName()); + wmb.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); + wmb.setUsername(BotConfig.getBotName()); - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(channelGoLiveEvent.getStream().getUserName(), twitchUrl)); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Twitch Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl(), null)); + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(channelGoLiveEvent.getStream().getUserName(), twitchUrl)); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Twitch Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl(), null)); - // Try getting the User. - Optional twitchUserRequest = getTwitchClient().getHelix().getUsers(null, null, Collections.singletonList(channelGoLiveEvent.getStream().getUserName())).execute().getUsers().stream().findFirst(); - if (twitchUserRequest.isPresent()) { - webhookEmbedBuilder.setThumbnailUrl(twitchUserRequest.orElseThrow().getProfileImageUrl()); - } - webhookEmbedBuilder.setImageUrl(channelGoLiveEvent.getStream().getThumbnailUrl()); - - // Set rest of the Information. - webhookEmbedBuilder.setDescription("**" + channelGoLiveEvent.getStream().getTitle() + "**\n[Watch Stream](" + twitchUrl + ")"); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Game**", channelGoLiveEvent.getStream().getGameName())); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Viewer**", String.valueOf(channelGoLiveEvent.getStream().getViewerCount()))); - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); - webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); - - wmb.addEmbeds(webhookEmbedBuilder.build()); - - // Go through every Webhook that is registered for the Twitch Channel - webhooks.forEach(webhook -> { - String message = webhook.getMessage() - .replace("%name%", channelGoLiveEvent.getStream().getUserName()) - .replace("%url%", twitchUrl); - wmb.setContent(message); - WebhookUtil.sendWebhook(wmb.build(), webhook); + // Try getting the User. + Optional twitchUserRequest = getTwitchClient().getHelix().getUsers(null, null, Collections.singletonList(channelGoLiveEvent.getStream().getUserName())).execute().getUsers().stream().findFirst(); + if (twitchUserRequest.isPresent()) { + webhookEmbedBuilder.setThumbnailUrl(twitchUserRequest.orElseThrow().getProfileImageUrl()); + } + webhookEmbedBuilder.setImageUrl(channelGoLiveEvent.getStream().getThumbnailUrl()); + + // Set rest of the Information. + webhookEmbedBuilder.setDescription("**" + channelGoLiveEvent.getStream().getTitle() + "**\n[Watch Stream](" + twitchUrl + ")"); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Game**", channelGoLiveEvent.getStream().getGameName())); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Viewer**", String.valueOf(channelGoLiveEvent.getStream().getViewerCount()))); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); + webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); + + wmb.addEmbeds(webhookEmbedBuilder.build()); + + // Go through every Webhook that is registered for the Twitch Channel + webhooks.forEach(webhook -> { + String message = webhook.getMessage() + .replace("%name%", channelGoLiveEvent.getStream().getUserName()) + .replace("%url%", twitchUrl); + wmb.setContent(message); + WebhookUtil.sendWebhook(wmb.build(), webhook); + }); }); }); getTwitchClient().getEventManager().onEvent(ChannelFollowCountUpdateEvent.class, channelFollowCountUpdateEvent -> { - List channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), "FROM ChannelStats WHERE LOWER(twitchFollowerChannelUsername) = :name", - Map.of("name", channelFollowCountUpdateEvent.getChannel().getName().toLowerCase())); - if (!channelStats.isEmpty()) { - for (ChannelStats channelStat : channelStats) { - if (channelStat.getTwitchFollowerChannelId() != null) { - GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getTwitchFollowerChannelId()); - if (guildChannel != null) { - if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) - continue; - - guildChannel.getManager().setName(LanguageService.getByGuild(guildChannel.getGuild(), "label.twitchCountName", channelFollowCountUpdateEvent.getFollowCount())).queue(); + Map.of("name", channelFollowCountUpdateEvent.getChannel().getName().toLowerCase())).thenAccept(channelStats -> { + if (!channelStats.isEmpty()) { + for (ChannelStats channelStat : channelStats) { + if (channelStat.getTwitchFollowerChannelId() != null) { + GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getTwitchFollowerChannelId()); + if (guildChannel != null) { + if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) + continue; + + LanguageService.getByGuild(guildChannel.getGuild(), "label.twitchCountName", channelFollowCountUpdateEvent.getFollowCount()).thenAccept(newName -> { + if (!guildChannel.getName().equalsIgnoreCase(newName)) { + guildChannel.getManager().setName(newName).queue(); + } + }); + } } } } - } + }); }); } @@ -638,14 +649,21 @@ public void unregisterTwitchChannel(String twitchChannel) { twitchChannel = twitchChannel.toLowerCase(); - if (!SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(twitchChannel).isEmpty() || - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitchFollowerChannelUsername=:name", Map.of("name", twitchChannel)) != null) - return; + String finalTwitchChannel = twitchChannel; + SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(twitchChannel).thenAccept(webhooks -> { + if (!webhooks.isEmpty()) return; + + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitchFollowerChannelUsername=:name", Map.of("name", finalTwitchChannel)) + .thenAccept(channelStats -> { + if (channelStats != null) return; - if (isTwitchRegistered(twitchChannel)) registeredTwitchChannels.remove(twitchChannel); + if (isTwitchRegistered(finalTwitchChannel)) + registeredTwitchChannels.remove(finalTwitchChannel); - getTwitchClient().getClientHelper().disableStreamEventListener(twitchChannel); - getTwitchClient().getClientHelper().disableFollowEventListener(twitchChannel); + getTwitchClient().getClientHelper().disableStreamEventListener(finalTwitchChannel); + getTwitchClient().getClientHelper().disableFollowEventListener(finalTwitchChannel); + }); + }); } /** @@ -696,13 +714,18 @@ public void unregisterTwitterUser(String twitterUser) { twitterUser = twitterUser.toLowerCase(); - if (!SQLSession.getSqlConnector().getSqlWorker().getTwitterWebhooksByName(twitterUser).isEmpty() || - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", Map.of("name", twitterUser)) != null) - return; + String finalTwitterUser = twitterUser; + SQLSession.getSqlConnector().getSqlWorker().getTwitterWebhooksByName(twitterUser).thenAccept(webhooks -> { + if (!webhooks.isEmpty()) return; - if (isTwitterRegistered(twitterUser)) { - registeredTwitterUsers.remove(twitterUser); - } + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", Map.of("name", finalTwitterUser)).thenAccept(x -> { + if (x != null) return; + + if (isTwitterRegistered(finalTwitterUser)) { + registeredTwitterUsers.remove(finalTwitterUser); + } + }); + }); } /** @@ -725,93 +748,94 @@ public boolean isTwitterRegistered(String twitterUser) { public void createYTStream() { ThreadUtil.createThread(x -> { for (String channel : registeredYouTubeChannels) { - List webhooks = SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(channel); + SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(channel).thenAccept(webhooks -> { + if (!webhooks.isEmpty()) { + try { + List playlistItemList = YouTubeAPIHandler.getInstance().getYouTubeUploads(channel); + if (!playlistItemList.isEmpty()) { + for (VideoResult playlistItem : playlistItemList) { - if (!webhooks.isEmpty()) { - try { - List playlistItemList = YouTubeAPIHandler.getInstance().getYouTubeUploads(channel); - if (!playlistItemList.isEmpty()) { - for (VideoResult playlistItem : playlistItemList) { + Main.getInstance().logAnalytic("Video: " + playlistItem.getTitle() + " | " + playlistItem.getUploadDate() + " | " + playlistItem.getActualUploadDate() + " | " + playlistItem.getTimeAgo()); + Main.getInstance().logAnalytic("Current: " + System.currentTimeMillis() + " | " + (playlistItem.getUploadDate() > System.currentTimeMillis() - Duration.ofMinutes(5).toMillis()) + " | " + + (playlistItem.getActualUploadDate() != null && playlistItem.getActualUploadDate().before(new Date(System.currentTimeMillis() - Duration.ofDays(2).toMillis()))) + " | " + (playlistItem.getTimeAgo() > 0 && Duration.ofMinutes(5).toMillis() >= playlistItem.getTimeAgo())); - Main.getInstance().logAnalytic("Video: " + playlistItem.getTitle() + " | " + playlistItem.getUploadDate() + " | " + playlistItem.getActualUploadDate() + " | " + playlistItem.getTimeAgo()); - Main.getInstance().logAnalytic("Current: " + System.currentTimeMillis() + " | " + (playlistItem.getUploadDate() > System.currentTimeMillis() - Duration.ofMinutes(5).toMillis()) + " | " - + (playlistItem.getActualUploadDate() != null && playlistItem.getActualUploadDate().before(new Date(System.currentTimeMillis() - Duration.ofDays(2).toMillis()))) + " | " + (playlistItem.getTimeAgo() > 0 && Duration.ofMinutes(5).toMillis() >= playlistItem.getTimeAgo())); + if (playlistItem.getUploadDate() != -1 && (playlistItem.getUploadDate() > System.currentTimeMillis() - Duration.ofMinutes(5).toMillis() || + (playlistItem.getTimeAgo() > 0 && Duration.ofMinutes(5).toMillis() >= playlistItem.getTimeAgo())) && + playlistItem.getActualUploadDate() != null && !playlistItem.getActualUploadDate().before(new Date(System.currentTimeMillis() - Duration.ofDays(2).toMillis()))) { - if (playlistItem.getUploadDate() != -1 && (playlistItem.getUploadDate() > System.currentTimeMillis() - Duration.ofMinutes(5).toMillis() || - (playlistItem.getTimeAgo() > 0 && Duration.ofMinutes(5).toMillis() >= playlistItem.getTimeAgo())) && - playlistItem.getActualUploadDate() != null && !playlistItem.getActualUploadDate().before(new Date(System.currentTimeMillis() - Duration.ofDays(2).toMillis()))) { + Main.getInstance().logAnalytic("Passed! -> " + playlistItem.getTitle() + " | " + playlistItem.getUploadDate() + " | " + playlistItem.getActualUploadDate()); + // Create a Webhook Message. + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - Main.getInstance().logAnalytic("Passed! -> " + playlistItem.getTitle() + " | " + playlistItem.getUploadDate() + " | " + playlistItem.getActualUploadDate()); - // Create a Webhook Message. - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName()); + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(playlistItem.getOwnerName(), null)); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("YouTube Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(playlistItem.getOwnerName(), null)); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("YouTube Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + webhookEmbedBuilder.setImageUrl(playlistItem.getThumbnail()); - webhookEmbedBuilder.setImageUrl(playlistItem.getThumbnail()); + webhookEmbedBuilder.setDescription("[**" + playlistItem.getTitle() + "**](https://www.youtube.com/watch?v=" + playlistItem.getId() + ")"); - webhookEmbedBuilder.setDescription("[**" + playlistItem.getTitle() + "**](https://www.youtube.com/watch?v=" + playlistItem.getId() + ")"); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + webhookEmbedBuilder.setColor(Color.RED.getRGB()); - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); - webhookEmbedBuilder.setColor(Color.RED.getRGB()); + webhooks.forEach(webhook -> { + String message = webhook.getMessage().replace("%name%", playlistItem.getOwnerName()) + .replace("%title%", playlistItem.getTitle()) + .replace("%description%", playlistItem.getDescriptionSnippet() != null ? "No Description" : playlistItem.getDescriptionSnippet()) + .replace("%url%", "https://www.youtube.com/watch?v=" + playlistItem.getId()); - webhooks.forEach(webhook -> { - String message = webhook.getMessage().replace("%name%", playlistItem.getOwnerName()) - .replace("%title%", playlistItem.getTitle()) - .replace("%description%", playlistItem.getDescriptionSnippet() != null ? "No Description" : playlistItem.getDescriptionSnippet()) - .replace("%url%", "https://www.youtube.com/watch?v=" + playlistItem.getId()); + webhookMessageBuilder.setContent(message); + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); + }); - webhookMessageBuilder.setContent(message); - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); - }); - - break; + break; + } } } + } catch (Exception exception) { + Sentry.captureException(exception); + log.error("Couldn't get user data of " + channel + "!", exception); } - } catch (Exception exception) { - Sentry.captureException(exception); - log.error("Couldn't get user data of " + channel + "!", exception); } - } - - List channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", Map.of("name", channel)); + }); - if (!channelStats.isEmpty()) { - ChannelResult youTubeChannel; - try { - // TODO:: change YT Tracker to use the ID instead of username. - youTubeChannel = YouTubeAPIHandler.getInstance().getYouTubeChannelById(channel); - } catch (Exception e) { - Sentry.captureException(e); - continue; - } + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), + "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", Map.of("name", channel)).thenAccept(channelStats -> { + if (!channelStats.isEmpty()) { + ChannelResult youTubeChannel; + try { + // TODO:: change YT Tracker to use the ID instead of username. + youTubeChannel = YouTubeAPIHandler.getInstance().getYouTubeChannelById(channel); + } catch (Exception e) { + Sentry.captureException(e); + return; + } - if (youTubeChannel == null) continue; + if (youTubeChannel == null) return; - for (ChannelStats channelStat : channelStats) { - if (channelStat.getYoutubeSubscribersChannelId() != null) { - GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getYoutubeSubscribersChannelId()); + for (ChannelStats channelStat : channelStats) { + if (channelStat.getYoutubeSubscribersChannelId() != null) { + GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getYoutubeSubscribersChannelId()); - if (guildChannel == null) continue; + if (guildChannel == null) continue; - String newName = LanguageService.getByGuild(guildChannel.getGuild(), "label.youtubeCountName", youTubeChannel.getSubscriberCountText()); - if (!guildChannel.getName().equalsIgnoreCase(newName)) { - if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) - continue; + LanguageService.getByGuild(guildChannel.getGuild(), "label.youtubeCountName", youTubeChannel.getSubscriberCountText()).thenAccept(newName -> { + if (!guildChannel.getName().equalsIgnoreCase(newName)) { + if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) + return; - guildChannel.getManager().setName(newName).queue(); + guildChannel.getManager().setName(newName).queue(); + } + }); } } } - } + }); } }, x -> { log.error("Couldn't run YT checker!", x); @@ -852,11 +876,15 @@ public void registerYouTubeChannel(List youtubeChannels) { public void unregisterYouTubeChannel(String youtubeChannel) { if (YouTubeAPIHandler.getInstance() == null) return; - if (!SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(youtubeChannel).isEmpty() || - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", Map.of("name", youtubeChannel)) != null) - return; + SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(youtubeChannel).thenAccept(webhooks -> { + if (!webhooks.isEmpty()) return; + + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", Map.of("name", youtubeChannel)).thenAccept(channelStats -> { + if (channelStats != null) return; - if (isYouTubeRegistered(youtubeChannel)) registeredYouTubeChannels.remove(youtubeChannel); + if (isYouTubeRegistered(youtubeChannel)) registeredYouTubeChannels.remove(youtubeChannel); + }); + }); } /** @@ -893,71 +921,71 @@ public void createRedditPostStream() { ThreadUtil.createThread(x -> { try { for (String subreddit : registeredSubreddits) { - List channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", Map.of("name", subreddit)); - - if (!channelStats.isEmpty()) { - RedditSubreddit subredditEntity; - try { - subredditEntity = Main.getInstance().getNotifier().getSubreddit(subreddit); - } catch (IOException | InterruptedException e) { - return; - } + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), + "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", Map.of("name", subreddit)).thenAccept(channelStats -> { + if (!channelStats.isEmpty()) { + RedditSubreddit subredditEntity; + try { + subredditEntity = Main.getInstance().getNotifier().getSubreddit(subreddit); + } catch (IOException | InterruptedException e) { + return; + } - for (ChannelStats channelStat : channelStats) { - if (channelStat.getSubredditMemberChannelId() != null) { - GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getSubredditMemberChannelId()); - String newName = "Subreddit Members: " + subredditEntity.getActiveUserCount(); - if (guildChannel != null && - !guildChannel.getName().equalsIgnoreCase(newName)) { + for (ChannelStats channelStat : channelStats) { + if (channelStat.getSubredditMemberChannelId() != null) { + GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getSubredditMemberChannelId()); + String newName = "Subreddit Members: " + subredditEntity.getActiveUserCount(); + if (guildChannel != null && + !guildChannel.getName().equalsIgnoreCase(newName)) { - if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) - continue; + if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) + continue; - guildChannel.getManager().setName(newName).queue(); + guildChannel.getManager().setName(newName).queue(); + } } } } - } + }); getSubredditPosts(subreddit, Sorting.NEW, 50).stream().filter(redditPost -> redditPost.getCreated() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())).forEach(redditPost -> { - List webhooks = SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit); + SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit).thenAccept(webhooks -> { + if (webhooks.isEmpty()) return; - if (webhooks.isEmpty()) return; - - // Create Webhook Message. - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + // Create Webhook Message. + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName()); + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(redditPost.getTitle(), redditPost.getUrl())); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Reddit Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(redditPost.getTitle(), redditPost.getUrl())); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Reddit Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); - if (!redditPost.getThumbnail().equalsIgnoreCase("self")) - webhookEmbedBuilder.setImageUrl(redditPost.getThumbnail()); + if (!redditPost.getThumbnail().equalsIgnoreCase("self")) + webhookEmbedBuilder.setImageUrl(redditPost.getThumbnail()); - // Set rest of the Information. - webhookEmbedBuilder.setDescription(URLDecoder.decode(redditPost.getSelftext(), StandardCharsets.UTF_8)); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Author**", redditPost.getAuthor())); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Subreddit**", redditPost.getSubreddit())); - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + // Set rest of the Information. + webhookEmbedBuilder.setDescription(URLDecoder.decode(redditPost.getSelftext(), StandardCharsets.UTF_8)); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Author**", redditPost.getAuthor())); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Subreddit**", redditPost.getSubreddit())); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); - webhookEmbedBuilder.setColor(Color.ORANGE.getRGB()); + webhookEmbedBuilder.setColor(Color.ORANGE.getRGB()); - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - webhooks.forEach(webhook -> { - String message = webhook.getMessage() - .replace("%title%", redditPost.getTitle()) - .replace("%author%", redditPost.getAuthor()) - .replace("%name%", redditPost.getSubreddit()) - .replace("%url%", redditPost.getUrl()); - webhookMessageBuilder.setContent(message); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); + webhooks.forEach(webhook -> { + String message = webhook.getMessage() + .replace("%title%", redditPost.getTitle()) + .replace("%author%", redditPost.getAuthor()) + .replace("%name%", redditPost.getSubreddit()) + .replace("%url%", redditPost.getUrl()); + webhookMessageBuilder.setContent(message); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); + }); }); }); } @@ -1015,11 +1043,15 @@ public void registerSubreddit(List subreddits) { public void unregisterSubreddit(String subreddit) { if (getRedditClient() == null) return; - if (!SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit).isEmpty() || - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", Map.of("name", subreddit)) != null) - return; + SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit).thenAccept(webhooks -> { + if (!webhooks.isEmpty()) return; + + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", Map.of("name", subreddit)).thenAccept(channelStats -> { + if (channelStats != null) return; - if (isSubredditRegistered(subreddit)) registeredSubreddits.remove(subreddit); + if (isSubredditRegistered(subreddit)) registeredSubreddits.remove(subreddit); + }); + }); } /** @@ -1048,71 +1080,72 @@ public void createInstagramPostStream() { instagramClient.actions().users().findByUsername(username).thenAccept(userAction -> { com.github.instagram4j.instagram4j.models.user.User user = userAction.getUser(); - List channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", Map.of("name", username)); + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), + "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", Map.of("name", username)).thenAccept(channelStats -> { + if (!channelStats.isEmpty()) { + for (ChannelStats channelStat : channelStats) { + if (channelStat.getInstagramFollowerChannelId() != null) { + GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getInstagramFollowerChannelId()); - if (!channelStats.isEmpty()) { - for (ChannelStats channelStat : channelStats) { - if (channelStat.getInstagramFollowerChannelId() != null) { - GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getInstagramFollowerChannelId()); - - if (guildChannel == null) continue; + if (guildChannel == null) continue; - String newName = LanguageService.getByGuild(guildChannel.getGuild(), "label.instagramCountName", user.getFollower_count()); - if (!guildChannel.getName().equalsIgnoreCase(newName)) { - if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) - continue; + LanguageService.getByGuild(guildChannel.getGuild(), "label.instagramCountName", user.getFollower_count()).thenAccept(newName -> { + if (!guildChannel.getName().equalsIgnoreCase(newName)) { + if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) + return; - guildChannel.getManager().setName(newName).queue(); + guildChannel.getManager().setName(newName).queue(); + } + }); } } } - } - - List webhooks = SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(username); + }); - if (webhooks.isEmpty()) return; + SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(username).thenAccept(webhooks -> { + if (webhooks.isEmpty()) return; - if (!user.is_private()) { - FeedIterator iterable = new FeedIterator<>(instagramClient, new FeedUserRequest(user.getPk())); + if (!user.is_private()) { + FeedIterator iterable = new FeedIterator<>(instagramClient, new FeedUserRequest(user.getPk())); - int limit = 1; - while (iterable.hasNext() && limit-- > 0) { - FeedUserResponse response = iterable.next(); - // Actions here - response.getItems().stream().filter(post -> post.getTaken_at() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())).forEach(instagramPost -> { - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + int limit = 1; + while (iterable.hasNext() && limit-- > 0) { + FeedUserResponse response = iterable.next(); + // Actions here + response.getItems().stream().filter(post -> post.getTaken_at() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())).forEach(instagramPost -> { + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName()); + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(user.getUsername(), "https://www.instagram.com/" + user.getUsername())); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Instagram Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(user.getUsername(), "https://www.instagram.com/" + user.getUsername())); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Instagram Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); - // Set rest of the Information. - if (instagramPost instanceof TimelineImageMedia timelineImageMedia) { - webhookEmbedBuilder.setImageUrl(timelineImageMedia.getImage_versions2().getCandidates().get(0).getUrl()); - webhookEmbedBuilder.setDescription(timelineImageMedia.getCaption().getText()); - } else if (instagramPost instanceof TimelineVideoMedia timelineVideoMedia) { - webhookEmbedBuilder.setDescription("[Click here to watch the video](" + timelineVideoMedia.getVideo_versions().get(0).getUrl() + ")"); - } else { - webhookEmbedBuilder.setDescription(user.getUsername() + " just posted something new on Instagram!"); - } + // Set the rest of the Information. + if (instagramPost instanceof TimelineImageMedia timelineImageMedia) { + webhookEmbedBuilder.setImageUrl(timelineImageMedia.getImage_versions2().getCandidates().get(0).getUrl()); + webhookEmbedBuilder.setDescription(timelineImageMedia.getCaption().getText()); + } else if (instagramPost instanceof TimelineVideoMedia timelineVideoMedia) { + webhookEmbedBuilder.setDescription("[Click here to watch the video](" + timelineVideoMedia.getVideo_versions().get(0).getUrl() + ")"); + } else { + webhookEmbedBuilder.setDescription(user.getUsername() + " just posted something new on Instagram!"); + } - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); - webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); + webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - // TODO:: add this with message. + // TODO:: add this with message. - webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook)); - }); + webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook)); + }); + } } - } + }); }).exceptionally(exception -> { log.error("Could not get Instagram User!", exception); Sentry.captureException(exception); @@ -1157,11 +1190,14 @@ public void registerInstagramUser(List usernames) { public void unregisterInstagramUser(String username) { if (getInstagramClient() == null) return; - if (!SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(username).isEmpty() || - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", Map.of("name", username)) != null) - return; + SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(username).thenAccept(webhooks -> { + if (!webhooks.isEmpty()) return; - if (isInstagramUserRegistered(username)) registeredInstagramUsers.remove(username); + if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", Map.of("name", username)) != null) + return; + + if (isInstagramUserRegistered(username)) registeredInstagramUsers.remove(username); + }); } /** @@ -1187,53 +1223,53 @@ public void createTikTokStream() { try { TikTokUser user = TikTokWrapper.getUser(id); - List webhooks = SQLSession.getSqlConnector().getSqlWorker().getTikTokWebhooksByName(user.getId()); - - if (webhooks.isEmpty()) { - return; - } + SQLSession.getSqlConnector().getSqlWorker().getTikTokWebhooksByName(user.getId()).thenAccept(webhooks -> { + if (webhooks.isEmpty()) { + return; + } - AtomicInteger limit = new AtomicInteger(); + AtomicInteger limit = new AtomicInteger(); - user.getPosts().forEach(post -> { - if (limit.get() > 3) return; + user.getPosts().forEach(post -> { + if (limit.get() > 3) return; - if (post.getCreationTime() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())) { - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + if (post.getCreationTime() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())) { + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName()); + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(user.getDisplayName(), "https://www.tiktok.com/@" + user.getName())); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("TikTok Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(user.getDisplayName(), "https://www.tiktok.com/@" + user.getName())); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("TikTok Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); - // Set rest of the Information. - if (post.getCover() != null) { - webhookEmbedBuilder.setImageUrl(post.getCover().getMediumUrl()); - webhookEmbedBuilder.setDescription("[Click here to watch the video](https://tiktok.com/share/video/" + post.getId() + ")"); - } else { - webhookEmbedBuilder.setDescription(user.getDisplayName() + " just posted something new on TikTok!"); - } + // Set rest of the Information. + if (post.getCover() != null) { + webhookEmbedBuilder.setImageUrl(post.getCover().getMediumUrl()); + webhookEmbedBuilder.setDescription("[Click here to watch the video](https://tiktok.com/share/video/" + post.getId() + ")"); + } else { + webhookEmbedBuilder.setDescription(user.getDisplayName() + " just posted something new on TikTok!"); + } - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); - webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); + webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - webhooks.forEach(webhook -> { - String message = webhook.getMessage() - .replace("%description%", post.getDescription()) - .replace("%author%", user.getName()) - .replace("%name%", user.getDisplayName()) - .replace("%url%", "https://tiktok.com/share/video/" + post.getId()); - webhookMessageBuilder.setContent(message); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); - }); - } - limit.incrementAndGet(); + webhooks.forEach(webhook -> { + String message = webhook.getMessage() + .replace("%description%", post.getDescription()) + .replace("%author%", user.getName()) + .replace("%name%", user.getDisplayName()) + .replace("%url%", "https://tiktok.com/share/video/" + post.getId()); + webhookMessageBuilder.setContent(message); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); + }); + } + limit.incrementAndGet(); + }); }); } catch (IOException e) { if (e instanceof HttpStatusException httpStatusException) { diff --git a/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java b/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java index bf858b72f..7750b429a 100644 --- a/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java +++ b/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java @@ -19,16 +19,14 @@ public class DatabaseStorageBackend implements IStorageBackend { */ @Override public List loadCredentials() { - List twitchIntegrations = - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), - "FROM TwitchIntegration", null); + return SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), + "FROM TwitchIntegration", null).thenApply(twitchIntegrations -> { + List credentials = new ArrayList<>(); - List credentials = new ArrayList<>(); - - twitchIntegrations.forEach(twitchIntegration -> credentials.add(new CustomOAuth2Credential(twitchIntegration.getUserId(),"twitch", twitchIntegration.getToken(), - twitchIntegration.getRefresh(), twitchIntegration.getChannelId(), twitchIntegration.getName(), twitchIntegration.getExpiresIn(), Collections.emptyList()))); - - return credentials; + twitchIntegrations.forEach(twitchIntegration -> credentials.add(new CustomOAuth2Credential(twitchIntegration.getUserId(),"twitch", twitchIntegration.getToken(), + twitchIntegration.getRefresh(), twitchIntegration.getChannelId(), twitchIntegration.getName(), twitchIntegration.getExpiresIn(), Collections.emptyList()))); + return credentials; + }).join(); } /** @@ -40,21 +38,20 @@ public List loadCredentials() { public void saveCredentials(List list) { list.forEach(credential -> { if (credential instanceof CustomOAuth2Credential oAuth2Credential) { - TwitchIntegration twitchIntegration = - SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), - "FROM TwitchIntegration WHERE channelId = :userid", Map.of("userid",oAuth2Credential.getUserId())); - - if (twitchIntegration == null) { - twitchIntegration = new TwitchIntegration(); - twitchIntegration.setChannelId(oAuth2Credential.getUserId()); - twitchIntegration.setUserId(oAuth2Credential.getDiscordId()); - } + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), + "FROM TwitchIntegration WHERE channelId = :userid", Map.of("userid",oAuth2Credential.getUserId())).thenAccept(twitchIntegration -> { + if (twitchIntegration == null) { + twitchIntegration = new TwitchIntegration(); + twitchIntegration.setChannelId(oAuth2Credential.getUserId()); + twitchIntegration.setUserId(oAuth2Credential.getDiscordId()); + } - twitchIntegration.setToken(oAuth2Credential.getAccessToken()); - twitchIntegration.setRefresh(oAuth2Credential.getRefreshToken()); - twitchIntegration.setName(oAuth2Credential.getUserName()); - twitchIntegration.setExpiresIn(oAuth2Credential.getExpiresIn()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(twitchIntegration); + twitchIntegration.setToken(oAuth2Credential.getAccessToken()); + twitchIntegration.setRefresh(oAuth2Credential.getRefreshToken()); + twitchIntegration.setName(oAuth2Credential.getUserName()); + twitchIntegration.setExpiresIn(oAuth2Credential.getExpiresIn()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(twitchIntegration).join(); + }); } }); } @@ -68,7 +65,7 @@ public void saveCredentials(List list) { @Override public Optional getCredentialByUserId(String userId) { Optional twitchIntegration = Optional.ofNullable(SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), - "FROM TwitchIntegration WHERE channelId = :userid", Map.of("userid", userId))); + "FROM TwitchIntegration WHERE channelId = :userid", Map.of("userid", userId)).join()); if (twitchIntegration.isPresent()) { TwitchIntegration twitchIntegration1 = twitchIntegration.get(); diff --git a/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java b/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java index 0b8464323..ffbe6e58f 100644 --- a/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java +++ b/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java @@ -8,6 +8,7 @@ import java.sql.Timestamp; import java.time.Instant; import java.util.Map; +import java.util.concurrent.CompletableFuture; /** * Utility class for Economy related stuff. @@ -20,7 +21,7 @@ public class EconomyUtil { * @param member The Member. * @return If the MoneyHolder has any cash. */ - public static boolean hasCash(Member member) { + public static CompletableFuture hasCash(Member member) { return hasCash(member.getGuild().getIdLong(), member.getIdLong()); } @@ -31,8 +32,8 @@ public static boolean hasCash(Member member) { * @param memberId The ID of the Member. * @return If the MoneyHolder has any cash. */ - public static boolean hasCash(long guildId, long memberId) { - return hasCash(getMoneyHolder(guildId, memberId)); + public static CompletableFuture hasCash(long guildId, long memberId) { + return getMoneyHolder(guildId, memberId).thenApply(EconomyUtil::hasCash); } /** @@ -51,7 +52,7 @@ public static boolean hasCash(MoneyHolder moneyHolder) { * @param member The Member. * @return The MoneyHolder. */ - public static MoneyHolder getMoneyHolder(Member member) { + public static CompletableFuture getMoneyHolder(Member member) { return getMoneyHolder(member.getGuild().getIdLong(), member.getIdLong()); } @@ -62,7 +63,7 @@ public static MoneyHolder getMoneyHolder(Member member) { * @param memberId The ID of the Member. * @return The MoneyHolder. */ - public static MoneyHolder getMoneyHolder(long guildId, long memberId) { + public static CompletableFuture getMoneyHolder(long guildId, long memberId) { return getMoneyHolder(guildId, memberId, true); } @@ -74,18 +75,18 @@ public static MoneyHolder getMoneyHolder(long guildId, long memberId) { * @param createIfNotExists If the MoneyHolder should be created if it does not exist. * @return The MoneyHolder. */ - public static MoneyHolder getMoneyHolder(long guildId, long memberId, boolean createIfNotExists) { - MoneyHolder moneyHolder = SQLSession.getSqlConnector().getSqlWorker().getEntity(new MoneyHolder(), "FROM MoneyHolder WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", - Map.of("gid", guildId, "uid", memberId)); - - if (moneyHolder == null && createIfNotExists) { - moneyHolder = new MoneyHolder(); - moneyHolder.setGuildId(guildId); - moneyHolder.setUserId(memberId); - moneyHolder = SQLSession.getSqlConnector().getSqlWorker().updateEntity(moneyHolder); - } + public static CompletableFuture getMoneyHolder(long guildId, long memberId, boolean createIfNotExists) { + return SQLSession.getSqlConnector().getSqlWorker().getEntity(new MoneyHolder(), "FROM MoneyHolder WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", + Map.of("gid", guildId, "uid", memberId)).thenApply(moneyHolder -> { + if (moneyHolder == null && createIfNotExists) { + moneyHolder = new MoneyHolder(); + moneyHolder.setGuildId(guildId); + moneyHolder.setUserId(memberId); + return SQLSession.getSqlConnector().getSqlWorker().updateEntity(moneyHolder).join(); + } - return moneyHolder; + return moneyHolder; + }); } /** diff --git a/src/main/java/de/presti/ree6/utils/others/GuildUtil.java b/src/main/java/de/presti/ree6/utils/others/GuildUtil.java index f083fab30..450dc5313 100644 --- a/src/main/java/de/presti/ree6/utils/others/GuildUtil.java +++ b/src/main/java/de/presti/ree6/utils/others/GuildUtil.java @@ -5,8 +5,10 @@ import de.presti.ree6.sql.SQLSession; import lombok.extern.slf4j.Slf4j; import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.interactions.Interaction; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.entities.User; import java.util.List; import java.util.Map; @@ -34,47 +36,52 @@ private GuildUtil() { */ public static void handleMemberJoin(Guild guild, Member member) { - if (!SQLSession.getSqlConnector().getSqlWorker().isAutoRoleSetup(guild.getIdLong())) return; + SQLSession.getSqlConnector().getSqlWorker().isAutoRoleSetup(guild.getIdLong()).thenAccept(x -> { + if (!x) return; - if (member.getIdLong() == guild.getOwnerIdLong()) return; + if (member.getIdLong() == guild.getOwnerIdLong()) return; - ThreadUtil.createThread(x -> { if (!guild.getSelfMember().canInteract(member)) { log.error("[AutoRole] Failed to give a role, when someone joined the Guild!"); log.error("[AutoRole] Server: {} ({})", guild.getName(), guild.getId()); log.error("[AutoRole] Member: {} ({})", member.getUser().getName(), member.getId()); if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, "message.brs.autoRole.hierarchy", "@everyone")) - .queue()); + LanguageService.getByGuild(guild, "message.brs.autoRole.hierarchy", "@everyone").thenAccept(message -> + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + privateChannel.sendMessage(message) + .queue())); return; } - for (de.presti.ree6.sql.entities.roles.Role roles : SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(guild.getIdLong())) { - Role role = guild.getRoleById(roles.getRoleId()); + SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(guild.getIdLong()).thenAccept(roles -> { + for (de.presti.ree6.sql.entities.roles.Role roleEntry : roles) { + Role role = guild.getRoleById(roleEntry.getRoleId()); - if (role != null && !guild.getSelfMember().canInteract(role)) { - if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? - "message.brs.autoRole.hierarchy" - : "message.brs.autoRole.missingPermission", role.getName())) - .queue()); - return; - } else if (role == null) { - if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, "message.brs.autoRole.deleted")) - .queue()); + if (role != null && !guild.getSelfMember().canInteract(role)) { + if (guild.getOwner() != null) + LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? + "message.brs.autoRole.hierarchy" + : "message.brs.autoRole.missingPermission", role.getName()).thenAccept(message -> + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + privateChannel.sendMessage(message) + .queue())); + return; + } else if (role == null) { + if (guild.getOwner() != null) + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + LanguageService.getByGuild(guild, "message.brs.autoRole.deleted").thenAccept(message -> + privateChannel.sendMessage(message) + .queue())); - SQLSession.getSqlConnector().getSqlWorker().removeAutoRole(guild.getIdLong(), roles.getRoleId()); - return; - } + SQLSession.getSqlConnector().getSqlWorker().removeAutoRole(guild.getIdLong(), roleEntry.getRoleId()); + return; + } - addRole(guild, member, role); - } - }, null, null, false, true); + addRole(guild, member, role); + } + }); + }); } /** @@ -85,55 +92,58 @@ public static void handleMemberJoin(Guild guild, Member member) { */ public static void handleVoiceLevelReward(Guild guild, Member member) { - if (!SQLSession.getSqlConnector().getSqlWorker().isVoiceLevelRewardSetup(guild.getIdLong())) - return; + SQLSession.getSqlConnector().getSqlWorker().isVoiceLevelRewardSetup(guild.getIdLong()).thenAccept(x -> { + if (!x) return; - if (member.getIdLong() == guild.getOwnerIdLong()) return; + if (member.getIdLong() == guild.getOwnerIdLong()) return; - ThreadUtil.createThread(x -> { - long level = SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelData(guild.getIdLong(), member.getUser().getIdLong()).getLevel(); + SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelData(guild.getIdLong(), member.getUser().getIdLong()).thenAccept(data -> { + if (data == null) return; - if (!guild.getSelfMember().canInteract(member)) { - log.error("[AutoRole] Failed to give a role, when someone leveled up in Voice!"); - log.error("[AutoRole] Server: {} ({})", guild.getName(), guild.getId()); - log.error("[AutoRole] Member: {} ({})", member.getUser().getName(), member.getId()); + if (!guild.getSelfMember().canInteract(member)) { + log.error("[AutoRole] Failed to give a role, when someone leveled up in Voice!"); + log.error("[AutoRole] Server: {} ({})", guild.getName(), guild.getId()); + log.error("[AutoRole] Member: {} ({})", member.getUser().getName(), member.getId()); - if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, "message.brs.autoRole.hierarchy", "@everyone")) - .queue()); + if (guild.getOwner() != null) + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + LanguageService.getByGuild(guild, "message.brs.autoRole.hierarchy", "@everyone").thenAccept(message -> + privateChannel.sendMessage(message).queue())); - return; - } + return; + } - for (Map.Entry entry : SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelRewards(guild.getIdLong()).entrySet()) { + SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelRewards(guild.getIdLong()).thenAccept(roles -> { + for (Map.Entry entry : roles.entrySet()) { - if (entry.getKey() <= level) { + if (entry.getKey() <= data.getLevel()) { - Role role = guild.getRoleById(entry.getValue()); + Role role = guild.getRoleById(entry.getValue()); - if (role != null && !guild.getSelfMember().canInteract(role)) { - if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? + if (role != null && !guild.getSelfMember().canInteract(role)) { + if (guild.getOwner() != null) + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? "message.brs.autoRole.hierarchy" - : "message.brs.autoRole.missingPermission", role.getName())) - .queue()); - return; - } else if (role == null) { - if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, "message.brs.autoRole.deleted")) - .queue()); - - SQLSession.getSqlConnector().getSqlWorker().removeAutoRole(guild.getIdLong(), entry.getValue()); - return; + : "message.brs.autoRole.missingPermission", role.getName()).thenAccept(message -> + privateChannel.sendMessage(message).queue())); + return; + } else if (role == null) { + if (guild.getOwner() != null) + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + LanguageService.getByGuild(guild, "message.brs.autoRole.deleted").thenAccept(message -> + privateChannel.sendMessage(message).queue())); + + SQLSession.getSqlConnector().getSqlWorker().removeAutoRole(guild.getIdLong(), entry.getValue()); + return; + } + + addRole(guild, member, role); + } } - - addRole(guild, member, role); - } - } - }, null, null, false, true); + }); + }); + }); } /** @@ -144,55 +154,55 @@ public static void handleVoiceLevelReward(Guild guild, Member member) { */ public static void handleChatLevelReward(Guild guild, Member member) { - if (!SQLSession.getSqlConnector().getSqlWorker().isChatLevelRewardSetup(guild.getIdLong())) - return; + SQLSession.getSqlConnector().getSqlWorker().isChatLevelRewardSetup(guild.getIdLong()).thenAccept(x -> { + if (!x) return; - if (member.getIdLong() == guild.getOwnerIdLong()) return; + if (member.getIdLong() == guild.getOwnerIdLong()) return; - ThreadUtil.createThread(x -> { + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(guild.getIdLong(), member.getUser().getIdLong()).thenAccept(data -> { + if (data == null) return; - long level = (SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(guild.getIdLong(), member.getUser().getIdLong()).getLevel()); + if (!guild.getSelfMember().canInteract(member)) { + log.error("[AutoRole] Failed to give a Role, when someone leveled up in Chat!"); + log.error("[AutoRole] Server: {} ({})", guild.getName(), guild.getId()); + log.error("[AutoRole] Member: {} ({})", member.getUser().getName(), member.getId()); - if (!guild.getSelfMember().canInteract(member)) { - log.error("[AutoRole] Failed to give a Role, when someone leveled up in Chat!"); - log.error("[AutoRole] Server: {} ({})", guild.getName(), guild.getId()); - log.error("[AutoRole] Member: {} ({})", member.getUser().getName(), member.getId()); - - if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, "message.brs.autoRole.hierarchy", "@everyone")) - .queue()); - - return; - } + if (guild.getOwner() != null) + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + LanguageService.getByGuild(guild, "message.brs.autoRole.hierarchy", "@everyone") + .thenAccept(message -> privateChannel.sendMessage(message).queue())); + return; + } - for (Map.Entry entry : SQLSession.getSqlConnector().getSqlWorker().getChatLevelRewards(guild.getIdLong()).entrySet()) { + SQLSession.getSqlConnector().getSqlWorker().getChatLevelRewards(guild.getIdLong()).thenAccept(roles -> { + for (Map.Entry entry : roles.entrySet()) { - if (entry.getKey() <= level) { - Role role = guild.getRoleById(entry.getValue()); + if (entry.getKey() <= data.getLevel()) { + Role role = guild.getRoleById(entry.getValue()); - if (role != null && !guild.getSelfMember().canInteract(role)) { - if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? + if (role != null && !guild.getSelfMember().canInteract(role)) { + if (guild.getOwner() != null) + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? "message.brs.autoRole.hierarchy" - : "message.brs.autoRole.missingPermission", role.getName())) - .queue()); - } else if (role == null) { - if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, "message.brs.autoRole.deleted")) - .queue()); - - SQLSession.getSqlConnector().getSqlWorker().removeAutoRole(guild.getIdLong(), entry.getValue()); - return; + : "message.brs.autoRole.missingPermission", role.getName()).thenAccept(message -> + privateChannel.sendMessage(message).queue())); + } else if (role == null) { + if (guild.getOwner() != null) + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> + LanguageService.getByGuild(guild, "message.brs.autoRole.deleted").thenAccept(message -> + privateChannel.sendMessage(message).queue())); + + SQLSession.getSqlConnector().getSqlWorker().removeAutoRole(guild.getIdLong(), entry.getValue()); + return; + } + + addRole(guild, member, role); + } } - - addRole(guild, member, role); - } - - } - }, null, null, false, true); + }); + }); + }); } /** @@ -212,15 +222,16 @@ private static void addRole(Guild guild, Member member, Role role) { log.error("[AutoRole] Server: {} ({})", guild.getName(), guild.getId()); if (guild.getOwner() != null) guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - privateChannel.sendMessage(LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? - "message.brs.autoRole.hierarchy" - : "message.brs.autoRole.missingPermission", role.getName())) - .queue()); + LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? + "message.brs.autoRole.hierarchy" + : "message.brs.autoRole.missingPermission", role.getName()).thenAccept(message -> + privateChannel.sendMessage(message).queue())); } } /** * Get all roles that Ree6 can manage. + * * @param guild the Guild to get the roles from. * @return a List of Roles that Ree6 can manage. */ @@ -230,6 +241,7 @@ public static List getManagableRoles(Guild guild) { /** * Checks if a specific user has supported Ree6 via Donations! + * * @param member the User of the current Guild to check. * @return true if the User has supported Ree6 via Donations, false if not. */ From ef48fb223b9f98075b1bee1656998f78673eb5e0 Mon Sep 17 00:00:00 2001 From: Presti Date: Tue, 21 May 2024 17:50:17 +0200 Subject: [PATCH 15/94] RAAAAAAAAAAAH --- .../de/presti/ree6/events/LoggingEvents.java | 1056 +++++++++-------- .../de/presti/ree6/events/MenuEvents.java | 247 ++-- 2 files changed, 684 insertions(+), 619 deletions(-) diff --git a/src/main/java/de/presti/ree6/events/LoggingEvents.java b/src/main/java/de/presti/ree6/events/LoggingEvents.java index 29bbd01c3..e962b8c97 100644 --- a/src/main/java/de/presti/ree6/events/LoggingEvents.java +++ b/src/main/java/de/presti/ree6/events/LoggingEvents.java @@ -112,7 +112,7 @@ public void onGuildBan(@Nonnull GuildBanEvent event) { auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor").join() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -150,7 +150,7 @@ public void onGuildUnban(@Nonnull GuildUnbanEvent event) { auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor").join() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -171,7 +171,7 @@ public void onGuildUnban(@Nonnull GuildUnbanEvent event) { public void onGuildMemberJoin(GuildMemberJoinEvent event) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { - if(!isSetup) return; + if (!isSetup) return; SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberjoin").thenAccept(shouldLog -> { if (!shouldLog.getBooleanValue()) return; @@ -248,38 +248,42 @@ public void onGuildMemberJoin(GuildMemberJoinEvent event) { @Override public void onGuildMemberRemove(@Nonnull GuildMemberRemoveEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberleave").getBooleanValue()) - return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberleave").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); - if (event.getMember() != null) { - we.setDescription(LanguageService.getByEvent(event, "logging.left.default", event.getUser().getAsMention(), TimeFormat.DATE_TIME_SHORT.format(event.getMember().getTimeJoined()))); - } else { - we.setDescription(LanguageService.getByEvent(event, "logging.left.slim", event.getUser().getAsMention())); - } + if (event.getMember() != null) { + we.setDescription(LanguageService.getByEvent(event, "logging.left.default", event.getUser().getAsMention(), TimeFormat.DATE_TIME_SHORT.format(event.getMember().getTimeJoined())).join()); + } else { + we.setDescription(LanguageService.getByEvent(event, "logging.left.slim", event.getUser().getAsMention()).join()); + } - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.KICK).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.KICK).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.SERVER_LEAVE, event.getUser())); + Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.SERVER_LEAVE, event.getUser())); + }); + }); + }); } /** @@ -289,46 +293,49 @@ public void onGuildMemberRemove(@Nonnull GuildMemberRemoveEvent event) { public void onGuildMemberUpdateTimeOut(@NotNull GuildMemberUpdateTimeOutEvent event) { super.onGuildMemberUpdateTimeOut(event); + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_timeout").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_timeout").getBooleanValue()) - return; + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - WebhookMessageBuilder wm = new WebhookMessageBuilder(); - - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); - - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setThumbnailUrl(event.getMember().getEffectiveAvatarUrl()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getMember().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - AuditLogPaginationAction paginationAction = event.getGuild().retrieveAuditLogs().user(event.getUser()).type(ActionType.MEMBER_UPDATE).limit(1); - if (event.getNewTimeOutEnd() != null) { - if (paginationAction.isEmpty()) { - we.setDescription(LanguageService.getByEvent(event, "logging.timeout.started", - event.getUser().getAsMention(), - TimeFormat.DATE_TIME_SHORT.format(event.getNewTimeOutEnd()))); - } else { - AuditLogEntry auditLogEntry = paginationAction.getFirst(); - we.setDescription(LanguageService.getByEvent(event, "logging.timeout.updated", - event.getUser().getAsMention(), - (auditLogEntry.getReason() == null ? "Couldn't find reason" : auditLogEntry.getReason()), - (auditLogEntry.getUser() != null ? auditLogEntry.getUser().getAsMention() : LanguageService.getByGuild(event.getGuild(), "label.unknown")), - TimeFormat.DATE_TIME_SHORT.format(event.getNewTimeOutEnd()))); - } - } else { - we.setDescription(LanguageService.getByEvent(event, "logging.timeout.ended", - event.getUser().getAsMention(), - TimeFormat.DATE_TIME_SHORT.format(event.getOldTimeOutEnd()))); - } + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - wm.addEmbeds(we.build()); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setThumbnailUrl(event.getMember().getEffectiveAvatarUrl()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getMember().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + AuditLogPaginationAction paginationAction = event.getGuild().retrieveAuditLogs().user(event.getUser()).type(ActionType.MEMBER_UPDATE).limit(1); + if (event.getNewTimeOutEnd() != null) { + if (paginationAction.isEmpty()) { + we.setDescription(LanguageService.getByEvent(event, "logging.timeout.started", + event.getUser().getAsMention(), + TimeFormat.DATE_TIME_SHORT.format(event.getNewTimeOutEnd())).join()); + } else { + AuditLogEntry auditLogEntry = paginationAction.getFirst(); + we.setDescription(LanguageService.getByEvent(event, "logging.timeout.updated", + event.getUser().getAsMention(), + (auditLogEntry.getReason() == null ? "Couldn't find reason" : auditLogEntry.getReason()), + (auditLogEntry.getUser() != null ? auditLogEntry.getUser().getAsMention() : LanguageService.getByGuild(event.getGuild(), "label.unknown")), + TimeFormat.DATE_TIME_SHORT.format(event.getNewTimeOutEnd())).join()); + } + } else { + we.setDescription(LanguageService.getByEvent(event, "logging.timeout.ended", + event.getUser().getAsMention(), + TimeFormat.DATE_TIME_SHORT.format(event.getOldTimeOutEnd())).join()); + } - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageMember(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ELSE, event.getMember())); + wm.addEmbeds(we.build()); + + Main.getInstance().getLoggerQueue().add(new LogMessageMember(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ELSE, event.getMember())); + }); + }); + }); } /** @@ -337,39 +344,41 @@ public void onGuildMemberUpdateTimeOut(@NotNull GuildMemberUpdateTimeOutEvent ev @Override public void onGuildMemberUpdateNickname(@Nonnull GuildMemberUpdateNicknameEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_nickname").getBooleanValue()) - return; - - - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_nickname").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setThumbnailUrl(event.getUser().getEffectiveAvatarUrl()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); - if (event.getNewNickname() == null) { - we.setDescription(LanguageService.getByEvent(event, "logging.nickname.reset", event.getUser().getAsMention(), event.getOldNickname())); - } else { - we.setDescription(LanguageService.getByEvent(event, "logging.nickname.changed", event.getUser().getAsMention(), event.getNewNickname(), (event.getOldNickname() != null ? event.getOldNickname() : event.getUser().getName()))); - } + if (event.getNewNickname() == null) { + we.setDescription(LanguageService.getByEvent(event, "logging.nickname.reset", event.getUser().getAsMention(), event.getOldNickname()).join()); + } else { + we.setDescription(LanguageService.getByEvent(event, "logging.nickname.changed", event.getUser().getAsMention(), event.getNewNickname(), (event.getOldNickname() != null ? event.getOldNickname() : event.getUser().getName())).join()); + } - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageMember(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.NICKNAME_CHANGE, event.getEntity(), event.getOldNickname(), event.getNewNickname())); + Main.getInstance().getLoggerQueue().add(new LogMessageMember(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.NICKNAME_CHANGE, event.getEntity(), event.getOldNickname(), event.getNewNickname())); + }); + }); + }); } //endregion @@ -383,83 +392,84 @@ public void onGuildMemberUpdateNickname(@Nonnull GuildMemberUpdateNicknameEvent @Override public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { super.onGuildVoiceUpdate(event); - if (event.getChannelLeft() == null) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicejoin").getBooleanValue()) - return; - + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + if (event.getChannelLeft() == null) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicejoin").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getEntity().getEffectiveName(), event.getEntity().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.join", event.getEntity().getUser().getAsMention(), event.getChannelJoined().getAsMention())); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getEntity().getEffectiveName(), event.getEntity().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.join", event.getEntity().getUser().getAsMention(), event.getChannelJoined().getAsMention()).join()); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageVoice(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.VC_JOIN, event.getEntity(), event.getChannelJoined())); - } else if (event.getChannelJoined() == null) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voiceleave").getBooleanValue()) - return; + Main.getInstance().getLoggerQueue().add(new LogMessageVoice(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.VC_JOIN, event.getEntity(), event.getChannelJoined())); + }); + } else if (event.getChannelJoined() == null) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voiceleave").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getEntity().getEffectiveName(), event.getEntity().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.leave", event.getEntity().getUser().getAsMention(), event.getChannelLeft().getAsMention())); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getEntity().getEffectiveName(), event.getEntity().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.leave", event.getEntity().getUser().getAsMention(), event.getChannelLeft().getAsMention()).join()); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_VOICE_KICK).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_VOICE_KICK).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageVoice(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.VC_LEAVE, event.getEntity(), event.getChannelLeft())); - } else { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicemove").getBooleanValue()) - return; + Main.getInstance().getLoggerQueue().add(new LogMessageVoice(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.VC_LEAVE, event.getEntity(), event.getChannelLeft())); + }); + } else { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicemove").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getEntity().getEffectiveName(), event.getEntity().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.move", event.getEntity().getUser().getAsMention(), event.getChannelLeft().getAsMention(), event.getChannelJoined().getAsMention())); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getEntity().getEffectiveName(), event.getEntity().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.move", event.getEntity().getUser().getAsMention(), event.getChannelLeft().getAsMention(), event.getChannelJoined().getAsMention()).join()); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_VOICE_MOVE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_VOICE_MOVE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageVoice(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.VC_MOVE, event.getEntity(), event.getChannelLeft(), event.getChannelJoined())); - } + Main.getInstance().getLoggerQueue().add(new LogMessageVoice(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.VC_MOVE, event.getEntity(), event.getChannelLeft(), event.getChannelJoined())); + }); + } + }); + }); } //endregion @@ -472,104 +482,106 @@ public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { @Override public void onGenericChannel(@Nonnull GenericChannelEvent event) { - if (event.getChannelType().isAudio()) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicechannel").getBooleanValue()) - return; - - WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); - - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.update.voice", event.getChannel().getAsMention())); - - AuditLogEntry entry; - - if (event instanceof ChannelCreateEvent) { - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.create.voice", event.getChannel().getAsMention())); - entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_CREATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); - } else if (event instanceof ChannelDeleteEvent) { - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.delete.voice", event.getChannel().getName())); - entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_DELETE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); - } else if (event instanceof ChannelUpdateNameEvent channelUpdateNameEvent) { - we.addField(new WebhookEmbed.EmbedField(true, "**Old name**", channelUpdateNameEvent.getOldValue() != null - ? ((ChannelUpdateNameEvent) event).getOldValue() : event.getChannel().getName())); - we.addField(new WebhookEmbed.EmbedField(true, "**New name**", channelUpdateNameEvent.getNewValue() != null - ? ((ChannelUpdateNameEvent) event).getNewValue() : event.getChannel().getName())); - entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); - } else { - return; - } - - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); - - wm.addEmbeds(we.build()); - - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessage(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.CHANNELDATA_CHANGE)); - } else if (event.getChannelType().isMessage()) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_textchannel").getBooleanValue()) - return; - - WebhookMessageBuilder wm = new WebhookMessageBuilder(); - - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); - - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.update.chat", event.getChannel().getAsMention())); - we.setDescription(":house: **TextChannel updated:** " + event.getChannel().getAsMention()); - - AuditLogEntry entry; - - if (event instanceof ChannelCreateEvent) { - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.create.chat", event.getChannel().getAsMention())); - entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_CREATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); - } else if (event instanceof ChannelDeleteEvent) { - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.delete.chat", event.getChannel().getName())); - entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_DELETE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); - } else if (event instanceof ChannelUpdateNameEvent channelUpdateNameEvent) { - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldName") + "**", channelUpdateNameEvent.getOldValue() != null - ? ((ChannelUpdateNameEvent) event).getOldValue() : event.getChannel().getName())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newName") + "**", channelUpdateNameEvent.getNewValue() != null - ? ((ChannelUpdateNameEvent) event).getNewValue() : event.getChannel().getName())); - entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); - } else if (event instanceof ChannelUpdateNSFWEvent channelUpdateNSFWEvent) { - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.nsfw") + "**", channelUpdateNSFWEvent.getNewValue() + "")); - entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); - } else { - return; - } - - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); - - wm.addEmbeds(we.build()); - - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessage(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.CHANNELDATA_CHANGE)); + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + if (event.getChannelType().isAudio()) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicechannel").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; - } + WebhookMessageBuilder wm = new WebhookMessageBuilder(); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); + + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.update.voice", event.getChannel().getAsMention()).join()); + + AuditLogEntry entry; + + if (event instanceof ChannelCreateEvent) { + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.create.voice", event.getChannel().getAsMention()).join()); + entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_CREATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); + } else if (event instanceof ChannelDeleteEvent) { + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.delete.voice", event.getChannel().getName()).join()); + entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_DELETE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); + } else if (event instanceof ChannelUpdateNameEvent channelUpdateNameEvent) { + we.addField(new WebhookEmbed.EmbedField(true, "**Old name**", channelUpdateNameEvent.getOldValue() != null + ? ((ChannelUpdateNameEvent) event).getOldValue() : event.getChannel().getName())); + we.addField(new WebhookEmbed.EmbedField(true, "**New name**", channelUpdateNameEvent.getNewValue() != null + ? ((ChannelUpdateNameEvent) event).getNewValue() : event.getChannel().getName())); + entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); + } else { + return; + } + + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); + + wm.addEmbeds(we.build()); + + Main.getInstance().getLoggerQueue().add(new LogMessage(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.CHANNELDATA_CHANGE)); + }); + } else { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_textchannel").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; + + WebhookMessageBuilder wm = new WebhookMessageBuilder(); + + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); + + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.update.chat", event.getChannel().getAsMention()).join()); + we.setDescription(":house: **TextChannel updated:** " + event.getChannel().getAsMention()); + + AuditLogEntry entry; + + if (event instanceof ChannelCreateEvent) { + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.create.chat", event.getChannel().getAsMention()).join()); + entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_CREATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); + } else if (event instanceof ChannelDeleteEvent) { + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.delete.chat", event.getChannel().getName()).join()); + entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_DELETE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); + } else if (event instanceof ChannelUpdateNameEvent channelUpdateNameEvent) { + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldName") + "**", channelUpdateNameEvent.getOldValue() != null + ? ((ChannelUpdateNameEvent) event).getOldValue() : event.getChannel().getName())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newName") + "**", channelUpdateNameEvent.getNewValue() != null + ? ((ChannelUpdateNameEvent) event).getNewValue() : event.getChannel().getName())); + entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); + } else if (event instanceof ChannelUpdateNSFWEvent channelUpdateNSFWEvent) { + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.nsfw") + "**", channelUpdateNSFWEvent.getNewValue() + "")); + entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); + } else { + return; + } + + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + + wm.addEmbeds(we.build()); + + Main.getInstance().getLoggerQueue().add(new LogMessage(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.CHANNELDATA_CHANGE)); + }); + } + }); + }); } //endregion @@ -582,41 +594,45 @@ public void onGenericChannel(@Nonnull GenericChannelEvent event) { @Override public void onGuildMemberRoleAdd(@Nonnull GuildMemberRoleAddEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roleadd").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roleadd").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setThumbnailUrl(event.getMember().getEffectiveAvatarUrl()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getMember().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setThumbnailUrl(event.getMember().getEffectiveAvatarUrl()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getMember().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); - StringBuilder finalString = new StringBuilder(); + StringBuilder finalString = new StringBuilder(); - for (Role r : event.getRoles()) { - finalString.append(":white_check_mark: ").append(r.getName()).append("\n"); - } + for (Role r : event.getRoles()) { + finalString.append(":white_check_mark: ").append(r.getName()).append("\n"); + } - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.member", event.getMember().getAsMention())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.roles") + ":**", finalString.toString())); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.member", event.getMember().getAsMention()).join()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.roles").join() + ":**", finalString.toString())); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageMember(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.MEMBERROLE_CHANGE, event.getMember(), null, new ArrayList<>(event.getRoles()))); + Main.getInstance().getLoggerQueue().add(new LogMessageMember(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.MEMBERROLE_CHANGE, event.getMember(), null, new ArrayList<>(event.getRoles()))); + }); + }); + }); } /** @@ -625,39 +641,46 @@ public void onGuildMemberRoleAdd(@Nonnull GuildMemberRoleAddEvent event) { @Override public void onGuildMemberRoleRemove(@Nonnull GuildMemberRoleRemoveEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roleremove").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roleremove").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); + + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); + + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setThumbnailUrl(event.getMember().getEffectiveAvatarUrl()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getMember().getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + StringBuilder finalString = new StringBuilder(); + for (Role r : event.getRoles()) { + finalString.append(":no_entry: ").append(r.getName()).append("\n"); + } - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setThumbnailUrl(event.getMember().getEffectiveAvatarUrl()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getMember().getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.member", event.getMember().getAsMention()).join()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.roles").join() + ":**", finalString.toString())); - StringBuilder finalString = new StringBuilder(); - for (Role r : event.getRoles()) { - finalString.append(":no_entry: ").append(r.getName()).append("\n"); - } + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.member", event.getMember().getAsMention())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.roles") + ":**", finalString.toString())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); + wm.addEmbeds(we.build()); - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + Main.getInstance().getLoggerQueue().add(new LogMessageMember(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.MEMBERROLE_CHANGE, event.getMember(), new ArrayList<>(event.getRoles()), null)); + }); + }); + }); - wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageMember(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.MEMBERROLE_CHANGE, event.getMember(), new ArrayList<>(event.getRoles()), null)); } /** @@ -665,32 +688,36 @@ public void onGuildMemberRoleRemove(@Nonnull GuildMemberRoleRemoveEvent event) { */ @Override public void onRoleCreate(@Nonnull RoleCreateEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolecreate").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolecreate").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.create", event.getRole().getName())); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.create", event.getRole().getName()).join()); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_CREATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_CREATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getRole().getName(), true, false, false, false)); + Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getRole().getName(), true, false, false, false)); + }); + }); + }); } /** @@ -698,32 +725,36 @@ public void onRoleCreate(@Nonnull RoleCreateEvent event) { */ @Override public void onRoleDelete(@Nonnull RoleDeleteEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roledelete").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roledelete").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.delete", event.getRole().getName())); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.delete", event.getRole().getName()).join()); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_DELETE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_DELETE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getRole().getName(), false, true, false, false)); + Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getRole().getName(), false, true, false, false)); + }); + }); + }); } /** @@ -731,34 +762,38 @@ public void onRoleDelete(@Nonnull RoleDeleteEvent event) { */ @Override public void onRoleUpdateName(@Nonnull RoleUpdateNameEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolename").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolename").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldName") + "**", event.getOldName())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newName") + "**", event.getNewName())); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).join()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldName").join() + "**", event.getOldName())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newName").join() + "**", event.getNewName())); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getOldName(), event.getNewName())); + Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getOldName(), event.getNewName())); + }); + }); + }); } /** @@ -766,34 +801,37 @@ public void onRoleUpdateName(@Nonnull RoleUpdateNameEvent event) { */ @Override public void onRoleUpdateMentionable(@Nonnull RoleUpdateMentionableEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolemention").getBooleanValue()) - return; - - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolemention").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldMentionable") + "**", event.getOldValue().toString())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newMentionable") + "**", event.getNewValue().toString())); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).join()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldMentionable").join() + "**", event.getOldValue().toString())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newMentionable").join() + "**", event.getNewValue().toString())); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getRole().getName(), false, false, false, true)); + Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getRole().getName(), false, false, false, true)); + }); + }); + }); } /** @@ -801,34 +839,40 @@ public void onRoleUpdateMentionable(@Nonnull RoleUpdateMentionableEvent event) { */ @Override public void onRoleUpdateHoisted(@Nonnull RoleUpdateHoistedEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolehoisted").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolehoisted").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldHoist") + "**", event.getOldValue().toString())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newHoist") + "**", event.getNewValue().toString())); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).join()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldHoist").join() + "**", event.getOldValue().toString())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newHoist").join() + "**", event.getNewValue().toString())); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); + + wm.addEmbeds(we.build()); + + Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getRole().getName(), false, false, true, false)); + }); + }); + }); - wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getRole().getName(), false, false, true, false)); } /** @@ -836,59 +880,65 @@ public void onRoleUpdateHoisted(@Nonnull RoleUpdateHoistedEvent event) { */ @Override public void onRoleUpdatePermissions(@Nonnull RoleUpdatePermissionsEvent event) { - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolepermission").getBooleanValue()) - return; + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolepermission").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; + + WebhookMessageBuilder wm = new WebhookMessageBuilder(); + + wm.setAvatarUrl(event.getJDA().getSelfUser().getAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).join()); - wm.setAvatarUrl(event.getJDA().getSelfUser().getAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + StringBuilder finalString = new StringBuilder(); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName())); + boolean b = false; + for (Permission r : event.getNewPermissions()) { + if (!event.getOldPermissions().contains(r)) { + if (b) { + finalString.append("\n:white_check_mark: ").append(r.getName()); + } else { + finalString.append(":white_check_mark: ").append(r.getName()); + b = true; + } + } + } - StringBuilder finalString = new StringBuilder(); + for (Permission r : event.getOldPermissions()) { + if (!event.getNewPermissions().contains(r)) { + if (b) { + finalString.append("\n:no_entry: ").append(r.getName()); + } else { + finalString.append(":no_entry: ").append(r.getName()); + b = true; + } + } + } - boolean b = false; - for (Permission r : event.getNewPermissions()) { - if (!event.getOldPermissions().contains(r)) { - if (b) { - finalString.append("\n:white_check_mark: ").append(r.getName()); - } else { - finalString.append(":white_check_mark: ").append(r.getName()); - b = true; - } - } - } + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newPermissions").join() + "**", finalString.toString())); - for (Permission r : event.getOldPermissions()) { - if (!event.getNewPermissions().contains(r)) { - if (b) { - finalString.append("\n:no_entry: ").append(r.getName()); - } else { - finalString.append(":no_entry: ").append(r.getName()); - b = true; - } - } - } + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newPermissions") + "**", finalString.toString())); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); + wm.addEmbeds(we.build()); - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getOldPermissions(), event.getNewPermissions())); + }); + }); + }); - wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), event.getOldPermissions(), event.getNewPermissions())); } /** @@ -896,35 +946,40 @@ public void onRoleUpdatePermissions(@Nonnull RoleUpdatePermissionsEvent event) { */ @Override public void onRoleUpdateColor(@Nonnull RoleUpdateColorEvent event) { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolecolor").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolecolor").getBooleanValue()) - return; + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + wm.setAvatarUrl(event.getJDA().getSelfUser().getAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - wm.setAvatarUrl(event.getJDA().getSelfUser().getAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).join()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldColor").join() + "**", (event.getOldColor() != null ? event.getOldColor() : Color.gray).getRGB() + "")); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newColor").join() + "**", (event.getNewColor() != null ? event.getNewColor() : Color.gray).getRGB() + "")); + + AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> + auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldColor") + "**", (event.getOldColor() != null ? event.getOldColor() : Color.gray).getRGB() + "")); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newColor") + "**", (event.getNewColor() != null ? event.getNewColor() : Color.gray).getRGB() + "")); + if (entry != null && entry.getUser() != null) + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); - AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> - auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); + wm.addEmbeds(we.build()); - if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), (event.getOldColor() != null ? event.getOldColor() : Color.gray), (event.getNewColor() != null ? event.getNewColor() : Color.gray))); + }); + }); + }); - wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageRole(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.ROLEDATA_CHANGE, event.getRole().getIdLong(), (event.getOldColor() != null ? event.getOldColor() : Color.gray), (event.getNewColor() != null ? event.getNewColor() : Color.gray))); } //endregion @@ -936,60 +991,63 @@ public void onRoleUpdateColor(@Nonnull RoleUpdateColorEvent event) { */ @Override public void onMessageDelete(@Nonnull MessageDeleteEvent event) { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + if (!isSetup) return; + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_messagedelete").thenAccept(shouldLog -> { + if (!shouldLog.getBooleanValue()) return; - if (!SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()) || - !SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_messagedelete").getBooleanValue()) - return; - - User user = ArrayUtil.getUserFromMessageList(event.getMessageId()); + User user = ArrayUtil.getUserFromMessageList(event.getMessageId()); - if (user != null) { - WebhookMessageBuilder wm = new WebhookMessageBuilder(); + if (user != null) { + WebhookMessageBuilder wm = new WebhookMessageBuilder(); - wm.setAvatarUrl(event.getJDA().getSelfUser().getAvatarUrl()); - wm.setUsername(BotConfig.getBotName() + "-Logs"); + wm.setAvatarUrl(event.getJDA().getSelfUser().getAvatarUrl()); + wm.setUsername(BotConfig.getBotName() + "-Logs"); - WebhookEmbedBuilder we = new WebhookEmbedBuilder(); - we.setColor(Color.BLACK.getRGB()); - we.setAuthor(new WebhookEmbed.EmbedAuthor(user.getName(), user.getEffectiveAvatarUrl(), null)); - we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - we.setTimestamp(Instant.now()); + WebhookEmbedBuilder we = new WebhookEmbedBuilder(); + we.setColor(Color.BLACK.getRGB()); + we.setAuthor(new WebhookEmbed.EmbedAuthor(user.getName(), user.getEffectiveAvatarUrl(), null)); + we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + we.setTimestamp(Instant.now()); - Message message = ArrayUtil.getMessageFromMessageListAndRemove(event.getMessageId()); + Message message = ArrayUtil.getMessageFromMessageListAndRemove(event.getMessageId()); - if (message != null && message.getActivity() != null) return; + if (message != null && message.getActivity() != null) return; - boolean isImageAdded = false; + boolean isImageAdded = false; - if (message != null && !message.getAttachments().isEmpty()) { - for (Message.Attachment attachment : message.getAttachments()) { - try { - if (!isImageAdded && attachment.isImage()) { - we.setImageUrl(attachment.getProxyUrl()); - isImageAdded = true; - } else { - wm.addFile(attachment.getFileName(), attachment.getProxy().download().get()); + if (message != null && !message.getAttachments().isEmpty()) { + for (Message.Attachment attachment : message.getAttachments()) { + try { + if (!isImageAdded && attachment.isImage()) { + we.setImageUrl(attachment.getProxyUrl()); + isImageAdded = true; + } else { + wm.addFile(attachment.getFileName(), attachment.getProxy().download().get()); + } + } catch (Exception exception) { + wm.append(LanguageService.getByGuild(event.getGuild(), "logging.message.attachmentFailed", attachment.getFileName()).join() + "\n"); + } + } + wm.append(LanguageService.getByGuild(event.getGuild(), "logging.message.attachmentNotice").join() + "\n"); } - } catch (Exception exception) { - wm.append(LanguageService.getByGuild(event.getGuild(), "logging.message.attachmentFailed", attachment.getFileName()) + "\n"); - } - } - wm.append(LanguageService.getByGuild(event.getGuild(), "logging.message.attachmentNotice") + "\n"); - } - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.message.deleted", user.getAsMention(), event.getChannel().getAsMention(), - message != null ? message.getContentRaw().length() >= 650 ? - LanguageService.getByGuild(event.getGuild(), "logging.message.tooLong") : - message.getContentRaw() : "")); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.message.deleted", user.getAsMention(), event.getChannel().getAsMention(), + message != null ? message.getContentRaw().length() >= 650 ? + LanguageService.getByGuild(event.getGuild(), "logging.message.tooLong").join() : + message.getContentRaw() : "").join()); - if (message != null && message.getContentRaw().length() >= 650) - wm.addFile("message.txt", message.getContentRaw().getBytes(StandardCharsets.UTF_8)); + if (message != null && message.getContentRaw().length() >= 650) + wm.addFile("message.txt", message.getContentRaw().getBytes(StandardCharsets.UTF_8)); - wm.addEmbeds(we.build()); + wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.MESSAGE_DELETE, user)); - } + Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.MESSAGE_DELETE, user)); + } + }); + }); + }); } //endregion diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index c91b3454c..8909914f7 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -4,6 +4,7 @@ import club.minnced.discord.webhook.send.WebhookEmbedBuilder; import club.minnced.discord.webhook.send.WebhookMessageBuilder; import de.presti.ree6.audio.music.GuildMusicManager; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.bot.util.WebhookUtil; import de.presti.ree6.commands.impl.mod.Setup; @@ -16,7 +17,6 @@ import de.presti.ree6.sql.entities.stats.ChannelStats; import de.presti.ree6.sql.entities.webhook.base.Webhook; import de.presti.ree6.utils.apis.YouTubeAPIHandler; -import de.presti.ree6.bot.BotConfig; import de.presti.wrapper.entities.channel.ChannelResult; import io.github.redouane59.twitter.dto.user.UserV2; import masecla.reddit4j.objects.subreddit.RedditSubreddit; @@ -54,8 +54,8 @@ import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; -import java.util.*; import java.util.List; +import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @@ -75,135 +75,142 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { String[] split = event.getComponentId().split(":"); if (split.length == 2) { - Recording recording = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Recording(), "FROM Recording WHERE identifier = :id AND guildId = :gid", Map.of("id", split[1], "gid", event.getGuild().getIdLong())); - MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); - if (recording != null) { - messageEditBuilder.setEmbeds(new EmbedBuilder() - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.recording.inChat")) - .setColor(Color.GREEN) - .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.recording.finished")) - .build()); - messageEditBuilder.setFiles(FileUpload.fromData(recording.getRecording(), "recording.wav")); - messageEditBuilder.setComponents(List.of()); - } else { - messageEditBuilder.setEmbeds(new EmbedBuilder() - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.recording.notFound")) - .setColor(Color.RED) - .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.error")) - .build()); - messageEditBuilder.setComponents(List.of()); - } + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Recording(), "FROM Recording WHERE identifier = :id AND guildId = :gid", Map.of("id", split[1], "gid", event.getGuild().getIdLong())).thenAccept(recording -> { + MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); + if (recording != null) { + messageEditBuilder.setEmbeds(new EmbedBuilder() + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.recording.inChat").join()) + .setColor(Color.GREEN) + .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.recording.finished").join()) + .build()); + messageEditBuilder.setFiles(FileUpload.fromData(recording.getRecording(), "recording.wav")); + messageEditBuilder.setComponents(List.of()); + } else { + messageEditBuilder.setEmbeds(new EmbedBuilder() + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.recording.notFound").join()) + .setColor(Color.RED) + .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.error").join()) + .build()); + messageEditBuilder.setComponents(List.of()); + } - event.editMessage(messageEditBuilder.build()).queue(); + event.editMessage(messageEditBuilder.build()).queue(); + }); } } switch (event.getComponentId()) { case "re_feedback" -> { - Modal.Builder builder = Modal.create("re_feedback_modal", LanguageService.getByGuild(event.getGuild(), "label.feedback")); - builder.addActionRow(TextInput.create("re_feedback_text", LanguageService.getByGuild(event.getGuild(), "label.feedback"), TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(2042).setMinLength(16).build()); - event.replyModal(builder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "label.feedback").thenAccept(modalString -> { + Modal.Builder builder = Modal.create("re_feedback_modal", modalString); + builder.addActionRow(TextInput.create("re_feedback_text", modalString, TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(2042).setMinLength(16).build()); + event.replyModal(builder.build()).queue(); + }); } case "re_suggestion" -> { - Modal.Builder builder = Modal.create("re_suggestion_modal", LanguageService.getByGuild(event.getGuild(), "label.suggestion")); - builder.addActionRow(TextInput.create("re_suggestion_text", LanguageService.getByGuild(event.getGuild(), "label.suggestion"), TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(2042).setMinLength(16).build()); - event.replyModal(builder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "label.suggestion").thenAccept(modalString -> { + Modal.Builder builder = Modal.create("re_suggestion_modal", modalString); + builder.addActionRow(TextInput.create("re_suggestion_text", modalString, TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(2042).setMinLength(16).build()); + event.replyModal(builder.build()).queue(); + }); } case "re_ticket_open" -> { event.deferReply(true).queue(); - Tickets tickets = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - - if (tickets != null) { - Category category = event.getGuild().getCategoryById(tickets.getTicketCategory()); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(tickets -> { + if (tickets != null) { + Category category = event.getGuild().getCategoryById(tickets.getTicketCategory()); + + if (category != null) { + if (category.getTextChannels().stream().anyMatch(c -> c.getName().contains(event.getUser().getName()))) { + event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.alreadyOpen").join()).queue(); + return; + } - if (category != null) { - if (category.getTextChannels().stream().anyMatch(c -> c.getName().contains(event.getUser().getName()))) { - event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.alreadyOpen")).queue(); - return; + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_ticket_open").thenAccept(ticketMessage -> { + category.createTextChannel("ticket-" + event.getUser().getName()) + .setTopic(event.getUser().getId()) + .syncPermissionOverrides() + .addPermissionOverride(event.getMember(), List.of(Permission.VIEW_CHANNEL, Permission.MESSAGE_SEND, Permission.MESSAGE_HISTORY, Permission.MESSAGE_ATTACH_FILES, Permission.MESSAGE_EMBED_LINKS), List.of()) + .queue(channel -> { + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); + messageCreateBuilder.setEmbeds(new EmbedBuilder().setTitle(LanguageService.getByGuild(event.getGuild(), "label.ticket").join()) + .setDescription(ticketMessage.getStringValue()) + .setThumbnail(event.getMember().getEffectiveAvatarUrl()).setColor(Color.GREEN).setTimestamp(Instant.now()).build()); + messageCreateBuilder.addActionRow(Button.primary("re_ticket_close", LanguageService.getByGuild(event.getGuild(), "label.closeTicket").join())); + Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), channel); + event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.created", channel.getAsMention()).join()).queue(); + }); + tickets.setTicketCount(tickets.getTicketCount() + 1); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(tickets).join(); + }); + } else { + event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.categoryNotFound").join()).queue(); } - - category.createTextChannel("ticket-" + event.getUser().getName()) - .setTopic(event.getUser().getId()) - .syncPermissionOverrides() - .addPermissionOverride(event.getMember(), List.of(Permission.VIEW_CHANNEL, Permission.MESSAGE_SEND, Permission.MESSAGE_HISTORY, Permission.MESSAGE_ATTACH_FILES, Permission.MESSAGE_EMBED_LINKS), List.of()) - .queue(channel -> { - MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); - messageCreateBuilder.setEmbeds(new EmbedBuilder().setTitle(LanguageService.getByGuild(event.getGuild(), "label.ticket")) - .setDescription(SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_ticket_open").getStringValue()) - .setThumbnail(event.getMember().getEffectiveAvatarUrl()).setColor(Color.GREEN).setTimestamp(Instant.now()).build()); - messageCreateBuilder.addActionRow(Button.primary("re_ticket_close", LanguageService.getByGuild(event.getGuild(), "label.closeTicket"))); - Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), channel); - event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.created", channel.getAsMention())).queue(); - }); - tickets.setTicketCount(tickets.getTicketCount() + 1); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(tickets); - } else { - event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.categoryNotFound")).queue(); } - } + }); } case "re_ticket_close" -> { event.deferReply(true).queue(); - Tickets tickets = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - - if (tickets != null) { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(BotConfig.getBotName() + " Ticket transcript") - .append(" ") - .append(ZonedDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG))) - .append("\n") - .append("\n"); - - - for (Message message : event.getChannel().asTextChannel().getIterableHistory().reverse()) { - stringBuilder - .append("[") - .append(message.getTimeCreated().toZonedDateTime().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT))) - .append("]") - .append(" ") - .append(message.getAuthor().getName()) + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(tickets -> { + if (tickets != null) { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(BotConfig.getBotName() + " Ticket transcript") .append(" ") - .append("->") - .append(" ") - .append(message.getContentRaw()); - - if (!message.getAttachments().isEmpty()) { - for (Message.Attachment attachment : message.getAttachments()) { - stringBuilder.append("\n").append(attachment.getUrl()); + .append(ZonedDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG))) + .append("\n") + .append("\n"); + + + for (Message message : event.getChannel().asTextChannel().getIterableHistory().reverse()) { + stringBuilder + .append("[") + .append(message.getTimeCreated().toZonedDateTime().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT))) + .append("]") + .append(" ") + .append(message.getAuthor().getName()) + .append(" ") + .append("->") + .append(" ") + .append(message.getContentRaw()); + + if (!message.getAttachments().isEmpty()) { + for (Message.Attachment attachment : message.getAttachments()) { + stringBuilder.append("\n").append(attachment.getUrl()); + } } - } - stringBuilder.append("\n"); - } + stringBuilder.append("\n"); + } - // TODO:: translate and fix the date being shown as UTC+1 and instead use the current server region. + // TODO:: translate and fix the date being shown as UTC+1 and instead use the current server region. - stringBuilder.append("\n").append("Closed by").append(" ").append(event.getUser().getName()); + stringBuilder.append("\n").append("Closed by").append(" ").append(event.getUser().getName()); - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - webhookMessageBuilder.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName() + "-Tickets"); + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + webhookMessageBuilder.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName() + "-Tickets"); - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - webhookEmbedBuilder.setDescription("Here is the transcript of the ticket " + tickets.getTicketCount() + "!"); - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - webhookEmbedBuilder.setColor(BotWorker.randomEmbedColor().getRGB()); + webhookEmbedBuilder.setDescription("Here is the transcript of the ticket " + tickets.getTicketCount() + "!"); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); + webhookEmbedBuilder.setColor(BotWorker.randomEmbedColor().getRGB()); - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - webhookMessageBuilder.addFile(tickets.getTicketCount() + "_transcript.txt", stringBuilder.toString().getBytes(StandardCharsets.UTF_8)); + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + webhookMessageBuilder.addFile(tickets.getTicketCount() + "_transcript.txt", stringBuilder.toString().getBytes(StandardCharsets.UTF_8)); - WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), tickets.getLogChannelId(), tickets.getLogChannelWebhookToken(), false); + WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), tickets.getLogChannelId(), tickets.getLogChannelWebhookToken(), false); - event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.close")).queue(); - event.getChannel().delete().delay(2, TimeUnit.SECONDS).queue(); - } + event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.close").join()).queue(); + event.getChannel().delete().delay(2, TimeUnit.SECONDS).queue(); + } + }); } case "re_music_play" -> { @@ -216,20 +223,20 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { EmbedBuilder em = new EmbedBuilder() .setAuthor(event.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").join()) .setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.resume")) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.resume").join()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); } else { EmbedBuilder em = new EmbedBuilder() .setAuthor(event.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").join()) .setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.pause")) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.pause").join()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); } @@ -248,10 +255,10 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { EmbedBuilder em = new EmbedBuilder() .setAuthor(event.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer")) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").join()) .setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.pause")) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.pause").join()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); } else { @@ -281,12 +288,12 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { em.setAuthor(event.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer")); + em.setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").join()); em.setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setColor(Color.GREEN); em.setDescription(Main.getInstance().getMusicWorker().getGuildAudioPlayer(event.getGuild()).getScheduler().loop() ? - LanguageService.getByGuild(event.getGuild(), "message.music.loop.enabled") : - LanguageService.getByGuild(event.getGuild(), "message.music.loop.disabled")); + LanguageService.getByGuild(event.getGuild(), "message.music.loop.enabled").join() : + LanguageService.getByGuild(event.getGuild(), "message.music.loop.disabled").join()); em.setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); @@ -307,10 +314,10 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { em.setAuthor(event.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer")); + em.setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").join()); em.setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setColor(Color.GREEN); - em.setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.shuffle")); + em.setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.shuffle").join()); em.setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); @@ -321,8 +328,8 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { } case "re_music_add" -> { - Modal.Builder builder = Modal.create("re_music_add_modal", LanguageService.getByGuild(event.getGuild(), "label.queueAdd")); - builder.addActionRow(TextInput.create("re_music_add_modal_song", LanguageService.getByGuild(event.getGuild(), "label.song"), TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(512).setMinLength(4).build()); + Modal.Builder builder = Modal.create("re_music_add_modal", LanguageService.getByGuild(event.getGuild(), "label.queueAdd").join()); + builder.addActionRow(TextInput.create("re_music_add_modal_song", LanguageService.getByGuild(event.getGuild(), "label.song").join(), TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(512).setMinLength(4).build()); event.replyModal(builder.build()).queue(); } } @@ -355,7 +362,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { musicTitleAmount = Double.parseDouble(musicQuizTitleString); } catch (Exception exception) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.rewards")) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.rewards").join()) .setColor(Color.RED) .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.incorrectNumbers")) .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()), null, event.getInteraction().getHook()); @@ -377,9 +384,9 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_title", "Payment Amount on Music Quiz Title guess", musicTitleAmount); Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.rewards")) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.rewards").join()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.rewards.success")) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.rewards.success").join()) .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()), null, event.getInteraction().getHook()); } @@ -387,7 +394,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { event.deferReply(true).queue(); EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.feedback")) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.feedback").join()) .setColor(Color.GREEN) .setThumbnail(event.getUser().getEffectiveAvatarUrl()) .setDescription("```" + event.getValue("re_feedback_text").getAsString() + "```") @@ -972,10 +979,10 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "autorole" -> Setup.createAutoRoleSetupSelectMenu(event.getGuild(), event.getHook()).thenAccept(selectMenu -> event.editMessageEmbeds(Setup.createAutoRoleSetupMessage(event.getGuild(), event.getHook()).build()) - .setComponents( - ActionRow.of(selectMenu), - ActionRow.of(Button.link(BotConfig.getWebinterface(), "Webinterface"))) - .queue()); + .setComponents( + ActionRow.of(selectMenu), + ActionRow.of(Button.link(BotConfig.getWebinterface(), "Webinterface"))) + .queue()); case "tempvoice" -> { optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setup"), "tempVoiceSetup")); From 4bb4d8df2aa2fb6052bd0bf2dbce8f2e1b6a08ee Mon Sep 17 00:00:00 2001 From: Presti Date: Tue, 21 May 2024 18:15:26 +0200 Subject: [PATCH 16/94] Methane --- .../de/presti/ree6/events/MenuEvents.java | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index 8909914f7..53aa76a6b 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -364,7 +364,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setTitle(LanguageService.getByGuild(event.getGuild(), "label.rewards").join()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.incorrectNumbers")) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.incorrectNumbers").join()) .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()), null, event.getInteraction().getHook()); } @@ -406,28 +406,28 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { } case "re_suggestion_modal" -> { - Suggestions suggestions = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Suggestions(), "FROM Suggestions WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Suggestions(), "FROM Suggestions WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(suggestions -> { + event.deferReply(true).queue(); - event.deferReply(true).queue(); + if (suggestions != null) { + MessageChannel messageChannel = (MessageChannel) event.getGuild().getGuildChannelById(suggestions.getGuildChannelId().getChannelId()); - if (suggestions != null) { - MessageChannel messageChannel = (MessageChannel) event.getGuild().getGuildChannelById(suggestions.getGuildChannelId().getChannelId()); + if (messageChannel == null) return; - if (messageChannel == null) return; + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.suggestion").join()) + .setColor(Color.ORANGE) + .setThumbnail(event.getMember().getEffectiveAvatarUrl()) + .setDescription("```" + event.getValue("re_suggestion_text").getAsString() + "```") + .setFooter(LanguageService.getByGuild(event.getGuild(), "message.suggestion.footer", event.getUser().getEffectiveName()).join(), event.getMember().getEffectiveAvatarUrl()) + .setTimestamp(Instant.now()); - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.suggestion")) - .setColor(Color.ORANGE) - .setThumbnail(event.getMember().getEffectiveAvatarUrl()) - .setDescription("```" + event.getValue("re_suggestion_text").getAsString() + "```") - .setFooter(LanguageService.getByGuild(event.getGuild(), "message.suggestion.footer", event.getUser().getEffectiveName()), event.getMember().getEffectiveAvatarUrl()) - .setTimestamp(Instant.now()); - - Main.getInstance().getCommandManager().sendMessage(embedBuilder, messageChannel); - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.suggestion.sent"), null, event.getInteraction().getHook()); - } else { - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.suggestion.notSetup"), null, event.getInteraction().getHook()); - } + Main.getInstance().getCommandManager().sendMessage(embedBuilder, messageChannel); + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.suggestion.sent"), null, event.getInteraction().getHook()); + } else { + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.suggestion.notSetup"), null, event.getInteraction().getHook()); + } + }); } case "re_music_add_modal" -> { @@ -445,12 +445,12 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { String twitchUsername = modalMapping.getAsString(); - java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics"), true); + java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics").join(), true); Category category; if (categories.isEmpty()) { - category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics")).complete(); + category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics").join()).complete(); } else { category = categories.get(0); } From f4a39e10f4439817afd38dcf2c7fa84ae43ef06e Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 22 May 2024 10:15:05 +0200 Subject: [PATCH 17/94] ONLY 139 ERRORS LEFT LETS GO --- .../de/presti/ree6/events/MenuEvents.java | 368 +++++++++--------- 1 file changed, 190 insertions(+), 178 deletions(-) diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index 53aa76a6b..3e7663975 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -346,63 +346,68 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { switch (event.getModalId()) { case "re_rewards_modal" -> { event.deferReply(true).queue(); - String blackJackString = event.getValue("re_rewards_BlackJackWin").getAsString(); - String musicQuizWinString = event.getValue("re_rewards_MusicQuizWin").getAsString(); - String musicQuizFeatureString = event.getValue("re_rewards_MusicQuizFeature").getAsString(); - String musicQuizArtistString = event.getValue("re_rewards_MusicQuizArtist").getAsString(); - String musicQuizTitleString = event.getValue("re_rewards_MusicQuizTitle").getAsString(); + LanguageService.getByGuild(event.getGuild(), "label.rewards").thenAccept(title -> { + String blackJackString = event.getValue("re_rewards_BlackJackWin").getAsString(); + String musicQuizWinString = event.getValue("re_rewards_MusicQuizWin").getAsString(); + String musicQuizFeatureString = event.getValue("re_rewards_MusicQuizFeature").getAsString(); + String musicQuizArtistString = event.getValue("re_rewards_MusicQuizArtist").getAsString(); + String musicQuizTitleString = event.getValue("re_rewards_MusicQuizTitle").getAsString(); + + double blackJackAmount = 0, musicWinAmount = 0, musicFeatureAmount = 0, musicArtistAmount = 0, musicTitleAmount = 0; + + try { + blackJackAmount = Double.parseDouble(blackJackString); + musicWinAmount = Double.parseDouble(musicQuizWinString); + musicFeatureAmount = Double.parseDouble(musicQuizFeatureString); + musicArtistAmount = Double.parseDouble(musicQuizArtistString); + musicTitleAmount = Double.parseDouble(musicQuizTitleString); + } catch (Exception exception) { + Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() + .setTitle(title) + .setColor(Color.RED) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.incorrectNumbers").join()) + .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()), null, event.getInteraction().getHook()); + } - double blackJackAmount = 0, musicWinAmount = 0, musicFeatureAmount = 0, musicArtistAmount = 0, musicTitleAmount = 0; + SQLSession.getSqlConnector().getSqlWorker() + .setSetting(event.getGuild().getIdLong(), "configuration_rewards_blackjack_win", "Payment Amount on BlackJack win", blackJackAmount); - try { - blackJackAmount = Double.parseDouble(blackJackString); - musicWinAmount = Double.parseDouble(musicQuizWinString); - musicFeatureAmount = Double.parseDouble(musicQuizFeatureString); - musicArtistAmount = Double.parseDouble(musicQuizArtistString); - musicTitleAmount = Double.parseDouble(musicQuizTitleString); - } catch (Exception exception) { - Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.rewards").join()) - .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.incorrectNumbers").join()) - .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()), null, event.getInteraction().getHook()); - } - - SQLSession.getSqlConnector().getSqlWorker() - .setSetting(event.getGuild().getIdLong(), "configuration_rewards_blackjack_win", "Payment Amount on BlackJack win", blackJackAmount); + SQLSession.getSqlConnector().getSqlWorker() + .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_win", "Payment Amount on Music Quiz win", musicWinAmount); - SQLSession.getSqlConnector().getSqlWorker() - .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_win", "Payment Amount on Music Quiz win", musicWinAmount); + SQLSession.getSqlConnector().getSqlWorker() + .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_feature", "Payment Amount on Music Quiz Feature guess", musicFeatureAmount); - SQLSession.getSqlConnector().getSqlWorker() - .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_feature", "Payment Amount on Music Quiz Feature guess", musicFeatureAmount); + SQLSession.getSqlConnector().getSqlWorker() + .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_artist", "Payment Amount on Music Quiz Artist guess", musicArtistAmount); - SQLSession.getSqlConnector().getSqlWorker() - .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_artist", "Payment Amount on Music Quiz Artist guess", musicArtistAmount); + SQLSession.getSqlConnector().getSqlWorker() + .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_title", "Payment Amount on Music Quiz Title guess", musicTitleAmount); - SQLSession.getSqlConnector().getSqlWorker() - .setSetting(event.getGuild().getIdLong(), "configuration_rewards_musicquiz_title", "Payment Amount on Music Quiz Title guess", musicTitleAmount); + Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() + .setTitle(title) + .setColor(Color.GREEN) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.rewards.success").join()) + .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()), null, event.getInteraction().getHook()); + }); - Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.rewards").join()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.rewards.success").join()) - .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()), null, event.getInteraction().getHook()); } case "re_feedback_modal" -> { event.deferReply(true).queue(); - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.feedback").join()) - .setColor(Color.GREEN) - .setThumbnail(event.getUser().getEffectiveAvatarUrl()) - .setDescription("```" + event.getValue("re_feedback_text").getAsString() + "```") - .setFooter("By " + event.getUser().getEffectiveName() + " (" + event.getUser().getId() + ")", event.getUser().getEffectiveAvatarUrl()) - .setTimestamp(Instant.now()); + LanguageService.getByGuild(event.getGuild(), "label.feedback").thenAccept(title -> { + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(title) + .setColor(Color.GREEN) + .setThumbnail(event.getUser().getEffectiveAvatarUrl()) + .setDescription("```" + event.getValue("re_feedback_text").getAsString() + "```") + .setFooter("By " + event.getUser().getEffectiveName() + " (" + event.getUser().getId() + ")", event.getUser().getEffectiveAvatarUrl()) + .setTimestamp(Instant.now()); - Main.getInstance().getCommandManager().sendMessage(embedBuilder, BotWorker.getShardManager().getTextChannelById(BotConfig.getFeedbackChannel())); - Main.getInstance().getCommandManager().sendMessage("Thank you!", null, event.getInteraction().getHook()); + Main.getInstance().getCommandManager().sendMessage(embedBuilder, BotWorker.getShardManager().getTextChannelById(BotConfig.getFeedbackChannel())); + Main.getInstance().getCommandManager().sendMessage("Thank you!", null, event.getInteraction().getHook()); + }); } case "re_suggestion_modal" -> { @@ -443,72 +448,77 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { if (event.getGuild() == null) return; - String twitchUsername = modalMapping.getAsString(); - - java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics").join(), true); - - Category category; + LanguageService.getByGuild(event.getGuild(), "label.statistics").thenAccept(label -> { + String twitchUsername = modalMapping.getAsString(); - if (categories.isEmpty()) { - category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics").join()).complete(); - } else { - category = categories.get(0); - } + java.util.List categories = event.getGuild().getCategoriesByName(label, true); - String channelId = Main.getInstance().getNotifier().getTwitchClient().getHelix().getUsers(null, null, Collections.singletonList(twitchUsername)).execute().getUsers().get(0).getId(); + Category category; - TwitchIntegration twitchIntegration = SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE channelId=:twitchId", Map.of("twitchId", channelId)); - if (twitchIntegration == null) { - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.stream-action.noTwitch", BotConfig.getTwitchAuth())); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - return; - } - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.twitchCountName", Main.getInstance().getNotifier().getTwitchClient().getHelix().getChannelFollowers(null, channelId, null, 1, null).execute().getTotal()), category) - .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - ChannelStats channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - if (channelStats != null) { + if (categories.isEmpty()) { + category = event.getGuild().createCategory(label).complete(); + } else { + category = categories.get(0); + } - if (channelStats.getTwitchFollowerChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getTwitchFollowerChannelId()); + String channelId = Main.getInstance().getNotifier().getTwitchClient().getHelix().getUsers(null, null, Collections.singletonList(twitchUsername)).execute().getUsers().get(0).getId(); - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE channelId=:twitchId", Map.of("twitchId", channelId)).thenAccept(twitchIntegration -> { + if (twitchIntegration == null) { + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.RED) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.stream-action.noTwitch", BotConfig.getTwitchAuth()).join()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + return; + } - channelStats.setTwitchFollowerChannelId(voiceChannel.getId()); - channelStats.setTwitchFollowerChannelUsername(twitchUsername); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerTwitchChannel(twitchUsername); - } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), - null, - null, - null, - voiceChannel.getId(), - twitchUsername, - null, - null, - null, - null, - null, - null, - null, - null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerTwitchChannel(twitchUsername); - } - }); + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.twitchCountName", Main.getInstance().getNotifier().getTwitchClient().getHelix().getChannelFollowers(null, channelId, null, 1, null).execute().getTotal()).join(), category) + .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(channelStats -> { + if (channelStats != null) { + + if (channelStats.getTwitchFollowerChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getTwitchFollowerChannelId()); + + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } + + channelStats.setTwitchFollowerChannelId(voiceChannel.getId()); + channelStats.setTwitchFollowerChannelUsername(twitchUsername); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + Main.getInstance().getNotifier().registerTwitchChannel(twitchUsername); + } else { + channelStats = new ChannelStats(event.getGuild().getIdLong(), + null, + null, + null, + voiceChannel.getId(), + twitchUsername, + null, + null, + null, + null, + null, + null, + null, + null); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + Main.getInstance().getNotifier().registerTwitchChannel(twitchUsername); + } + }); + }); - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitchSuccess")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.GREEN) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitchSuccess").join()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); + }); } case "statisticsSetupYouTubeModal" -> { @@ -518,93 +528,95 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { if (event.getGuild() == null) return; - String youtubeChannelName = modalMapping.getAsString(); - - java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics"), true); + LanguageService.getByGuild(event.getGuild(), "label.statistics").thenAccept(label -> { + String youtubeChannelName = modalMapping.getAsString(); - Category category; + java.util.List categories = event.getGuild().getCategoriesByName(label, true); - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeSuccess")); + Category category; - if (categories.isEmpty()) { - category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics")).complete(); - } else { - category = categories.get(0); - } + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.GREEN) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeSuccess").join()); - ChannelResult youTubeChannel; - try { - if (YouTubeAPIHandler.getInstance().isValidChannelId(youtubeChannelName)) { - youTubeChannel = YouTubeAPIHandler.getInstance().getYouTubeChannelById(youtubeChannelName); + if (categories.isEmpty()) { + category = event.getGuild().createCategory(label).complete(); } else { - youTubeChannel = YouTubeAPIHandler.getInstance().getYouTubeChannelBySearch(youtubeChannelName); + category = categories.get(0); } - } catch (Exception e) { - embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - return; - } - if (youTubeChannel == null) { - embedBuilder = embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeNotFound")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - return; - } + ChannelResult youTubeChannel; + try { + if (YouTubeAPIHandler.getInstance().isValidChannelId(youtubeChannelName)) { + youTubeChannel = YouTubeAPIHandler.getInstance().getYouTubeChannelById(youtubeChannelName); + } else { + youTubeChannel = YouTubeAPIHandler.getInstance().getYouTubeChannelBySearch(youtubeChannelName); + } + } catch (Exception e) { + embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.RED) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError").join()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + return; + } - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.youtubeCountName", youTubeChannel.getSubscriberCountText()), category) - .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - ChannelStats channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - if (channelStats != null) { + if (youTubeChannel == null) { + embedBuilder = embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.RED) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeNotFound").join()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + return; + } - if (channelStats.getYoutubeSubscribersChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getYoutubeSubscribersChannelId()); + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.youtubeCountName", youTubeChannel.getSubscriberCountText()).join(), category) + .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(channelStats -> { + if (channelStats != null) { + if (channelStats.getYoutubeSubscribersChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getYoutubeSubscribersChannelId()); - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } - channelStats.setYoutubeSubscribersChannelId(voiceChannel.getId()); - channelStats.setYoutubeSubscribersChannelUsername(youTubeChannel.getId()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerYouTubeChannel(youTubeChannel.getId()); - } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), - null, - null, - null, - null, - null, - null, - null, - null, - null, - voiceChannel.getId(), - youTubeChannel.getId(), - null, - null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerYouTubeChannel(youTubeChannel.getId()); - } - }); + channelStats.setYoutubeSubscribersChannelId(voiceChannel.getId()); + channelStats.setYoutubeSubscribersChannelUsername(youTubeChannel.getId()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + Main.getInstance().getNotifier().registerYouTubeChannel(youTubeChannel.getId()); + } else { + channelStats = new ChannelStats(event.getGuild().getIdLong(), + null, + null, + null, + null, + null, + null, + null, + null, + null, + voiceChannel.getId(), + youTubeChannel.getId(), + null, + null); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + Main.getInstance().getNotifier().registerYouTubeChannel(youTubeChannel.getId()); + } + }); + }); - embedBuilder = embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeSuccess")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + embedBuilder = embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.GREEN) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeSuccess").join()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); } case "statisticsSetupRedditModal" -> { From 93d8ff38f9c45c269929c1e2af9b42f43df7c63a Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 22 May 2024 14:05:15 +0200 Subject: [PATCH 18/94] ONLY 95 ERRORS LEFT RAAAAAAAAAAAAAAAAH --- .../de/presti/ree6/events/MenuEvents.java | 501 +++++++++--------- 1 file changed, 258 insertions(+), 243 deletions(-) diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index 3e7663975..a46088407 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -626,79 +626,81 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { if (event.getGuild() == null) return; - String subredditName = modalMapping.getAsString(); - - java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics"), true); - - Category category; + LanguageService.getByGuild(event.getGuild(), "label.statistics").thenAccept(label -> { + String subredditName = modalMapping.getAsString(); - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.redditSuccess")); + java.util.List categories = event.getGuild().getCategoriesByName(label, true); - if (categories.isEmpty()) { - category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics")).complete(); - } else { - category = categories.get(0); - } + Category category; - RedditSubreddit subreddit; - try { - subreddit = Main.getInstance().getNotifier().getSubreddit(subredditName); - } catch (IOException | InterruptedException e) { - embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - return; - } + .setColor(Color.GREEN) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.redditSuccess").join()); - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.redditCountName", subreddit.getActiveUserCount()), category) - .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - ChannelStats channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - if (channelStats != null) { + if (categories.isEmpty()) { + category = event.getGuild().createCategory(label).complete(); + } else { + category = categories.get(0); + } - if (channelStats.getSubredditMemberChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getSubredditMemberChannelId()); + RedditSubreddit subreddit; + try { + subreddit = Main.getInstance().getNotifier().getSubreddit(subredditName); + } catch (IOException | InterruptedException e) { + embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.RED) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError").join()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + return; + } - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.redditCountName", subreddit.getActiveUserCount()).join(), category) + .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(channelStats -> { + if (channelStats != null) { + if (channelStats.getSubredditMemberChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getSubredditMemberChannelId()); - channelStats.setSubredditMemberChannelId(voiceChannel.getId()); - channelStats.setSubredditMemberChannelSubredditName(subredditName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerSubreddit(subredditName); - } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - voiceChannel.getId(), - subredditName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerSubreddit(subredditName); - } - }); + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } - embedBuilder = embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.redditSuccess")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + channelStats.setSubredditMemberChannelId(voiceChannel.getId()); + channelStats.setSubredditMemberChannelSubredditName(subredditName); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + Main.getInstance().getNotifier().registerSubreddit(subredditName); + } else { + channelStats = new ChannelStats(event.getGuild().getIdLong(), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + voiceChannel.getId(), + subredditName); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + Main.getInstance().getNotifier().registerSubreddit(subredditName); + } + }); + }); + + embedBuilder = embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.GREEN) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.redditSuccess").join()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); } case "statisticsSetupTwitterModal" -> { @@ -708,79 +710,81 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { if (event.getGuild() == null) return; - String twitterName = modalMapping.getAsString(); - - java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics"), true); - - Category category; + LanguageService.getByGuild(event.getGuild(), "label.statistics").thenAccept(label -> { + String twitterName = modalMapping.getAsString(); - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitterSuccess")); + java.util.List categories = event.getGuild().getCategoriesByName(label, true); - if (categories.isEmpty()) { - category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics")).complete(); - } else { - category = categories.get(0); - } + Category category; - UserV2 twitterUser; - try { - twitterUser = Main.getInstance().getNotifier().getTwitterClient().getUserFromUserName(twitterName); - } catch (NoSuchElementException e) { - embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - return; - } + .setColor(Color.GREEN) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitterSuccess").join()); - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.twitterCountName", twitterUser.getFollowersCount()), category) - .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - ChannelStats channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - if (channelStats != null) { + if (categories.isEmpty()) { + category = event.getGuild().createCategory(label).complete(); + } else { + category = categories.get(0); + } - if (channelStats.getTwitterFollowerChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getTwitterFollowerChannelId()); + UserV2 twitterUser; + try { + twitterUser = Main.getInstance().getNotifier().getTwitterClient().getUserFromUserName(twitterName); + } catch (NoSuchElementException e) { + embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.RED) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError").join()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + return; + } - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.twitterCountName", twitterUser.getFollowersCount()).join(), category) + .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(channelStats -> { + if (channelStats != null) { + if (channelStats.getTwitterFollowerChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getTwitterFollowerChannelId()); - channelStats.setTwitterFollowerChannelId(voiceChannel.getId()); - channelStats.setTwitterFollowerChannelUsername(twitterName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerTwitterUser(twitterName); - } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), - null, - null, - null, - voiceChannel.getId(), - twitterName, - null, - null, - null, - null, - null, - null, - null, - null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerTwitterUser(twitterName); - } - }); + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } + + channelStats.setTwitterFollowerChannelId(voiceChannel.getId()); + channelStats.setTwitterFollowerChannelUsername(twitterName); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + Main.getInstance().getNotifier().registerTwitterUser(twitterName); + } else { + channelStats = new ChannelStats(event.getGuild().getIdLong(), + null, + null, + null, + voiceChannel.getId(), + twitterName, + null, + null, + null, + null, + null, + null, + null, + null); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + Main.getInstance().getNotifier().registerTwitterUser(twitterName); + } + }); + }); - embedBuilder = embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitterSuccess")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + embedBuilder = embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.GREEN) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitterSuccess").join()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); } case "statisticsSetupInstagramModal" -> { @@ -790,86 +794,90 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { if (event.getGuild() == null) return; - String instagramName = modalMapping.getAsString(); + LanguageService.getByGuild(event.getGuild(), "label.statistics").thenAccept(label -> { + String instagramName = modalMapping.getAsString(); - java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics"), true); + java.util.List categories = event.getGuild().getCategoriesByName(label, true); - Category category; + Category category; - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.instagramSuccess")); + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.GREEN) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.instagramSuccess").join()); - if (categories.isEmpty()) { - category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics")).complete(); - } else { - category = categories.get(0); - } + if (categories.isEmpty()) { + category = event.getGuild().createCategory(label).complete(); + } else { + category = categories.get(0); + } - com.github.instagram4j.instagram4j.models.user.User instagramUser; - try { - instagramUser = Main.getInstance().getNotifier().getInstagramClient().getActions().users().findByUsername(instagramName).get().getUser(); - } catch (ExecutionException | InterruptedException e) { - embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - return; - } + com.github.instagram4j.instagram4j.models.user.User instagramUser; + try { + instagramUser = Main.getInstance().getNotifier().getInstagramClient().getActions().users().findByUsername(instagramName).get().getUser(); + } catch (ExecutionException | InterruptedException e) { + embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.RED) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError").join()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + return; + } - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.instagramCountName", instagramUser.getFollower_count()), category) - .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - ChannelStats channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - if (channelStats != null) { + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.instagramCountName", instagramUser.getFollower_count()).join(), category) + .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(channelStats -> { + if (channelStats != null) { - if (channelStats.getInstagramFollowerChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getInstagramFollowerChannelId()); + if (channelStats.getInstagramFollowerChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getInstagramFollowerChannelId()); - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } - channelStats.setInstagramFollowerChannelId(voiceChannel.getId()); - channelStats.setInstagramFollowerChannelUsername(instagramName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerInstagramUser(instagramName); - } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), - null, - null, - null, - null, - null, - voiceChannel.getId(), - instagramName, - null, - null, - null, - null, - null, - null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - Main.getInstance().getNotifier().registerInstagramUser(instagramName); - } - }); + channelStats.setInstagramFollowerChannelId(voiceChannel.getId()); + channelStats.setInstagramFollowerChannelUsername(instagramName); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + Main.getInstance().getNotifier().registerInstagramUser(instagramName); + } else { + channelStats = new ChannelStats(event.getGuild().getIdLong(), + null, + null, + null, + null, + null, + voiceChannel.getId(), + instagramName, + null, + null, + null, + null, + null, + null); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + Main.getInstance().getNotifier().registerInstagramUser(instagramName); + } + }); - embedBuilder = embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu")) - .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.instagramSuccess")); - event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); + + embedBuilder = embedBuilder + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) + .setColor(Color.GREEN) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.instagramSuccess").join()); + event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); } default -> event.deferEdit().setEmbeds(new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.unknownMenu")) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.unknownMenu").join()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.unknownMenu")) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.unknownMenu").join()) .build()).setComponents(new ArrayList<>()).queue(); } } @@ -898,33 +906,35 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even return; } - // We are doing this because a normal List can't be modified. - ArrayList values = new ArrayList<>(event.getValues()); + SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(event.getGuild().getIdLong()).thenAccept(roles -> { + // We are doing this because a normal List can't be modified. + ArrayList values = new ArrayList<>(event.getValues()); - EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); - if (event.getSelectedOptions().isEmpty()) { - SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(event.getGuild().getIdLong()).forEach(autoRole -> - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(autoRole)); - } else { - SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(event.getGuild().getIdLong()).forEach(autoRole -> { - String value = String.valueOf(autoRole.getRoleId()); + EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); + if (event.getSelectedOptions().isEmpty()) { + roles.forEach(autoRole -> + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(autoRole)); + } else { + roles.forEach(autoRole -> { + String value = String.valueOf(autoRole.getRoleId()); - if (!event.getValues().contains(value)) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(autoRole); - values.remove(value); - } - }); + if (!event.getValues().contains(value)) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(autoRole); + values.remove(value); + } + }); - for (String roleId : values) { - Role role = event.getGuild().getRoleById(roleId); - if (role != null) { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new AutoRole(event.getGuild().getIdLong(), role.getIdLong())); + for (String roleId : values) { + Role role = event.getGuild().getRoleById(roleId); + if (role != null) { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new AutoRole(event.getGuild().getIdLong(), role.getIdLong())); + } } } - } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.autoRole.setupSuccess")); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.autoRole.setupSuccess").join()); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); } case "setupActionMenu" -> { @@ -940,24 +950,27 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even switch (event.getInteraction().getValues().get(0)) { case "rewards" -> { - TextInput blackJackWin = TextInput.create("re_rewards_BlackJackWin", LanguageService.getByGuild(event.getGuild(), "label.blackJackWin"), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - TextInput musicQuizWin = TextInput.create("re_rewards_MusicQuizWin", LanguageService.getByGuild(event.getGuild(), "label.musicQuizWin"), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - TextInput musicQuizFeature = TextInput.create("re_rewards_MusicQuizFeature", LanguageService.getByGuild(event.getGuild(), "label.musicQuizFeatureGuess"), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - TextInput musicQuizArtist = TextInput.create("re_rewards_MusicQuizArtist", LanguageService.getByGuild(event.getGuild(), "label.musicQuizArtistGuess"), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - TextInput musicQuizTitle = TextInput.create("re_rewards_MusicQuizTitle", LanguageService.getByGuild(event.getGuild(), "label.musicQuizTitleGuess"), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - Modal modal = Modal.create("re_rewards_modal", LanguageService.getByGuild(event.getGuild(), "label.rewards")).addActionRow(blackJackWin).addActionRow(musicQuizWin).addActionRow(musicQuizFeature).addActionRow(musicQuizArtist).addActionRow(musicQuizTitle).build(); - event.replyModal(modal).queue(); + LanguageService.getByGuild(event.getGuild(), "label.rewards").thenAccept(rewardLabel -> { + TextInput blackJackWin = TextInput.create("re_rewards_BlackJackWin", LanguageService.getByGuild(event.getGuild(), "label.blackJackWin").join(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + TextInput musicQuizWin = TextInput.create("re_rewards_MusicQuizWin", LanguageService.getByGuild(event.getGuild(), "label.musicQuizWin").join(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + TextInput musicQuizFeature = TextInput.create("re_rewards_MusicQuizFeature", LanguageService.getByGuild(event.getGuild(), "label.musicQuizFeatureGuess").join(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + TextInput musicQuizArtist = TextInput.create("re_rewards_MusicQuizArtist", LanguageService.getByGuild(event.getGuild(), "label.musicQuizArtistGuess").join(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + TextInput musicQuizTitle = TextInput.create("re_rewards_MusicQuizTitle", LanguageService.getByGuild(event.getGuild(), "label.musicQuizTitleGuess").join(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + Modal modal = Modal.create("re_rewards_modal", rewardLabel).addActionRow(blackJackWin).addActionRow(musicQuizWin).addActionRow(musicQuizFeature).addActionRow(musicQuizArtist).addActionRow(musicQuizTitle).build(); + event.replyModal(modal).queue(); + }); } case "lang" -> { + LanguageService.getByGuild(event.getGuild(), "message.setup.steps.lang").thenAccept(description -> { + for (DiscordLocale locale : LanguageService.getSupported()) { + optionList.add(SelectOption.of(locale.getLanguageName(), locale.getLocale())); + } - for (DiscordLocale locale : LanguageService.getSupported()) { - optionList.add(SelectOption.of(locale.getLanguageName(), locale.getLocale())); - } - - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.lang")); + embedBuilder.setDescription(description); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLangMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired"), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLangMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").join(), 1, 1, false, optionList)).queue(); + }); } case "log" -> { @@ -1541,20 +1554,22 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even * @param event The InteractionEvent of the SelectMenu. */ public void sendDefaultChoice(StringSelectInteractionEvent event) { - EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); - - List optionList = new ArrayList<>(); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.language"), "lang")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.auditLog"), "log")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.welcomeChannel"), "welcome")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.autoRole"), "autorole")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.temporalVoice"), "tempvoice")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.statistics"), "statistics")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.ticketSystem"), "tickets")); - - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.setupMenu")); - - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupActionMenu", LanguageService.getByGuild(event.getGuild(), "message.setup.setupMenuPlaceholder"), 1, 1, false, optionList)).queue(); + LanguageService.getByGuild(event.getGuild(), "message.setup.setupMenu").thenAccept(description -> { + EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); + + List optionList = new ArrayList<>(); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.language").join(), "lang")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.auditLog").join(), "log")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.welcomeChannel").join(), "welcome")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.autoRole").join(), "autorole")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.temporalVoice").join(), "tempvoice")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.statistics").join(), "statistics")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.ticketSystem").join(), "tickets")); + + embedBuilder.setDescription(description); + + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupActionMenu", LanguageService.getByGuild(event.getGuild(), "message.setup.setupMenuPlaceholder").join(), 1, 1, false, optionList)).queue(); + }); } /** @@ -1566,12 +1581,12 @@ public void sendDefaultChoice(StringSelectInteractionEvent event) { */ private boolean checkPerms(Member member, MessageChannel channel) { if (member == null || !member.hasPermission(Permission.ADMINISTRATOR)) { - channel.sendMessage(LanguageService.getByGuild((member == null ? null : member.getGuild()), "message.default.insufficientPermission", Permission.ADMINISTRATOR.name())).queue(); + channel.sendMessage(LanguageService.getByGuild((member == null ? null : member.getGuild()), "message.default.insufficientPermission", Permission.ADMINISTRATOR.name()).join()).queue(); return true; } if (!member.getGuild().getSelfMember().hasPermission(Permission.MANAGE_WEBHOOKS)) { - channel.sendMessage(LanguageService.getByGuild(member.getGuild(), "message.default.needPermission", Permission.MANAGE_WEBHOOKS.name())).queue(); + channel.sendMessage(LanguageService.getByGuild(member.getGuild(), "message.default.needPermission", Permission.MANAGE_WEBHOOKS.name()).join()).queue(); return true; } From d2f86350af924d68204be2c3706e76a470e26cf1 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 22 May 2024 14:42:03 +0200 Subject: [PATCH 19/94] 0 ERRORS RAAAAAAAAAAAAH --- .../ree6/audio/AudioPlayerReceiveHandler.java | 2 +- .../impl/community/StreamActionCommand.java | 2 +- .../ree6/commands/impl/community/Ticket.java | 2 +- .../presti/ree6/commands/impl/mod/Setup.java | 6 +- .../ree6/commands/impl/mod/Suggestion.java | 4 +- .../presti/ree6/commands/impl/mod/Warn.java | 25 +- .../de/presti/ree6/events/LoggingEvents.java | 4 +- .../de/presti/ree6/events/MenuEvents.java | 569 ++++++++++-------- .../de/presti/ree6/events/OtherEvents.java | 4 +- src/main/java/de/presti/ree6/main/Main.java | 4 +- .../module/invite/InviteContainerManager.java | 2 +- .../presti/ree6/utils/data/EconomyUtil.java | 8 +- 12 files changed, 353 insertions(+), 279 deletions(-) diff --git a/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java b/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java index 46d24047b..52fe5c15d 100644 --- a/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java +++ b/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java @@ -196,7 +196,7 @@ public void endReceiving() { boolean failedToUpload = false; try { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(recording); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(recording).join(); } catch (Exception ignore) { failedToUpload = true; } diff --git a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java index 01002d15d..fe7af917c 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java @@ -164,7 +164,7 @@ public void onPerform(CommandEvent commandEvent) { streamAction.setGuildId(commandEvent.getGuild().getIdLong()); streamAction.setName(name.getAsString()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction).join(); commandEvent.reply(commandEvent.getResource("message.stream-action.added", name.getAsString())); } else { commandEvent.reply(commandEvent.getResource("message.stream-action.noTwitch", BotConfig.getTwitchAuth())); diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java b/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java index 9925fcdf6..41171f2db 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java @@ -79,7 +79,7 @@ public void onPerform(CommandEvent commandEvent) { finalTickets.setLogChannelWebhookToken(webhook.getToken()); commandEvent.getGuild().createCategory("Tickets").addPermissionOverride(commandEvent.getGuild().getPublicRole(), null, EnumSet.of(Permission.VIEW_CHANNEL)).queue(category1 -> { finalTickets.setTicketCategory(category1.getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(finalTickets); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(finalTickets).join(); MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); messageCreateBuilder.setEmbeds(new EmbedBuilder() diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java index 4aac1330e..ab540bfa0 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java @@ -203,8 +203,9 @@ public void onPerform(CommandEvent commandEvent) { case "tempvoice" -> { if (commandEvent.getSubcommand().equals("set")) { if (guildChannelUnion.getType() == ChannelType.VOICE) { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new TemporalVoicechannel(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong())); - commandEvent.reply(commandEvent.getResource("message.temporalVoice.setupSuccess")); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new TemporalVoicechannel(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong())).thenAccept(save -> { + commandEvent.reply(commandEvent.getResource("message.temporalVoice.setupSuccess")); + }); } else { commandEvent.reply(commandEvent.getResource("message.default.invalidOptionChannel")); } @@ -252,6 +253,7 @@ public void onPerform(CommandEvent commandEvent) { for (Setting setting : SettingsManager.getSettings()) { if (!setting.getName().startsWith("configuration_rewards_")) continue; + // TODO:: thing of how to handle this. SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Setting(commandEvent.getGuild().getIdLong(), setting.getName(), setting.getDisplayName(), setting.getValue())); } diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java b/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java index 16617141c..98c2d9aff 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java @@ -80,9 +80,9 @@ public void createSuggestions(CommandEvent commandEvent, MessageChannel channel, SQLSession.getSqlConnector().getSqlWorker().deleteEntity(suggestions); suggestions.getGuildChannelId().setChannelId(channel.getIdLong()); - return SQLSession.getSqlConnector().getSqlWorker().updateEntity(suggestions); + return SQLSession.getSqlConnector().getSqlWorker().updateEntity(suggestions).join(); } else { - return SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Suggestions(commandEvent.getGuild().getIdLong(), channel.getIdLong())); + return SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Suggestions(commandEvent.getGuild().getIdLong(), channel.getIdLong())).join(); } }).thenAccept(suggestions -> SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_suggestion_menu").thenAccept(setting -> { MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java b/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java index c7c93a07d..142ff00e8 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java @@ -71,8 +71,9 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(2); punishments.setRoleId(roleMapping.getAsRole().getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments); - commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).thenAccept(save -> { + commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); + }); } case "roleremove" -> { @@ -81,8 +82,9 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(3); punishments.setRoleId(roleMapping.getAsRole().getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments); - commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).thenAccept(save -> { + commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); + }); } case "timeout" -> { @@ -91,8 +93,9 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(1); punishments.setTimeoutTime(secondsMapping.getAsLong() * 1000); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments); - commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).thenAccept(save -> { + commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); + }); } case "kick" -> { @@ -101,8 +104,9 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(4); if (reasonMapping != null) punishments.setReason(reasonMapping.getAsString()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments); - commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).thenAccept(save -> { + commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); + }); } case "ban" -> { @@ -111,8 +115,9 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(5); if (reasonMapping != null) punishments.setReason(reasonMapping.getAsString()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments); - commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).thenAccept(save -> { + commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); + }); } case "list" -> { diff --git a/src/main/java/de/presti/ree6/events/LoggingEvents.java b/src/main/java/de/presti/ree6/events/LoggingEvents.java index e962b8c97..1a335faa9 100644 --- a/src/main/java/de/presti/ree6/events/LoggingEvents.java +++ b/src/main/java/de/presti/ree6/events/LoggingEvents.java @@ -74,12 +74,12 @@ public void onGuildUpdateVanityCode(@NotNull GuildUpdateVanityCodeEvent event) { if (event.getOldVanityCode() == null) { event.getGuild().retrieveVanityInvite().onErrorMap(throwable -> null).queue(vanityInvite -> - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Invite(event.getGuild().getIdLong(), event.getGuild().getOwnerIdLong(), vanityInvite.getUses(), event.getNewVanityCode()))); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Invite(event.getGuild().getIdLong(), event.getGuild().getOwnerIdLong(), vanityInvite.getUses(), event.getNewVanityCode())).join()); } else { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Invite(), "FROM Invite WHERE guildAndCode.guildId = :gid AND guildAndCode.code = :code", Map.of("gid", event.getGuild().getIdLong(), "code", event.getOldVanityCode())).thenAccept(invite -> { invite.setCode(event.getNewVanityCode()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(invite); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(invite).join(); }); } } diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index a46088407..d95260864 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -15,7 +15,6 @@ import de.presti.ree6.sql.entities.*; import de.presti.ree6.sql.entities.roles.AutoRole; import de.presti.ree6.sql.entities.stats.ChannelStats; -import de.presti.ree6.sql.entities.webhook.base.Webhook; import de.presti.ree6.utils.apis.YouTubeAPIHandler; import de.presti.wrapper.entities.channel.ChannelResult; import io.github.redouane59.twitter.dto.user.UserV2; @@ -488,7 +487,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { channelStats.setTwitchFollowerChannelId(voiceChannel.getId()); channelStats.setTwitchFollowerChannelUsername(twitchUsername); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); Main.getInstance().getNotifier().registerTwitchChannel(twitchUsername); } else { channelStats = new ChannelStats(event.getGuild().getIdLong(), @@ -505,7 +504,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { null, null, null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); Main.getInstance().getNotifier().registerTwitchChannel(twitchUsername); } }); @@ -587,7 +586,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { channelStats.setYoutubeSubscribersChannelId(voiceChannel.getId()); channelStats.setYoutubeSubscribersChannelUsername(youTubeChannel.getId()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); Main.getInstance().getNotifier().registerYouTubeChannel(youTubeChannel.getId()); } else { channelStats = new ChannelStats(event.getGuild().getIdLong(), @@ -604,7 +603,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { youTubeChannel.getId(), null, null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); Main.getInstance().getNotifier().registerYouTubeChannel(youTubeChannel.getId()); } }); @@ -671,7 +670,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { channelStats.setSubredditMemberChannelId(voiceChannel.getId()); channelStats.setSubredditMemberChannelSubredditName(subredditName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); Main.getInstance().getNotifier().registerSubreddit(subredditName); } else { channelStats = new ChannelStats(event.getGuild().getIdLong(), @@ -688,7 +687,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { null, voiceChannel.getId(), subredditName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); Main.getInstance().getNotifier().registerSubreddit(subredditName); } }); @@ -755,7 +754,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { channelStats.setTwitterFollowerChannelId(voiceChannel.getId()); channelStats.setTwitterFollowerChannelUsername(twitterName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); Main.getInstance().getNotifier().registerTwitterUser(twitterName); } else { channelStats = new ChannelStats(event.getGuild().getIdLong(), @@ -772,7 +771,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { null, null, null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); Main.getInstance().getNotifier().registerTwitterUser(twitterName); } }); @@ -840,7 +839,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { channelStats.setInstagramFollowerChannelId(voiceChannel.getId()); channelStats.setInstagramFollowerChannelUsername(instagramName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); Main.getInstance().getNotifier().registerInstagramUser(instagramName); } else { channelStats = new ChannelStats(event.getGuild().getIdLong(), @@ -857,7 +856,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { null, null, null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); Main.getInstance().getNotifier().registerInstagramUser(instagramName); } }); @@ -927,7 +926,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even for (String roleId : values) { Role role = event.getGuild().getRoleById(roleId); if (role != null) { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new AutoRole(event.getGuild().getIdLong(), role.getIdLong())); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new AutoRole(event.getGuild().getIdLong(), role.getIdLong())).join(); } } } @@ -974,31 +973,35 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even } case "log" -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setup"), "logSetup")); + LanguageService.getByGuild(event.getGuild(), "label.setup").thenAccept(label -> { + optionList.add(SelectOption.of(label, "logSetup")); - if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong())) - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete"), "logDelete")); + if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).join()) + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").join(), "logDelete")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu"), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").join(), "backToSetupMenu")); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.auditLog")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.auditLog").join()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired"), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").join(), 1, 1, false, optionList)).queue(); + }); } case "welcome" -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setup"), "welcomeSetup")); + LanguageService.getByGuild(event.getGuild(), "label.setup").thenAccept(label -> { + optionList.add(SelectOption.of(label, "welcomeSetup")); - if (SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong())) - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete"), "welcomeDelete")); + if (SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong()).join()) + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").join(), "welcomeDelete")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setImage"), "welcomeImage")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setImage").join(), "welcomeImage")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu"), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").join(), "backToSetupMenu")); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.welcome")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.welcome").join()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired"), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").join(), 1, 1, false, optionList)).queue(); + }); } case "autorole" -> @@ -1010,49 +1013,57 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even .queue()); case "tempvoice" -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setup"), "tempVoiceSetup")); + LanguageService.getByGuild(event.getGuild(), "label.setup").thenAccept(label -> { + optionList.add(SelectOption.of(label, "tempVoiceSetup")); - if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())) != null) - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete"), "tempVoiceDelete")); + if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).join() != null) + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").join(), "tempVoiceDelete")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu"), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").join(), "backToSetupMenu")); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.temporalVoice")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.temporalVoice").join()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoiceMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired"), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoiceMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").join(), 1, 1, false, optionList)).queue(); + }); } case "statistics" -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupMemberStatistics"), "statisticsSetupMember")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupTwitchStatistics"), "statisticsSetupTwitch")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupYoutubeStatistics"), "statisticsSetupYouTube")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupRedditStatistics"), "statisticsSetupReddit")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupTwitterStatistics"), "statisticsSetupTwitter")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupInstagramStatistics"), "statisticsSetupInstagram")); + LanguageService.getByGuild(event.getGuild(), "message.statistics.setup").thenAccept(description -> { + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupMemberStatistics").join(), "statisticsSetupMember")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupTwitchStatistics").join(), "statisticsSetupTwitch")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupYoutubeStatistics").join(), "statisticsSetupYouTube")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupRedditStatistics").join(), "statisticsSetupReddit")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupTwitterStatistics").join(), "statisticsSetupTwitter")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupInstagramStatistics").join(), "statisticsSetupInstagram")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu"), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").join(), "backToSetupMenu")); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.setup")); + embedBuilder.setDescription(description); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupStatisticsMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired"), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupStatisticsMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").join(), 1, 1, false, optionList)).queue(); + }); } case "tickets" -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setup"), "ticketsSetup")); + LanguageService.getByGuild(event.getGuild(), "label.setup").thenAccept(label -> { + optionList.add(SelectOption.of(label, "ticketsSetup")); - if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())) != null) - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete"), "ticketsDelete")); + if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).join() != null) + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").join(), "ticketsDelete")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu"), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").join(), "backToSetupMenu")); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.setup")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.setup").join()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTicketsMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired"), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTicketsMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").join(), 1, 1, false, optionList)).queue(); + }); } default -> { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").thenAccept(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } } @@ -1070,117 +1081,136 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); case "statisticsSetupMember" -> { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.memberSuccess")); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics"), true); - - Category category; + LanguageService.getByGuild(event.getGuild(), "message.statistics.memberSuccess").thenAccept(description -> { + embedBuilder.setDescription(description); + embedBuilder.setColor(Color.GREEN); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics").join(), true); - if (categories.isEmpty()) { - category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics")).complete(); - } else { - category = categories.get(0); - } + Category category; - event.getGuild().loadMembers().onSuccess(members -> event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.overallMembersName", event.getGuild().getMemberCount()), category).queue(voiceChannel -> { - voiceChannel.getManager().setUserLimit(0).queue(); - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.realMembersName", members.stream().filter(member -> !member.getUser().isBot()).count()), category).queue(voiceChannel1 -> { - voiceChannel1.getManager().setUserLimit(0).queue(); - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.botMembersName", members.stream().filter(member -> member.getUser().isBot()).count()), category).queue(voiceChannel2 -> { - voiceChannel2.getManager().setUserLimit(0).queue(); - ChannelStats channelStats = SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - if (channelStats != null) { - if (channelStats.getMemberStatsChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getMemberStatsChannelId()); - - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } - if (channelStats.getRealMemberStatsChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getRealMemberStatsChannelId()); + if (categories.isEmpty()) { + category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics").join()).complete(); + } else { + category = categories.get(0); + } - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } - if (channelStats.getBotMemberStatsChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getBotMemberStatsChannelId()); + event.getGuild().loadMembers().onSuccess(members -> event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.overallMembersName", event.getGuild().getMemberCount()).join(), category).queue(voiceChannel -> { + voiceChannel.getManager().setUserLimit(0).queue(); + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.realMembersName", members.stream().filter(member -> !member.getUser().isBot()).count()).join(), category).queue(voiceChannel1 -> { + voiceChannel1.getManager().setUserLimit(0).queue(); + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.botMembersName", members.stream().filter(member -> member.getUser().isBot()).count()).join(), category).queue(voiceChannel2 -> { + voiceChannel2.getManager().setUserLimit(0).queue(); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(channelStats -> { + if (channelStats != null) { + if (channelStats.getMemberStatsChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getMemberStatsChannelId()); + + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } + if (channelStats.getRealMemberStatsChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getRealMemberStatsChannelId()); + + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } + if (channelStats.getBotMemberStatsChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getBotMemberStatsChannelId()); + + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } + channelStats.setMemberStatsChannelId(voiceChannel.getId()); + channelStats.setRealMemberStatsChannelId(voiceChannel1.getId()); + channelStats.setBotMemberStatsChannelId(voiceChannel2.getId()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); + } else { + channelStats = new ChannelStats(event.getGuild().getIdLong(), + voiceChannel.getId(), + voiceChannel1.getId(), + voiceChannel2.getId(), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); + } + }); - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } - channelStats.setMemberStatsChannelId(voiceChannel.getId()); - channelStats.setRealMemberStatsChannelId(voiceChannel1.getId()); - channelStats.setBotMemberStatsChannelId(voiceChannel2.getId()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), - voiceChannel.getId(), - voiceChannel1.getId(), - voiceChannel2.getId(), - null, - null, - null, - null, - null, - null, - null, - null, - null, - null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats); - } + }); }); - }); - })); + })); + }); } case "statisticsSetupTwitch" -> { - TextInput input = TextInput.create("twitchChannelName", LanguageService.getByGuild(event.getGuild(), "label.channelName"), TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Twitch Channel name here!").build(); + LanguageService.getByGuild(event.getGuild(), "label.channelName").thenAccept(label -> { + TextInput input = TextInput.create("twitchChannelName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Twitch Channel name here!").build(); - Modal modal = Modal.create("statisticsSetupTwitchModal", LanguageService.getByGuild(event.getGuild(), "label.setupTwitchStatistics")).addActionRow(input).build(); + Modal modal = Modal.create("statisticsSetupTwitchModal", LanguageService.getByGuild(event.getGuild(), "label.setupTwitchStatistics").join()).addActionRow(input).build(); + + event.replyModal(modal).queue(); + }); - event.replyModal(modal).queue(); } case "statisticsSetupYouTube" -> { - TextInput input = TextInput.create("youtubeChannelName", LanguageService.getByGuild(event.getGuild(), "label.channelName"), TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the YouTube Channel name here!").build(); + LanguageService.getByGuild(event.getGuild(), "label.channelName").thenAccept(label -> { + TextInput input = TextInput.create("youtubeChannelName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the YouTube Channel name here!").build(); - Modal modal = Modal.create("statisticsSetupYouTubeModal", LanguageService.getByGuild(event.getGuild(), "label.setupYoutubeStatistics")).addActionRow(input).build(); + Modal modal = Modal.create("statisticsSetupYouTubeModal", LanguageService.getByGuild(event.getGuild(), "label.setupYoutubeStatistics").join()).addActionRow(input).build(); - event.replyModal(modal).queue(); + event.replyModal(modal).queue(); + }); } case "statisticsSetupReddit" -> { - TextInput input = TextInput.create("subredditName", LanguageService.getByGuild(event.getGuild(), "label.subreddit"), TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Subreddit name here!").build(); + LanguageService.getByGuild(event.getGuild(), "label.subreddit").thenAccept(label -> { + TextInput input = TextInput.create("subredditName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Subreddit name here!").build(); - Modal modal = Modal.create("statisticsSetupRedditModal", LanguageService.getByGuild(event.getGuild(), "label.setupRedditStatistics")).addActionRow(input).build(); + Modal modal = Modal.create("statisticsSetupRedditModal", LanguageService.getByGuild(event.getGuild(), "label.setupRedditStatistics").join()).addActionRow(input).build(); - event.replyModal(modal).queue(); + event.replyModal(modal).queue(); + }); } case "statisticsSetupTwitter" -> { - TextInput input = TextInput.create("twitterName", LanguageService.getByGuild(event.getGuild(), "label.name"), TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Twitter name here!").build(); + LanguageService.getByGuild(event.getGuild(), "label.name").thenAccept(label -> { + TextInput input = TextInput.create("twitterName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Twitter name here!").build(); - Modal modal = Modal.create("statisticsSetupTwitterModal", LanguageService.getByGuild(event.getGuild(), "label.setupTwitterStatistics")).addActionRow(input).build(); + Modal modal = Modal.create("statisticsSetupTwitterModal", LanguageService.getByGuild(event.getGuild(), "label.setupTwitterStatistics").join()).addActionRow(input).build(); + + event.replyModal(modal).queue(); + }); - event.replyModal(modal).queue(); } case "statisticsSetupInstagram" -> { - TextInput input = TextInput.create("instagramName", LanguageService.getByGuild(event.getGuild(), "label.name"), TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Instagram name here!").build(); + LanguageService.getByGuild(event.getGuild(), "label.name").thenAccept(label -> { + TextInput input = TextInput.create("instagramName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Instagram name here!").build(); + + Modal modal = Modal.create("statisticsSetupInstagramModal", LanguageService.getByGuild(event.getGuild(), "label.setupInstagramStatistics").join()).addActionRow(input).build(); - Modal modal = Modal.create("statisticsSetupInstagramModal", LanguageService.getByGuild(event.getGuild(), "label.setupInstagramStatistics")).addActionRow(input).build(); + event.replyModal(modal).queue(); + }); - event.replyModal(modal).queue(); } default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").thenAccept(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } } @@ -1197,28 +1227,31 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); case "ticketsSetup" -> { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.setupDescription")); - - event.editMessageEmbeds(embedBuilder.build()).setComponents().queue(); + LanguageService.getByGuild(event.getGuild(), "message.ticket.setupDescription").thenAccept(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).setComponents().queue(); + }); } case "ticketsDelete" -> { - Tickets tickets = SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - - if (tickets != null) { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.deleted")); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(tickets); - } + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(tickets -> { + if (tickets != null) { + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.deleted").join()); + embedBuilder.setColor(Color.GREEN); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(tickets); + } + }); } default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").thenAccept(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } } @@ -1233,28 +1266,34 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); if (value.equalsIgnoreCase("more")) { - java.util.List optionList = new ArrayList<>(); + LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupDescription").thenAccept(description -> { + java.util.List optionList = new ArrayList<>(); - for (VoiceChannel channel : event.getGuild().getVoiceChannels().stream().skip(24).toList()) { - optionList.add(SelectOption.of(channel.getName(), channel.getId())); - } + for (VoiceChannel channel : event.getGuild().getVoiceChannels().stream().skip(24).toList()) { + optionList.add(SelectOption.of(channel.getName(), channel.getId())); + } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupDescription")); + embedBuilder.setDescription(description); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoicechannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel"), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoicechannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").join(), 1, 1, false, optionList)).queue(); + }); return; } VoiceChannel voiceChannel = event.getGuild().getVoiceChannelById(value); if (voiceChannel != null) { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new TemporalVoicechannel(event.getGuild().getIdLong(), voiceChannel.getIdLong())); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupSuccess")); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupSuccess").thenAccept(description -> { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new TemporalVoicechannel(event.getGuild().getIdLong(), voiceChannel.getIdLong())).join(); + embedBuilder.setDescription(description); + embedBuilder.setColor(Color.GREEN); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); } else { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel").thenAccept(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } @@ -1273,37 +1312,41 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); case "tempVoiceSetup" -> { - for (VoiceChannel channel : event.getGuild().getVoiceChannels()) { - if (optionList.size() == 24) { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.more"), "more")); - break; - } + LanguageService.getByGuild(event.getGuild(), "label.more").thenAccept(labelMore -> { + for (VoiceChannel channel : event.getGuild().getVoiceChannels()) { + if (optionList.size() == 24) { + optionList.add(SelectOption.of(labelMore, "more")); + break; + } - optionList.add(SelectOption.of(channel.getName(), channel.getId())); - } + optionList.add(SelectOption.of(channel.getName(), channel.getId())); + } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupDescription")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupDescription").join()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoicechannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel"), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoicechannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").join(), 1, 1, false, optionList)).queue(); + }); } case "tempVoiceDelete" -> { - TemporalVoicechannel temporalVoicechannel = SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())); - - if (temporalVoicechannel != null) { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.deleted")); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel); - } + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(temporalVoicechannel -> { + if (temporalVoicechannel != null) { + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.deleted").join()); + embedBuilder.setColor(Color.GREEN); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel); + } + }); } default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").thenAccept(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } } @@ -1319,13 +1362,17 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even if (selectedLocale != DiscordLocale.UNKNOWN && LanguageService.getSupported().contains(selectedLocale)) { Language language = LanguageService.languageResources.get(selectedLocale); - SQLSession.getSqlConnector().getSqlWorker().setSetting(event.getGuild().getIdLong(), "configuration_language", "Language", selectedLocale.getLocale()); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.lang.setupSuccess", language.getName() + " by " + language.getAuthor())); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.lang.setupSuccess", language.getName() + " by " + language.getAuthor()).thenAccept(description -> { + SQLSession.getSqlConnector().getSqlWorker().setSetting(event.getGuild().getIdLong(), "configuration_language", "Language", selectedLocale.getLocale()); + embedBuilder.setDescription(description); + embedBuilder.setColor(Color.GREEN); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + }); } else { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").thenAccept(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } @@ -1344,40 +1391,44 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); case "logSetup" -> { - for (TextChannel channel : event.getGuild().getTextChannels()) { - if (optionList.size() == 24) { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.more"), "more")); - break; - } + LanguageService.getByGuild(event.getGuild(), "label.more").thenAccept(labelMore -> { + for (TextChannel channel : event.getGuild().getTextChannels()) { + if (optionList.size() == 24) { + optionList.add(SelectOption.of(labelMore, "more")); + break; + } - optionList.add(SelectOption.of(channel.getName(), channel.getId())); - } + optionList.add(SelectOption.of(channel.getName(), channel.getId())); + } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupDescription")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupDescription").join()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel"), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").join(), 1, 1, false, optionList)).queue(); + }); } case "logDelete" -> { - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()); - - if (webhook != null) { - event.getJDA().retrieveWebhookById(webhook.getChannelId()).queue(webhook1 -> { - webhook1.delete().queue(); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.deleted")); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhook); - }); - } + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + if (webhook != null) { + event.getJDA().retrieveWebhookById(webhook.getChannelId()).queue(webhook1 -> { + webhook1.delete().queue(); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.deleted").join()); + embedBuilder.setColor(Color.GREEN); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhook); + }); + } + }); } default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").thenAccept(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } } @@ -1393,20 +1444,22 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); if (value.equals("more")) { - java.util.List optionList = new ArrayList<>(); + LanguageService.getByGuild(event.getGuild(), "label.more").thenAccept(labelMore -> { + java.util.List optionList = new ArrayList<>(); - for (TextChannel channel : event.getGuild().getTextChannels().stream().skip(24).toList()) { - if (optionList.size() == 24) { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.more"), "more")); - break; - } + for (TextChannel channel : event.getGuild().getTextChannels().stream().skip(24).toList()) { + if (optionList.size() == 24) { + optionList.add(SelectOption.of(labelMore, "more")); + break; + } - optionList.add(SelectOption.of(channel.getName(), channel.getId())); - } + optionList.add(SelectOption.of(channel.getName(), channel.getId())); + } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupDescription")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupDescription").join()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel"), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").join(), 1, 1, false, optionList)).queue(); + }); return; } @@ -1415,17 +1468,17 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even if (textChannel != null) { textChannel.createWebhook(BotConfig.getBotName() + "-Logs").queue(webhook -> { - if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong())) { - WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong())); + if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).join()) { + WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).join()); } SQLSession.getSqlConnector().getSqlWorker().setLogWebhook(event.getGuild().getIdLong(), textChannel.getIdLong(), webhook.getIdLong(), webhook.getToken()); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupSuccess")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupSuccess").join()); embedBuilder.setColor(Color.GREEN); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } else { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel").join()); event.editMessageEmbeds(embedBuilder.build()).queue(); } @@ -1446,45 +1499,51 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); case "welcomeSetup" -> { - for (TextChannel channel : event.getGuild().getTextChannels()) { - if (optionList.size() == 24) { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.more"), "more")); - break; - } + LanguageService.getByGuild(event.getGuild(), "label.more").thenAccept(moreLabel -> { + for (TextChannel channel : event.getGuild().getTextChannels()) { + if (optionList.size() == 24) { + optionList.add(SelectOption.of(moreLabel, "more")); + break; + } - optionList.add(SelectOption.of(channel.getName(), channel.getId())); - } + optionList.add(SelectOption.of(channel.getName(), channel.getId())); + } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupDescription")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupDescription").join()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel"), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").join(), 1, 1, false, optionList)).queue(); + }); } case "welcomeImage" -> { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.imageRequired")); - event.editMessageEmbeds(embedBuilder.build()).setComponents().queue(); + LanguageService.getByGuild(event.getGuild(), "message.welcome.imageRequired").thenAccept(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).setComponents().queue(); + }); } case "welcomeDelete" -> { - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()); - - if (webhook != null) { - event.getJDA().retrieveWebhookById(webhook.getChannelId()).queue(webhook1 -> { - webhook1.delete().queue(); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.deleted")); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhook); - }); - } + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + if (webhook != null) { + event.getJDA().retrieveWebhookById(webhook.getChannelId()).queue(webhook1 -> { + webhook1.delete().queue(); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.deleted").join()); + embedBuilder.setColor(Color.GREEN); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhook); + }); + } + }); } default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").thenAccept(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } } @@ -1500,20 +1559,22 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even String value = event.getInteraction().getValues().get(0); if (value.equals("more")) { - java.util.List optionList = new ArrayList<>(); + LanguageService.getByGuild(event.getGuild(), "label.more").thenAccept(labelMore -> { + java.util.List optionList = new ArrayList<>(); - for (TextChannel channel : event.getGuild().getTextChannels().stream().skip(24).toList()) { - if (optionList.size() == 24) { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.more"), "more")); - break; - } + for (TextChannel channel : event.getGuild().getTextChannels().stream().skip(24).toList()) { + if (optionList.size() == 24) { + optionList.add(SelectOption.of(labelMore, "more")); + break; + } - optionList.add(SelectOption.of(channel.getName(), channel.getId())); - } + optionList.add(SelectOption.of(channel.getName(), channel.getId())); + } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupDescription")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupDescription").join()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel"), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").join(), 1, 1, false, optionList)).queue(); + }); return; } @@ -1521,18 +1582,21 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even if (textChannel != null) { textChannel.createWebhook(BotConfig.getBotName() + "-Welcome").queue(webhook -> { - if (SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong())) { - WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong())); + // .join() can be called here because its being queued. + if (SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong()).join()) { + WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).join()); } SQLSession.getSqlConnector().getSqlWorker().setWelcomeWebhook(event.getGuild().getIdLong(), textChannel.getIdLong(), webhook.getIdLong(), webhook.getToken()); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupSuccess")); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupSuccess").join()); embedBuilder.setColor(Color.GREEN); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } else { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel")); - event.editMessageEmbeds(embedBuilder.build()).queue(); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel").thenAccept(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } @@ -1540,10 +1604,13 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").thenAccept(description -> { + EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); + + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption")); - event.editMessageEmbeds(embedBuilder.build()).queue(); } } } diff --git a/src/main/java/de/presti/ree6/events/OtherEvents.java b/src/main/java/de/presti/ree6/events/OtherEvents.java index f006ebb60..417abbf74 100644 --- a/src/main/java/de/presti/ree6/events/OtherEvents.java +++ b/src/main/java/de/presti/ree6/events/OtherEvents.java @@ -573,7 +573,7 @@ public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) { } ReactionRole reactionRole = new ReactionRole(event.getGuild().getIdLong(), emojiId, emojiUnion.getFormatted(), role.getIdLong(), message.getMessageReference().getMessageIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRole); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRole).join(); if (message.getMessageReference().getMessage() != null) { message.getMessageReference().getMessage().addReaction(event.getEmoji()).queue(); @@ -608,7 +608,7 @@ public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) { } if (changes) - SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRole); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRole).join(); } }); } diff --git a/src/main/java/de/presti/ree6/main/Main.java b/src/main/java/de/presti/ree6/main/Main.java index 22bd2a6dc..497adab11 100644 --- a/src/main/java/de/presti/ree6/main/Main.java +++ b/src/main/java/de/presti/ree6/main/Main.java @@ -671,7 +671,7 @@ public void createCheckerThread() { .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); scheduledMessage.setLastExecute(Timestamp.from(Instant.now())); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage).join(); } } else { if (Timestamp.from(Instant.now()).after(Timestamp.from(scheduledMessage.getLastUpdated().toInstant().plusMillis(scheduledMessage.getDelayAmount())))) { @@ -682,7 +682,7 @@ public void createCheckerThread() { .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); scheduledMessage.setLastExecute(Timestamp.from(Instant.now())); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage).join(); } } } diff --git a/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java b/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java index dbc74fff2..85185b25e 100644 --- a/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java +++ b/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java @@ -82,7 +82,7 @@ public void add(InviteContainer inviteContainer) { getList().add(inviteContainer); try { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new de.presti.ree6.sql.entities.Invite(inviteContainer.getGuildId(), inviteContainer.getCreatorId(), inviteContainer.getUses(), inviteContainer.getCode())); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new de.presti.ree6.sql.entities.Invite(inviteContainer.getGuildId(), inviteContainer.getCreatorId(), inviteContainer.getUses(), inviteContainer.getCode())).join(); } catch (Exception ex) { log.error("[InviteManager] Error while Saving Invites: " + ex.getMessage()); } diff --git a/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java b/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java index ffbe6e58f..09b62386a 100644 --- a/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java +++ b/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java @@ -134,7 +134,7 @@ public static boolean set(MoneyHolder holder, double amount, boolean setBank) { holder.setAmount(amount); } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(holder); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(holder).join(); return true; } @@ -160,7 +160,7 @@ public static boolean pay(MoneyHolder sender, MoneyHolder receiver, double amoun receiver.setAmount(receiver.getAmount() + amount); } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(receiver); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(receiver).join(); if (!isSystem) { if (fromBank) { @@ -169,10 +169,10 @@ public static boolean pay(MoneyHolder sender, MoneyHolder receiver, double amoun sender.setAmount(sender.getAmount() - amount); } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(sender); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(sender).join(); } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new MoneyTransaction(0L, isSystem, isSystem ? receiver.getGuildUserId().getGuildId() : sender.getGuildUserId().getGuildId(), isSystem && sender == null ? receiver : sender, receiver, toBank, fromBank, amount, Timestamp.from(Instant.now()))); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new MoneyTransaction(0L, isSystem, isSystem ? receiver.getGuildUserId().getGuildId() : sender.getGuildUserId().getGuildId(), isSystem && sender == null ? receiver : sender, receiver, toBank, fromBank, amount, Timestamp.from(Instant.now()))).join(); return true; } From c22e9fe9e3abe3c0089a6e5c2cae4a737f375fdb Mon Sep 17 00:00:00 2001 From: Presti Date: Tue, 11 Jun 2024 14:50:43 +0200 Subject: [PATCH 20/94] Use the reactor version. --- pom.xml | 2 +- .../CustomEventContainerCreator.java | 10 +- .../StreamActionContainerCreator.java | 5 +- .../ree6/audio/AudioPlayerReceiveHandler.java | 63 ++- .../presti/ree6/audio/music/MusicWorker.java | 40 +- .../ree6/audio/music/TrackScheduler.java | 40 +- .../java/de/presti/ree6/bot/BotWorker.java | 3 + .../de/presti/ree6/bot/util/WebhookUtil.java | 18 +- .../de/presti/ree6/commands/CommandEvent.java | 2 +- .../presti/ree6/commands/CommandManager.java | 83 ++-- .../commands/impl/community/Giveaway.java | 2 +- .../commands/impl/community/Notifier.java | 14 +- .../commands/impl/community/Reactions.java | 4 +- .../commands/impl/community/Schedule.java | 15 +- .../impl/community/StreamActionCommand.java | 53 +-- .../ree6/commands/impl/community/Ticket.java | 10 +- .../ree6/commands/impl/economy/Money.java | 24 +- .../ree6/commands/impl/economy/Steal.java | 6 +- .../ree6/commands/impl/economy/Work.java | 8 +- .../presti/ree6/commands/impl/fun/Slap.java | 3 +- .../presti/ree6/commands/impl/info/Help.java | 4 +- .../ree6/commands/impl/info/Infractions.java | 2 +- .../ree6/commands/impl/info/Optout.java | 2 +- .../presti/ree6/commands/impl/info/Stats.java | 4 +- .../ree6/commands/impl/level/Level.java | 2 +- .../ree6/commands/impl/level/LevelRole.java | 4 +- .../ree6/commands/impl/mod/Blacklist.java | 8 +- .../presti/ree6/commands/impl/mod/Import.java | 8 +- .../presti/ree6/commands/impl/mod/News.java | 4 +- .../presti/ree6/commands/impl/mod/Setup.java | 33 +- .../ree6/commands/impl/mod/Suggestion.java | 8 +- .../presti/ree6/commands/impl/mod/Warn.java | 22 +- .../ree6/commands/interfaces/ICommand.java | 2 +- .../de/presti/ree6/events/CustomEvents.java | 2 +- .../de/presti/ree6/events/LoggingEvents.java | 252 +++++----- .../de/presti/ree6/events/MenuEvents.java | 438 +++++++++--------- .../de/presti/ree6/events/OtherEvents.java | 72 +-- .../de/presti/ree6/game/core/base/IGame.java | 2 +- .../ree6/game/impl/blackjack/Blackjack.java | 60 +-- .../ree6/game/impl/musicquiz/MusicQuiz.java | 54 +-- .../presti/ree6/language/LanguageService.java | 37 +- .../de/presti/ree6/logger/LoggerQueue.java | 20 +- src/main/java/de/presti/ree6/main/Main.java | 38 +- .../ree6/module/giveaway/GiveawayManager.java | 6 +- .../module/invite/InviteContainerManager.java | 6 +- .../de/presti/ree6/utils/apis/ChatGPTAPI.java | 2 +- .../de/presti/ree6/utils/apis/Notifier.java | 58 +-- .../utils/data/DatabaseStorageBackend.java | 10 +- .../presti/ree6/utils/data/EconomyUtil.java | 25 +- .../presti/ree6/utils/others/GuildUtil.java | 36 +- .../ree6/utils/others/ModerationUtil.java | 18 +- 51 files changed, 828 insertions(+), 816 deletions(-) diff --git a/pom.xml b/pom.xml index 9744ff19a..a6a4853f2 100644 --- a/pom.xml +++ b/pom.xml @@ -177,7 +177,7 @@ de.ree6 Ree6-SQL - 8d0581e75e + 68d594a700 diff --git a/src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainerCreator.java b/src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainerCreator.java index 5bfc1ac6b..d38e84a19 100644 --- a/src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainerCreator.java +++ b/src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainerCreator.java @@ -8,12 +8,12 @@ import org.reflections.Reflections; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; +import reactor.core.publisher.Mono; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.concurrent.CompletableFuture; /** * A Utility class used to create CustomEventContainers. @@ -73,10 +73,10 @@ public static Class getAction(String action) { * @param typ The typ of the CustomEventAction. * @return A List of CustomEventContainer. */ - public static CompletableFuture> getContainers(CustomEventTyp typ) { + public static Mono> getContainers(CustomEventTyp typ) { return SQLSession.getSqlConnector().getSqlWorker() .getEntityList(new CustomEventAction(), "FROM CustomEventAction WHERE event = :typ", Map.of("typ", typ.name())) - .thenApply(list -> list.stream().map(CustomEventContainer::new).toList()); + .map(list -> list.stream().map(CustomEventContainer::new).toList()); } /** @@ -86,10 +86,10 @@ public static CompletableFuture> getContainers(Custom * @param typ The typ of the CustomEventAction. * @return A List of CustomEventContainer. */ - public static CompletableFuture> getContainers(String guildId, CustomEventTyp typ) { + public static Mono> getContainers(String guildId, CustomEventTyp typ) { return SQLSession.getSqlConnector().getSqlWorker() .getEntityList(new CustomEventAction(), "FROM CustomEventAction WHERE guildId = :guild AND event = :typ", Map.of("guild", guildId, "typ", typ.name())) - .thenApply(list -> list.stream().map(CustomEventContainer::new).toList()); + .map(list -> list.stream().map(CustomEventContainer::new).toList()); } } diff --git a/src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainerCreator.java b/src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainerCreator.java index 1c7734c8e..10af29a83 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainerCreator.java +++ b/src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainerCreator.java @@ -8,6 +8,7 @@ import org.reflections.Reflections; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; +import reactor.core.publisher.Mono; import java.util.HashMap; import java.util.List; @@ -78,10 +79,10 @@ public static Class getAction(String action) { * @param listenerId The Listener to get the Containers for. * @return A List of StreamActionContainers. */ - public static CompletableFuture> getContainers(int listenerId) { + public static Mono> getContainers(int listenerId) { return SQLSession.getSqlConnector().getSqlWorker() .getEntityList(new StreamAction(), "FROM StreamAction WHERE listener = :listener", Map.of("listener", listenerId)) - .thenApply(list -> list.stream().map(StreamActionContainer::new).toList()); + .map(list -> list.stream().map(StreamActionContainer::new).toList()); } } diff --git a/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java b/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java index 52fe5c15d..830d2dafe 100644 --- a/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java +++ b/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java @@ -81,8 +81,8 @@ public AudioPlayerReceiveHandler(Member member, AudioChannelUnion audioChannelUn this.creatorId = member.getIdLong(); this.audioChannelUnion = audioChannelUnion; if (audioChannelUnion.getGuild().getSelfMember().hasPermission(Permission.NICKNAME_CHANGE)) { - LanguageService.getByGuild(member.getGuild(), "label.recording.name").thenAccept(name -> - LanguageService.getByGuild(member.getGuild(), "message.recording.startReason", member.getUser().getName()).thenAccept(reason -> + LanguageService.getByGuild(member.getGuild(), "label.recording.name").subscribe(name -> + LanguageService.getByGuild(member.getGuild(), "message.recording.startReason", member.getUser().getName()).subscribe(reason -> audioChannelUnion.getGuild().getSelfMember().modifyNickname(name).reason(reason).onErrorMap(throwable -> { boolean canTalk = audioChannelUnion.getType() == ChannelType.STAGE ? @@ -90,7 +90,7 @@ public AudioPlayerReceiveHandler(Member member, AudioChannelUnion audioChannelUn audioChannelUnion.asVoiceChannel().canTalk(); if (canTalk) { - LanguageService.getByGuild(member.getGuild(), "message.default.nameChangeFailed").thenAccept(message -> { + LanguageService.getByGuild(member.getGuild(), "message.default.nameChangeFailed").subscribe(message -> { audioChannelUnion.asGuildMessageChannel().sendMessage(message).queue(); }); } @@ -99,15 +99,16 @@ public AudioPlayerReceiveHandler(Member member, AudioChannelUnion audioChannelUn } message = audioChannelUnion.asGuildMessageChannel().sendMessageEmbeds(new EmbedBuilder() - .setDescription(LanguageService.getByGuild(member.getGuild(), "message.recording.started").join()) + .setDescription(LanguageService.getByGuild(member.getGuild(), "message.recording.started").block()) .setColor(Color.YELLOW) - .setFooter(LanguageService.getByGuild(member.getGuild(), "label.footerMessage", member.getEffectiveName(), BotConfig.getAdvertisement()).join(), member.getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(member.getGuild(), "label.recording.start").join()) + .setFooter(LanguageService.getByGuild(member.getGuild(), "label.footerMessage", member.getEffectiveName(), BotConfig.getAdvertisement()).block(), member.getEffectiveAvatarUrl()) + .setTitle(LanguageService.getByGuild(member.getGuild(), "label.recording.start").block()) .build()).complete(); if (audioChannelUnion.getGuild().getSelfMember().hasPermission(Permission.VOICE_SET_STATUS)) { if (audioChannelUnion.getType() == ChannelType.VOICE) { - audioChannelUnion.asVoiceChannel().modifyStatus(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.recording.name").join()).queue(); + LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.recording.name").subscribe(name -> + audioChannelUnion.asVoiceChannel().modifyStatus(name).queue()); } } } @@ -173,12 +174,12 @@ public void endReceiving() { audioChannelUnion.asVoiceChannel().canTalk(); if (audioChannelUnion.getGuild().getSelfMember().hasPermission(Permission.NICKNAME_CHANGE)) { - LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.stopReason").thenAccept(reason -> + LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.stopReason").subscribe(reason -> audioChannelUnion.getGuild().getSelfMember().modifyNickname(audioChannelUnion.getGuild().getSelfMember().getUser().getName()).reason(reason).onErrorMap(throwable -> { if (canTalk) LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.default.nameChangeFailed") - .thenAccept(message -> audioChannelUnion.asGuildMessageChannel().sendMessage(message).queue()); + .subscribe(message -> audioChannelUnion.asGuildMessageChannel().sendMessage(message).queue()); return null; }).queue()); } @@ -193,40 +194,32 @@ public void endReceiving() { Recording recording = new Recording(audioChannelUnion.getGuild().getIdLong(), audioChannelUnion.getIdLong(), creatorId, AudioUtil.convertPCMtoWAV(byteBuffer), JsonParser.parseString(new Gson().toJson(participants)).getAsJsonArray()); - boolean failedToUpload = false; - - try { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(recording).join(); - } catch (Exception ignore) { - failedToUpload = true; - } - - if (canTalk) { - message.editMessageEmbeds(new EmbedBuilder() - .setDescription(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.stopped").join()) - .setColor(Color.GREEN) - .setFooter(BotConfig.getAdvertisement(), audioChannelUnion.getGuild().getIconUrl()) - .setTitle(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.recording.finished").join()) - .build()) - .setActionRow( - new ButtonImpl("ree6RedirectButton", LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.download").join(), ButtonStyle.LINK, - BotConfig.getRecordingUrl() + "?id=" + recording.getIdentifier(), failedToUpload, Emoji.fromCustom("shiba", 941219375535509504L, true)), - Button.primary("r_recordingDownload:" + recording.getIdentifier(), Emoji.fromCustom("sip", 1011956355810209852L, false)) - .withLabel(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.sendToChat").join()).withDisabled(!BotConfig.allowRecordingInChat() || failedToUpload)).complete(); - - if (failedToUpload) { - audioChannelUnion.asGuildMessageChannel().sendMessage(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.error", "Upload failed").join()).setFiles(FileUpload.fromData(recording.getRecording(), "recording.wav")); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(recording).doOnError(x -> { + audioChannelUnion.asGuildMessageChannel().sendMessage(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.error", "Upload failed").block()).setFiles(FileUpload.fromData(recording.getRecording(), "recording.wav")); + }).subscribe(newRecording -> { + if (canTalk) { + message.editMessageEmbeds(new EmbedBuilder() + .setDescription(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.stopped").block()) + .setColor(Color.GREEN) + .setFooter(BotConfig.getAdvertisement(), audioChannelUnion.getGuild().getIconUrl()) + .setTitle(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.recording.finished").block()) + .build()) + .setActionRow( + new ButtonImpl("ree6RedirectButton", LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.download").block(), ButtonStyle.LINK, + BotConfig.getRecordingUrl() + "?id=" + recording.getIdentifier(), true, Emoji.fromCustom("shiba", 941219375535509504L, true)), + Button.primary("r_recordingDownload:" + recording.getIdentifier(), Emoji.fromCustom("sip", 1011956355810209852L, false)) + .withLabel(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.sendToChat").block()).withDisabled(!BotConfig.allowRecordingInChat())).complete(); } - } + }); // Find a way to still notify that the bot couldn't send the audio. } catch (Exception ex) { if (canTalk) { message.editMessageEmbeds(new EmbedBuilder() - .setDescription(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.error", ex.getMessage()).join()) + .setDescription(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.error", ex.getMessage()).block()) .setColor(Color.RED) .setFooter(BotConfig.getAdvertisement(), audioChannelUnion.getGuild().getIconUrl()) - .setTitle(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.error").join()) + .setTitle(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.error").block()) .build()).complete(); } diff --git a/src/main/java/de/presti/ree6/audio/music/MusicWorker.java b/src/main/java/de/presti/ree6/audio/music/MusicWorker.java index dd7f3c8f4..482901451 100644 --- a/src/main/java/de/presti/ree6/audio/music/MusicWorker.java +++ b/src/main/java/de/presti/ree6/audio/music/MusicWorker.java @@ -186,10 +186,10 @@ public void loadAndPlay(final Guild guild, GuildMessageChannelUnion channel, Aud Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guild, "message.music.notPlaying").join()) + .setDescription(LanguageService.getByGuild(guild, "message.music.notPlaying").block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()) , channel, interactionHook); return; @@ -210,10 +210,10 @@ public void trackLoaded(AudioTrack track) { if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").block()) .setImage((track.getInfo().artworkUrl != null && track.getInfo().artworkUrl.isBlank()) ? guild.getJDA().getSelfUser().getEffectiveAvatarUrl() : track.getInfo().artworkUrl) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guild, "message.music.queueAdded.default", FormatUtil.filter(track.getInfo().title)).join()) + .setDescription(LanguageService.getByGuild(guild, "message.music.queueAdded.default", FormatUtil.filter(track.getInfo().title)).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()), 5, messageChannel, interactionHook); play(finalAudioChannel, musicManager, track, force); @@ -235,10 +235,10 @@ public void playlistLoaded(AudioPlaylist playlist) { if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guild, "message.music.queueAdded.firstOfList", FormatUtil.filter(firstTrack.getInfo().title), FormatUtil.filter(playlist.getName())).join()) + .setDescription(LanguageService.getByGuild(guild, "message.music.queueAdded.firstOfList", FormatUtil.filter(firstTrack.getInfo().title), FormatUtil.filter(playlist.getName())).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()), 5, messageChannel, interactionHook); play(finalAudioChannel, musicManager, firstTrack, force); @@ -260,10 +260,10 @@ public void noMatches() { if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guild, "message.music.searchUrlFailed", FormatUtil.filter(trackUrl)).join()) + .setDescription(LanguageService.getByGuild(guild, "message.music.searchUrlFailed", FormatUtil.filter(trackUrl)).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()), 5, messageChannel, interactionHook); } @@ -277,10 +277,10 @@ public void loadFailed(FriendlyException exception) { if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guild, "message.music.failedLoading", exception.getMessage()).join()) + .setDescription(LanguageService.getByGuild(guild, "message.music.failedLoading", exception.getMessage()).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()), 5, messageChannel, interactionHook); } }); @@ -370,10 +370,10 @@ public void playSong(String value, Guild guild, Member member, GuildMessageChann EmbedBuilder em = new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFound", value).join()) + .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFound", value).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, 5, channel, interactionHook); return; @@ -407,10 +407,10 @@ public void playSong(String value, Guild guild, Member member, GuildMessageChann EmbedBuilder em = new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFoundMultiple", loadFailed.size()).join()) + .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFoundMultiple", loadFailed.size()).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, 5, channel, interactionHook); } @@ -423,10 +423,10 @@ public void playSong(String value, Guild guild, Member member, GuildMessageChann } catch (Exception exception) { EmbedBuilder em = new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.searchFailed").join()) + .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.searchFailed").block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, 5, channel, interactionHook); log.error("Error while searching for " + value + " on YouTube", exception); @@ -436,10 +436,10 @@ public void playSong(String value, Guild guild, Member member, GuildMessageChann if (ytResult == null) { EmbedBuilder em = new EmbedBuilder() .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.YELLOW) - .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFound", FormatUtil.filter(value)).join()) + .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFound", FormatUtil.filter(value)).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, 5, channel, interactionHook); } else { @@ -470,10 +470,10 @@ public void skipTrack(GuildMessageChannelUnion channel, InteractionHook interact public void skipTrack(GuildMessageChannelUnion channel, InteractionHook interactionHook, int skipAmount, boolean silent) { if (!silent) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder().setAuthor(channel.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), channel.getJDA().getSelfUser().getAvatarUrl()) - .setTitle(LanguageService.getByGuild(channel.getGuild(), "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(channel.getGuild(), "label.musicPlayer").block()) .setThumbnail(channel.getJDA().getSelfUser().getAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(channel.getGuild(), "message.music.skip").join()) + .setDescription(LanguageService.getByGuild(channel.getGuild(), "message.music.skip").block()) .setFooter(channel.getGuild().getName() + " - " + BotConfig.getAdvertisement(), channel.getGuild().getIconUrl()), 5, channel, interactionHook); } diff --git a/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java b/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java index 6426fefbc..cd7e72d3a 100644 --- a/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java +++ b/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java @@ -178,10 +178,10 @@ public void nextTrack(GuildMessageChannelUnion textChannel, int position, boolea if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.songNext", FormatUtil.filter(track.getInfo().title)).join()) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.songNext", FormatUtil.filter(track.getInfo().title)).block()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); Main.getInstance().getEventBus().post(new MusicPlayerStateChangeEvent(guildMusicManager.getGuild(), MusicPlayerStateChangeEvent.State.PLAYING, track)); @@ -190,10 +190,10 @@ public void nextTrack(GuildMessageChannelUnion textChannel, int position, boolea if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.songQueueReachedEnd").join()) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.songQueueReachedEnd").block()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); Main.getInstance().getEventBus().post(new MusicPlayerStateChangeEvent(guildMusicManager.getGuild(), MusicPlayerStateChangeEvent.State.QUEUE_EMPTY, null)); @@ -210,10 +210,10 @@ public void seekPosition(GuildMessageChannelUnion channel, int seekAmountInSecon if (player.getPlayingTrack() == null) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.notPlaying").join()) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.notPlaying").block()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); return; } @@ -221,10 +221,10 @@ public void seekPosition(GuildMessageChannelUnion channel, int seekAmountInSecon if (player.getPlayingTrack().getPosition() / 1000 + seekAmountInSeconds > player.getPlayingTrack().getDuration() / 1000) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.seek.failed").join()) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.seek.failed").block()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); return; } @@ -238,10 +238,10 @@ public void seekPosition(GuildMessageChannelUnion channel, int seekAmountInSecon Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.seek.success", FormatUtil.formatTime(player.getPlayingTrack().getPosition())).join()) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.seek.success", FormatUtil.formatTime(player.getPlayingTrack().getPosition())).block()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); } @@ -277,10 +277,10 @@ public void onTrackEnd(IPlayer player, AudioTrack track, AudioTrackEndReason end if (getChannel() != null) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), "Track does not exist (Internally?)").join()) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), "Track does not exist (Internally?)").block()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); } @@ -293,10 +293,10 @@ public void onTrackEnd(IPlayer player, AudioTrack track, AudioTrackEndReason end if (getChannel() != null) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), endReason.name()).join()) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), endReason.name()).block()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); } @@ -314,10 +314,10 @@ public void onTrackEnd(IPlayer player, AudioTrack track, AudioTrackEndReason end Main.getInstance().getEventBus().post(new MusicPlayerStateChangeEvent(guildMusicManager.getGuild(), MusicPlayerStateChangeEvent.State.ERROR, null)); Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), endReason.name()).join()) + .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.failedPlaying", FormatUtil.filter(track.getInfo().title), endReason.name()).block()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); } nextTrack(getChannel(), track.getSourceManager() instanceof LocalAudioSourceManager); @@ -342,16 +342,16 @@ public void stopAll(InteractionHook interactionHook) { Main.getInstance().getMusicWorker().disconnect(guildMusicManager.getGuild()); em.setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()); - em.setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()); + em.setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()); em.setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()); em.setColor(Color.GREEN); - em.setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.stop").join()); + em.setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.stop").block()); } else { em.setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()); - em.setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").join()); + em.setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()); em.setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()); em.setColor(Color.RED); - em.setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.notPlaying").join()); + em.setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.notPlaying").block()); } em.setFooter(BotConfig.getAdvertisement()); diff --git a/src/main/java/de/presti/ree6/bot/BotWorker.java b/src/main/java/de/presti/ree6/bot/BotWorker.java index 0d0b919ba..bc9150527 100644 --- a/src/main/java/de/presti/ree6/bot/BotWorker.java +++ b/src/main/java/de/presti/ree6/bot/BotWorker.java @@ -278,6 +278,9 @@ public static String getBranch() { * @return the repository. */ public static String getRepository() { + if (gitRepository == null) { + gitRepository = "https://github.com/Ree6-Applications/Ree6"; + } return gitRepository; } diff --git a/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java b/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java index 68528da2b..3b291fe85 100644 --- a/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java +++ b/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java @@ -91,7 +91,7 @@ public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, // Check if the given data is in the Database. if (isLog) { - SQLSession.getSqlConnector().getSqlWorker().existsLogData(webhookId, webhookToken).thenAccept(x -> { + SQLSession.getSqlConnector().getSqlWorker().existsLogData(webhookId, webhookToken).subscribe(x -> { if (!x) { // If not, inform about invalid send. log.error("[Webhook] Invalid Webhook: {} - {}", webhookId, webhookToken); @@ -127,49 +127,49 @@ private static void sendWebhookMessage(LogMessage loggerMessage, WebhookMessage } else { // TODO:: this has become worst so please for the love of god find a better solution brain. SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookWelcome(), "FROM WebhookWelcome WHERE webhookId = :cid AND token = :token", - Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).thenAccept(welcome -> { + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(welcome -> { if (welcome != null) { SQLSession.getSqlConnector().getSqlWorker().deleteEntity(welcome); log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookYouTube(), "FROM WebhookYouTube WHERE webhookId = :cid AND token = :token", - Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).thenAccept(webhookYouTube -> { + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookYouTube -> { if (webhookYouTube != null) { SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookYouTube); log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTwitter(), "FROM WebhookTwitter WHERE webhookId = :cid AND token = :token", - Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).thenAccept(webhookTwitter -> { + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookTwitter -> { if (webhookTwitter != null) { SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTwitter); log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTwitch(), "FROM WebhookTwitch WHERE webhookId = :cid AND token = :token", - Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).thenAccept(webhookTwitch -> { + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookTwitch -> { if (webhookTwitch != null) { SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTwitch); log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookReddit(), "FROM WebhookReddit WHERE webhookId = :cid AND token = :token", - Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).thenAccept(webhookReddit -> { + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookReddit -> { if (webhookReddit != null) { SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookReddit); log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookInstagram(), "FROM WebhookInstagram WHERE webhookId = :cid AND token = :token", - Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).thenAccept(webhookInstagram -> { + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookInstagram -> { if (webhookInstagram != null) { SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookInstagram); log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTikTok(), "FROM WebhookTikTok WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).thenAccept(webhookTikTok -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTikTok(), "FROM WebhookTikTok WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookTikTok -> { if (webhookTikTok != null) { log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new RSSFeed(), "FROM WebhookTikTok WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).thenAccept(rssFeed -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new RSSFeed(), "FROM WebhookTikTok WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(rssFeed -> { if (rssFeed != null) { log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { diff --git a/src/main/java/de/presti/ree6/commands/CommandEvent.java b/src/main/java/de/presti/ree6/commands/CommandEvent.java index d5acd0ae6..5eedfb857 100644 --- a/src/main/java/de/presti/ree6/commands/CommandEvent.java +++ b/src/main/java/de/presti/ree6/commands/CommandEvent.java @@ -183,7 +183,7 @@ public void setEphemeral(boolean ephemeral) { * @return the Message. */ public String getResource(String key, Object... parameters) { - return LanguageService.getByEvent(this, key, parameters).join(); + return LanguageService.getByEvent(this, key, parameters).block(); } /** diff --git a/src/main/java/de/presti/ree6/commands/CommandManager.java b/src/main/java/de/presti/ree6/commands/CommandManager.java index c6c5a365c..0b8dfb1fe 100644 --- a/src/main/java/de/presti/ree6/commands/CommandManager.java +++ b/src/main/java/de/presti/ree6/commands/CommandManager.java @@ -39,6 +39,7 @@ import net.dv8tion.jda.api.utils.messages.MessageCreateData; import net.dv8tion.jda.internal.interactions.CommandDataImpl; import org.reflections.Reflections; +import reactor.core.publisher.Mono; import java.lang.reflect.InvocationTargetException; import java.time.Duration; @@ -219,10 +220,10 @@ public void addSlashCommand(JDA jda) { if (!isValidDescription) continue; - String localizedDescription = LanguageService.getByLocale(discordLocale, commandAnnotation.description()).join(); + String localizedDescription = LanguageService.getByLocale(discordLocale, commandAnnotation.description()).block(); if (localizedDescription.equals("Missing language resource!")) { - localizedDescription = LanguageService.getDefault(commandAnnotation.description()).join(); + localizedDescription = LanguageService.getDefault(commandAnnotation.description()).block(); } if (!localizedDescription.equals("Missing language resource!")) { @@ -233,7 +234,7 @@ public void addSlashCommand(JDA jda) { } if (isValidDescription) { - String localizedDescription = LanguageService.getDefault(commandAnnotation.description()).join(); + String localizedDescription = LanguageService.getDefault(commandAnnotation.description()).block(); if (!localizedDescription.equals("Missing language resource!")) { commandData1.setDescription(localizedDescription); @@ -269,10 +270,10 @@ public void translateSubgroups(SubcommandGroupData subcommandGroupData, DiscordL String groupDescription = subcommandGroupData.getDescription(); if (groupDescription.matches(RegExUtil.ALLOWED_LANGUAGE_PATHS)) { - groupDescription = LanguageService.getByLocale(locale, groupDescription).join(); + groupDescription = LanguageService.getByLocale(locale, groupDescription).block(); if (groupDescription.equals("Missing language resource!")) { - groupDescription = LanguageService.getDefault(subcommandGroupData.getDescription()).join(); + groupDescription = LanguageService.getDefault(subcommandGroupData.getDescription()).block(); } if (!groupDescription.equals("Missing language resource!")) { @@ -284,10 +285,10 @@ public void translateSubgroups(SubcommandGroupData subcommandGroupData, DiscordL String commandDescription = subcommandData.getDescription(); if (groupDescription.matches(RegExUtil.ALLOWED_LANGUAGE_PATHS)) { - commandDescription = LanguageService.getByLocale(locale, commandDescription).join(); + commandDescription = LanguageService.getByLocale(locale, commandDescription).block(); if (commandDescription.equals("Missing language resource!")) { - commandDescription = LanguageService.getDefault(subcommandData.getDescription()).join(); + commandDescription = LanguageService.getDefault(subcommandData.getDescription()).block(); } if (!commandDescription.equals("Missing language resource!")) { @@ -362,7 +363,7 @@ public void removeCommand(ICommand command) { * @param slashCommandInteractionEvent the Slash Command Event if it was a Slash Command. * @return true, if a command has been performed. */ - public CompletableFuture perform(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion messageChannel, SlashCommandInteractionEvent slashCommandInteractionEvent) { + public Mono perform(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion messageChannel, SlashCommandInteractionEvent slashCommandInteractionEvent) { boolean isSlashCommand = slashCommandInteractionEvent != null; // Check if the User is under Cooldown. @@ -370,27 +371,27 @@ public CompletableFuture perform(Member member, Guild guild, String mes // Check if it is a Slash Command or not. if (isSlashCommand) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.cooldown").join(), 5, messageChannel, slashCommandInteractionEvent.getHook().setEphemeral(true)); + sendMessage(LanguageService.getByGuild(guild, "command.perform.cooldown").block(), 5, messageChannel, slashCommandInteractionEvent.getHook().setEphemeral(true)); deleteMessage(message, slashCommandInteractionEvent.getHook().setEphemeral(true)); } else { - SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").thenAccept(setting -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").subscribe(setting -> { if (setting != null && messageContent.toLowerCase().startsWith(setting.getStringValue().toLowerCase())) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.cooldown").join(), 5, messageChannel, null); + sendMessage(LanguageService.getByGuild(guild, "command.perform.cooldown").block(), 5, messageChannel, null); deleteMessage(message, null); } }); } // Return false. - return CompletableFuture.completedFuture(false); + return Mono.just(false); } // Check if it is a Slash Command. if (isSlashCommand) { - if (!BotConfig.isModuleActive("slashcommands")) return CompletableFuture.completedFuture(false); + if (!BotConfig.isModuleActive("slashcommands")) return Mono.just(false); return performSlashCommand(messageChannel, slashCommandInteractionEvent); } else { - if (!BotConfig.isModuleActive("messagecommands")) return CompletableFuture.completedFuture(false); + if (!BotConfig.isModuleActive("messagecommands")) return Mono.just(false); return performMessageCommand(member, guild, messageContent, message, messageChannel); } } @@ -417,14 +418,14 @@ public void timeoutUser(User user) { * @param textChannel the TextChannel where the command has been performed. * @return true, if a command has been performed. */ - private CompletableFuture performMessageCommand(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion textChannel) { + private Mono performMessageCommand(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion textChannel) { // Check if the Message is null. if (message == null) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.error").join(), 5, textChannel, null); - return CompletableFuture.completedFuture(false); + sendMessage(LanguageService.getByGuild(guild, "command.perform.error").block(), 5, textChannel, null); + return Mono.just(false); } - return SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").thenApply(setting -> { + return SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").map(setting -> { String currentPrefix = setting.getStringValue().toLowerCase(); @@ -436,7 +437,7 @@ private CompletableFuture performMessageCommand(Member member, Guild gu String[] arguments = messageContent.substring(currentPrefix.length()).split("\\s+"); if (arguments.length == 0 || arguments[0].isBlank()) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.missingCommand").join(), 5, textChannel, null); + sendMessage(LanguageService.getByGuild(guild, "command.perform.missingCommand").block(), 5, textChannel, null); return false; } @@ -445,7 +446,7 @@ private CompletableFuture performMessageCommand(Member member, Guild gu // Check if there is even a Command with that name. if (command == null && BotConfig.isModuleActive("customcommands")) { - CustomCommand customCommand = SQLSession.getSqlConnector().getSqlWorker().getEntity(new CustomCommand(), "FROM CustomCommand WHERE guildId=:gid AND name=:command", Map.of("gid", guild.getIdLong(), "command", arguments[0].toLowerCase())).join(); + CustomCommand customCommand = SQLSession.getSqlConnector().getSqlWorker().getEntity(new CustomCommand(), "FROM CustomCommand WHERE guildId=:gid AND name=:command", Map.of("gid", guild.getIdLong(), "command", arguments[0].toLowerCase())).block(); if (customCommand != null) { GuildMessageChannelUnion messageChannelUnion = textChannel; @@ -465,19 +466,19 @@ private CompletableFuture performMessageCommand(Member member, Guild gu return true; } - sendMessage(LanguageService.getByGuild(guild, "command.perform.notFound").join(), 5, textChannel, null); + sendMessage(LanguageService.getByGuild(guild, "command.perform.notFound").block(), 5, textChannel, null); return false; } else if (command == null) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.notFound").join(), 5, textChannel, null); + sendMessage(LanguageService.getByGuild(guild, "command.perform.notFound").block(), 5, textChannel, null); return false; } if (command.getClass().getAnnotation(Command.class).category() != Category.HIDDEN) { - Setting blacklistSetting = SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()).join(); + Setting blacklistSetting = SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()).block(); // Check if the Command is blacklisted. if (blacklistSetting != null && !blacklistSetting.getBooleanValue()) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.blocked").join(), 5, textChannel, null); + sendMessage(LanguageService.getByGuild(guild, "command.perform.blocked").block(), 5, textChannel, null); return false; } } @@ -499,19 +500,19 @@ private CompletableFuture performMessageCommand(Member member, Guild gu * @param slashCommandInteractionEvent the Slash-Command Event. * @return true, if a command has been performed. */ - private CompletableFuture performSlashCommand(GuildMessageChannelUnion messageChannel, SlashCommandInteractionEvent slashCommandInteractionEvent) { + private Mono performSlashCommand(GuildMessageChannelUnion messageChannel, SlashCommandInteractionEvent slashCommandInteractionEvent) { //Get the Command by the Slash Command Name. ICommand command = getCommandBySlashName(slashCommandInteractionEvent.getName()); // Check if there is a command with that Name. if (command == null || slashCommandInteractionEvent.getGuild() == null || slashCommandInteractionEvent.getMember() == null) { - sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.notFound").join(), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); - return CompletableFuture.completedFuture(false); + sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.notFound").block(), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); + return Mono.just(false); } - return SQLSession.getSqlConnector().getSqlWorker().getSetting(slashCommandInteractionEvent.getGuild().getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()).thenApply(setting -> { + return SQLSession.getSqlConnector().getSqlWorker().getSetting(slashCommandInteractionEvent.getGuild().getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()).map(setting -> { if (command.getClass().getAnnotation(Command.class).category() != Category.HIDDEN && setting != null && !setting.getBooleanValue()) { - sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.blocked").join(), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); + sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.blocked").block(), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); return false; } @@ -613,45 +614,45 @@ public void sendMessage(MessageCreateData messageCreateData, int deleteSecond, M /** * Send a message to a special Message-Channel. * - * @param message the Message content as {@link CompletableFuture}. + * @param message the Message content as {@link Mono}. * @param messageChannel the Message-Channel. */ - public void sendMessage(CompletableFuture message, MessageChannel messageChannel) { - message.thenAccept(s -> sendMessage(s, messageChannel)); + public void sendMessage(Mono message, MessageChannel messageChannel) { + message.subscribe(s -> sendMessage(s, messageChannel)); } /** * Send a message to a special Message-Channel, with a deletion delay. * - * @param message the Message content as {@link CompletableFuture}. + * @param message the Message content as {@link Mono}. * @param deleteSecond the delete delay * @param messageChannel the Message-Channel. */ - public void sendMessage(CompletableFuture message, int deleteSecond, MessageChannel messageChannel) { - message.thenAccept(s -> sendMessage(s, deleteSecond, messageChannel)); + public void sendMessage(Mono message, int deleteSecond, MessageChannel messageChannel) { + message.subscribe(s -> sendMessage(s, deleteSecond, messageChannel)); } /** * Send a message to a special Message-Channel. * - * @param message the Message content as {@link CompletableFuture}. + * @param message the Message content as {@link Mono}. * @param messageChannel the Message-Channel. * @param interactionHook the Interaction-hook if it is a slash command. */ - public void sendMessage(CompletableFuture message, MessageChannel messageChannel, InteractionHook interactionHook) { - message.thenAccept(s -> sendMessage(s, messageChannel, interactionHook)); + public void sendMessage(Mono message, MessageChannel messageChannel, InteractionHook interactionHook) { + message.subscribe(s -> sendMessage(s, messageChannel, interactionHook)); } /** * Send a message to a special Message-Channel, with a deletion delay. * - * @param messageContent the Message content as {@link CompletableFuture}. + * @param messageContent the Message content as {@link Mono}. * @param messageChannel the Message-Channel. * @param interactionHook the Interaction-hook if it is a slash command. * @param deleteSecond the delete delay */ - public void sendMessage(CompletableFuture messageContent, int deleteSecond, MessageChannel messageChannel, InteractionHook interactionHook) { - messageContent.thenAccept(s -> sendMessage(s, deleteSecond, messageChannel, interactionHook)); + public void sendMessage(Mono messageContent, int deleteSecond, MessageChannel messageChannel, InteractionHook interactionHook) { + messageContent.subscribe(s -> sendMessage(s, deleteSecond, messageChannel, interactionHook)); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java b/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java index 6873b7ec4..79fc9e2b8 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java @@ -97,7 +97,7 @@ public void onPerform(CommandEvent commandEvent) { new de.presti.ree6.sql.entities.Giveaway(message.getIdLong(), commandEvent.getMember().getIdLong(), commandEvent.getGuild().getIdLong(), commandEvent.getChannel().getIdLong(), prize, winners, endTime); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(giveaway).thenAccept(giveaway1 -> { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(giveaway).subscribe(giveaway1 -> { if (giveaway1 == null) { commandEvent.reply(commandEvent.getResource("message.default.internalError")); return; diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java b/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java index e01adb97a..9fdeae148 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java @@ -70,7 +70,7 @@ public void onPerform(CommandEvent commandEvent) { switch (command) { case "instagram" -> - SQLSession.getSqlConnector().getSqlWorker().getAllInstagramUsers(commandEvent.getGuild().getIdLong()).thenAccept(users -> { + SQLSession.getSqlConnector().getSqlWorker().getAllInstagramUsers(commandEvent.getGuild().getIdLong()).subscribe(users -> { for (String user : users) { end.append(user).append("\n"); } @@ -79,7 +79,7 @@ public void onPerform(CommandEvent commandEvent) { }); case "youtube" -> - SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels(commandEvent.getGuild().getIdLong()).thenAccept(userList -> { + SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels(commandEvent.getGuild().getIdLong()).subscribe(userList -> { for (String users : userList) { ChannelResult channelResult = null; @@ -104,7 +104,7 @@ public void onPerform(CommandEvent commandEvent) { }); case "twitch" -> - SQLSession.getSqlConnector().getSqlWorker().getAllTwitchNames(commandEvent.getGuild().getIdLong()).thenAccept(users -> { + SQLSession.getSqlConnector().getSqlWorker().getAllTwitchNames(commandEvent.getGuild().getIdLong()).subscribe(users -> { for (String user : users) { end.append(user).append("\n"); } @@ -113,7 +113,7 @@ public void onPerform(CommandEvent commandEvent) { }); case "twitter" -> - SQLSession.getSqlConnector().getSqlWorker().getAllTwitterNames(commandEvent.getGuild().getIdLong()).thenAccept(users -> { + SQLSession.getSqlConnector().getSqlWorker().getAllTwitterNames(commandEvent.getGuild().getIdLong()).subscribe(users -> { for (String user : users) { end.append(user).append("\n"); } @@ -122,7 +122,7 @@ public void onPerform(CommandEvent commandEvent) { }); case "tiktok" -> - SQLSession.getSqlConnector().getSqlWorker().getAllTikTokNames(commandEvent.getGuild().getIdLong()).thenAccept(users -> { + SQLSession.getSqlConnector().getSqlWorker().getAllTikTokNames(commandEvent.getGuild().getIdLong()).subscribe(users -> { for (String user : users) { end.append(user); try { @@ -137,7 +137,7 @@ public void onPerform(CommandEvent commandEvent) { }); case "reddit" -> - SQLSession.getSqlConnector().getSqlWorker().getAllSubreddits(commandEvent.getGuild().getIdLong()).thenAccept(users -> { + SQLSession.getSqlConnector().getSqlWorker().getAllSubreddits(commandEvent.getGuild().getIdLong()).subscribe(users -> { for (String user : users) { end.append(user).append("\n"); } @@ -146,7 +146,7 @@ public void onPerform(CommandEvent commandEvent) { }); case "rss" -> - SQLSession.getSqlConnector().getSqlWorker().getAllRSSUrls(commandEvent.getGuild().getIdLong()).thenAccept(users -> { + SQLSession.getSqlConnector().getSqlWorker().getAllRSSUrls(commandEvent.getGuild().getIdLong()).subscribe(users -> { for (String user : users) { end.append(user).append("\n"); } diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java b/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java index 88201a925..613526a98 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java @@ -63,7 +63,7 @@ public void onPerform(CommandEvent commandEvent) { }).queue(msg -> { if (msg == null) return; MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); - messageCreateBuilder.setContent(LanguageService.getByGuild(commandEvent.getGuild(), "message.reactions.reactionNeeded", role.getAsRole().getAsMention()).join()); + messageCreateBuilder.setContent(LanguageService.getByGuild(commandEvent.getGuild(), "message.reactions.reactionNeeded", role.getAsRole().getAsMention()).block()); msg.reply(messageCreateBuilder.build()).queue(); }); @@ -87,7 +87,7 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new ReactionRole(), "FROM ReactionRole WHERE guildRoleId.guildId=:gid AND guildRoleId.roleId=:roleId AND messageId=:messageId", - Map.of("gid", commandEvent.getGuild().getIdLong(), "roleId", role.getAsRole().getIdLong(), "messageId", messageId)).thenAccept(reactionRole -> { + Map.of("gid", commandEvent.getGuild().getIdLong(), "roleId", role.getAsRole().getIdLong(), "messageId", messageId)).subscribe(reactionRole -> { if (reactionRole != null) { SQLSession.getSqlConnector().getSqlWorker().deleteEntity(reactionRole); diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java b/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java index 64353babb..dfb39815b 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java @@ -57,7 +57,7 @@ public void onPerform(CommandEvent commandEvent) { case "list" -> SQLSession.getSqlConnector().getSqlWorker() .getEntityList(new ScheduledMessage(), "FROM ScheduledMessage WHERE guildAndId.guildId = :gid ", - Map.of("gid", commandEvent.getGuild().getIdLong())).thenAccept(scheduledMessages -> { + Map.of("gid", commandEvent.getGuild().getIdLong())).subscribe(scheduledMessages -> { StringBuilder stringBuilder = new StringBuilder(); for (ScheduledMessage scheduledMessage : scheduledMessages) { @@ -75,7 +75,7 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker() .getEntity(new ScheduledMessage(), "FROM ScheduledMessage WHERE guildAndId.guildId = :gid AND guildAndId.id = :id", - Map.of("gid", commandEvent.getGuild().getIdLong(), "id", id.getAsLong())).thenAccept(scheduledMessage -> { + Map.of("gid", commandEvent.getGuild().getIdLong(), "id", id.getAsLong())).subscribe(scheduledMessage -> { if (scheduledMessage != null) { SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage); commandEvent.reply(commandEvent.getResource("message.schedule.delete.success")); @@ -93,6 +93,8 @@ public void onPerform(CommandEvent commandEvent) { OptionMapping channel = commandEvent.getOption("channel"); OptionMapping repeat = commandEvent.getOption("repeat"); + boolean shouldRepeat = repeat != null && repeat.getAsBoolean(); + long fullTime = 0; if (month != null) fullTime += Duration.ofDays(31 * month.getAsLong()).toMillis(); if (day != null) fullTime += Duration.ofDays(day.getAsLong()).toMillis(); @@ -111,19 +113,18 @@ public void onPerform(CommandEvent commandEvent) { long finalFullTime = fullTime; SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookScheduledMessage(), "FROM WebhookScheduledMessage WHERE guildAndId.guildId = :gid AND channelId = :channel", - Map.of("gid", commandEvent.getGuild().getId(), "channel", guildChannel.getIdLong())).thenAccept(webhookScheduledMessage -> { + Map.of("gid", commandEvent.getGuild().getId(), "channel", guildChannel.getIdLong())).subscribe(webhookScheduledMessage -> { if (webhookScheduledMessage == null) { Webhook webhook = guildChannel.asStandardGuildMessageChannel().createWebhook(BotConfig.getBotName() + "-Schedule").complete(); webhookScheduledMessage = SQLSession.getSqlConnector().getSqlWorker() - .updateEntity(new WebhookScheduledMessage(commandEvent.getGuild().getIdLong(), guildChannel.getIdLong(), webhook.getIdLong(), webhook.getToken())).join(); + .updateEntity(new WebhookScheduledMessage(commandEvent.getGuild().getIdLong(), guildChannel.getIdLong(), webhook.getIdLong(), webhook.getToken())).block(); } scheduledMessage.setScheduledMessageWebhook(webhookScheduledMessage); scheduledMessage.setDelayAmount(finalFullTime); - scheduledMessage.setRepeated(repeat.getAsBoolean()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage).join(); - commandEvent.reply(commandEvent.getResource("message.schedule.added")); + scheduledMessage.setRepeated(shouldRepeat); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage).subscribe(x -> commandEvent.reply(commandEvent.getResource("message.schedule.added"))); }); } diff --git a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java index fe7af917c..3a125db59 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java @@ -2,18 +2,17 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; +import de.presti.ree6.actions.ActionInfo; +import de.presti.ree6.actions.streamtools.container.StreamActionContainer; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.StreamAction; import de.presti.ree6.sql.entities.TwitchIntegration; -import de.presti.ree6.actions.streamtools.container.StreamActionContainer; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; @@ -27,7 +26,6 @@ import java.nio.charset.StandardCharsets; import java.util.Arrays; -import java.util.List; import java.util.Map; /** @@ -63,7 +61,7 @@ public void onPerform(CommandEvent commandEvent) { switch (subCommandGroup) { case "manage" -> - SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.name = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).thenAccept(streamAction -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.name = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).subscribe(streamAction -> { if (streamAction != null) { switch (subCommand) { case "create" -> { @@ -85,7 +83,7 @@ public void onPerform(CommandEvent commandEvent) { streamAction.getActions().getAsJsonArray().add(jsonObject); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction).subscribe(); commandEvent.reply(commandEvent.getResource("message.stream-action.addedLine", actionName)); } @@ -96,7 +94,7 @@ public void onPerform(CommandEvent commandEvent) { int value = line.getAsInt(); if (streamAction.getActions().getAsJsonArray().size() >= value && value > 0) { streamAction.getActions().getAsJsonArray().remove(value - 1); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction).subscribe(); commandEvent.reply(commandEvent.getResource("message.stream-action.deletedLine", "" + value)); } else { commandEvent.reply(commandEvent.getResource("message.default.missingOption", "manageActionValue")); @@ -133,7 +131,7 @@ public void onPerform(CommandEvent commandEvent) { if (values.length >= 2) streamAction.setArgument(values[1]); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction).subscribe(); if (values.length >= 2) { commandEvent.reply(commandEvent.getResource("message.stream-action.listenerArgument", values[0], values[1])); } else { @@ -144,7 +142,8 @@ public void onPerform(CommandEvent commandEvent) { } } - default -> commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); + default -> + commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); } } else { commandEvent.reply(commandEvent.getResource("message.stream-action.notFound", name.getAsString())); @@ -155,27 +154,29 @@ public void onPerform(CommandEvent commandEvent) { switch (subCommand) { case "create" -> - SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.actionName = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).thenAccept(streamAction -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.actionName = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).subscribe(streamAction -> { if (streamAction == null) { - TwitchIntegration twitchIntegration = SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())).join(); - if (twitchIntegration != null) { - streamAction = new StreamAction(); - streamAction.setIntegration(twitchIntegration); - streamAction.setGuildId(commandEvent.getGuild().getIdLong()); - streamAction.setName(name.getAsString()); - - SQLSession.getSqlConnector().getSqlWorker().updateEntity(streamAction).join(); - commandEvent.reply(commandEvent.getResource("message.stream-action.added", name.getAsString())); - } else { - commandEvent.reply(commandEvent.getResource("message.stream-action.noTwitch", BotConfig.getTwitchAuth())); - } + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())) + .subscribe(twitchIntegration -> { + if (twitchIntegration != null) { + StreamAction newStreamAction = new StreamAction(); + newStreamAction.setIntegration(twitchIntegration); + newStreamAction.setGuildId(commandEvent.getGuild().getIdLong()); + newStreamAction.setName(name.getAsString()); + + SQLSession.getSqlConnector().getSqlWorker().updateEntity(newStreamAction).subscribe(); + commandEvent.reply(commandEvent.getResource("message.stream-action.added", name.getAsString())); + } else { + commandEvent.reply(commandEvent.getResource("message.stream-action.noTwitch", BotConfig.getTwitchAuth())); + } + }); } else { commandEvent.reply(commandEvent.getResource("message.stream-action.alreadyExisting", name.getAsString())); } }); case "delete" -> - SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.actionName = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).thenAccept(streamAction -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.actionName = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).subscribe(streamAction -> { if (streamAction != null) { SQLSession.getSqlConnector().getSqlWorker().deleteEntity(streamAction); commandEvent.reply(commandEvent.getResource("message.stream-action.deleted", name.getAsString())); @@ -185,12 +186,12 @@ public void onPerform(CommandEvent commandEvent) { }); case "list" -> - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new StreamAction(), "FROM StreamAction WHERE guildAndName.guildId = :gid", Map.of("gid", commandEvent.getGuild().getIdLong())).thenAccept(streamActions -> { + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new StreamAction(), "FROM StreamAction WHERE guildAndName.guildId = :gid", Map.of("gid", commandEvent.getGuild().getIdLong())).subscribe(streamActions -> { commandEvent.reply(commandEvent.getResource("message.stream-action.list", String.join("\n", streamActions.stream().map(StreamAction::getName).toArray(String[]::new)))); }); case "points" -> - SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())).thenAccept(twitchIntegration -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())).subscribe(twitchIntegration -> { if (twitchIntegration != null) { StringBuilder stringBuilder = new StringBuilder(); Main.getInstance().getNotifier().getTwitchClient().getHelix().getCustomRewards(twitchIntegration.getToken(), twitchIntegration.getChannelId(), null, false).execute().getRewards().forEach(c -> stringBuilder.append(c.getId()).append(" - ").append(c.getTitle()).append("\n")); diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java b/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java index 41171f2db..7b10544dd 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java @@ -59,7 +59,7 @@ public void onPerform(CommandEvent commandEvent) { EmbedBuilder embedBuilder = new EmbedBuilder(); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", commandEvent.getGuild().getId())).thenAccept(tickets -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", commandEvent.getGuild().getId())).subscribe(tickets -> { if (tickets != null) { SQLSession.getSqlConnector().getSqlWorker().deleteEntity(tickets); @@ -79,17 +79,17 @@ public void onPerform(CommandEvent commandEvent) { finalTickets.setLogChannelWebhookToken(webhook.getToken()); commandEvent.getGuild().createCategory("Tickets").addPermissionOverride(commandEvent.getGuild().getPublicRole(), null, EnumSet.of(Permission.VIEW_CHANNEL)).queue(category1 -> { finalTickets.setTicketCategory(category1.getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(finalTickets).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(finalTickets).block(); MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); messageCreateBuilder.setEmbeds(new EmbedBuilder() - .setTitle(LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket").join()) - .setDescription(SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_ticket_menu").join().getStringValue()) + .setTitle(LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket").block()) + .setDescription(SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_ticket_menu").block().getStringValue()) .setColor(0x55ff00) .setThumbnail(commandEvent.getGuild().getIconUrl()) .setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) .build()); - messageCreateBuilder.setActionRow(Button.of(ButtonStyle.PRIMARY, "re_ticket_open", LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket").join(), Emoji.fromUnicode("U+1F4E9"))); + messageCreateBuilder.setActionRow(Button.of(ButtonStyle.PRIMARY, "re_ticket_open", LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket").block(), Emoji.fromUnicode("U+1F4E9"))); Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), ticketChannel.getAsChannel().asTextChannel()); }); }); diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Money.java b/src/main/java/de/presti/ree6/commands/impl/economy/Money.java index 681614a20..3bb9b14be 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Money.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Money.java @@ -19,7 +19,7 @@ /** * Command to manage the player specific economy. */ -@Command(name = "money", description = "command.description.money", category = Category.ECONOMY) +@Command(name = "money", description = "command.description.money.default", category = Category.ECONOMY) public class Money implements ICommand { @Override @@ -45,7 +45,7 @@ public void onPerform(CommandEvent commandEvent) { double withdrawAmount = RandomUtils.round(amount.getAsDouble(), 2); - EconomyUtil.getMoneyHolder(commandEvent.getMember()).thenAccept(moneyHolder -> { + EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> { if (EconomyUtil.hasEnoughMoney(moneyHolder, withdrawAmount, true)) { EconomyUtil.pay(moneyHolder, moneyHolder, withdrawAmount, true, false); commandEvent.reply(commandEvent.getResource("message.money.withdraw", EconomyUtil.formatMoney(withdrawAmount)), 5); @@ -62,7 +62,7 @@ public void onPerform(CommandEvent commandEvent) { double depositAmount = RandomUtils.round(amount.getAsDouble(), 2); - EconomyUtil.getMoneyHolder(commandEvent.getMember()).thenAccept(moneyHolder -> { + EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> { if (EconomyUtil.hasEnoughMoney(moneyHolder, depositAmount, false)) { EconomyUtil.pay(moneyHolder, moneyHolder, depositAmount, false, true); commandEvent.reply(commandEvent.getResource("message.money.deposit", EconomyUtil.formatMoney(depositAmount)), 5); @@ -86,8 +86,8 @@ public void onPerform(CommandEvent commandEvent) { double sendAmount = RandomUtils.round(amount.getAsDouble(), 2); - EconomyUtil.getMoneyHolder(commandEvent.getMember()).thenAccept(moneyHolder -> { - EconomyUtil.getMoneyHolder(member).thenAccept(target -> { + EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> { + EconomyUtil.getMoneyHolder(member).subscribe(target -> { if (EconomyUtil.pay(moneyHolder, target, sendAmount, true, true)) { commandEvent.reply(commandEvent.getResource("message.money.send", EconomyUtil.formatMoney(sendAmount), member.getAsMention())); } else { @@ -105,11 +105,11 @@ public void onPerform(CommandEvent commandEvent) { return; } - EconomyUtil.getMoneyHolder(member).thenAccept(moneyHolder -> + EconomyUtil.getMoneyHolder(member).subscribe(moneyHolder -> commandEvent.reply(commandEvent.getResource("message.money.balance", member.getAsMention(), EconomyUtil.formatMoney(moneyHolder.getAmount()), EconomyUtil.formatMoney(moneyHolder.getBankAmount())))); } else { - EconomyUtil.getMoneyHolder(commandEvent.getMember()).thenAccept(moneyHolder -> + EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> commandEvent.reply(commandEvent.getResource("message.money.balance", commandEvent.getMember().getAsMention(), EconomyUtil.formatMoney(moneyHolder.getAmount()), EconomyUtil.formatMoney(moneyHolder.getBankAmount())))); } @@ -142,22 +142,22 @@ public void onPerform(CommandEvent commandEvent) { if (subcommandGroup.equals("admin")) { switch (subcommand) { case "add" -> { - EconomyUtil.getMoneyHolder(commandEvent.getMember()).thenAccept(moneyHolder -> { - EconomyUtil.getMoneyHolder(member).thenAccept(target -> { + EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> { + EconomyUtil.getMoneyHolder(member).subscribe(target -> { EconomyUtil.pay(moneyHolder, target, optionAmount, false, transferToBank, true); commandEvent.reply(commandEvent.getResource("message.money.add", EconomyUtil.formatMoney(optionAmount), member.getAsMention()), 5); }); }); } case "set" -> { - EconomyUtil.getMoneyHolder(member).thenAccept(moneyHolder -> { + EconomyUtil.getMoneyHolder(member).subscribe(moneyHolder -> { EconomyUtil.set(moneyHolder, optionAmount, transferToBank); commandEvent.reply(commandEvent.getResource("message.money.set", member.getAsMention(), EconomyUtil.formatMoney(optionAmount)), 5); }); } case "remove" -> { - EconomyUtil.getMoneyHolder(commandEvent.getMember()).thenAccept(moneyHolder -> { - EconomyUtil.getMoneyHolder(member).thenAccept(target -> { + EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> { + EconomyUtil.getMoneyHolder(member).subscribe(target -> { EconomyUtil.pay(moneyHolder, target, -optionAmount, false, transferToBank, true); commandEvent.reply(commandEvent.getResource("message.money.remove", EconomyUtil.formatMoney(optionAmount), member.getAsMention()), 5); }); diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java b/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java index ec323cf6f..e5181243c 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java @@ -43,7 +43,7 @@ public void onPerform(CommandEvent commandEvent) { String entryString = commandEvent.getGuild().getIdLong() + "-" + commandEvent.getMember().getIdLong(); SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_steal_delay")).thenAccept(value -> { + Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_steal_delay")).subscribe(value -> { long delay = Long.parseLong(value.getStringValue()); if (stealTimeout.contains(entryString)) { @@ -70,7 +70,7 @@ public void onPerform(CommandEvent commandEvent) { return; } - EconomyUtil.getMoneyHolder(commandEvent.getGuild().getIdLong(), member.getIdLong(), false).thenAccept(targetHolder -> { + EconomyUtil.getMoneyHolder(commandEvent.getGuild().getIdLong(), member.getIdLong(), false).subscribe(targetHolder -> { if (targetHolder == null) { commandEvent.reply(commandEvent.getResource("message.steal.notEnoughMoney", member.getAsMention()), 5); return; @@ -84,7 +84,7 @@ public void onPerform(CommandEvent commandEvent) { double stealAmount = RandomUtils.round(targetHolder.getAmount() * RandomUtils.nextDouble(0.01, 0.25), 2); - EconomyUtil.getMoneyHolder(commandEvent.getMember()).thenAccept(holder -> { + EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(holder -> { if (holder == null) { commandEvent.reply(commandEvent.getResource("message.steal.notEnoughMoney", member.getAsMention()), 5); return; diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Work.java b/src/main/java/de/presti/ree6/commands/impl/economy/Work.java index 623c3176f..1c93bf9a9 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Work.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Work.java @@ -34,7 +34,7 @@ public void onPerform(CommandEvent commandEvent) { String entryString = commandEvent.getGuild().getIdLong() + "-" + commandEvent.getMember().getIdLong(); SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_delay")).thenAccept(value -> { + Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_delay")).subscribe(value -> { long delay = Long.parseLong(value.getStringValue()); if (workTimeout.contains(entryString)) { @@ -43,14 +43,14 @@ public void onPerform(CommandEvent commandEvent) { } double min = Double.parseDouble((String) SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_min")).join().getStringValue()); + Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_min")).block().getStringValue()); double max = Double.parseDouble((String) SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_max")).join().getStringValue()); + Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_max")).block().getStringValue()); double amount = RandomUtils.round(RandomUtils.nextDouble(min, max), 2); - EconomyUtil.getMoneyHolder(commandEvent.getMember()).thenAccept(moneyHolder -> { + EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> { if (moneyHolder == null) return; if (EconomyUtil.pay(null, moneyHolder, amount, false, false, true)) { diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Slap.java b/src/main/java/de/presti/ree6/commands/impl/fun/Slap.java index 898bbeb50..03a6af716 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Slap.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Slap.java @@ -79,7 +79,8 @@ public void sendSlap(Member member, CommandEvent commandEvent) { Image im = null; try { im = ip.getRandomImage("slap").execute(); - } catch (Exception ignored) { + } catch (Exception exception) { + log.error("Failed to get Image from Neko4J API!", exception); } Main.getInstance().getCommandManager().sendMessage((im != null ? im.getUrl() : "https://images.ree6.de/notfound.png"), commandEvent.getChannel(), null); diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Help.java b/src/main/java/de/presti/ree6/commands/impl/info/Help.java index 6202341af..d2be9f245 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Help.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Help.java @@ -79,7 +79,7 @@ public void sendHelpInformation(String categoryString, CommandEvent commandEvent ); if (categoryString == null) { - SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "chatprefix").thenAccept(setting -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "chatprefix").subscribe(setting -> { for (Category cat : Category.values()) { if (cat != Category.HIDDEN) { if (!BotConfig.isModuleActive(cat.name().toLowerCase())) continue; @@ -97,7 +97,7 @@ public void sendHelpInformation(String categoryString, CommandEvent commandEvent Category category = getCategoryFromString(categoryString); - SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "chatprefix").thenAccept(setting -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "chatprefix").subscribe(setting -> { for (ICommand cmd : Main.getInstance().getCommandManager().getCommands().stream().filter(command -> command.getClass().getAnnotation(Command.class).category() == category).toList()) { end.append("``") .append(setting.getStringValue()) diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Infractions.java b/src/main/java/de/presti/ree6/commands/impl/info/Infractions.java index 59e4281d3..292d1cd39 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Infractions.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Infractions.java @@ -38,7 +38,7 @@ public void onPerform(CommandEvent commandEvent) { return; } - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Warning(), "FROM Warning WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", Map.of("gid", commandEvent.getGuild().getIdLong(), "uid", member.getIdLong())).thenAccept(warning -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Warning(), "FROM Warning WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", Map.of("gid", commandEvent.getGuild().getIdLong(), "uid", member.getIdLong())).subscribe(warning -> { if (warning != null) { commandEvent.reply(commandEvent.getResource("message.infractions.success", member.getAsMention(), warning.getWarnings())); } else { diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Optout.java b/src/main/java/de/presti/ree6/commands/impl/info/Optout.java index 12300c325..54169f150 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Optout.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Optout.java @@ -18,7 +18,7 @@ public class Optout implements ICommand { */ @Override public void onPerform(CommandEvent commandEvent) { - SQLSession.getSqlConnector().getSqlWorker().isOptOut(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong()).thenAccept(value -> { + SQLSession.getSqlConnector().getSqlWorker().isOptOut(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong()).subscribe(value -> { if (value) { SQLSession.getSqlConnector().getSqlWorker().optIn(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong()); commandEvent.reply(commandEvent.getResource("message.optout.optedIn")); diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java index ba9f350ab..bfc13d9c9 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java @@ -73,14 +73,14 @@ public void onPerform(CommandEvent commandEvent) { StringBuilder end = new StringBuilder(); - SQLSession.getSqlConnector().getSqlWorker().getStats(commandEvent.getGuild().getIdLong()).thenAccept(stats -> { + SQLSession.getSqlConnector().getSqlWorker().getStats(commandEvent.getGuild().getIdLong()).subscribe(stats -> { for (GuildCommandStats values : stats) { end.append(values.getCommand()).append(" - ").append(values.getUses()).append("\n"); } StringBuilder end2 = new StringBuilder(); - SQLSession.getSqlConnector().getSqlWorker().getStatsGlobal().thenAccept(statsGlobal -> { + SQLSession.getSqlConnector().getSqlWorker().getStatsGlobal().subscribe(statsGlobal -> { for (CommandStats values : statsGlobal) { end2.append(values.getCommand()).append(" - ").append(values.getUses()).append("\n"); } diff --git a/src/main/java/de/presti/ree6/commands/impl/level/Level.java b/src/main/java/de/presti/ree6/commands/impl/level/Level.java index e10d7320a..f353cbf0b 100644 --- a/src/main/java/de/presti/ree6/commands/impl/level/Level.java +++ b/src/main/java/de/presti/ree6/commands/impl/level/Level.java @@ -82,7 +82,7 @@ public String[] getAlias() { public void sendLevel(Member member, CommandEvent commandEvent, String type) { (type.equalsIgnoreCase("voice") ? SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelData(commandEvent.getGuild().getIdLong(), member.getIdLong()) : - SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), member.getIdLong())).thenAccept(userLevel -> { + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), member.getIdLong())).subscribe(userLevel -> { try { MessageCreateBuilder createBuilder = new MessageCreateBuilder(); createBuilder.addFiles(FileUpload.fromData(ImageCreationUtility.createRankImage(userLevel), "rank.png")); diff --git a/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java b/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java index e0ccc1aea..0dbef764d 100644 --- a/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java +++ b/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java @@ -76,7 +76,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.levelRole.removed", role.getName(), level)); } case "list" -> - SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelRewards(commandEvent.getGuild().getIdLong()).thenAccept(level -> { + SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelRewards(commandEvent.getGuild().getIdLong()).subscribe(level -> { MessageCreateBuilder createBuilder = new MessageCreateBuilder(); StringBuilder voiceStringBuilder = new StringBuilder(); StringBuilder chatStringBuilder = new StringBuilder(); @@ -84,7 +84,7 @@ public void onPerform(CommandEvent commandEvent) { level.forEach((level1, role1) -> voiceStringBuilder.append(level1).append(" -> ").append(role1)); - SQLSession.getSqlConnector().getSqlWorker().getChatLevelRewards(commandEvent.getGuild().getIdLong()).join() + SQLSession.getSqlConnector().getSqlWorker().getChatLevelRewards(commandEvent.getGuild().getIdLong()).block() .forEach((level2, role2) -> chatStringBuilder.append(level2).append(" -> ").append(role2)); createBuilder.addFiles(FileUpload.fromData(voiceStringBuilder.toString().getBytes(StandardCharsets.UTF_8), "voice.txt"), diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java b/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java index eed366720..1d08fff6e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java @@ -59,9 +59,9 @@ public void onPerform(CommandEvent commandEvent) { } default -> { - ModerationUtil.shouldModerate(commandEvent.getGuild().getIdLong()).thenAccept(aBoolean -> { + ModerationUtil.shouldModerate(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { if (aBoolean) { - ModerationUtil.getBlacklist(commandEvent.getGuild().getIdLong()).thenAccept(blacklists -> { + ModerationUtil.getBlacklist(commandEvent.getGuild().getIdLong()).subscribe(blacklists -> { StringBuilder end = new StringBuilder(); for (String s : blacklists) { @@ -88,9 +88,9 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.default.invalidQuery"), 5); commandEvent.reply(commandEvent.getResource("message.default.usage", "blacklist remove WORD"), 5); } else if (commandEvent.getArguments()[0].equalsIgnoreCase("list")) { - ModerationUtil.shouldModerate(commandEvent.getGuild().getIdLong()).thenAccept(aBoolean -> { + ModerationUtil.shouldModerate(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { if (aBoolean) { - ModerationUtil.getBlacklist(commandEvent.getGuild().getIdLong()).thenAccept(blacklists -> { + ModerationUtil.getBlacklist(commandEvent.getGuild().getIdLong()).subscribe(blacklists -> { StringBuilder end = new StringBuilder(); for (String s : blacklists) { diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Import.java b/src/main/java/de/presti/ree6/commands/impl/mod/Import.java index 6e4e3c9f6..1f359b6b0 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Import.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Import.java @@ -71,7 +71,7 @@ public void importFromMee6(CommandEvent commandEvent) { JsonElement xp = player.getAsJsonObject().get("xp"); if (id.isJsonPrimitive() && xp.isJsonPrimitive()) { - SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), id.getAsLong()).thenAccept(chatUserLevel -> { + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), id.getAsLong()).subscribe(chatUserLevel -> { if (chatUserLevel != null && chatUserLevel.getExperience() > xp.getAsLong()) { return; } @@ -82,7 +82,7 @@ public void importFromMee6(CommandEvent commandEvent) { chatUserLevel.setExperience(xp.getAsLong()); } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(chatUserLevel).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(chatUserLevel).block(); }); } } @@ -122,7 +122,7 @@ public void importFromAmari(CommandEvent commandEvent) { Leaderboard leaderboard = AmariAPI.getAmari4J().getRawLeaderboard(commandEvent.getGuild().getId(), Integer.MAX_VALUE); leaderboard.getMembers().forEach(member -> { - SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), Long.parseLong(member.getUserid())).thenAccept(chatUserLevel -> { + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), Long.parseLong(member.getUserid())).subscribe(chatUserLevel -> { if (chatUserLevel != null && chatUserLevel.getExperience() > member.getExperience()) { return; } @@ -133,7 +133,7 @@ public void importFromAmari(CommandEvent commandEvent) { chatUserLevel.setExperience(member.getExperience()); } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(chatUserLevel).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(chatUserLevel).block(); }); }); commandEvent.reply(commandEvent.getResource("message.import.success", leaderboard.getCount()), 5); diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/News.java b/src/main/java/de/presti/ree6/commands/impl/mod/News.java index 8a3e1e256..af1df9215 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/News.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/News.java @@ -25,7 +25,7 @@ public void onPerform(CommandEvent commandEvent) { return; } - SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").thenAccept(setting -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").subscribe(setting -> { if (setting == null) { SQLSession.getSqlConnector().getSqlWorker().setSetting(commandEvent.getGuild().getIdLong(), "configuration_news", "Receive News", true); commandEvent.reply(commandEvent.getResource("message.news.enabled"), 5); @@ -40,7 +40,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.news.enabled"), 5); } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(setting).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(setting).block(); }); } diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java index ab540bfa0..0975be4ca 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java @@ -33,6 +33,7 @@ import net.dv8tion.jda.api.interactions.components.selections.SelectOption; import net.dv8tion.jda.internal.interactions.CommandDataImpl; import net.dv8tion.jda.internal.interactions.component.StringSelectMenuImpl; +import reactor.core.publisher.Mono; import java.awt.*; import java.io.InputStream; @@ -115,7 +116,7 @@ public void onPerform(CommandEvent commandEvent) { .addActionRow(selectMenu).queue(); } } else if (commandEvent.getSubcommand().equalsIgnoreCase("autorole")) { - createAutoRoleSetupSelectMenu(commandEvent.getGuild(), commandEvent.getInteractionHook()).thenAccept(menu -> { + createAutoRoleSetupSelectMenu(commandEvent.getGuild(), commandEvent.getInteractionHook()).subscribe(menu -> { MessageEmbed embed = createAutoRoleSetupMessage(commandEvent.getGuild(), commandEvent.getInteractionHook()).build(); Button webinterface = Button.link(BotConfig.getWebinterface(), "Webinterface"); @@ -145,9 +146,9 @@ public void onPerform(CommandEvent commandEvent) { if (commandEvent.getSubcommand().equals("set")) { if (guildChannelUnion.getType() == ChannelType.TEXT) { guildChannelUnion.asTextChannel().createWebhook(BotConfig.getBotName() + "-Logs").queue(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong()).thenAccept(aBoolean -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { if (aBoolean) { - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong()).thenAccept(webhookEntity -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> { WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), webhookEntity); }); } @@ -160,9 +161,9 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.default.invalidOptionChannel")); } } else { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong()).thenAccept(aBoolean -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { if (aBoolean) { - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong()).thenAccept(webhookEntity -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> { WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), webhookEntity); commandEvent.reply(commandEvent.getResource("message.auditLog.deleted")); }); @@ -176,9 +177,9 @@ public void onPerform(CommandEvent commandEvent) { if (commandEvent.getSubcommand().equals("set")) { if (guildChannelUnion.getType() == ChannelType.TEXT) { guildChannelUnion.asTextChannel().createWebhook(BotConfig.getBotName() + "-Welcome").queue(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong()).thenAccept(aBoolean -> { + SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { if (aBoolean) { - SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong()).thenAccept(webhookEntity -> { + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> { WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), webhookEntity); }); } @@ -190,9 +191,9 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.default.invalidOptionChannel")); } } else { - SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong()).thenAccept(aBoolean -> { + SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { if (aBoolean) { - SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong()).thenAccept(webhookEntity -> + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), webhookEntity)); commandEvent.reply(commandEvent.getResource("message.welcome.deleted")); } @@ -203,14 +204,14 @@ public void onPerform(CommandEvent commandEvent) { case "tempvoice" -> { if (commandEvent.getSubcommand().equals("set")) { if (guildChannelUnion.getType() == ChannelType.VOICE) { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new TemporalVoicechannel(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong())).thenAccept(save -> { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new TemporalVoicechannel(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong())).subscribe(save -> { commandEvent.reply(commandEvent.getResource("message.temporalVoice.setupSuccess")); }); } else { commandEvent.reply(commandEvent.getResource("message.default.invalidOptionChannel")); } } else { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", commandEvent.getGuild().getId())).thenAccept(temporalVoicechannel -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", commandEvent.getGuild().getId())).subscribe(temporalVoicechannel -> { if (temporalVoicechannel != null) { SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel); commandEvent.reply(commandEvent.getResource("message.temporalVoice.deleted")); @@ -273,20 +274,20 @@ public static EmbedBuilder createAutoRoleSetupMessage(Guild guild, InteractionHo boolean hasRoles = !GuildUtil.getManagableRoles(guild).isEmpty(); return new EmbedBuilder() - .setTitle(LanguageService.getByGuildOrInteractionHook(guild, interactionHook, "label.setup").join()) + .setTitle(LanguageService.getByGuildOrInteractionHook(guild, interactionHook, "label.setup").block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()) .setColor(hasRoles ? Color.cyan : Color.red) - .setDescription(LanguageService.getByGuildOrInteractionHook(guild, interactionHook, hasRoles ? "message.autoRole.setupDescription" : "message.default.needPermission", (hasRoles ? null : Permission.MANAGE_ROLES.name())).join()); + .setDescription(LanguageService.getByGuildOrInteractionHook(guild, interactionHook, hasRoles ? "message.autoRole.setupDescription" : "message.default.needPermission", (hasRoles ? null : Permission.MANAGE_ROLES.name())).block()); } - public static CompletableFuture createAutoRoleSetupSelectMenu(Guild guild, InteractionHook interactionHook) { + public static Mono createAutoRoleSetupSelectMenu(Guild guild, InteractionHook interactionHook) { List optionList = new ArrayList<>(); for (Role role : GuildUtil.getManagableRoles(guild)) { optionList.add(SelectOption.of(role.getName(), role.getId())); } - return SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(guild.getIdLong()).thenApply(list -> { + return SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(guild.getIdLong()).map(list -> { list.forEach(autoRole -> { SelectOption option = optionList.stream().filter(selectOption -> selectOption.getValue().equals(String.valueOf(autoRole.getRoleId()))).findFirst().orElse(null); if (option != null) { @@ -296,7 +297,7 @@ public static CompletableFuture createAutoRoleSetupSelectMenu(Guild }); return new StringSelectMenuImpl("setupAutoRole", LanguageService.getByGuildOrInteractionHook(guild, interactionHook, - "message.autoRole.setupPlaceholder").join(), + "message.autoRole.setupPlaceholder").block(), 0, Math.min(10, Math.max(1, optionList.size())), optionList.isEmpty(), optionList); }); } diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java b/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java index 98c2d9aff..77f2e9179 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java @@ -75,16 +75,16 @@ public void onPerform(CommandEvent commandEvent) { public void createSuggestions(CommandEvent commandEvent, MessageChannel channel, MessageChannel messageChannel) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Suggestions(), "FROM Suggestions WHERE guildChannelId.guildId = :id", Map.of("id", commandEvent.getGuild().getIdLong())) - .thenApply(suggestions -> { + .map(suggestions -> { if (suggestions != null) { SQLSession.getSqlConnector().getSqlWorker().deleteEntity(suggestions); suggestions.getGuildChannelId().setChannelId(channel.getIdLong()); - return SQLSession.getSqlConnector().getSqlWorker().updateEntity(suggestions).join(); + return SQLSession.getSqlConnector().getSqlWorker().updateEntity(suggestions).block(); } else { - return SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Suggestions(commandEvent.getGuild().getIdLong(), channel.getIdLong())).join(); + return SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Suggestions(commandEvent.getGuild().getIdLong(), channel.getIdLong())).block(); } - }).thenAccept(suggestions -> SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_suggestion_menu").thenAccept(setting -> { + }).subscribe(suggestions -> SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_suggestion_menu").subscribe(setting -> { MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(); embedBuilder.setTitle(commandEvent.getResource("label.suggestionMenu")); diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java b/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java index 142ff00e8..42905bf43 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java @@ -71,7 +71,7 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(2); punishments.setRoleId(roleMapping.getAsRole().getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).thenAccept(save -> { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> { commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); }); } @@ -82,7 +82,7 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(3); punishments.setRoleId(roleMapping.getAsRole().getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).thenAccept(save -> { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> { commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); }); } @@ -93,7 +93,7 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(1); punishments.setTimeoutTime(secondsMapping.getAsLong() * 1000); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).thenAccept(save -> { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> { commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); }); } @@ -104,7 +104,7 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(4); if (reasonMapping != null) punishments.setReason(reasonMapping.getAsString()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).thenAccept(save -> { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> { commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); }); } @@ -115,13 +115,13 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(5); if (reasonMapping != null) punishments.setReason(reasonMapping.getAsString()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).thenAccept(save -> { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> { commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); }); } case "list" -> { - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid", Map.of("gid", commandEvent.getGuild().getIdLong())).thenAccept(punishmentsList -> { + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid", Map.of("gid", commandEvent.getGuild().getIdLong())).subscribe(punishmentsList -> { StringBuilder stringBuilder = new StringBuilder(); for (Punishments punishments : punishmentsList) { int action = punishments.getAction(); @@ -148,7 +148,7 @@ public void onPerform(CommandEvent commandEvent) { case "delete" -> { int id = idMapping.getAsInt(); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid AND guildAndId.id = :id", Map.of("gid", commandEvent.getGuild().getIdLong(), "id", id)).thenAccept(punishment -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid AND guildAndId.id = :id", Map.of("gid", commandEvent.getGuild().getIdLong(), "id", id)).subscribe(punishment -> { if (punishment != null) { SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment); commandEvent.reply(commandEvent.getResource("message.warn.punishment.deleted", id)); @@ -163,7 +163,7 @@ public void onPerform(CommandEvent commandEvent) { default -> { Member member = userMapping.getAsMember(); if (commandEvent.getGuild().getSelfMember().canInteract(member) && commandEvent.getMember().canInteract(member)) { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Warning(), "FROM Warning WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", Map.of("gid", commandEvent.getGuild().getIdLong(), "uid", member.getIdLong())).thenApplyAsync(warning -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Warning(), "FROM Warning WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", Map.of("gid", commandEvent.getGuild().getIdLong(), "uid", member.getIdLong())).map(warning -> { int warnings = warning != null ? warning.getWarnings() + 1 : 1; if (warning == null) { warning = new Warning(); @@ -173,10 +173,10 @@ public void onPerform(CommandEvent commandEvent) { warning.setWarnings(warnings); - return SQLSession.getSqlConnector().getSqlWorker().updateEntity(warning).join(); - }).thenAccept(warning -> { + return SQLSession.getSqlConnector().getSqlWorker().updateEntity(warning).block(); + }).subscribe(warning -> { commandEvent.reply(commandEvent.getResource("message.warn.success", member.getAsMention(), warning.getWarnings())); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid AND warnings = :amount", Map.of("gid", commandEvent.getGuild().getIdLong(), "amount", warning.getWarnings())).thenAccept(punishment -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid AND warnings = :amount", Map.of("gid", commandEvent.getGuild().getIdLong(), "amount", warning.getWarnings())).subscribe(punishment -> { if (punishment != null) { switch (punishment.getAction()) { case 1 -> diff --git a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java index 9631a9d8d..d16db885d 100644 --- a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java +++ b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java @@ -43,7 +43,7 @@ default void onASyncPerform(CommandEvent commandEvent) { // Update Stats. SQLSession.getSqlConnector().getSqlWorker().addStats(commandEvent.getGuild().getIdLong(), commandEvent.getCommand()); - SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").thenAccept(setting -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").subscribe(setting -> { if (!setting.getBooleanValue()) return; AnnouncementManager.getAnnouncementList().forEach(a -> { if (!AnnouncementManager.hasReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id())) { diff --git a/src/main/java/de/presti/ree6/events/CustomEvents.java b/src/main/java/de/presti/ree6/events/CustomEvents.java index 536d5295f..9487955b8 100644 --- a/src/main/java/de/presti/ree6/events/CustomEvents.java +++ b/src/main/java/de/presti/ree6/events/CustomEvents.java @@ -78,7 +78,7 @@ public void checkForNew(Class clazz, long guildId) { lastCheck = System.currentTimeMillis(); SQLSession.getSqlConnector().getSqlWorker().getEntityList(new CustomEventAction(), "FROM CustomEventAction WHERE guildId=:gid", - Map.of("gid", guildId)).thenApply(x -> x.stream().map(CustomEventContainer::new).toList()).thenAccept(list -> { + Map.of("gid", guildId)).map(x -> x.stream().map(CustomEventContainer::new).toList()).subscribe(list -> { CustomEventTyp typ = CustomEventMapper.getEventTyp(clazz); list.forEach(c -> { diff --git a/src/main/java/de/presti/ree6/events/LoggingEvents.java b/src/main/java/de/presti/ree6/events/LoggingEvents.java index 1a335faa9..e58e2a0bf 100644 --- a/src/main/java/de/presti/ree6/events/LoggingEvents.java +++ b/src/main/java/de/presti/ree6/events/LoggingEvents.java @@ -74,12 +74,12 @@ public void onGuildUpdateVanityCode(@NotNull GuildUpdateVanityCodeEvent event) { if (event.getOldVanityCode() == null) { event.getGuild().retrieveVanityInvite().onErrorMap(throwable -> null).queue(vanityInvite -> - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Invite(event.getGuild().getIdLong(), event.getGuild().getOwnerIdLong(), vanityInvite.getUses(), event.getNewVanityCode())).join()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Invite(event.getGuild().getIdLong(), event.getGuild().getOwnerIdLong(), vanityInvite.getUses(), event.getNewVanityCode())).block()); } else { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Invite(), "FROM Invite WHERE guildAndCode.guildId = :gid AND guildAndCode.code = :code", - Map.of("gid", event.getGuild().getIdLong(), "code", event.getOldVanityCode())).thenAccept(invite -> { + Map.of("gid", event.getGuild().getIdLong(), "code", event.getOldVanityCode())).subscribe(invite -> { invite.setCode(event.getNewVanityCode()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(invite).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(invite).block(); }); } } @@ -90,9 +90,9 @@ public void onGuildUpdateVanityCode(@NotNull GuildUpdateVanityCodeEvent event) { @Override public void onGuildBan(@Nonnull GuildBanEvent event) { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberban").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberban").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -106,18 +106,19 @@ public void onGuildBan(@Nonnull GuildBanEvent event) { we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.banned", event.getUser().getAsMention()).join()); + we.setDescription(LanguageService.getByEvent(event, "logging.banned", event.getUser().getAsMention()).block()); AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.BAN).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor").join() + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).join(); - Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.USER_BAN, event.getUser())); + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(x -> { + Main.getInstance().getLoggerQueue().add(new LogMessageUser(x.getWebhookId(), x.getToken(), wm.build(), event.getGuild(), LogTyp.USER_BAN, event.getUser())); + }); }); }); } @@ -128,9 +129,9 @@ public void onGuildBan(@Nonnull GuildBanEvent event) { @Override public void onGuildUnban(@Nonnull GuildUnbanEvent event) { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberunban").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberunban").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -144,18 +145,19 @@ public void onGuildUnban(@Nonnull GuildUnbanEvent event) { we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.unbanned", event.getUser().getAsMention()).join()); + we.setDescription(LanguageService.getByEvent(event, "logging.unbanned", event.getUser().getAsMention()).block()); AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.UNBAN).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor").join() + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); - Webhook webhook = SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).join(); - Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.USER_UNBAN, event.getUser())); + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(x -> { + Main.getInstance().getLoggerQueue().add(new LogMessageUser(x.getWebhookId(), x.getToken(), wm.build(), event.getGuild(), LogTyp.USER_BAN, event.getUser())); + }); }); }); } @@ -170,10 +172,10 @@ public void onGuildUnban(@Nonnull GuildUnbanEvent event) { @Override public void onGuildMemberJoin(GuildMemberJoinEvent event) { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberjoin").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberjoin").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -186,14 +188,14 @@ public void onGuildMemberJoin(GuildMemberJoinEvent event) { we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getUser().getEffectiveName(), event.getUser().getEffectiveAvatarUrl(), null)); we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.joined.default", event.getUser().getAsMention(), TimeFormat.DATE_TIME_SHORT.format(event.getUser().getTimeCreated()), TimeFormat.RELATIVE.format(event.getUser().getTimeCreated())).join()); + we.setDescription(LanguageService.getByEvent(event, "logging.joined.default", event.getUser().getAsMention(), TimeFormat.DATE_TIME_SHORT.format(event.getUser().getTimeCreated()), TimeFormat.RELATIVE.format(event.getUser().getTimeCreated())).block()); wm.addEmbeds(we.build()); Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.SERVER_JOIN, event.getUser())); }); if (event.getGuild().getSelfMember().hasPermission(Permission.MANAGE_SERVER)) { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_invite").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_invite").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm2 = new WebhookMessageBuilder(); @@ -203,20 +205,20 @@ public void onGuildMemberJoin(GuildMemberJoinEvent event) { if (event.getUser().isBot()) { event.getGuild().retrieveAuditLogs().type(ActionType.BOT_ADD).limit(1).queue(auditLogEntries -> { if (auditLogEntries.isEmpty()) { - wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention()).join()); + wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention()).block()); return; } AuditLogEntry entry = auditLogEntries.get(0); if (entry.getUser() == null) { - wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention()).join()); + wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention()).block()); return; } if (entry.getTargetId().equals(event.getUser().getId())) { - wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.found", event.getUser().getAsMention(), entry.getUser().getAsMention()).join()); + wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.found", event.getUser().getAsMention(), entry.getUser().getAsMention()).block()); } else { - wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention()).join()); + wm2.append(LanguageService.getByEvent(event, "logging.joined.bot.notFound", event.getUser().getAsMention()).block()); } }); } else { @@ -224,13 +226,13 @@ public void onGuildMemberJoin(GuildMemberJoinEvent event) { if (inviteContainer != null) { inviteContainer.setUses(inviteContainer.getUses() + 1); if (inviteContainer.isVanity()) { - wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.vanity", event.getUser().getAsMention()).join()); + wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.vanity", event.getUser().getAsMention()).block()); } else { - wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.default", event.getUser().getAsMention(), "<@" + inviteContainer.getCreatorId() + ">", inviteContainer.getCode(), inviteContainer.getUses()).join()); + wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.default", event.getUser().getAsMention(), "<@" + inviteContainer.getCreatorId() + ">", inviteContainer.getCode(), inviteContainer.getUses()).block()); } Main.getInstance().getInviteContainerManager().add(inviteContainer); } else { - wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.notFound", event.getMember().getAsMention()).join()); + wm2.append(LanguageService.getByEvent(event, "logging.joined.invite.notFound", event.getMember().getAsMention()).block()); } } @@ -249,10 +251,10 @@ public void onGuildMemberJoin(GuildMemberJoinEvent event) { public void onGuildMemberRemove(@Nonnull GuildMemberRemoveEvent event) { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberleave").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberleave").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -267,9 +269,9 @@ public void onGuildMemberRemove(@Nonnull GuildMemberRemoveEvent event) { we.setTimestamp(Instant.now()); if (event.getMember() != null) { - we.setDescription(LanguageService.getByEvent(event, "logging.left.default", event.getUser().getAsMention(), TimeFormat.DATE_TIME_SHORT.format(event.getMember().getTimeJoined())).join()); + we.setDescription(LanguageService.getByEvent(event, "logging.left.default", event.getUser().getAsMention(), TimeFormat.DATE_TIME_SHORT.format(event.getMember().getTimeJoined())).block()); } else { - we.setDescription(LanguageService.getByEvent(event, "logging.left.slim", event.getUser().getAsMention()).join()); + we.setDescription(LanguageService.getByEvent(event, "logging.left.slim", event.getUser().getAsMention()).block()); } AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.KICK).limit(5).stream().filter(auditLogEntry -> @@ -293,10 +295,10 @@ public void onGuildMemberRemove(@Nonnull GuildMemberRemoveEvent event) { public void onGuildMemberUpdateTimeOut(@NotNull GuildMemberUpdateTimeOutEvent event) { super.onGuildMemberUpdateTimeOut(event); - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_timeout").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_timeout").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -315,19 +317,19 @@ public void onGuildMemberUpdateTimeOut(@NotNull GuildMemberUpdateTimeOutEvent ev if (paginationAction.isEmpty()) { we.setDescription(LanguageService.getByEvent(event, "logging.timeout.started", event.getUser().getAsMention(), - TimeFormat.DATE_TIME_SHORT.format(event.getNewTimeOutEnd())).join()); + TimeFormat.DATE_TIME_SHORT.format(event.getNewTimeOutEnd())).block()); } else { AuditLogEntry auditLogEntry = paginationAction.getFirst(); we.setDescription(LanguageService.getByEvent(event, "logging.timeout.updated", event.getUser().getAsMention(), (auditLogEntry.getReason() == null ? "Couldn't find reason" : auditLogEntry.getReason()), (auditLogEntry.getUser() != null ? auditLogEntry.getUser().getAsMention() : LanguageService.getByGuild(event.getGuild(), "label.unknown")), - TimeFormat.DATE_TIME_SHORT.format(event.getNewTimeOutEnd())).join()); + TimeFormat.DATE_TIME_SHORT.format(event.getNewTimeOutEnd())).block()); } } else { we.setDescription(LanguageService.getByEvent(event, "logging.timeout.ended", event.getUser().getAsMention(), - TimeFormat.DATE_TIME_SHORT.format(event.getOldTimeOutEnd())).join()); + TimeFormat.DATE_TIME_SHORT.format(event.getOldTimeOutEnd())).block()); } wm.addEmbeds(we.build()); @@ -344,10 +346,10 @@ public void onGuildMemberUpdateTimeOut(@NotNull GuildMemberUpdateTimeOutEvent ev @Override public void onGuildMemberUpdateNickname(@Nonnull GuildMemberUpdateNicknameEvent event) { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_nickname").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_nickname").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -362,9 +364,9 @@ public void onGuildMemberUpdateNickname(@Nonnull GuildMemberUpdateNicknameEvent we.setTimestamp(Instant.now()); if (event.getNewNickname() == null) { - we.setDescription(LanguageService.getByEvent(event, "logging.nickname.reset", event.getUser().getAsMention(), event.getOldNickname()).join()); + we.setDescription(LanguageService.getByEvent(event, "logging.nickname.reset", event.getUser().getAsMention(), event.getOldNickname()).block()); } else { - we.setDescription(LanguageService.getByEvent(event, "logging.nickname.changed", event.getUser().getAsMention(), event.getNewNickname(), (event.getOldNickname() != null ? event.getOldNickname() : event.getUser().getName())).join()); + we.setDescription(LanguageService.getByEvent(event, "logging.nickname.changed", event.getUser().getAsMention(), event.getNewNickname(), (event.getOldNickname() != null ? event.getOldNickname() : event.getUser().getName())).block()); } AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_UPDATE).limit(5).stream().filter(auditLogEntry -> @@ -392,11 +394,11 @@ public void onGuildMemberUpdateNickname(@Nonnull GuildMemberUpdateNicknameEvent @Override public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { super.onGuildVoiceUpdate(event); - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { if (event.getChannelLeft() == null) { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicejoin").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicejoin").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -409,14 +411,14 @@ public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getEntity().getEffectiveName(), event.getEntity().getEffectiveAvatarUrl(), null)); we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.join", event.getEntity().getUser().getAsMention(), event.getChannelJoined().getAsMention()).join()); + we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.join", event.getEntity().getUser().getAsMention(), event.getChannelJoined().getAsMention()).block()); wm.addEmbeds(we.build()); Main.getInstance().getLoggerQueue().add(new LogMessageVoice(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.VC_JOIN, event.getEntity(), event.getChannelJoined())); }); } else if (event.getChannelJoined() == null) { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voiceleave").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voiceleave").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -429,7 +431,7 @@ public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getEntity().getEffectiveName(), event.getEntity().getEffectiveAvatarUrl(), null)); we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.leave", event.getEntity().getUser().getAsMention(), event.getChannelLeft().getAsMention()).join()); + we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.leave", event.getEntity().getUser().getAsMention(), event.getChannelLeft().getAsMention()).block()); AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_VOICE_KICK).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); @@ -442,7 +444,7 @@ public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { Main.getInstance().getLoggerQueue().add(new LogMessageVoice(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.VC_LEAVE, event.getEntity(), event.getChannelLeft())); }); } else { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicemove").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicemove").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -455,7 +457,7 @@ public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getEntity().getEffectiveName(), event.getEntity().getEffectiveAvatarUrl(), null)); we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.move", event.getEntity().getUser().getAsMention(), event.getChannelLeft().getAsMention(), event.getChannelJoined().getAsMention()).join()); + we.setDescription(LanguageService.getByEvent(event, "logging.voicechannel.move", event.getEntity().getUser().getAsMention(), event.getChannelLeft().getAsMention(), event.getChannelJoined().getAsMention()).block()); AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_VOICE_MOVE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); @@ -482,11 +484,11 @@ public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { @Override public void onGenericChannel(@Nonnull GenericChannelEvent event) { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { if (event.getChannelType().isAudio()) { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicechannel").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicechannel").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -499,16 +501,16 @@ public void onGenericChannel(@Nonnull GenericChannelEvent event) { we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.update.voice", event.getChannel().getAsMention()).join()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.update.voice", event.getChannel().getAsMention()).block()); AuditLogEntry entry; if (event instanceof ChannelCreateEvent) { - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.create.voice", event.getChannel().getAsMention()).join()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.create.voice", event.getChannel().getAsMention()).block()); entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_CREATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); } else if (event instanceof ChannelDeleteEvent) { - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.delete.voice", event.getChannel().getName()).join()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.delete.voice", event.getChannel().getName()).block()); entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_DELETE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); } else if (event instanceof ChannelUpdateNameEvent channelUpdateNameEvent) { @@ -523,14 +525,14 @@ public void onGenericChannel(@Nonnull GenericChannelEvent event) { } if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); Main.getInstance().getLoggerQueue().add(new LogMessage(webhook.getWebhookId(), webhook.getToken(), wm.build(), event.getGuild(), LogTyp.CHANNELDATA_CHANGE)); }); } else { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_textchannel").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_textchannel").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -544,17 +546,17 @@ public void onGenericChannel(@Nonnull GenericChannelEvent event) { we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.update.chat", event.getChannel().getAsMention()).join()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.update.chat", event.getChannel().getAsMention()).block()); we.setDescription(":house: **TextChannel updated:** " + event.getChannel().getAsMention()); AuditLogEntry entry; if (event instanceof ChannelCreateEvent) { - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.create.chat", event.getChannel().getAsMention()).join()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.create.chat", event.getChannel().getAsMention()).block()); entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_CREATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); } else if (event instanceof ChannelDeleteEvent) { - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.delete.chat", event.getChannel().getName()).join()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.channel.delete.chat", event.getChannel().getName()).block()); entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_DELETE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); } else if (event instanceof ChannelUpdateNameEvent channelUpdateNameEvent) { @@ -594,10 +596,10 @@ public void onGenericChannel(@Nonnull GenericChannelEvent event) { @Override public void onGuildMemberRoleAdd(@Nonnull GuildMemberRoleAddEvent event) { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roleadd").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roleadd").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -618,14 +620,14 @@ public void onGuildMemberRoleAdd(@Nonnull GuildMemberRoleAddEvent event) { finalString.append(":white_check_mark: ").append(r.getName()).append("\n"); } - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.member", event.getMember().getAsMention()).join()); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.roles").join() + ":**", finalString.toString())); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.member", event.getMember().getAsMention()).block()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.roles").block() + ":**", finalString.toString())); AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -641,10 +643,10 @@ public void onGuildMemberRoleAdd(@Nonnull GuildMemberRoleAddEvent event) { @Override public void onGuildMemberRoleRemove(@Nonnull GuildMemberRoleRemoveEvent event) { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roleremove").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roleremove").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -664,14 +666,14 @@ public void onGuildMemberRoleRemove(@Nonnull GuildMemberRoleRemoveEvent event) { finalString.append(":no_entry: ").append(r.getName()).append("\n"); } - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.member", event.getMember().getAsMention()).join()); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.roles").join() + ":**", finalString.toString())); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.member", event.getMember().getAsMention()).block()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.roles").block() + ":**", finalString.toString())); AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -688,10 +690,10 @@ public void onGuildMemberRoleRemove(@Nonnull GuildMemberRoleRemoveEvent event) { */ @Override public void onRoleCreate(@Nonnull RoleCreateEvent event) { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolecreate").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolecreate").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -704,13 +706,13 @@ public void onRoleCreate(@Nonnull RoleCreateEvent event) { we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.create", event.getRole().getName()).join()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.create", event.getRole().getName()).block()); AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_CREATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -725,10 +727,10 @@ public void onRoleCreate(@Nonnull RoleCreateEvent event) { */ @Override public void onRoleDelete(@Nonnull RoleDeleteEvent event) { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roledelete").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roledelete").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -741,13 +743,13 @@ public void onRoleDelete(@Nonnull RoleDeleteEvent event) { we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.delete", event.getRole().getName()).join()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.delete", event.getRole().getName()).block()); AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_DELETE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -762,10 +764,10 @@ public void onRoleDelete(@Nonnull RoleDeleteEvent event) { */ @Override public void onRoleUpdateName(@Nonnull RoleUpdateNameEvent event) { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolename").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolename").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -778,15 +780,15 @@ public void onRoleUpdateName(@Nonnull RoleUpdateNameEvent event) { we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).join()); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldName").join() + "**", event.getOldName())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newName").join() + "**", event.getNewName())); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).block()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldName").block() + "**", event.getOldName())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newName").block() + "**", event.getNewName())); AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -801,10 +803,10 @@ public void onRoleUpdateName(@Nonnull RoleUpdateNameEvent event) { */ @Override public void onRoleUpdateMentionable(@Nonnull RoleUpdateMentionableEvent event) { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolemention").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolemention").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -816,15 +818,15 @@ public void onRoleUpdateMentionable(@Nonnull RoleUpdateMentionableEvent event) { we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).join()); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldMentionable").join() + "**", event.getOldValue().toString())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newMentionable").join() + "**", event.getNewValue().toString())); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).block()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldMentionable").block() + "**", event.getOldValue().toString())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newMentionable").block() + "**", event.getNewValue().toString())); AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -839,10 +841,10 @@ public void onRoleUpdateMentionable(@Nonnull RoleUpdateMentionableEvent event) { */ @Override public void onRoleUpdateHoisted(@Nonnull RoleUpdateHoistedEvent event) { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolehoisted").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolehoisted").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -855,15 +857,15 @@ public void onRoleUpdateHoisted(@Nonnull RoleUpdateHoistedEvent event) { we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).join()); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldHoist").join() + "**", event.getOldValue().toString())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newHoist").join() + "**", event.getNewValue().toString())); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).block()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldHoist").block() + "**", event.getOldValue().toString())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newHoist").block() + "**", event.getNewValue().toString())); AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -880,10 +882,10 @@ public void onRoleUpdateHoisted(@Nonnull RoleUpdateHoistedEvent event) { */ @Override public void onRoleUpdatePermissions(@Nonnull RoleUpdatePermissionsEvent event) { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolepermission").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolepermission").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -896,7 +898,7 @@ public void onRoleUpdatePermissions(@Nonnull RoleUpdatePermissionsEvent event) { we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).join()); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).block()); StringBuilder finalString = new StringBuilder(); @@ -923,13 +925,13 @@ public void onRoleUpdatePermissions(@Nonnull RoleUpdatePermissionsEvent event) { } } - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newPermissions").join() + "**", finalString.toString())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newPermissions").block() + "**", finalString.toString())); AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -946,10 +948,10 @@ public void onRoleUpdatePermissions(@Nonnull RoleUpdatePermissionsEvent event) { */ @Override public void onRoleUpdateColor(@Nonnull RoleUpdateColorEvent event) { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolecolor").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolecolor").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -962,15 +964,15 @@ public void onRoleUpdateColor(@Nonnull RoleUpdateColorEvent event) { we.setAuthor(new WebhookEmbed.EmbedAuthor(event.getGuild().getName(), event.getGuild().getIconUrl(), null)); we.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); we.setTimestamp(Instant.now()); - we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).join()); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldColor").join() + "**", (event.getOldColor() != null ? event.getOldColor() : Color.gray).getRGB() + "")); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newColor").join() + "**", (event.getNewColor() != null ? event.getNewColor() : Color.gray).getRGB() + "")); + we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.role.update", event.getRole().getName()).block()); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldColor").block() + "**", (event.getOldColor() != null ? event.getOldColor() : Color.gray).getRGB() + "")); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newColor").block() + "**", (event.getNewColor() != null ? event.getNewColor() : Color.gray).getRGB() + "")); AuditLogEntry entry = event.getGuild().retrieveAuditLogs().type(ActionType.ROLE_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getRole().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").join() + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -991,10 +993,10 @@ public void onRoleUpdateColor(@Nonnull RoleUpdateColorEvent event) { */ @Override public void onMessageDelete(@Nonnull MessageDeleteEvent event) { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).thenAccept(isSetup -> { + SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_messagedelete").thenAccept(shouldLog -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_messagedelete").subscribe(shouldLog -> { if (!shouldLog.getBooleanValue()) return; User user = ArrayUtil.getUserFromMessageList(event.getMessageId()); @@ -1027,16 +1029,16 @@ public void onMessageDelete(@Nonnull MessageDeleteEvent event) { wm.addFile(attachment.getFileName(), attachment.getProxy().download().get()); } } catch (Exception exception) { - wm.append(LanguageService.getByGuild(event.getGuild(), "logging.message.attachmentFailed", attachment.getFileName()).join() + "\n"); + wm.append(LanguageService.getByGuild(event.getGuild(), "logging.message.attachmentFailed", attachment.getFileName()).block() + "\n"); } } - wm.append(LanguageService.getByGuild(event.getGuild(), "logging.message.attachmentNotice").join() + "\n"); + wm.append(LanguageService.getByGuild(event.getGuild(), "logging.message.attachmentNotice").block() + "\n"); } we.setDescription(LanguageService.getByGuild(event.getGuild(), "logging.message.deleted", user.getAsMention(), event.getChannel().getAsMention(), message != null ? message.getContentRaw().length() >= 650 ? - LanguageService.getByGuild(event.getGuild(), "logging.message.tooLong").join() : - message.getContentRaw() : "").join()); + LanguageService.getByGuild(event.getGuild(), "logging.message.tooLong").block() : + message.getContentRaw() : "").block()); if (message != null && message.getContentRaw().length() >= 650) wm.addFile("message.txt", message.getContentRaw().getBytes(StandardCharsets.UTF_8)); diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index d95260864..abe061b31 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -74,23 +74,23 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { String[] split = event.getComponentId().split(":"); if (split.length == 2) { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Recording(), "FROM Recording WHERE identifier = :id AND guildId = :gid", Map.of("id", split[1], "gid", event.getGuild().getIdLong())).thenAccept(recording -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Recording(), "FROM Recording WHERE identifier = :id AND guildId = :gid", Map.of("id", split[1], "gid", event.getGuild().getIdLong())).subscribe(recording -> { MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); if (recording != null) { messageEditBuilder.setEmbeds(new EmbedBuilder() - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.recording.inChat").join()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.recording.inChat").block()) .setColor(Color.GREEN) .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.recording.finished").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.recording.finished").block()) .build()); messageEditBuilder.setFiles(FileUpload.fromData(recording.getRecording(), "recording.wav")); messageEditBuilder.setComponents(List.of()); } else { messageEditBuilder.setEmbeds(new EmbedBuilder() - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.recording.notFound").join()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.recording.notFound").block()) .setColor(Color.RED) .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.error").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.error").block()) .build()); messageEditBuilder.setComponents(List.of()); } @@ -102,7 +102,7 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { switch (event.getComponentId()) { case "re_feedback" -> { - LanguageService.getByGuild(event.getGuild(), "label.feedback").thenAccept(modalString -> { + LanguageService.getByGuild(event.getGuild(), "label.feedback").subscribe(modalString -> { Modal.Builder builder = Modal.create("re_feedback_modal", modalString); builder.addActionRow(TextInput.create("re_feedback_text", modalString, TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(2042).setMinLength(16).build()); event.replyModal(builder.build()).queue(); @@ -110,7 +110,7 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { } case "re_suggestion" -> { - LanguageService.getByGuild(event.getGuild(), "label.suggestion").thenAccept(modalString -> { + LanguageService.getByGuild(event.getGuild(), "label.suggestion").subscribe(modalString -> { Modal.Builder builder = Modal.create("re_suggestion_modal", modalString); builder.addActionRow(TextInput.create("re_suggestion_text", modalString, TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(2042).setMinLength(16).build()); event.replyModal(builder.build()).queue(); @@ -119,35 +119,35 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { case "re_ticket_open" -> { event.deferReply(true).queue(); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(tickets -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(tickets -> { if (tickets != null) { Category category = event.getGuild().getCategoryById(tickets.getTicketCategory()); if (category != null) { if (category.getTextChannels().stream().anyMatch(c -> c.getName().contains(event.getUser().getName()))) { - event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.alreadyOpen").join()).queue(); + event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.alreadyOpen").block()).queue(); return; } - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_ticket_open").thenAccept(ticketMessage -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_ticket_open").subscribe(ticketMessage -> { category.createTextChannel("ticket-" + event.getUser().getName()) .setTopic(event.getUser().getId()) .syncPermissionOverrides() .addPermissionOverride(event.getMember(), List.of(Permission.VIEW_CHANNEL, Permission.MESSAGE_SEND, Permission.MESSAGE_HISTORY, Permission.MESSAGE_ATTACH_FILES, Permission.MESSAGE_EMBED_LINKS), List.of()) .queue(channel -> { MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); - messageCreateBuilder.setEmbeds(new EmbedBuilder().setTitle(LanguageService.getByGuild(event.getGuild(), "label.ticket").join()) + messageCreateBuilder.setEmbeds(new EmbedBuilder().setTitle(LanguageService.getByGuild(event.getGuild(), "label.ticket").block()) .setDescription(ticketMessage.getStringValue()) .setThumbnail(event.getMember().getEffectiveAvatarUrl()).setColor(Color.GREEN).setTimestamp(Instant.now()).build()); - messageCreateBuilder.addActionRow(Button.primary("re_ticket_close", LanguageService.getByGuild(event.getGuild(), "label.closeTicket").join())); + messageCreateBuilder.addActionRow(Button.primary("re_ticket_close", LanguageService.getByGuild(event.getGuild(), "label.closeTicket").block())); Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), channel); - event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.created", channel.getAsMention()).join()).queue(); + event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.created", channel.getAsMention()).block()).queue(); }); tickets.setTicketCount(tickets.getTicketCount() + 1); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(tickets).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(tickets).block(); }); } else { - event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.categoryNotFound").join()).queue(); + event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.categoryNotFound").block()).queue(); } } }); @@ -156,7 +156,7 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { case "re_ticket_close" -> { event.deferReply(true).queue(); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(tickets -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(tickets -> { if (tickets != null) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(BotConfig.getBotName() + " Ticket transcript") @@ -206,7 +206,7 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), tickets.getLogChannelId(), tickets.getLogChannelWebhookToken(), false); - event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.close").join()).queue(); + event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.close").block()).queue(); event.getChannel().delete().delay(2, TimeUnit.SECONDS).queue(); } }); @@ -222,20 +222,20 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { EmbedBuilder em = new EmbedBuilder() .setAuthor(event.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").block()) .setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.resume").join()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.resume").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); } else { EmbedBuilder em = new EmbedBuilder() .setAuthor(event.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").block()) .setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.pause").join()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.pause").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); } @@ -254,10 +254,10 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { EmbedBuilder em = new EmbedBuilder() .setAuthor(event.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").block()) .setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.pause").join()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.pause").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); } else { @@ -287,12 +287,12 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { em.setAuthor(event.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").join()); + em.setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").block()); em.setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setColor(Color.GREEN); em.setDescription(Main.getInstance().getMusicWorker().getGuildAudioPlayer(event.getGuild()).getScheduler().loop() ? - LanguageService.getByGuild(event.getGuild(), "message.music.loop.enabled").join() : - LanguageService.getByGuild(event.getGuild(), "message.music.loop.disabled").join()); + LanguageService.getByGuild(event.getGuild(), "message.music.loop.enabled").block() : + LanguageService.getByGuild(event.getGuild(), "message.music.loop.disabled").block()); em.setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); @@ -313,10 +313,10 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { em.setAuthor(event.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").join()); + em.setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").block()); em.setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setColor(Color.GREEN); - em.setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.shuffle").join()); + em.setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.shuffle").block()); em.setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); @@ -327,8 +327,8 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { } case "re_music_add" -> { - Modal.Builder builder = Modal.create("re_music_add_modal", LanguageService.getByGuild(event.getGuild(), "label.queueAdd").join()); - builder.addActionRow(TextInput.create("re_music_add_modal_song", LanguageService.getByGuild(event.getGuild(), "label.song").join(), TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(512).setMinLength(4).build()); + Modal.Builder builder = Modal.create("re_music_add_modal", LanguageService.getByGuild(event.getGuild(), "label.queueAdd").block()); + builder.addActionRow(TextInput.create("re_music_add_modal_song", LanguageService.getByGuild(event.getGuild(), "label.song").block(), TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(512).setMinLength(4).build()); event.replyModal(builder.build()).queue(); } } @@ -345,7 +345,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { switch (event.getModalId()) { case "re_rewards_modal" -> { event.deferReply(true).queue(); - LanguageService.getByGuild(event.getGuild(), "label.rewards").thenAccept(title -> { + LanguageService.getByGuild(event.getGuild(), "label.rewards").subscribe(title -> { String blackJackString = event.getValue("re_rewards_BlackJackWin").getAsString(); String musicQuizWinString = event.getValue("re_rewards_MusicQuizWin").getAsString(); String musicQuizFeatureString = event.getValue("re_rewards_MusicQuizFeature").getAsString(); @@ -364,7 +364,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setTitle(title) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.incorrectNumbers").join()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.incorrectNumbers").block()) .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()), null, event.getInteraction().getHook()); } @@ -386,7 +386,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setTitle(title) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.rewards.success").join()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.rewards.success").block()) .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()), null, event.getInteraction().getHook()); }); @@ -395,7 +395,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { case "re_feedback_modal" -> { event.deferReply(true).queue(); - LanguageService.getByGuild(event.getGuild(), "label.feedback").thenAccept(title -> { + LanguageService.getByGuild(event.getGuild(), "label.feedback").subscribe(title -> { EmbedBuilder embedBuilder = new EmbedBuilder() .setTitle(title) .setColor(Color.GREEN) @@ -410,7 +410,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { } case "re_suggestion_modal" -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Suggestions(), "FROM Suggestions WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(suggestions -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Suggestions(), "FROM Suggestions WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(suggestions -> { event.deferReply(true).queue(); if (suggestions != null) { @@ -419,11 +419,11 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { if (messageChannel == null) return; EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.suggestion").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.suggestion").block()) .setColor(Color.ORANGE) .setThumbnail(event.getMember().getEffectiveAvatarUrl()) .setDescription("```" + event.getValue("re_suggestion_text").getAsString() + "```") - .setFooter(LanguageService.getByGuild(event.getGuild(), "message.suggestion.footer", event.getUser().getEffectiveName()).join(), event.getMember().getEffectiveAvatarUrl()) + .setFooter(LanguageService.getByGuild(event.getGuild(), "message.suggestion.footer", event.getUser().getEffectiveName()).block(), event.getMember().getEffectiveAvatarUrl()) .setTimestamp(Instant.now()); Main.getInstance().getCommandManager().sendMessage(embedBuilder, messageChannel); @@ -447,7 +447,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { if (event.getGuild() == null) return; - LanguageService.getByGuild(event.getGuild(), "label.statistics").thenAccept(label -> { + LanguageService.getByGuild(event.getGuild(), "label.statistics").subscribe(label -> { String twitchUsername = modalMapping.getAsString(); java.util.List categories = event.getGuild().getCategoriesByName(label, true); @@ -462,20 +462,20 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { String channelId = Main.getInstance().getNotifier().getTwitchClient().getHelix().getUsers(null, null, Collections.singletonList(twitchUsername)).execute().getUsers().get(0).getId(); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE channelId=:twitchId", Map.of("twitchId", channelId)).thenAccept(twitchIntegration -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE channelId=:twitchId", Map.of("twitchId", channelId)).subscribe(twitchIntegration -> { if (twitchIntegration == null) { EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.stream-action.noTwitch", BotConfig.getTwitchAuth()).join()); + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.stream-action.noTwitch", BotConfig.getTwitchAuth()).block()); event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); return; } - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.twitchCountName", Main.getInstance().getNotifier().getTwitchClient().getHelix().getChannelFollowers(null, channelId, null, 1, null).execute().getTotal()).join(), category) + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.twitchCountName", Main.getInstance().getNotifier().getTwitchClient().getHelix().getChannelFollowers(null, channelId, null, 1, null).execute().getTotal()).block(), category) .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(channelStats -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStats -> { if (channelStats != null) { if (channelStats.getTwitchFollowerChannelId() != null) { @@ -487,7 +487,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { channelStats.setTwitchFollowerChannelId(voiceChannel.getId()); channelStats.setTwitchFollowerChannelUsername(twitchUsername); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); Main.getInstance().getNotifier().registerTwitchChannel(twitchUsername); } else { channelStats = new ChannelStats(event.getGuild().getIdLong(), @@ -504,17 +504,17 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { null, null, null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); Main.getInstance().getNotifier().registerTwitchChannel(twitchUsername); } }); }); EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitchSuccess").join()); + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitchSuccess").block()); event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); }); @@ -527,7 +527,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { if (event.getGuild() == null) return; - LanguageService.getByGuild(event.getGuild(), "label.statistics").thenAccept(label -> { + LanguageService.getByGuild(event.getGuild(), "label.statistics").subscribe(label -> { String youtubeChannelName = modalMapping.getAsString(); java.util.List categories = event.getGuild().getCategoriesByName(label, true); @@ -535,10 +535,10 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { Category category; EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeSuccess").join()); + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeSuccess").block()); if (categories.isEmpty()) { category = event.getGuild().createCategory(label).complete(); @@ -555,27 +555,27 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { } } catch (Exception e) { embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError").join()); + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError").block()); event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); return; } if (youTubeChannel == null) { embedBuilder = embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeNotFound").join()); + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeNotFound").block()); event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); return; } - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.youtubeCountName", youTubeChannel.getSubscriberCountText()).join(), category) + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.youtubeCountName", youTubeChannel.getSubscriberCountText()).block(), category) .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(channelStats -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStats -> { if (channelStats != null) { if (channelStats.getYoutubeSubscribersChannelId() != null) { VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getYoutubeSubscribersChannelId()); @@ -586,7 +586,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { channelStats.setYoutubeSubscribersChannelId(voiceChannel.getId()); channelStats.setYoutubeSubscribersChannelUsername(youTubeChannel.getId()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); Main.getInstance().getNotifier().registerYouTubeChannel(youTubeChannel.getId()); } else { channelStats = new ChannelStats(event.getGuild().getIdLong(), @@ -603,17 +603,17 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { youTubeChannel.getId(), null, null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); Main.getInstance().getNotifier().registerYouTubeChannel(youTubeChannel.getId()); } }); }); embedBuilder = embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeSuccess").join()); + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeSuccess").block()); event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } @@ -625,7 +625,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { if (event.getGuild() == null) return; - LanguageService.getByGuild(event.getGuild(), "label.statistics").thenAccept(label -> { + LanguageService.getByGuild(event.getGuild(), "label.statistics").subscribe(label -> { String subredditName = modalMapping.getAsString(); java.util.List categories = event.getGuild().getCategoriesByName(label, true); @@ -633,10 +633,10 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { Category category; EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.redditSuccess").join()); + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.redditSuccess").block()); if (categories.isEmpty()) { category = event.getGuild().createCategory(label).complete(); @@ -649,17 +649,17 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { subreddit = Main.getInstance().getNotifier().getSubreddit(subredditName); } catch (IOException | InterruptedException e) { embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError").join()); + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError").block()); event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); return; } - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.redditCountName", subreddit.getActiveUserCount()).join(), category) + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.redditCountName", subreddit.getActiveUserCount()).block(), category) .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(channelStats -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStats -> { if (channelStats != null) { if (channelStats.getSubredditMemberChannelId() != null) { VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getSubredditMemberChannelId()); @@ -670,7 +670,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { channelStats.setSubredditMemberChannelId(voiceChannel.getId()); channelStats.setSubredditMemberChannelSubredditName(subredditName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); Main.getInstance().getNotifier().registerSubreddit(subredditName); } else { channelStats = new ChannelStats(event.getGuild().getIdLong(), @@ -687,17 +687,17 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { null, voiceChannel.getId(), subredditName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); Main.getInstance().getNotifier().registerSubreddit(subredditName); } }); }); embedBuilder = embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.redditSuccess").join()); + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.redditSuccess").block()); event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } @@ -709,7 +709,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { if (event.getGuild() == null) return; - LanguageService.getByGuild(event.getGuild(), "label.statistics").thenAccept(label -> { + LanguageService.getByGuild(event.getGuild(), "label.statistics").subscribe(label -> { String twitterName = modalMapping.getAsString(); java.util.List categories = event.getGuild().getCategoriesByName(label, true); @@ -717,10 +717,10 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { Category category; EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitterSuccess").join()); + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitterSuccess").block()); if (categories.isEmpty()) { category = event.getGuild().createCategory(label).complete(); @@ -733,17 +733,17 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { twitterUser = Main.getInstance().getNotifier().getTwitterClient().getUserFromUserName(twitterName); } catch (NoSuchElementException e) { embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError").join()); + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError").block()); event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); return; } - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.twitterCountName", twitterUser.getFollowersCount()).join(), category) + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.twitterCountName", twitterUser.getFollowersCount()).block(), category) .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(channelStats -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStats -> { if (channelStats != null) { if (channelStats.getTwitterFollowerChannelId() != null) { VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getTwitterFollowerChannelId()); @@ -754,7 +754,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { channelStats.setTwitterFollowerChannelId(voiceChannel.getId()); channelStats.setTwitterFollowerChannelUsername(twitterName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); Main.getInstance().getNotifier().registerTwitterUser(twitterName); } else { channelStats = new ChannelStats(event.getGuild().getIdLong(), @@ -771,17 +771,17 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { null, null, null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); Main.getInstance().getNotifier().registerTwitterUser(twitterName); } }); }); embedBuilder = embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitterSuccess").join()); + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitterSuccess").block()); event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } @@ -793,7 +793,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { if (event.getGuild() == null) return; - LanguageService.getByGuild(event.getGuild(), "label.statistics").thenAccept(label -> { + LanguageService.getByGuild(event.getGuild(), "label.statistics").subscribe(label -> { String instagramName = modalMapping.getAsString(); java.util.List categories = event.getGuild().getCategoriesByName(label, true); @@ -801,10 +801,10 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { Category category; EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.instagramSuccess").join()); + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.instagramSuccess").block()); if (categories.isEmpty()) { category = event.getGuild().createCategory(label).complete(); @@ -817,17 +817,17 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { instagramUser = Main.getInstance().getNotifier().getInstagramClient().getActions().users().findByUsername(instagramName).get().getUser(); } catch (ExecutionException | InterruptedException e) { embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError").join()); + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError").block()); event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); return; } - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.instagramCountName", instagramUser.getFollower_count()).join(), category) + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.instagramCountName", instagramUser.getFollower_count()).block(), category) .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(channelStats -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStats -> { if (channelStats != null) { if (channelStats.getInstagramFollowerChannelId() != null) { @@ -839,7 +839,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { channelStats.setInstagramFollowerChannelId(voiceChannel.getId()); channelStats.setInstagramFollowerChannelUsername(instagramName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); Main.getInstance().getNotifier().registerInstagramUser(instagramName); } else { channelStats = new ChannelStats(event.getGuild().getIdLong(), @@ -856,7 +856,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { null, null, null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); Main.getInstance().getNotifier().registerInstagramUser(instagramName); } }); @@ -864,19 +864,19 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { }); embedBuilder = embedBuilder - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.GREEN) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.instagramSuccess").join()); + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.instagramSuccess").block()); event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } default -> event.deferEdit().setEmbeds(new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.unknownMenu").join()) + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.unknownMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setColor(Color.RED) - .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.unknownMenu").join()) + .setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.unknownMenu").block()) .build()).setComponents(new ArrayList<>()).queue(); } } @@ -905,7 +905,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even return; } - SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(event.getGuild().getIdLong()).thenAccept(roles -> { + SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(event.getGuild().getIdLong()).subscribe(roles -> { // We are doing this because a normal List can't be modified. ArrayList values = new ArrayList<>(event.getValues()); @@ -926,12 +926,12 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even for (String roleId : values) { Role role = event.getGuild().getRoleById(roleId); if (role != null) { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new AutoRole(event.getGuild().getIdLong(), role.getIdLong())).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new AutoRole(event.getGuild().getIdLong(), role.getIdLong())).block(); } } } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.autoRole.setupSuccess").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.autoRole.setupSuccess").block()); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } @@ -949,63 +949,63 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even switch (event.getInteraction().getValues().get(0)) { case "rewards" -> { - LanguageService.getByGuild(event.getGuild(), "label.rewards").thenAccept(rewardLabel -> { - TextInput blackJackWin = TextInput.create("re_rewards_BlackJackWin", LanguageService.getByGuild(event.getGuild(), "label.blackJackWin").join(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - TextInput musicQuizWin = TextInput.create("re_rewards_MusicQuizWin", LanguageService.getByGuild(event.getGuild(), "label.musicQuizWin").join(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - TextInput musicQuizFeature = TextInput.create("re_rewards_MusicQuizFeature", LanguageService.getByGuild(event.getGuild(), "label.musicQuizFeatureGuess").join(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - TextInput musicQuizArtist = TextInput.create("re_rewards_MusicQuizArtist", LanguageService.getByGuild(event.getGuild(), "label.musicQuizArtistGuess").join(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - TextInput musicQuizTitle = TextInput.create("re_rewards_MusicQuizTitle", LanguageService.getByGuild(event.getGuild(), "label.musicQuizTitleGuess").join(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + LanguageService.getByGuild(event.getGuild(), "label.rewards").subscribe(rewardLabel -> { + TextInput blackJackWin = TextInput.create("re_rewards_BlackJackWin", LanguageService.getByGuild(event.getGuild(), "label.blackJackWin").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + TextInput musicQuizWin = TextInput.create("re_rewards_MusicQuizWin", LanguageService.getByGuild(event.getGuild(), "label.musicQuizWin").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + TextInput musicQuizFeature = TextInput.create("re_rewards_MusicQuizFeature", LanguageService.getByGuild(event.getGuild(), "label.musicQuizFeatureGuess").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + TextInput musicQuizArtist = TextInput.create("re_rewards_MusicQuizArtist", LanguageService.getByGuild(event.getGuild(), "label.musicQuizArtistGuess").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + TextInput musicQuizTitle = TextInput.create("re_rewards_MusicQuizTitle", LanguageService.getByGuild(event.getGuild(), "label.musicQuizTitleGuess").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); Modal modal = Modal.create("re_rewards_modal", rewardLabel).addActionRow(blackJackWin).addActionRow(musicQuizWin).addActionRow(musicQuizFeature).addActionRow(musicQuizArtist).addActionRow(musicQuizTitle).build(); event.replyModal(modal).queue(); }); } case "lang" -> { - LanguageService.getByGuild(event.getGuild(), "message.setup.steps.lang").thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.setup.steps.lang").subscribe(description -> { for (DiscordLocale locale : LanguageService.getSupported()) { optionList.add(SelectOption.of(locale.getLanguageName(), locale.getLocale())); } embedBuilder.setDescription(description); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLangMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").join(), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLangMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); }); } case "log" -> { - LanguageService.getByGuild(event.getGuild(), "label.setup").thenAccept(label -> { + LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { optionList.add(SelectOption.of(label, "logSetup")); - if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).join()) - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").join(), "logDelete")); + if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).block()) + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "logDelete")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").join(), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.auditLog").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.auditLog").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").join(), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); }); } case "welcome" -> { - LanguageService.getByGuild(event.getGuild(), "label.setup").thenAccept(label -> { + LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { optionList.add(SelectOption.of(label, "welcomeSetup")); - if (SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong()).join()) - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").join(), "welcomeDelete")); + if (SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong()).block()) + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "welcomeDelete")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setImage").join(), "welcomeImage")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setImage").block(), "welcomeImage")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").join(), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.welcome").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.welcome").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").join(), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); }); } case "autorole" -> - Setup.createAutoRoleSetupSelectMenu(event.getGuild(), event.getHook()).thenAccept(selectMenu -> + Setup.createAutoRoleSetupSelectMenu(event.getGuild(), event.getHook()).subscribe(selectMenu -> event.editMessageEmbeds(Setup.createAutoRoleSetupMessage(event.getGuild(), event.getHook()).build()) .setComponents( ActionRow.of(selectMenu), @@ -1013,54 +1013,54 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even .queue()); case "tempvoice" -> { - LanguageService.getByGuild(event.getGuild(), "label.setup").thenAccept(label -> { + LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { optionList.add(SelectOption.of(label, "tempVoiceSetup")); - if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).join() != null) - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").join(), "tempVoiceDelete")); + if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).block() != null) + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "tempVoiceDelete")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").join(), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.temporalVoice").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.temporalVoice").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoiceMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").join(), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoiceMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); }); } case "statistics" -> { - LanguageService.getByGuild(event.getGuild(), "message.statistics.setup").thenAccept(description -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupMemberStatistics").join(), "statisticsSetupMember")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupTwitchStatistics").join(), "statisticsSetupTwitch")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupYoutubeStatistics").join(), "statisticsSetupYouTube")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupRedditStatistics").join(), "statisticsSetupReddit")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupTwitterStatistics").join(), "statisticsSetupTwitter")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupInstagramStatistics").join(), "statisticsSetupInstagram")); + LanguageService.getByGuild(event.getGuild(), "message.statistics.setup").subscribe(description -> { + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupMemberStatistics").block(), "statisticsSetupMember")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupTwitchStatistics").block(), "statisticsSetupTwitch")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupYoutubeStatistics").block(), "statisticsSetupYouTube")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupRedditStatistics").block(), "statisticsSetupReddit")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupTwitterStatistics").block(), "statisticsSetupTwitter")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupInstagramStatistics").block(), "statisticsSetupInstagram")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").join(), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); embedBuilder.setDescription(description); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupStatisticsMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").join(), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupStatisticsMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); }); } case "tickets" -> { - LanguageService.getByGuild(event.getGuild(), "label.setup").thenAccept(label -> { + LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { optionList.add(SelectOption.of(label, "ticketsSetup")); - if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).join() != null) - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").join(), "ticketsDelete")); + if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).block() != null) + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "ticketsDelete")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").join(), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.setup").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.setup").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTicketsMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").join(), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTicketsMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); }); } default -> { - LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { embedBuilder.setDescription(description); event.editMessageEmbeds(embedBuilder.build()).queue(); }); @@ -1081,27 +1081,27 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); case "statisticsSetupMember" -> { - LanguageService.getByGuild(event.getGuild(), "message.statistics.memberSuccess").thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.statistics.memberSuccess").subscribe(description -> { embedBuilder.setDescription(description); embedBuilder.setColor(Color.GREEN); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics").join(), true); + java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics").block(), true); Category category; if (categories.isEmpty()) { - category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics").join()).complete(); + category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics").block()).complete(); } else { category = categories.get(0); } - event.getGuild().loadMembers().onSuccess(members -> event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.overallMembersName", event.getGuild().getMemberCount()).join(), category).queue(voiceChannel -> { + event.getGuild().loadMembers().onSuccess(members -> event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.overallMembersName", event.getGuild().getMemberCount()).block(), category).queue(voiceChannel -> { voiceChannel.getManager().setUserLimit(0).queue(); - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.realMembersName", members.stream().filter(member -> !member.getUser().isBot()).count()).join(), category).queue(voiceChannel1 -> { + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.realMembersName", members.stream().filter(member -> !member.getUser().isBot()).count()).block(), category).queue(voiceChannel1 -> { voiceChannel1.getManager().setUserLimit(0).queue(); - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.botMembersName", members.stream().filter(member -> member.getUser().isBot()).count()).join(), category).queue(voiceChannel2 -> { + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.botMembersName", members.stream().filter(member -> member.getUser().isBot()).count()).block(), category).queue(voiceChannel2 -> { voiceChannel2.getManager().setUserLimit(0).queue(); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(channelStats -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStats -> { if (channelStats != null) { if (channelStats.getMemberStatsChannelId() != null) { VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getMemberStatsChannelId()); @@ -1124,7 +1124,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even channelStats.setMemberStatsChannelId(voiceChannel.getId()); channelStats.setRealMemberStatsChannelId(voiceChannel1.getId()); channelStats.setBotMemberStatsChannelId(voiceChannel2.getId()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); } else { channelStats = new ChannelStats(event.getGuild().getIdLong(), voiceChannel.getId(), @@ -1140,7 +1140,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even null, null, null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); } }); @@ -1151,10 +1151,10 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even } case "statisticsSetupTwitch" -> { - LanguageService.getByGuild(event.getGuild(), "label.channelName").thenAccept(label -> { + LanguageService.getByGuild(event.getGuild(), "label.channelName").subscribe(label -> { TextInput input = TextInput.create("twitchChannelName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Twitch Channel name here!").build(); - Modal modal = Modal.create("statisticsSetupTwitchModal", LanguageService.getByGuild(event.getGuild(), "label.setupTwitchStatistics").join()).addActionRow(input).build(); + Modal modal = Modal.create("statisticsSetupTwitchModal", LanguageService.getByGuild(event.getGuild(), "label.setupTwitchStatistics").block()).addActionRow(input).build(); event.replyModal(modal).queue(); }); @@ -1162,30 +1162,30 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even } case "statisticsSetupYouTube" -> { - LanguageService.getByGuild(event.getGuild(), "label.channelName").thenAccept(label -> { + LanguageService.getByGuild(event.getGuild(), "label.channelName").subscribe(label -> { TextInput input = TextInput.create("youtubeChannelName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the YouTube Channel name here!").build(); - Modal modal = Modal.create("statisticsSetupYouTubeModal", LanguageService.getByGuild(event.getGuild(), "label.setupYoutubeStatistics").join()).addActionRow(input).build(); + Modal modal = Modal.create("statisticsSetupYouTubeModal", LanguageService.getByGuild(event.getGuild(), "label.setupYoutubeStatistics").block()).addActionRow(input).build(); event.replyModal(modal).queue(); }); } case "statisticsSetupReddit" -> { - LanguageService.getByGuild(event.getGuild(), "label.subreddit").thenAccept(label -> { + LanguageService.getByGuild(event.getGuild(), "label.subreddit").subscribe(label -> { TextInput input = TextInput.create("subredditName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Subreddit name here!").build(); - Modal modal = Modal.create("statisticsSetupRedditModal", LanguageService.getByGuild(event.getGuild(), "label.setupRedditStatistics").join()).addActionRow(input).build(); + Modal modal = Modal.create("statisticsSetupRedditModal", LanguageService.getByGuild(event.getGuild(), "label.setupRedditStatistics").block()).addActionRow(input).build(); event.replyModal(modal).queue(); }); } case "statisticsSetupTwitter" -> { - LanguageService.getByGuild(event.getGuild(), "label.name").thenAccept(label -> { + LanguageService.getByGuild(event.getGuild(), "label.name").subscribe(label -> { TextInput input = TextInput.create("twitterName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Twitter name here!").build(); - Modal modal = Modal.create("statisticsSetupTwitterModal", LanguageService.getByGuild(event.getGuild(), "label.setupTwitterStatistics").join()).addActionRow(input).build(); + Modal modal = Modal.create("statisticsSetupTwitterModal", LanguageService.getByGuild(event.getGuild(), "label.setupTwitterStatistics").block()).addActionRow(input).build(); event.replyModal(modal).queue(); }); @@ -1193,10 +1193,10 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even } case "statisticsSetupInstagram" -> { - LanguageService.getByGuild(event.getGuild(), "label.name").thenAccept(label -> { + LanguageService.getByGuild(event.getGuild(), "label.name").subscribe(label -> { TextInput input = TextInput.create("instagramName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Instagram name here!").build(); - Modal modal = Modal.create("statisticsSetupInstagramModal", LanguageService.getByGuild(event.getGuild(), "label.setupInstagramStatistics").join()).addActionRow(input).build(); + Modal modal = Modal.create("statisticsSetupInstagramModal", LanguageService.getByGuild(event.getGuild(), "label.setupInstagramStatistics").block()).addActionRow(input).build(); event.replyModal(modal).queue(); }); @@ -1207,7 +1207,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { embedBuilder.setDescription(description); event.editMessageEmbeds(embedBuilder.build()).queue(); }); @@ -1227,16 +1227,16 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); case "ticketsSetup" -> { - LanguageService.getByGuild(event.getGuild(), "message.ticket.setupDescription").thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.ticket.setupDescription").subscribe(description -> { embedBuilder.setDescription(description); event.editMessageEmbeds(embedBuilder.build()).setComponents().queue(); }); } case "ticketsDelete" -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(tickets -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(tickets -> { if (tickets != null) { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.deleted").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.deleted").block()); embedBuilder.setColor(Color.GREEN); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); SQLSession.getSqlConnector().getSqlWorker().deleteEntity(tickets); @@ -1248,7 +1248,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { embedBuilder.setDescription(description); event.editMessageEmbeds(embedBuilder.build()).queue(); }); @@ -1266,7 +1266,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); if (value.equalsIgnoreCase("more")) { - LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupDescription").thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupDescription").subscribe(description -> { java.util.List optionList = new ArrayList<>(); for (VoiceChannel channel : event.getGuild().getVoiceChannels().stream().skip(24).toList()) { @@ -1275,7 +1275,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even embedBuilder.setDescription(description); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoicechannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").join(), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoicechannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); }); return; } @@ -1283,14 +1283,14 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even VoiceChannel voiceChannel = event.getGuild().getVoiceChannelById(value); if (voiceChannel != null) { - LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupSuccess").thenAccept(description -> { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new TemporalVoicechannel(event.getGuild().getIdLong(), voiceChannel.getIdLong())).join(); + LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupSuccess").subscribe(description -> { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new TemporalVoicechannel(event.getGuild().getIdLong(), voiceChannel.getIdLong())).block(); embedBuilder.setDescription(description); embedBuilder.setColor(Color.GREEN); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } else { - LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel").thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel").subscribe(description -> { embedBuilder.setDescription(description); event.editMessageEmbeds(embedBuilder.build()).queue(); }); @@ -1312,7 +1312,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); case "tempVoiceSetup" -> { - LanguageService.getByGuild(event.getGuild(), "label.more").thenAccept(labelMore -> { + LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(labelMore -> { for (VoiceChannel channel : event.getGuild().getVoiceChannels()) { if (optionList.size() == 24) { optionList.add(SelectOption.of(labelMore, "more")); @@ -1322,16 +1322,16 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even optionList.add(SelectOption.of(channel.getName(), channel.getId())); } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupDescription").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupDescription").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoicechannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").join(), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoicechannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); }); } case "tempVoiceDelete" -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(temporalVoicechannel -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(temporalVoicechannel -> { if (temporalVoicechannel != null) { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.deleted").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.deleted").block()); embedBuilder.setColor(Color.GREEN); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel); @@ -1343,7 +1343,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { embedBuilder.setDescription(description); event.editMessageEmbeds(embedBuilder.build()).queue(); }); @@ -1362,14 +1362,14 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even if (selectedLocale != DiscordLocale.UNKNOWN && LanguageService.getSupported().contains(selectedLocale)) { Language language = LanguageService.languageResources.get(selectedLocale); - LanguageService.getByGuild(event.getGuild(), "message.lang.setupSuccess", language.getName() + " by " + language.getAuthor()).thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.lang.setupSuccess", language.getName() + " by " + language.getAuthor()).subscribe(description -> { SQLSession.getSqlConnector().getSqlWorker().setSetting(event.getGuild().getIdLong(), "configuration_language", "Language", selectedLocale.getLocale()); embedBuilder.setDescription(description); embedBuilder.setColor(Color.GREEN); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } else { - LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { embedBuilder.setDescription(description); event.editMessageEmbeds(embedBuilder.build()).queue(); }); @@ -1391,7 +1391,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); case "logSetup" -> { - LanguageService.getByGuild(event.getGuild(), "label.more").thenAccept(labelMore -> { + LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(labelMore -> { for (TextChannel channel : event.getGuild().getTextChannels()) { if (optionList.size() == 24) { optionList.add(SelectOption.of(labelMore, "more")); @@ -1401,18 +1401,18 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even optionList.add(SelectOption.of(channel.getName(), channel.getId())); } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupDescription").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupDescription").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").join(), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); }); } case "logDelete" -> { - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { if (webhook != null) { event.getJDA().retrieveWebhookById(webhook.getChannelId()).queue(webhook1 -> { webhook1.delete().queue(); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.deleted").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.deleted").block()); embedBuilder.setColor(Color.GREEN); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhook); @@ -1425,7 +1425,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { embedBuilder.setDescription(description); event.editMessageEmbeds(embedBuilder.build()).queue(); }); @@ -1444,7 +1444,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); if (value.equals("more")) { - LanguageService.getByGuild(event.getGuild(), "label.more").thenAccept(labelMore -> { + LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(labelMore -> { java.util.List optionList = new ArrayList<>(); for (TextChannel channel : event.getGuild().getTextChannels().stream().skip(24).toList()) { @@ -1456,9 +1456,9 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even optionList.add(SelectOption.of(channel.getName(), channel.getId())); } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupDescription").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupDescription").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").join(), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); }); return; } @@ -1468,17 +1468,17 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even if (textChannel != null) { textChannel.createWebhook(BotConfig.getBotName() + "-Logs").queue(webhook -> { - if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).join()) { - WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).join()); + if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).block()) { + WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).block()); } SQLSession.getSqlConnector().getSqlWorker().setLogWebhook(event.getGuild().getIdLong(), textChannel.getIdLong(), webhook.getIdLong(), webhook.getToken()); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupSuccess").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupSuccess").block()); embedBuilder.setColor(Color.GREEN); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } else { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel").block()); event.editMessageEmbeds(embedBuilder.build()).queue(); } @@ -1499,7 +1499,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); case "welcomeSetup" -> { - LanguageService.getByGuild(event.getGuild(), "label.more").thenAccept(moreLabel -> { + LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(moreLabel -> { for (TextChannel channel : event.getGuild().getTextChannels()) { if (optionList.size() == 24) { optionList.add(SelectOption.of(moreLabel, "more")); @@ -1509,25 +1509,25 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even optionList.add(SelectOption.of(channel.getName(), channel.getId())); } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupDescription").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupDescription").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").join(), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); }); } case "welcomeImage" -> { - LanguageService.getByGuild(event.getGuild(), "message.welcome.imageRequired").thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.welcome.imageRequired").subscribe(description -> { embedBuilder.setDescription(description); event.editMessageEmbeds(embedBuilder.build()).setComponents().queue(); }); } case "welcomeDelete" -> { - SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { if (webhook != null) { event.getJDA().retrieveWebhookById(webhook.getChannelId()).queue(webhook1 -> { webhook1.delete().queue(); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.deleted").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.deleted").block()); embedBuilder.setColor(Color.GREEN); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhook); @@ -1540,7 +1540,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { embedBuilder.setDescription(description); event.editMessageEmbeds(embedBuilder.build()).queue(); }); @@ -1559,7 +1559,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even String value = event.getInteraction().getValues().get(0); if (value.equals("more")) { - LanguageService.getByGuild(event.getGuild(), "label.more").thenAccept(labelMore -> { + LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(labelMore -> { java.util.List optionList = new ArrayList<>(); for (TextChannel channel : event.getGuild().getTextChannels().stream().skip(24).toList()) { @@ -1571,9 +1571,9 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even optionList.add(SelectOption.of(channel.getName(), channel.getId())); } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupDescription").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupDescription").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").join(), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); }); return; } @@ -1582,18 +1582,18 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even if (textChannel != null) { textChannel.createWebhook(BotConfig.getBotName() + "-Welcome").queue(webhook -> { - // .join() can be called here because its being queued. - if (SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong()).join()) { - WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).join()); + // .block() can be called here because its being queued. + if (SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong()).block()) { + WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).block()); } SQLSession.getSqlConnector().getSqlWorker().setWelcomeWebhook(event.getGuild().getIdLong(), textChannel.getIdLong(), webhook.getIdLong(), webhook.getToken()); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupSuccess").join()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupSuccess").block()); embedBuilder.setColor(Color.GREEN); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } else { - LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel").thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOptionChannel").subscribe(description -> { embedBuilder.setDescription(description); event.editMessageEmbeds(embedBuilder.build()).queue(); }); @@ -1604,7 +1604,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) return; - LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); embedBuilder.setDescription(description); @@ -1621,21 +1621,21 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even * @param event The InteractionEvent of the SelectMenu. */ public void sendDefaultChoice(StringSelectInteractionEvent event) { - LanguageService.getByGuild(event.getGuild(), "message.setup.setupMenu").thenAccept(description -> { + LanguageService.getByGuild(event.getGuild(), "message.setup.setupMenu").subscribe(description -> { EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); List optionList = new ArrayList<>(); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.language").join(), "lang")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.auditLog").join(), "log")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.welcomeChannel").join(), "welcome")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.autoRole").join(), "autorole")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.temporalVoice").join(), "tempvoice")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.statistics").join(), "statistics")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.ticketSystem").join(), "tickets")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.language").block(), "lang")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.auditLog").block(), "log")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.welcomeChannel").block(), "welcome")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.autoRole").block(), "autorole")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.temporalVoice").block(), "tempvoice")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.statistics").block(), "statistics")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.ticketSystem").block(), "tickets")); embedBuilder.setDescription(description); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupActionMenu", LanguageService.getByGuild(event.getGuild(), "message.setup.setupMenuPlaceholder").join(), 1, 1, false, optionList)).queue(); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupActionMenu", LanguageService.getByGuild(event.getGuild(), "message.setup.setupMenuPlaceholder").block(), 1, 1, false, optionList)).queue(); }); } @@ -1648,12 +1648,12 @@ public void sendDefaultChoice(StringSelectInteractionEvent event) { */ private boolean checkPerms(Member member, MessageChannel channel) { if (member == null || !member.hasPermission(Permission.ADMINISTRATOR)) { - channel.sendMessage(LanguageService.getByGuild((member == null ? null : member.getGuild()), "message.default.insufficientPermission", Permission.ADMINISTRATOR.name()).join()).queue(); + channel.sendMessage(LanguageService.getByGuild((member == null ? null : member.getGuild()), "message.default.insufficientPermission", Permission.ADMINISTRATOR.name()).block()).queue(); return true; } if (!member.getGuild().getSelfMember().hasPermission(Permission.MANAGE_WEBHOOKS)) { - channel.sendMessage(LanguageService.getByGuild(member.getGuild(), "message.default.needPermission", Permission.MANAGE_WEBHOOKS.name()).join()).queue(); + channel.sendMessage(LanguageService.getByGuild(member.getGuild(), "message.default.needPermission", Permission.MANAGE_WEBHOOKS.name()).block()).queue(); return true; } diff --git a/src/main/java/de/presti/ree6/events/OtherEvents.java b/src/main/java/de/presti/ree6/events/OtherEvents.java index 417abbf74..dcee8d12a 100644 --- a/src/main/java/de/presti/ree6/events/OtherEvents.java +++ b/src/main/java/de/presti/ree6/events/OtherEvents.java @@ -104,7 +104,7 @@ public void onGuildLeave(@Nonnull GuildLeaveEvent event) { @Override public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getId())).thenAccept(channelStats -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getId())).subscribe(channelStats -> { if (channelStats != null) { if (channelStats.getMemberStatsChannelId() != null) { GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStats.getMemberStatsChannelId()); @@ -133,20 +133,20 @@ public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { GuildUtil.handleMemberJoin(event.getGuild(), event.getMember()); - SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong()).thenAccept(x -> { + SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong()).subscribe(x -> { if (x) { WebhookMessageBuilder wmb = new WebhookMessageBuilder(); wmb.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); wmb.setUsername("Welcome!"); - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join").thenAccept(messageSetting -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join").subscribe(messageSetting -> { final String messageContent = messageSetting.getStringValue() .replace("%user_name%", event.getMember().getUser().getName()) .replace("%guild_name%", event.getGuild().getName()) .replace("%guild_member_count%", String.valueOf(event.getGuild().getMemberCount())); - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join_image").thenAccept(joinImage -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join_image").subscribe(joinImage -> { if (!joinImage.getStringValue().isBlank()) { try { wmb.addFile("welcome.png", ImageCreationUtility.createJoinImage(event.getUser(), joinImage.getStringValue(), @@ -159,7 +159,7 @@ public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { wmb.setContent(messageContent.replace("%user_mention%", event.getMember().getUser().getAsMention())); } - SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).thenAccept(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { if (webhook == null) return; WebhookUtil.sendWebhook(wmb.build(), webhook); @@ -178,7 +178,7 @@ public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) { super.onGuildMemberRemove(event); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getId())).thenAccept(channelStats -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getId())).subscribe(channelStats -> { if (channelStats != null) { if (channelStats.getMemberStatsChannelId() != null) { GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStats.getMemberStatsChannelId()); @@ -206,7 +206,7 @@ public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) { }); if (BotConfig.isModuleActive("tickets")) { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).thenAccept(tickets -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(tickets -> { if (tickets != null) { Category category = event.getGuild().getCategoryById(tickets.getTicketCategory()); @@ -325,7 +325,7 @@ public void onGuildVoiceUpdate(@Nonnull GuildVoiceUpdateEvent event) { private void checkCreationChannel(Guild guild, Member member, long channelId) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", guild.getId())) - .thenAccept(temporalVoicechannel -> { + .subscribe(temporalVoicechannel -> { if (temporalVoicechannel != null) { VoiceChannel voiceChannel = guild.getVoiceChannelById(channelId); @@ -337,12 +337,12 @@ private void checkCreationChannel(Guild guild, Member member, long channelId) { } if (voiceChannel.getParentCategory() != null) { - LanguageService.getByGuild(guild, "label.temporalVoiceName", "SPLIT").thenAccept(preName -> { + LanguageService.getByGuild(guild, "label.temporalVoiceName", "SPLIT").subscribe(preName -> { preName = preName.split("SPLIT")[0]; String finalPreName = preName; LanguageService.getByGuild(guild, "label.temporalVoiceName", guild.getVoiceChannels().stream().filter(c -> c.getName().startsWith(finalPreName)).count() + 1) - .thenAccept(name -> voiceChannel.getParentCategory().createVoiceChannel(name) + .subscribe(name -> voiceChannel.getParentCategory().createVoiceChannel(name) .queue(channel -> { guild.moveVoiceMember(member, channel).queue(); ArrayUtil.temporalVoicechannel.add(channel.getId()); @@ -413,7 +413,7 @@ public void doVoiceXPStuff(Member member) { int addXP = IntStream.rangeClosed(1, min).map(i -> RandomUtils.random.nextInt(5, 11)).sum(); - SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelData(member.getGuild().getIdLong(), member.getIdLong()).thenAccept(x -> { + SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelData(member.getGuild().getIdLong(), member.getIdLong()).subscribe(x -> { x.addExperience(addXP); SQLSession.getSqlConnector().getSqlWorker().addVoiceLevelData(member.getGuild().getIdLong(), x); @@ -449,7 +449,7 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { if (event.isFromType(ChannelType.NEWS) && BotConfig.isModuleActive("autopublish")) { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "configuration_autopublish").thenAccept(x -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "configuration_autopublish").subscribe(x -> { if (x.getBooleanValue()) event.getMessage().crosspost().queue(c -> c.addReaction(Emoji.fromUnicode("U+1F4E2")).queue()); }); @@ -467,22 +467,26 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { ArrayUtil.messageIDwithUser.put(event.getMessageId(), event.getAuthor()); } - ModerationUtil.shouldModerate(event.getGuild().getIdLong()).thenAccept(x -> { - AtomicBoolean moderated = new AtomicBoolean(false); + ModerationUtil.shouldModerate(event.getGuild().getIdLong()).subscribe(x -> { + + log.info("Message received from {} in {} with content: {}", event.getAuthor().getGlobalName(), event.getChannel().getName(), event.getMessage().getContentRaw()); + + boolean moderated = false; if (x) { - ModerationUtil.checkMessage(event.getGuild().getIdLong(), event.getMessage().getContentRaw()).thenAccept(y -> { - if (y) { - Main.getInstance().getCommandManager().deleteMessage(event.getMessage(), null); + moderated = Boolean.TRUE.equals(ModerationUtil.checkMessage(event.getGuild().getIdLong(), event.getMessage().getContentRaw()).block()); - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.blacklisted"), event.getChannel(), null); - moderated.set(true); - } - }); + if (moderated) { + Main.getInstance().getCommandManager().deleteMessage(event.getMessage(), null); + + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.blacklisted"), event.getChannel(), null); + } } - if (moderated.get()) return; + log.info("Message was moderated: {}", moderated); + + if (moderated) return; - Main.getInstance().getCommandManager().perform(event.getMember(), event.getGuild(), event.getMessage().getContentRaw(), event.getMessage(), event.getGuildChannel(), null).thenAccept(value -> { + Main.getInstance().getCommandManager().perform(event.getMember(), event.getGuild(), event.getMessage().getContentRaw(), event.getMessage(), event.getGuildChannel(), null).subscribe(value -> { if (!value) { if (!event.getMessage().getMentions().getUsers().isEmpty() && event.getMessage().getMentions().getUsers().contains(event.getJDA().getSelfUser())) { if (event.getMessage().getMessageReference() != null) return; @@ -501,9 +505,9 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { if (BotConfig.isModuleActive("level")) { if (!ArrayUtil.timeout.contains(event.getMember())) { - SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(event.getGuild().getIdLong(), event.getMember().getIdLong()).thenAccept(userLevel -> { + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(event.getGuild().getIdLong(), event.getMember().getIdLong()).subscribe(userLevel -> { if (userLevel.addExperience(RandomUtils.random.nextInt(15, 26))) { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "level_message").thenAccept(z -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "level_message").subscribe(z -> { if (z.getBooleanValue()) { Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.levelUp", userLevel.getLevel(), LanguageService.getByGuild(event.getGuild(), "label.chat") @@ -557,37 +561,37 @@ public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) { if (message.getAuthor().getId().equalsIgnoreCase(event.getJDA().getSelfUser().getId())) { String messageContent = message.getContentRaw(); - LanguageService.getByGuild(event.getGuild(), "message.reactions.reactionNeeded", "SPLIT_HERE").thenAccept(translation -> { + LanguageService.getByGuild(event.getGuild(), "message.reactions.reactionNeeded", "SPLIT_HERE").subscribe(translation -> { if (messageContent.startsWith(translation.split("SPLIT_HERE")[0])) { if (event.getMember().hasPermission(Permission.ADMINISTRATOR) && message.getMessageReference() != null) { if (message.getMentions().getRoles().isEmpty()) { - LanguageService.getByGuild(event.getGuild(), "message.reactions.roleNotFound").thenApply(message::editMessage).thenAccept(MessageEditAction::queue); + LanguageService.getByGuild(event.getGuild(), "message.reactions.roleNotFound").map(message::editMessage).subscribe(MessageEditAction::queue); return; } Role role = message.getMentions().getRoles().get(0); if (role == null) { - LanguageService.getByGuild(event.getGuild(), "message.reactions.roleNotFound").thenApply(message::editMessage).thenAccept(MessageEditAction::queue); + LanguageService.getByGuild(event.getGuild(), "message.reactions.roleNotFound").map(message::editMessage).subscribe(MessageEditAction::queue); return; } ReactionRole reactionRole = new ReactionRole(event.getGuild().getIdLong(), emojiId, emojiUnion.getFormatted(), role.getIdLong(), message.getMessageReference().getMessageIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRole).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRole).block(); if (message.getMessageReference().getMessage() != null) { message.getMessageReference().getMessage().addReaction(event.getEmoji()).queue(); } LanguageService.getByGuild(event.getGuild(), "message.reactions.roleAssign", role.getAsMention()) - .thenAccept(x -> message.editMessage(x).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue()); + .subscribe(x -> message.editMessage(x).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue()); } } }); } else { SQLSession.getSqlConnector().getSqlWorker() .getEntity(new ReactionRole(), "FROM ReactionRole WHERE guildRoleId.guildId=:gid AND emoteId=:emoteId AND messageId=:messageId", - Map.of("gid", event.getGuild().getIdLong(), "emoteId", emojiId, "messageId", message.getIdLong())).thenAccept(reactionRole -> { + Map.of("gid", event.getGuild().getIdLong(), "emoteId", emojiId, "messageId", message.getIdLong())).subscribe(reactionRole -> { if (reactionRole != null) { Role role = event.getGuild().getRoleById(reactionRole.getId()); @@ -608,7 +612,7 @@ public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) { } if (changes) - SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRole).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRole).block(); } }); } @@ -634,7 +638,7 @@ public void onMessageReactionRemove(@NotNull MessageReactionRemoveEvent event) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new ReactionRole(), "FROM ReactionRole WHERE guildRoleId.guildId=:gid AND emoteId=:emoteId AND messageId=:messageId", - Map.of("gid", event.getGuild().getIdLong(), "emoteId", emojiId, "messageId", event.getMessageIdLong())).thenAccept(reactionRole -> { + Map.of("gid", event.getGuild().getIdLong(), "emoteId", emojiId, "messageId", event.getMessageIdLong())).subscribe(reactionRole -> { if (reactionRole != null) { Role role = event.getGuild().getRoleById(reactionRole.getId()); @@ -657,7 +661,7 @@ public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent even event.deferReply(true).queue(); - Main.getInstance().getCommandManager().perform(Objects.requireNonNull(event.getMember()), event.getGuild(), null, null, event.getGuildChannel(), event).thenAccept(x -> { + Main.getInstance().getCommandManager().perform(Objects.requireNonNull(event.getMember()), event.getGuild(), null, null, event.getGuildChannel(), event).subscribe(x -> { if (x != null) { Main.getInstance().getCommandManager().timeoutUser(event.getUser()); } diff --git a/src/main/java/de/presti/ree6/game/core/base/IGame.java b/src/main/java/de/presti/ree6/game/core/base/IGame.java index d499aac9e..1c0525595 100644 --- a/src/main/java/de/presti/ree6/game/core/base/IGame.java +++ b/src/main/java/de/presti/ree6/game/core/base/IGame.java @@ -77,7 +77,7 @@ default void rewardPlayer(GameSession gameSession, GamePlayer player, Object par } } if (parameter instanceof Double money) { - EconomyUtil.getMoneyHolder(gameSession.getGuild().getIdLong(), player.getRelatedUserId(), true).thenAccept(moneyHolder -> { + EconomyUtil.getMoneyHolder(gameSession.getGuild().getIdLong(), player.getRelatedUserId(), true).subscribe(moneyHolder -> { if (moneyHolder == null) return; EconomyUtil.pay(null, moneyHolder, money, false, false, true); }); diff --git a/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java b/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java index c001139f7..72978b610 100644 --- a/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java +++ b/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java @@ -77,20 +77,20 @@ public Blackjack(GameSession gameSession) { @Override public void createGame() { if (session.getParticipants().isEmpty() || session.getParticipants().size() > 2) { - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(session.getGuild(), "message.gameCore.needMore", 2).join(), session.getChannel()); + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(session.getGuild(), "message.gameCore.needMore", 2).block(), session.getChannel()); stopGame(); } MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").join()); + embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").block()); embedBuilder.setColor(BotWorker.randomEmbedColor()); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.welcome", session.getGameIdentifier()).join()); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.welcome", session.getGameIdentifier()).block()); messageCreateBuilder.setEmbeds(embedBuilder.build()); - messageCreateBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").join()).asDisabled(), - Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame").join()).asEnabled()); + messageCreateBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").block()).asDisabled(), + Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame").block()).asEnabled()); session.getChannel().sendMessage(messageCreateBuilder.build()).queue(message -> menuMessage = message); } @@ -127,17 +127,17 @@ public void startGame() { @Override public void joinGame(GamePlayer user) { if (session.getGameState() == GameState.STARTED) { - user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyStarted").join()).queue(); + user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyStarted").block()).queue(); return; } if (player != null && playerTwo != null) { - user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.full").join()).queue(); + user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.full").block()).queue(); return; } if ((player != null && user.getRelatedUserId() == player.getRelatedUserId()) || (playerTwo != null && user.getRelatedUserId() == playerTwo.getRelatedUserId())) { - user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyIn").join()).queue(); + user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyIn").block()).queue(); return; } @@ -151,18 +151,18 @@ public void joinGame(GamePlayer user) { MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); messageEditBuilder.applyMessage(menuMessage); EmbedBuilder embedBuilder = new EmbedBuilder(messageEditBuilder.getEmbeds().get(0)); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.minimalReached").join()); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.minimalReached").block()); messageEditBuilder.setEmbeds(embedBuilder.build()); - messageEditBuilder.setActionRow(Button.success("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").join()).asEnabled()); + messageEditBuilder.setActionRow(Button.success("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").block()).asEnabled()); menuMessage.editMessage(messageEditBuilder.build()).queue(); messageEditBuilder.clear(); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined").join()); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined").block()); messageEditBuilder.setEmbeds(embedBuilder.build()); playerTwo.getInteractionHook().editOriginal(messageEditBuilder.build()).queue(); messageEditBuilder.clear(); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.minimalReachedHost").join()); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.minimalReachedHost").block()); messageEditBuilder.setEmbeds(embedBuilder.build()); player.getInteractionHook().editOriginal(messageEditBuilder.build()).queue(); } @@ -292,18 +292,18 @@ public void stand(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlayer) { public void stopGame(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlayer) { MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").join()); + embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").block()); embedBuilder.setColor(BotWorker.randomEmbedColor()); BlackJackPlayer winner = findWinner(); if (winner == null) { - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.end.draw").join()); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.end.draw").block()); } else { - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.end.win", winner.getRelatedUser().getAsMention(), winner.getHandValue(true)).join()); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.end.win", winner.getRelatedUser().getAsMention(), winner.getHandValue(true)).block()); } - embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", currentPlayer.getRelatedUser().getEffectiveName()).join(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", currentPlayer.getHandAsString(true), currentPlayer.getHandValue(true)).join(), true); - embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", nextPlayer.getRelatedUser().getEffectiveName()).join(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", nextPlayer.getHandAsString(true), nextPlayer.getHandValue(true)).join(), true); + embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", currentPlayer.getRelatedUser().getEffectiveName()).block(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", currentPlayer.getHandAsString(true), currentPlayer.getHandValue(true)).block(), true); + embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", nextPlayer.getRelatedUser().getEffectiveName()).block(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", nextPlayer.getHandAsString(true), nextPlayer.getHandValue(true)).block(), true); messageCreateBuilder.setEmbeds(embedBuilder.build()); messageCreateBuilder.setComponents(new ArrayList<>()); @@ -313,7 +313,7 @@ public void stopGame(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlayer) Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), session.getChannel()); SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_blackjack_win")) - .thenAccept(setting -> rewardPlayer(session, winner, setting.getValue())); + .subscribe(setting -> rewardPlayer(session, winner, setting.getValue())); stopGame(); } @@ -339,33 +339,33 @@ public void updateViews(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlaye MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); EmbedBuilder currentPlayerEmbed = new EmbedBuilder(); - currentPlayerEmbed.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").join()); + currentPlayerEmbed.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").block()); currentPlayerEmbed.setColor(Color.GREEN); currentPlayerEmbed.setAuthor(currentPlayer.getRelatedUser().getEffectiveName(), null, currentPlayer.getRelatedUser().getEffectiveAvatarUrl()); - currentPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCardsSelf").join(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", - currentPlayer.getHandAsString(true), currentPlayer.getHandValue(true)).join(), true); - currentPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", nextPlayer.getRelatedUser().getEffectiveName()).join(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", - nextPlayer.getHandAsString(false), nextPlayer.getHandValue(false)).join(), true); + currentPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCardsSelf").block(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", + currentPlayer.getHandAsString(true), currentPlayer.getHandValue(true)).block(), true); + currentPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", nextPlayer.getRelatedUser().getEffectiveName()).block(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", + nextPlayer.getHandAsString(false), nextPlayer.getHandValue(false)).block(), true); - currentPlayerEmbed.setFooter(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.turn.player").join()); + currentPlayerEmbed.setFooter(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.turn.player").block()); messageEditBuilder.setEmbeds(currentPlayerEmbed.build()); if (addButtons) { - messageEditBuilder.setActionRow(Button.primary("game_blackjack_hit", LanguageService.getByGuild(session.getGuild(), "label.hit").join()), - Button.success("game_blackjack_stand", LanguageService.getByGuild(session.getGuild(), "label.stand").join())); + messageEditBuilder.setActionRow(Button.primary("game_blackjack_hit", LanguageService.getByGuild(session.getGuild(), "label.hit").block()), + Button.success("game_blackjack_stand", LanguageService.getByGuild(session.getGuild(), "label.stand").block())); } currentPlayer.getInteractionHook().editOriginal(messageEditBuilder.build()).queue(); EmbedBuilder nextPlayerEmbed = new EmbedBuilder(); - nextPlayerEmbed.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").join()); + nextPlayerEmbed.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").block()); nextPlayerEmbed.setColor(Color.red); nextPlayerEmbed.setAuthor(nextPlayer.getRelatedUser().getEffectiveName(), null, nextPlayer.getRelatedUser().getEffectiveAvatarUrl()); - nextPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCardsSelf").join(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", nextPlayer.getHandAsString(true), nextPlayer.getHandValue(true)).join(), true); - nextPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", currentPlayer.getRelatedUser().getEffectiveName()).join(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", currentPlayer.getHandAsString(false), currentPlayer.getHandValue(false)).join(), true); - nextPlayerEmbed.setFooter(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.turn.wait").join()); + nextPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCardsSelf").block(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", nextPlayer.getHandAsString(true), nextPlayer.getHandValue(true)).block(), true); + nextPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", currentPlayer.getRelatedUser().getEffectiveName()).block(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", currentPlayer.getHandAsString(false), currentPlayer.getHandValue(false)).block(), true); + nextPlayerEmbed.setFooter(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.turn.wait").block()); messageEditBuilder.setEmbeds(nextPlayerEmbed.build()); nextPlayer.getInteractionHook().editOriginal(messageEditBuilder.build()).queue(); diff --git a/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java b/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java index 2fc6de6b4..daadd0287 100644 --- a/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java +++ b/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java @@ -105,20 +105,20 @@ public MusicQuiz(GameSession gameSession) { public void createGame() { if (session.getHost().getVoiceState() == null || session.getHost().getVoiceState().getChannel() == null) { - session.getChannel().sendMessage(LanguageService.getByGuild(session.getGuild(), "message.default.notInVoiceChannel").join()).queue(); + session.getChannel().sendMessage(LanguageService.getByGuild(session.getGuild(), "message.default.notInVoiceChannel").block()).queue(); return; } MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.musicQuiz").join()); + embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.musicQuiz").block()); embedBuilder.setColor(BotWorker.randomEmbedColor()); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.welcome", session.getGameIdentifier()).join()); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.welcome", session.getGameIdentifier()).block()); messageCreateBuilder.setEmbeds(embedBuilder.build()); - messageCreateBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").join()).asDisabled(), - Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame").join()).asEnabled()); + messageCreateBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").block()).asDisabled(), + Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame").block()).asEnabled()); menuMessage = session.getChannel().sendMessage(messageCreateBuilder.build()).complete(); } @@ -150,7 +150,7 @@ public void startGame() { public void joinGame(GamePlayer user) { if (participants.stream().anyMatch(c -> c.getRelatedUserId() == user.getRelatedUserId())) { - user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyJoined").join()).queue(); + user.getInteractionHook().editOriginal(LanguageService.getByInteraction(user.getInteractionHook().getInteraction(), "message.gameCore.alreadyJoined").block()).queue(); return; } @@ -159,16 +159,16 @@ public void joinGame(GamePlayer user) { MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(menuMessage.getEmbeds().get(0)); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined").join()); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined").block()); messageEditBuilder.setEmbeds(embedBuilder.build()); - messageEditBuilder.setActionRow(Button.secondary("game_leave:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.leaveGame").join()).asEnabled()); + messageEditBuilder.setActionRow(Button.secondary("game_leave:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.leaveGame").block()).asEnabled()); user.getInteractionHook().editOriginal(messageEditBuilder.build()).queue(); if (participants.size() >= 2) { - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.welcome", session.getGameIdentifier()).join()); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.welcome", session.getGameIdentifier()).block()); messageEditBuilder.setEmbeds(embedBuilder.build()); - messageEditBuilder.setActionRow(Button.success("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").join()).asEnabled(), - Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame").join()).asEnabled()); + messageEditBuilder.setActionRow(Button.success("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").block()).asEnabled(), + Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame").block()).asEnabled()); menuMessage.editMessage(messageEditBuilder.build()).queue(); } } @@ -186,10 +186,10 @@ public void leaveGame(GamePlayer user) { messageEditBuilder.applyMessage(menuMessage); EmbedBuilder embedBuilder = new EmbedBuilder(messageEditBuilder.getEmbeds().get(0)); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined").join()); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.gameCore.joined").block()); messageEditBuilder.setEmbeds(embedBuilder.build()); - messageEditBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").join()).asDisabled(), - Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame").join()).asEnabled()); + messageEditBuilder.setActionRow(Button.primary("game_start:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.startGame").block()).asDisabled(), + Button.secondary("game_join:" + session.getGameIdentifier(), LanguageService.getByGuild(session.getGuild(), "label.joinGame").block()).asEnabled()); menuMessage = menuMessage.editMessage(messageEditBuilder.build()).complete(); } } @@ -216,9 +216,9 @@ public void onMessageReceive(MessageReceivedEvent messageReceivedEvent) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_title")) - .thenAccept(setting -> rewardPlayer(session, musicQuizPlayer, setting.getValue())); + .subscribe(setting -> rewardPlayer(session, musicQuizPlayer, setting.getValue())); - messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundTitle", currentEntry.getTitle()).join()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); + messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundTitle", currentEntry.getTitle()).block()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); messageReceivedEvent.getMessage().delete().queue(); } @@ -227,9 +227,9 @@ public void onMessageReceive(MessageReceivedEvent messageReceivedEvent) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_artist")) - .thenAccept(setting -> rewardPlayer(session, musicQuizPlayer, setting.getValue())); + .subscribe(setting -> rewardPlayer(session, musicQuizPlayer, setting.getValue())); - messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundArtists", currentEntry.getArtist()).join()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); + messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundArtists", currentEntry.getArtist()).block()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); messageReceivedEvent.getMessage().delete().queue(); } @@ -238,14 +238,14 @@ public void onMessageReceive(MessageReceivedEvent messageReceivedEvent) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_feature")) - .thenAccept(setting -> rewardPlayer(session, musicQuizPlayer, setting.getValue())); + .subscribe(setting -> rewardPlayer(session, musicQuizPlayer, setting.getValue())); - messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundFeature", String.join(",", currentEntry.getFeatures())).join()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); + messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundFeature", String.join(",", currentEntry.getFeatures())).block()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); messageReceivedEvent.getMessage().delete().queue(); } if (currentEntry.isTitleGuessed() && currentEntry.isArtistGuessed() && currentEntry.isFeaturesGuessed()) { - messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundAll").join()).queue(); + messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundAll").block()).queue(); selectNextSong(); } } @@ -272,14 +272,14 @@ public void stopGame() { MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(menuMessage.getEmbeds().get(0)); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.newSong").join()); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.newSong").block()); List sortedList = participants.stream().sorted(Comparator.comparingInt(MusicQuizPlayer::getPoints).reversed()).toList(); for (int i = 0; i < sortedList.size(); i++) { MusicQuizPlayer musicQuizPlayer = sortedList.get(i); - embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.position", i + 1).join(), + embedBuilder.addField(LanguageService.getByGuild(session.getGuild(), "label.position", i + 1).block(), LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.points", musicQuizPlayer.getRelatedUser().getAsMention(), - musicQuizPlayer.getPoints()).join(), false); + musicQuizPlayer.getPoints()).block(), false); } messageCreateBuilder.setEmbeds(embedBuilder.build()); @@ -288,7 +288,7 @@ public void stopGame() { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_win")) - .thenAccept(setting -> rewardPlayer(session, sortedList.get(0), setting.getValue())); + .subscribe(setting -> rewardPlayer(session, sortedList.get(0), setting.getValue())); Main.getInstance().getMusicWorker().disconnect(session.getGuild()); } @@ -324,9 +324,9 @@ public void selectNextSong() { messageEditBuilder.applyMessage(menuMessage); EmbedBuilder embedBuilder = new EmbedBuilder(messageEditBuilder.getEmbeds().get(0)); - embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.newSong").join()); + embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.newSong").block()); messageEditBuilder.setEmbeds(embedBuilder.build()); - messageEditBuilder.setActionRow(Button.success("game_musicquiz_skip", LanguageService.getByGuild(session.getGuild(), "label.skip").join()).asEnabled()); + messageEditBuilder.setActionRow(Button.success("game_musicquiz_skip", LanguageService.getByGuild(session.getGuild(), "label.skip").block()).asEnabled()); menuMessage.editMessage(messageEditBuilder.build()).queue(); AudioChannel audioChannel = session.getGuild().getMember(session.getHost()).getVoiceState().getChannel(); diff --git a/src/main/java/de/presti/ree6/language/LanguageService.java b/src/main/java/de/presti/ree6/language/LanguageService.java index be72d2dec..5e88eb4b5 100644 --- a/src/main/java/de/presti/ree6/language/LanguageService.java +++ b/src/main/java/de/presti/ree6/language/LanguageService.java @@ -14,6 +14,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.simpleyaml.configuration.file.YamlConfiguration; +import reactor.core.publisher.Mono; import java.io.File; import java.io.IOException; @@ -164,7 +165,7 @@ public static void downloadLanguages() { * @param parameter the parameter to replace. * @return the String. */ - public static @NotNull CompletableFuture getByEvent(@NotNull CommandEvent commandEvent, @NotNull String key, @Nullable Object... parameter) { + public static @NotNull Mono getByEvent(@NotNull CommandEvent commandEvent, @NotNull String key, @Nullable Object... parameter) { if (commandEvent.isSlashCommand()) { return getByInteraction(commandEvent.getInteractionHook().getInteraction(), key, parameter); } else { @@ -180,7 +181,7 @@ public static void downloadLanguages() { * @param parameter the parameter to replace. * @return the String. */ - public static @NotNull CompletableFuture getByEvent(@NotNull GenericGuildEvent commandEvent, @NotNull String key, @Nullable Object... parameter) { + public static @NotNull Mono getByEvent(@NotNull GenericGuildEvent commandEvent, @NotNull String key, @Nullable Object... parameter) { return getByGuild(commandEvent.getGuild(), key, parameter); } @@ -193,7 +194,7 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull CompletableFuture getByGuildOrInteractionHook(Guild guild, InteractionHook interaction, @NotNull String key, @Nullable Object... parameter) { + public static @NotNull Mono getByGuildOrInteractionHook(Guild guild, InteractionHook interaction, @NotNull String key, @Nullable Object... parameter) { return getByGuildOrInteraction(guild, interaction != null ? interaction.getInteraction() : null, key, parameter); } @@ -207,7 +208,7 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull CompletableFuture getByGuildOrInteraction(Guild guild, Interaction interaction, @NotNull String key, @Nullable Object... parameter) { + public static @NotNull Mono getByGuildOrInteraction(Guild guild, Interaction interaction, @NotNull String key, @Nullable Object... parameter) { if (interaction != null) { return getByInteraction(interaction, key, parameter); } else { @@ -223,7 +224,7 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull CompletableFuture getByGuild(Guild guild, @NotNull String key, @Nullable Object... parameter) { + public static @NotNull Mono getByGuild(Guild guild, @NotNull String key, @Nullable Object... parameter) { return getByGuild(guild != null ? guild.getIdLong() : -1, key, parameter); } @@ -235,15 +236,15 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull CompletableFuture getByGuild(long guildId, @NotNull String key, @Nullable Object... parameter) { + public static @NotNull Mono getByGuild(long guildId, @NotNull String key, @Nullable Object... parameter) { if (guildId == -1) { return getDefault(key, parameter); } return SQLSession.getSqlConnector().getSqlWorker().getSetting(guildId, "configuration_language") - .thenApply(setting -> getByLocale(setting.getStringValue(), key, parameter).join()) - .thenApply(resource -> SQLSession.getSqlConnector().getSqlWorker().getSetting(guildId, "chatprefix"). - thenApply(prefix -> resource.replace("{guild_prefix}", prefix.getStringValue())).join()); + .mapNotNull(setting -> getByLocale(setting.getStringValue(), key, parameter).block()) + .mapNotNull(resource -> SQLSession.getSqlConnector().getSqlWorker().getSetting(guildId, "chatprefix"). + map(prefix -> resource.replace("{guild_prefix}", prefix.getStringValue())).block()); } /** @@ -254,15 +255,15 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull CompletableFuture getByInteraction(Interaction interaction, @NotNull String key, @Nullable Object... parameter) { + public static @NotNull Mono getByInteraction(Interaction interaction, @NotNull String key, @Nullable Object... parameter) { if (!interaction.isFromGuild()) { return getByLocale(interaction.getUserLocale(), key, parameter); } - return getByLocale(interaction.getUserLocale(), key, parameter).thenApply(resource -> { + return getByLocale(interaction.getUserLocale(), key, parameter).mapNotNull(resource -> { if (resource.contains("{guild_prefix}")) { return SQLSession.getSqlConnector().getSqlWorker().getSetting(interaction.getGuild().getIdLong(), "chatprefix") - .thenApply(prefix -> resource.replace("{guild_prefix}", prefix.getStringValue())).join(); + .map(prefix -> resource.replace("{guild_prefix}", prefix.getStringValue())).block(); } return resource; @@ -276,7 +277,7 @@ public static void downloadLanguages() { * @param parameter The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull CompletableFuture getDefault(@NotNull String key, @Nullable Object... parameter) { + public static @NotNull Mono getDefault(@NotNull String key, @Nullable Object... parameter) { return getByLocale(DiscordLocale.from(BotConfig.getDefaultLanguage()), key, parameter); } @@ -288,7 +289,7 @@ public static void downloadLanguages() { * @param parameters The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull CompletableFuture getByLocale(@NotNull String locale, @NotNull String key, @Nullable Object... parameters) { + public static @NotNull Mono getByLocale(@NotNull String locale, @NotNull String key, @Nullable Object... parameters) { return getByLocale(DiscordLocale.from(locale), key, parameters); } @@ -300,15 +301,15 @@ public static void downloadLanguages() { * @param parameters The Parameters to replace placeholders in the String. * @return The String. */ - public static @NotNull CompletableFuture getByLocale(@NotNull DiscordLocale discordLocale, @NotNull String key, @Nullable Object... parameters) { - return CompletableFuture.supplyAsync(() -> { - if (discordLocale == DiscordLocale.UNKNOWN) return getDefault(key, parameters).join(); + public static @NotNull Mono getByLocale(@NotNull DiscordLocale discordLocale, @NotNull String key, @Nullable Object... parameters) { + return Mono.fromFuture(CompletableFuture.supplyAsync(() -> { + if (discordLocale == DiscordLocale.UNKNOWN) return getDefault(key, parameters).block(); Language language = languageResources.containsKey(discordLocale) ? languageResources.get(discordLocale) : languageResources.get(DiscordLocale.from(BotConfig.getDefaultLanguage())); return language != null ? language.getResource(key, parameters) : "Missing language resource!"; - }); + })); } /** diff --git a/src/main/java/de/presti/ree6/logger/LoggerQueue.java b/src/main/java/de/presti/ree6/logger/LoggerQueue.java index 6e2757d96..c46a391ba 100644 --- a/src/main/java/de/presti/ree6/logger/LoggerQueue.java +++ b/src/main/java/de/presti/ree6/logger/LoggerQueue.java @@ -72,7 +72,7 @@ public void add(LogMessage loggerMessage) { webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(logMessageVoice.getMember().getUser().getEffectiveName(), logMessageVoice.getMember().getEffectiveAvatarUrl(), null)); webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.voicechannel.rejoin", - logMessageVoice.getMember().getAsMention(), logMessageVoice.getCurrentVoiceChannel().getAsMention()).join()); + logMessageVoice.getMember().getAsMention(), logMessageVoice.getCurrentVoiceChannel().getAsMention()).block()); modified = true; } @@ -94,7 +94,7 @@ else if (loggerMessage.getType() == LogTyp.VC_MOVE && loggerMessage instanceof L webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(logMessageVoice.getMember().getUser().getEffectiveName(), logMessageVoice.getMember().getEffectiveAvatarUrl(), null)); webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.voicechannel.moveMany", - logMessageVoice.getMember().getAsMention(), logMessageVoice.getCurrentVoiceChannel().getAsMention()).join()); + logMessageVoice.getMember().getAsMention(), logMessageVoice.getCurrentVoiceChannel().getAsMention()).block()); modified = true; } @@ -115,7 +115,7 @@ else if (loggerMessage.getType() == LogTyp.VC_LEAVE && loggerMessage instanceof webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(logMessageVoice.getMember().getUser().getEffectiveName(), logMessageVoice.getMember().getEffectiveAvatarUrl(), null)); webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.voicechannel.leaveInstant", - logMessageVoice.getMember().getAsMention(), logMessageVoice.getPreviousVoiceChannel().getAsMention()).join()); + logMessageVoice.getMember().getAsMention(), logMessageVoice.getPreviousVoiceChannel().getAsMention()).block()); modified = true; } @@ -149,7 +149,7 @@ else if (loggerMessage.getType() == LogTyp.NICKNAME_CHANGE && loggerMessage inst webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.nickname.changed", logMessageMember.getMember().getAsMention(), logMessageMember.getPreviousName(), - memberData != null && memberData.getPreviousName() != null ? memberData.getPreviousName() : logMessageMember.getMember().getUser().getName()).join()); + memberData != null && memberData.getPreviousName() != null ? memberData.getPreviousName() : logMessageMember.getMember().getUser().getName()).block()); modified = true; } @@ -219,7 +219,7 @@ else if (loggerMessage.getType() == LogTyp.MEMBERROLE_CHANGE && loggerMessage in logMessageMember.getMember().getEffectiveAvatarUrl(), null)); webhookEmbedBuilder.setThumbnailUrl(logMessageMember.getMember().getEffectiveAvatarUrl()); webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.member", - logMessageMember.getMember().getAsMention()).join()); + logMessageMember.getMember().getAsMention()).block()); if (!logMessageMember.getAddedRoles().isEmpty() || !logMessageMember.getRemovedRoles().isEmpty()) webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.roles") + ":**", stringBuilder.toString())); @@ -315,7 +315,7 @@ else if (loggerMessage.getType() == LogTyp.ROLEDATA_CHANGE && loggerMessage inst if (!logMessageRole.isCreated() && !logMessageRole.isDeleted()) { // Set update as Description - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.update", logMessageRole.getCurrentName()).join()); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.update", logMessageRole.getCurrentName()).block()); // Check if there is a previous and current Name. if (logMessageRole.getPreviousName() != null && logMessageRole.getCurrentName() != null) { @@ -395,10 +395,10 @@ else if (loggerMessage.getType() == LogTyp.ROLEDATA_CHANGE && loggerMessage inst if (logMessageRole.isCreated()) { // Set description to new Role created. - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.create", logMessageRole.getCurrentName()).join()); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.create", logMessageRole.getCurrentName()).block()); } else { // Set description to Role deleted. - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.delete", logMessageRole.getCurrentName()).join()); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.role.delete", logMessageRole.getCurrentName()).block()); } } @@ -428,12 +428,12 @@ else if (loggerMessage.getType() == LogTyp.SERVER_LEAVE && loggerMessage instanc loggerMessages instanceof LogMessageUser logMessageUser1 && logMessageUser1.getUser().getIdLong() == logMessageUser.getUser().getIdLong()) .anyMatch(loggerMessages -> loggerMessages.getType() == LogTyp.USER_BAN)) { - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.banned", logMessageUser.getUser().getAsMention()).join()); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.banned", logMessageUser.getUser().getAsMention()).block()); logs.stream().filter(logMessage -> logMessage != loggerMessage && logMessage.getId() == loggerMessage.getId() && logMessage instanceof LogMessageUser logMessageUser1 && logMessageUser1.getUser().getIdLong() == logMessageUser.getUser().getIdLong()).forEach(LogMessage::cancel); } else { - webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.joined.leave", logMessageUser.getUser().getAsMention()).join()); + webhookEmbedBuilder.setDescription(LanguageService.getByGuild(loggerMessage.getGuild(), "logging.joined.leave", logMessageUser.getUser().getAsMention()).block()); } modified = true; diff --git a/src/main/java/de/presti/ree6/main/Main.java b/src/main/java/de/presti/ree6/main/Main.java index 497adab11..bd80e793e 100644 --- a/src/main/java/de/presti/ree6/main/Main.java +++ b/src/main/java/de/presti/ree6/main/Main.java @@ -344,10 +344,10 @@ public static void main(String[] args) { if (BotConfig.isModuleActive("notifier")) { ThreadUtil.createThread(x -> { log.info("Loading Notifier data."); - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), "FROM ChannelStats", null).thenAccept(channelStats -> { + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), "FROM ChannelStats", null).subscribe(channelStats -> { try { // Register all Twitch Channels. - SQLSession.getSqlConnector().getSqlWorker().getAllTwitchNames().thenAccept(getInstance().getNotifier()::registerTwitchChannel); + SQLSession.getSqlConnector().getSqlWorker().getAllTwitchNames().subscribe(getInstance().getNotifier()::registerTwitchChannel); getInstance().getNotifier().registerTwitchChannel(channelStats.stream().map(ChannelStats::getTwitchFollowerChannelUsername).filter(Objects::nonNull).toList()); // Register the Event-handler. @@ -359,7 +359,7 @@ public static void main(String[] args) { try { // Register all Twitter Users. - SQLSession.getSqlConnector().getSqlWorker().getAllTwitterNames().thenAccept(getInstance().getNotifier()::registerTwitterUser); + SQLSession.getSqlConnector().getSqlWorker().getAllTwitterNames().subscribe(getInstance().getNotifier()::registerTwitterUser); getInstance().getNotifier().registerTwitterUser(channelStats.stream().map(ChannelStats::getTwitterFollowerChannelUsername).filter(Objects::nonNull).toList()); } catch (Exception exception) { log.error("Error while loading Twitter data: {}", exception.getMessage()); @@ -368,7 +368,7 @@ public static void main(String[] args) { try { // Register all YouTube channels. - SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels().thenAccept(getInstance().getNotifier()::registerYouTubeChannel); + SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels().subscribe(getInstance().getNotifier()::registerYouTubeChannel); getInstance().getNotifier().registerYouTubeChannel(channelStats.stream().map(ChannelStats::getYoutubeSubscribersChannelUsername).filter(Objects::nonNull).toList()); } catch (Exception exception) { log.error("Error while loading YouTube data: {}", exception.getMessage()); @@ -377,7 +377,7 @@ public static void main(String[] args) { try { // Register all Reddit Subreddits. - SQLSession.getSqlConnector().getSqlWorker().getAllSubreddits().thenAccept(getInstance().getNotifier()::registerSubreddit); + SQLSession.getSqlConnector().getSqlWorker().getAllSubreddits().subscribe(getInstance().getNotifier()::registerSubreddit); getInstance().getNotifier().registerSubreddit(channelStats.stream().map(ChannelStats::getSubredditMemberChannelSubredditName).filter(Objects::nonNull).toList()); } catch (Exception exception) { log.error("Error while loading Reddit data: {}", exception.getMessage()); @@ -386,7 +386,7 @@ public static void main(String[] args) { try { // Register all Instagram Users. - SQLSession.getSqlConnector().getSqlWorker().getAllInstagramUsers().thenAccept(getInstance().getNotifier()::registerInstagramUser); + SQLSession.getSqlConnector().getSqlWorker().getAllInstagramUsers().subscribe(getInstance().getNotifier()::registerInstagramUser); getInstance().getNotifier().registerInstagramUser(channelStats.stream().map(ChannelStats::getInstagramFollowerChannelUsername).filter(Objects::nonNull).toList()); } catch (Exception exception) { log.error("Error while loading Instagram data: {}", exception.getMessage()); @@ -395,7 +395,7 @@ public static void main(String[] args) { try { // Register all TikTok Users. - SQLSession.getSqlConnector().getSqlWorker().getAllTikTokNames().thenAccept(tiktokNames -> + SQLSession.getSqlConnector().getSqlWorker().getAllTikTokNames().subscribe(tiktokNames -> tiktokNames.forEach(tikTokName -> getInstance().getNotifier().registerTikTokUser(Long.parseLong(tikTokName)))); } catch (Exception exception) { log.error("Error while loading TikTok data: {}", exception.getMessage()); @@ -404,7 +404,7 @@ public static void main(String[] args) { try { // Register all RSS-Feeds. - SQLSession.getSqlConnector().getSqlWorker().getAllRSSUrls().thenAccept(getInstance().getNotifier()::registerRSS); + SQLSession.getSqlConnector().getSqlWorker().getAllRSSUrls().subscribe(getInstance().getNotifier()::registerRSS); } catch (Exception exception) { log.error("Error while loading RSS data: {}", exception.getMessage()); Sentry.captureException(exception); @@ -587,7 +587,7 @@ public void createCheckerThread() { log.info("[Stats] "); LocalDate yesterday = LocalDate.now().minusDays(1); - SQLSession.getSqlConnector().getSqlWorker().getStatistics(yesterday.getDayOfMonth(), yesterday.getMonthValue(), yesterday.getYear()).thenAccept(statistics -> { + SQLSession.getSqlConnector().getSqlWorker().getStatistics(yesterday.getDayOfMonth(), yesterday.getMonthValue(), yesterday.getYear()).subscribe(statistics -> { JsonObject jsonObject = statistics != null ? statistics.getStatsObject() : new JsonObject(); JsonObject guildStats = statistics != null && jsonObject.has("guild") ? jsonObject.getAsJsonObject("guild") : new JsonObject(); @@ -600,7 +600,7 @@ public void createCheckerThread() { }); SQLSession.getSqlConnector().getSqlWorker() - .getBirthdays().thenAccept(birthdayWishes -> { + .getBirthdays().subscribe(birthdayWishes -> { Calendar currentCalendar = Calendar.getInstance(); birthdayWishes.stream().filter(birthday -> { @@ -612,7 +612,7 @@ public void createCheckerThread() { TextChannel textChannel = BotWorker.getShardManager().getTextChannelById(birthday.getChannelId()); if (textChannel != null && textChannel.canTalk()) - textChannel.sendMessage(LanguageService.getByGuild(textChannel.getGuild(), "message.birthday.wish", birthday.getUserId()).join()).queue(); + textChannel.sendMessage(LanguageService.getByGuild(textChannel.getGuild(), "message.birthday.wish", birthday.getUserId()).block()).queue(); }); }); @@ -645,7 +645,7 @@ public void createCheckerThread() { //region Schedules Message sending. try { - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ScheduledMessage(), "FROM ScheduledMessage", null).thenAccept(messages -> { + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ScheduledMessage(), "FROM ScheduledMessage", null).subscribe(messages -> { for (ScheduledMessage scheduledMessage : messages) { if (!scheduledMessage.isRepeated()) { if (scheduledMessage.getLastExecute() == null) { @@ -671,7 +671,7 @@ public void createCheckerThread() { .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); scheduledMessage.setLastExecute(Timestamp.from(Instant.now())); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage).block(); } } else { if (Timestamp.from(Instant.now()).after(Timestamp.from(scheduledMessage.getLastUpdated().toInstant().plusMillis(scheduledMessage.getDelayAmount())))) { @@ -682,7 +682,7 @@ public void createCheckerThread() { .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); scheduledMessage.setLastExecute(Timestamp.from(Instant.now())); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage).block(); } } } @@ -739,13 +739,13 @@ public void createCheckerThread() { MessageEditBuilder messageEditBuilder = MessageEditBuilder.fromMessage(message); reaction.retrieveUsers().mapToResult().onErrorMap(throwable -> { - messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.error").join()); + messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.error").block()); message.editMessage(messageEditBuilder.build()).queue(); toDelete.add(giveaway); return null; }).queue(users -> { if (users == null) { - messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.less").join()); + messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.less").block()); message.editMessage(messageEditBuilder.build()).queue(); return; } @@ -753,13 +753,13 @@ public void createCheckerThread() { users.onSuccess(userList -> { if (userList.isEmpty()) { - messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.none").join()); + messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.none").block()); message.editMessage(messageEditBuilder.build()).queue(); return; } if (userList.stream().filter(user -> !user.isBot()).count() < giveaway.getWinners()) { - messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.less").join()); + messageEditBuilder.setContent(LanguageService.getByGuild(guild, "message.giveaway.reaction.less").block()); message.editMessage(messageEditBuilder.build()).queue(); return; } @@ -788,7 +788,7 @@ public void createCheckerThread() { if (BotConfig.isModuleActive("notifier")) Main.getInstance().getNotifier().getCredentialManager().load(); - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), "FROM TwitchIntegration", null).thenAccept(integrations -> { + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), "FROM TwitchIntegration", null).subscribe(integrations -> { for (TwitchIntegration twitchIntegrations : integrations) { CustomOAuth2Credential credential = CustomOAuth2Util.convert(twitchIntegrations); diff --git a/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java b/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java index 166e3971a..e820be850 100644 --- a/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java +++ b/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java @@ -37,7 +37,7 @@ public GiveawayManager() { public void load() { SQLSession.getSqlConnector().getSqlWorker() .getEntityList(new Giveaway(), "FROM Giveaway", null) - .thenAccept(this::replace); + .subscribe(this::replace); } /** @@ -59,13 +59,13 @@ public Giveaway get(long value) { } } - return SQLSession.getSqlConnector().getSqlWorker().getEntity(new Giveaway(), "FROM Giveaway WHERE messageId = :id", Map.of("id", value)).thenApply(giveaway -> { + return SQLSession.getSqlConnector().getSqlWorker().getEntity(new Giveaway(), "FROM Giveaway WHERE messageId = :id", Map.of("id", value)).map(giveaway -> { if (giveaway != null) { giveaways.add(giveaway); return giveaway; } return null; - }).join(); + }).block(); } @Override diff --git a/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java b/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java index 85185b25e..42fa63b75 100644 --- a/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java +++ b/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java @@ -44,7 +44,7 @@ public List getInvites(long guildId) { @Override public void load() { SQLSession.getSqlConnector().getSqlWorker().getEntityList(new de.presti.ree6.sql.entities.Invite(), "FROM Invite", null) - .thenAccept(invites1 -> replace(invites1.stream().map(InviteContainer::new).toList())); + .subscribe(invites1 -> replace(invites1.stream().map(InviteContainer::new).toList())); } /** @@ -55,7 +55,7 @@ public void load() { public void refreshGuild(long guildId) { invites.removeIf(x -> x.guildId == guildId); SQLSession.getSqlConnector().getSqlWorker().getEntityList(new de.presti.ree6.sql.entities.Invite(), "FROM Invite WHERE guildAndCode.guildId = :gid", Map.of("gid", guildId)) - .thenAccept(invites1 -> replace(invites1.stream().map(InviteContainer::new).toList())); + .subscribe(invites1 -> replace(invites1.stream().map(InviteContainer::new).toList())); } /** @@ -82,7 +82,7 @@ public void add(InviteContainer inviteContainer) { getList().add(inviteContainer); try { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new de.presti.ree6.sql.entities.Invite(inviteContainer.getGuildId(), inviteContainer.getCreatorId(), inviteContainer.getUses(), inviteContainer.getCode())).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new de.presti.ree6.sql.entities.Invite(inviteContainer.getGuildId(), inviteContainer.getCreatorId(), inviteContainer.getUses(), inviteContainer.getCode())).block(); } catch (Exception ex) { log.error("[InviteManager] Error while Saving Invites: " + ex.getMessage()); } diff --git a/src/main/java/de/presti/ree6/utils/apis/ChatGPTAPI.java b/src/main/java/de/presti/ree6/utils/apis/ChatGPTAPI.java index f6b10da93..cfbd2a74b 100644 --- a/src/main/java/de/presti/ree6/utils/apis/ChatGPTAPI.java +++ b/src/main/java/de/presti/ree6/utils/apis/ChatGPTAPI.java @@ -79,7 +79,7 @@ public static String getResponse(Member member, String message) { response = getResponse(messages); } catch (BizException e) { Sentry.captureException(e); - return LanguageService.getByGuild(member.getGuild(), "message.default.retrievalError").join(); + return LanguageService.getByGuild(member.getGuild(), "message.default.retrievalError").block(); } messages.add(new Message("assistant", response)); diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index 48601930c..574c4e58a 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -184,7 +184,7 @@ public Notifier() { .withCredentialManager(credentialManager) .build(); - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), "FROM TwitchIntegration", null).thenAccept(twitchIntegrations -> { + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), "FROM TwitchIntegration", null).subscribe(twitchIntegrations -> { for (TwitchIntegration twitchIntegration : twitchIntegrations) { OAuth2Credential credential = new OAuth2Credential("twitch", twitchIntegration.getToken()); @@ -199,7 +199,7 @@ public Notifier() { }); twitchClient.getEventManager().onEvent(RewardRedeemedEvent.class, event -> { - StreamActionContainerCreator.getContainers(0).thenAccept(list -> { + StreamActionContainerCreator.getContainers(0).subscribe(list -> { list.forEach(container -> { if (!event.getRedemption().getChannelId().equalsIgnoreCase(container.getTwitchChannelId())) return; @@ -212,7 +212,7 @@ public Notifier() { }); twitchClient.getEventManager().onEvent(FollowEvent.class, event -> { - StreamActionContainerCreator.getContainers(1).thenAccept(list -> { + StreamActionContainerCreator.getContainers(1).subscribe(list -> { list.forEach(container -> { if (!event.getChannel().getId().equalsIgnoreCase(container.getTwitchChannelId())) return; @@ -222,7 +222,7 @@ public Notifier() { }); twitchClient.getEventManager().onEvent(ChannelSubscribeEvent.class, event -> { - StreamActionContainerCreator.getContainers(2).thenAccept(list -> { + StreamActionContainerCreator.getContainers(2).subscribe(list -> { list.forEach(container -> { if (!event.getBroadcasterUserId().equalsIgnoreCase(container.getTwitchChannelId())) return; @@ -305,7 +305,7 @@ public Notifier() { ThreadUtil.createThread(x -> { for (String twitterName : registeredTwitterUsers) { SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", Map.of("name", twitterName)).thenAccept(channelStats -> { + "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", Map.of("name", twitterName)).subscribe(channelStats -> { if (!channelStats.isEmpty()) { UserV2 twitterUser; try { @@ -321,7 +321,7 @@ public Notifier() { GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getTwitchFollowerChannelId()); if (guildChannel == null) continue; - LanguageService.getByGuild(guildChannel.getGuild(), "label.twitterCountName", twitterUser.getFollowersCount()).thenAccept(newName -> { + LanguageService.getByGuild(guildChannel.getGuild(), "label.twitterCountName", twitterUser.getFollowersCount()).subscribe(newName -> { if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) return; @@ -430,7 +430,7 @@ public void createRssStream() { if (typ.equals("tw")) { - SQLSession.getSqlConnector().getSqlWorker().getTwitterWebhooksByName(item.getChannel().getLink().replace("https://nitter.net/", "")).thenAccept(webhooks -> { + SQLSession.getSqlConnector().getSqlWorker().getTwitterWebhooksByName(item.getChannel().getLink().replace("https://nitter.net/", "")).subscribe(webhooks -> { if (webhooks.isEmpty()) return; @@ -480,7 +480,7 @@ public void createRssStream() { }); } else { try { - SQLSession.getSqlConnector().getSqlWorker().getRSSWebhooksByUrl(id).thenAccept(webhooks -> { + SQLSession.getSqlConnector().getSqlWorker().getRSSWebhooksByUrl(id).subscribe(webhooks -> { if (webhooks.isEmpty()) return; WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); @@ -534,7 +534,7 @@ public void createRssStream() { public void registerTwitchEventHandler() { getTwitchClient().getEventManager().onEvent(ChannelGoLiveEvent.class, channelGoLiveEvent -> { - SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(channelGoLiveEvent.getChannel().getName()).thenAccept(webhooks -> { + SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(channelGoLiveEvent.getChannel().getName()).subscribe(webhooks -> { if (webhooks.isEmpty()) { return; } @@ -582,7 +582,7 @@ public void registerTwitchEventHandler() { getTwitchClient().getEventManager().onEvent(ChannelFollowCountUpdateEvent.class, channelFollowCountUpdateEvent -> { SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), "FROM ChannelStats WHERE LOWER(twitchFollowerChannelUsername) = :name", - Map.of("name", channelFollowCountUpdateEvent.getChannel().getName().toLowerCase())).thenAccept(channelStats -> { + Map.of("name", channelFollowCountUpdateEvent.getChannel().getName().toLowerCase())).subscribe(channelStats -> { if (!channelStats.isEmpty()) { for (ChannelStats channelStat : channelStats) { if (channelStat.getTwitchFollowerChannelId() != null) { @@ -591,7 +591,7 @@ public void registerTwitchEventHandler() { if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) continue; - LanguageService.getByGuild(guildChannel.getGuild(), "label.twitchCountName", channelFollowCountUpdateEvent.getFollowCount()).thenAccept(newName -> { + LanguageService.getByGuild(guildChannel.getGuild(), "label.twitchCountName", channelFollowCountUpdateEvent.getFollowCount()).subscribe(newName -> { if (!guildChannel.getName().equalsIgnoreCase(newName)) { guildChannel.getManager().setName(newName).queue(); } @@ -650,11 +650,11 @@ public void unregisterTwitchChannel(String twitchChannel) { twitchChannel = twitchChannel.toLowerCase(); String finalTwitchChannel = twitchChannel; - SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(twitchChannel).thenAccept(webhooks -> { + SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(twitchChannel).subscribe(webhooks -> { if (!webhooks.isEmpty()) return; SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitchFollowerChannelUsername=:name", Map.of("name", finalTwitchChannel)) - .thenAccept(channelStats -> { + .subscribe(channelStats -> { if (channelStats != null) return; if (isTwitchRegistered(finalTwitchChannel)) @@ -715,10 +715,10 @@ public void unregisterTwitterUser(String twitterUser) { twitterUser = twitterUser.toLowerCase(); String finalTwitterUser = twitterUser; - SQLSession.getSqlConnector().getSqlWorker().getTwitterWebhooksByName(twitterUser).thenAccept(webhooks -> { + SQLSession.getSqlConnector().getSqlWorker().getTwitterWebhooksByName(twitterUser).subscribe(webhooks -> { if (!webhooks.isEmpty()) return; - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", Map.of("name", finalTwitterUser)).thenAccept(x -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", Map.of("name", finalTwitterUser)).subscribe(x -> { if (x != null) return; if (isTwitterRegistered(finalTwitterUser)) { @@ -748,7 +748,7 @@ public boolean isTwitterRegistered(String twitterUser) { public void createYTStream() { ThreadUtil.createThread(x -> { for (String channel : registeredYouTubeChannels) { - SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(channel).thenAccept(webhooks -> { + SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(channel).subscribe(webhooks -> { if (!webhooks.isEmpty()) { try { List playlistItemList = YouTubeAPIHandler.getInstance().getYouTubeUploads(channel); @@ -805,7 +805,7 @@ public void createYTStream() { }); SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", Map.of("name", channel)).thenAccept(channelStats -> { + "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", Map.of("name", channel)).subscribe(channelStats -> { if (!channelStats.isEmpty()) { ChannelResult youTubeChannel; try { @@ -824,7 +824,7 @@ public void createYTStream() { if (guildChannel == null) continue; - LanguageService.getByGuild(guildChannel.getGuild(), "label.youtubeCountName", youTubeChannel.getSubscriberCountText()).thenAccept(newName -> { + LanguageService.getByGuild(guildChannel.getGuild(), "label.youtubeCountName", youTubeChannel.getSubscriberCountText()).subscribe(newName -> { if (!guildChannel.getName().equalsIgnoreCase(newName)) { if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) return; @@ -876,10 +876,10 @@ public void registerYouTubeChannel(List youtubeChannels) { public void unregisterYouTubeChannel(String youtubeChannel) { if (YouTubeAPIHandler.getInstance() == null) return; - SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(youtubeChannel).thenAccept(webhooks -> { + SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(youtubeChannel).subscribe(webhooks -> { if (!webhooks.isEmpty()) return; - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", Map.of("name", youtubeChannel)).thenAccept(channelStats -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", Map.of("name", youtubeChannel)).subscribe(channelStats -> { if (channelStats != null) return; if (isYouTubeRegistered(youtubeChannel)) registeredYouTubeChannels.remove(youtubeChannel); @@ -922,7 +922,7 @@ public void createRedditPostStream() { try { for (String subreddit : registeredSubreddits) { SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", Map.of("name", subreddit)).thenAccept(channelStats -> { + "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", Map.of("name", subreddit)).subscribe(channelStats -> { if (!channelStats.isEmpty()) { RedditSubreddit subredditEntity; try { @@ -949,7 +949,7 @@ public void createRedditPostStream() { }); getSubredditPosts(subreddit, Sorting.NEW, 50).stream().filter(redditPost -> redditPost.getCreated() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())).forEach(redditPost -> { - SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit).thenAccept(webhooks -> { + SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit).subscribe(webhooks -> { if (webhooks.isEmpty()) return; // Create Webhook Message. @@ -1043,10 +1043,10 @@ public void registerSubreddit(List subreddits) { public void unregisterSubreddit(String subreddit) { if (getRedditClient() == null) return; - SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit).thenAccept(webhooks -> { + SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit).subscribe(webhooks -> { if (!webhooks.isEmpty()) return; - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", Map.of("name", subreddit)).thenAccept(channelStats -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", Map.of("name", subreddit)).subscribe(channelStats -> { if (channelStats != null) return; if (isSubredditRegistered(subreddit)) registeredSubreddits.remove(subreddit); @@ -1081,7 +1081,7 @@ public void createInstagramPostStream() { com.github.instagram4j.instagram4j.models.user.User user = userAction.getUser(); SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", Map.of("name", username)).thenAccept(channelStats -> { + "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", Map.of("name", username)).subscribe(channelStats -> { if (!channelStats.isEmpty()) { for (ChannelStats channelStat : channelStats) { if (channelStat.getInstagramFollowerChannelId() != null) { @@ -1089,7 +1089,7 @@ public void createInstagramPostStream() { if (guildChannel == null) continue; - LanguageService.getByGuild(guildChannel.getGuild(), "label.instagramCountName", user.getFollower_count()).thenAccept(newName -> { + LanguageService.getByGuild(guildChannel.getGuild(), "label.instagramCountName", user.getFollower_count()).subscribe(newName -> { if (!guildChannel.getName().equalsIgnoreCase(newName)) { if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) return; @@ -1102,7 +1102,7 @@ public void createInstagramPostStream() { } }); - SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(username).thenAccept(webhooks -> { + SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(username).subscribe(webhooks -> { if (webhooks.isEmpty()) return; if (!user.is_private()) { @@ -1190,7 +1190,7 @@ public void registerInstagramUser(List usernames) { public void unregisterInstagramUser(String username) { if (getInstagramClient() == null) return; - SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(username).thenAccept(webhooks -> { + SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(username).subscribe(webhooks -> { if (!webhooks.isEmpty()) return; if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", Map.of("name", username)) != null) @@ -1223,7 +1223,7 @@ public void createTikTokStream() { try { TikTokUser user = TikTokWrapper.getUser(id); - SQLSession.getSqlConnector().getSqlWorker().getTikTokWebhooksByName(user.getId()).thenAccept(webhooks -> { + SQLSession.getSqlConnector().getSqlWorker().getTikTokWebhooksByName(user.getId()).subscribe(webhooks -> { if (webhooks.isEmpty()) { return; } diff --git a/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java b/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java index 7750b429a..15c45b4b0 100644 --- a/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java +++ b/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java @@ -20,13 +20,13 @@ public class DatabaseStorageBackend implements IStorageBackend { @Override public List loadCredentials() { return SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), - "FROM TwitchIntegration", null).thenApply(twitchIntegrations -> { + "FROM TwitchIntegration", null).map(twitchIntegrations -> { List credentials = new ArrayList<>(); twitchIntegrations.forEach(twitchIntegration -> credentials.add(new CustomOAuth2Credential(twitchIntegration.getUserId(),"twitch", twitchIntegration.getToken(), twitchIntegration.getRefresh(), twitchIntegration.getChannelId(), twitchIntegration.getName(), twitchIntegration.getExpiresIn(), Collections.emptyList()))); return credentials; - }).join(); + }).block(); } /** @@ -39,7 +39,7 @@ public void saveCredentials(List list) { list.forEach(credential -> { if (credential instanceof CustomOAuth2Credential oAuth2Credential) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), - "FROM TwitchIntegration WHERE channelId = :userid", Map.of("userid",oAuth2Credential.getUserId())).thenAccept(twitchIntegration -> { + "FROM TwitchIntegration WHERE channelId = :userid", Map.of("userid",oAuth2Credential.getUserId())).subscribe(twitchIntegration -> { if (twitchIntegration == null) { twitchIntegration = new TwitchIntegration(); twitchIntegration.setChannelId(oAuth2Credential.getUserId()); @@ -50,7 +50,7 @@ public void saveCredentials(List list) { twitchIntegration.setRefresh(oAuth2Credential.getRefreshToken()); twitchIntegration.setName(oAuth2Credential.getUserName()); twitchIntegration.setExpiresIn(oAuth2Credential.getExpiresIn()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(twitchIntegration).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(twitchIntegration).block(); }); } }); @@ -65,7 +65,7 @@ public void saveCredentials(List list) { @Override public Optional getCredentialByUserId(String userId) { Optional twitchIntegration = Optional.ofNullable(SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), - "FROM TwitchIntegration WHERE channelId = :userid", Map.of("userid", userId)).join()); + "FROM TwitchIntegration WHERE channelId = :userid", Map.of("userid", userId)).block()); if (twitchIntegration.isPresent()) { TwitchIntegration twitchIntegration1 = twitchIntegration.get(); diff --git a/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java b/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java index 09b62386a..6c7febea7 100644 --- a/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java +++ b/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java @@ -4,6 +4,7 @@ import de.presti.ree6.sql.entities.economy.MoneyHolder; import de.presti.ree6.sql.entities.economy.MoneyTransaction; import net.dv8tion.jda.api.entities.Member; +import reactor.core.publisher.Mono; import java.sql.Timestamp; import java.time.Instant; @@ -21,7 +22,7 @@ public class EconomyUtil { * @param member The Member. * @return If the MoneyHolder has any cash. */ - public static CompletableFuture hasCash(Member member) { + public static Mono hasCash(Member member) { return hasCash(member.getGuild().getIdLong(), member.getIdLong()); } @@ -32,8 +33,8 @@ public static CompletableFuture hasCash(Member member) { * @param memberId The ID of the Member. * @return If the MoneyHolder has any cash. */ - public static CompletableFuture hasCash(long guildId, long memberId) { - return getMoneyHolder(guildId, memberId).thenApply(EconomyUtil::hasCash); + public static Mono hasCash(long guildId, long memberId) { + return getMoneyHolder(guildId, memberId).map(EconomyUtil::hasCash); } /** @@ -52,7 +53,7 @@ public static boolean hasCash(MoneyHolder moneyHolder) { * @param member The Member. * @return The MoneyHolder. */ - public static CompletableFuture getMoneyHolder(Member member) { + public static Mono getMoneyHolder(Member member) { return getMoneyHolder(member.getGuild().getIdLong(), member.getIdLong()); } @@ -63,7 +64,7 @@ public static CompletableFuture getMoneyHolder(Member member) { * @param memberId The ID of the Member. * @return The MoneyHolder. */ - public static CompletableFuture getMoneyHolder(long guildId, long memberId) { + public static Mono getMoneyHolder(long guildId, long memberId) { return getMoneyHolder(guildId, memberId, true); } @@ -75,14 +76,14 @@ public static CompletableFuture getMoneyHolder(long guildId, long m * @param createIfNotExists If the MoneyHolder should be created if it does not exist. * @return The MoneyHolder. */ - public static CompletableFuture getMoneyHolder(long guildId, long memberId, boolean createIfNotExists) { + public static Mono getMoneyHolder(long guildId, long memberId, boolean createIfNotExists) { return SQLSession.getSqlConnector().getSqlWorker().getEntity(new MoneyHolder(), "FROM MoneyHolder WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", - Map.of("gid", guildId, "uid", memberId)).thenApply(moneyHolder -> { + Map.of("gid", guildId, "uid", memberId)).map(moneyHolder -> { if (moneyHolder == null && createIfNotExists) { moneyHolder = new MoneyHolder(); moneyHolder.setGuildId(guildId); moneyHolder.setUserId(memberId); - return SQLSession.getSqlConnector().getSqlWorker().updateEntity(moneyHolder).join(); + return SQLSession.getSqlConnector().getSqlWorker().updateEntity(moneyHolder).block(); } return moneyHolder; @@ -134,7 +135,7 @@ public static boolean set(MoneyHolder holder, double amount, boolean setBank) { holder.setAmount(amount); } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(holder).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(holder).block(); return true; } @@ -160,7 +161,7 @@ public static boolean pay(MoneyHolder sender, MoneyHolder receiver, double amoun receiver.setAmount(receiver.getAmount() + amount); } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(receiver).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(receiver).block(); if (!isSystem) { if (fromBank) { @@ -169,10 +170,10 @@ public static boolean pay(MoneyHolder sender, MoneyHolder receiver, double amoun sender.setAmount(sender.getAmount() - amount); } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(sender).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(sender).block(); } - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new MoneyTransaction(0L, isSystem, isSystem ? receiver.getGuildUserId().getGuildId() : sender.getGuildUserId().getGuildId(), isSystem && sender == null ? receiver : sender, receiver, toBank, fromBank, amount, Timestamp.from(Instant.now()))).join(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new MoneyTransaction(0L, isSystem, isSystem ? receiver.getGuildUserId().getGuildId() : sender.getGuildUserId().getGuildId(), isSystem && sender == null ? receiver : sender, receiver, toBank, fromBank, amount, Timestamp.from(Instant.now()))).block(); return true; } diff --git a/src/main/java/de/presti/ree6/utils/others/GuildUtil.java b/src/main/java/de/presti/ree6/utils/others/GuildUtil.java index 450dc5313..16cbe9e79 100644 --- a/src/main/java/de/presti/ree6/utils/others/GuildUtil.java +++ b/src/main/java/de/presti/ree6/utils/others/GuildUtil.java @@ -36,7 +36,7 @@ private GuildUtil() { */ public static void handleMemberJoin(Guild guild, Member member) { - SQLSession.getSqlConnector().getSqlWorker().isAutoRoleSetup(guild.getIdLong()).thenAccept(x -> { + SQLSession.getSqlConnector().getSqlWorker().isAutoRoleSetup(guild.getIdLong()).subscribe(x -> { if (!x) return; if (member.getIdLong() == guild.getOwnerIdLong()) return; @@ -47,14 +47,14 @@ public static void handleMemberJoin(Guild guild, Member member) { log.error("[AutoRole] Member: {} ({})", member.getUser().getName(), member.getId()); if (guild.getOwner() != null) - LanguageService.getByGuild(guild, "message.brs.autoRole.hierarchy", "@everyone").thenAccept(message -> + LanguageService.getByGuild(guild, "message.brs.autoRole.hierarchy", "@everyone").subscribe(message -> guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage(message) .queue())); return; } - SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(guild.getIdLong()).thenAccept(roles -> { + SQLSession.getSqlConnector().getSqlWorker().getAutoRoles(guild.getIdLong()).subscribe(roles -> { for (de.presti.ree6.sql.entities.roles.Role roleEntry : roles) { Role role = guild.getRoleById(roleEntry.getRoleId()); @@ -62,7 +62,7 @@ public static void handleMemberJoin(Guild guild, Member member) { if (guild.getOwner() != null) LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? "message.brs.autoRole.hierarchy" - : "message.brs.autoRole.missingPermission", role.getName()).thenAccept(message -> + : "message.brs.autoRole.missingPermission", role.getName()).subscribe(message -> guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage(message) .queue())); @@ -70,7 +70,7 @@ public static void handleMemberJoin(Guild guild, Member member) { } else if (role == null) { if (guild.getOwner() != null) guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - LanguageService.getByGuild(guild, "message.brs.autoRole.deleted").thenAccept(message -> + LanguageService.getByGuild(guild, "message.brs.autoRole.deleted").subscribe(message -> privateChannel.sendMessage(message) .queue())); @@ -92,12 +92,12 @@ public static void handleMemberJoin(Guild guild, Member member) { */ public static void handleVoiceLevelReward(Guild guild, Member member) { - SQLSession.getSqlConnector().getSqlWorker().isVoiceLevelRewardSetup(guild.getIdLong()).thenAccept(x -> { + SQLSession.getSqlConnector().getSqlWorker().isVoiceLevelRewardSetup(guild.getIdLong()).subscribe(x -> { if (!x) return; if (member.getIdLong() == guild.getOwnerIdLong()) return; - SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelData(guild.getIdLong(), member.getUser().getIdLong()).thenAccept(data -> { + SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelData(guild.getIdLong(), member.getUser().getIdLong()).subscribe(data -> { if (data == null) return; if (!guild.getSelfMember().canInteract(member)) { @@ -107,13 +107,13 @@ public static void handleVoiceLevelReward(Guild guild, Member member) { if (guild.getOwner() != null) guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - LanguageService.getByGuild(guild, "message.brs.autoRole.hierarchy", "@everyone").thenAccept(message -> + LanguageService.getByGuild(guild, "message.brs.autoRole.hierarchy", "@everyone").subscribe(message -> privateChannel.sendMessage(message).queue())); return; } - SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelRewards(guild.getIdLong()).thenAccept(roles -> { + SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelRewards(guild.getIdLong()).subscribe(roles -> { for (Map.Entry entry : roles.entrySet()) { if (entry.getKey() <= data.getLevel()) { @@ -125,13 +125,13 @@ public static void handleVoiceLevelReward(Guild guild, Member member) { guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? "message.brs.autoRole.hierarchy" - : "message.brs.autoRole.missingPermission", role.getName()).thenAccept(message -> + : "message.brs.autoRole.missingPermission", role.getName()).subscribe(message -> privateChannel.sendMessage(message).queue())); return; } else if (role == null) { if (guild.getOwner() != null) guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - LanguageService.getByGuild(guild, "message.brs.autoRole.deleted").thenAccept(message -> + LanguageService.getByGuild(guild, "message.brs.autoRole.deleted").subscribe(message -> privateChannel.sendMessage(message).queue())); SQLSession.getSqlConnector().getSqlWorker().removeAutoRole(guild.getIdLong(), entry.getValue()); @@ -154,12 +154,12 @@ public static void handleVoiceLevelReward(Guild guild, Member member) { */ public static void handleChatLevelReward(Guild guild, Member member) { - SQLSession.getSqlConnector().getSqlWorker().isChatLevelRewardSetup(guild.getIdLong()).thenAccept(x -> { + SQLSession.getSqlConnector().getSqlWorker().isChatLevelRewardSetup(guild.getIdLong()).subscribe(x -> { if (!x) return; if (member.getIdLong() == guild.getOwnerIdLong()) return; - SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(guild.getIdLong(), member.getUser().getIdLong()).thenAccept(data -> { + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(guild.getIdLong(), member.getUser().getIdLong()).subscribe(data -> { if (data == null) return; if (!guild.getSelfMember().canInteract(member)) { @@ -170,11 +170,11 @@ public static void handleChatLevelReward(Guild guild, Member member) { if (guild.getOwner() != null) guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> LanguageService.getByGuild(guild, "message.brs.autoRole.hierarchy", "@everyone") - .thenAccept(message -> privateChannel.sendMessage(message).queue())); + .subscribe(message -> privateChannel.sendMessage(message).queue())); return; } - SQLSession.getSqlConnector().getSqlWorker().getChatLevelRewards(guild.getIdLong()).thenAccept(roles -> { + SQLSession.getSqlConnector().getSqlWorker().getChatLevelRewards(guild.getIdLong()).subscribe(roles -> { for (Map.Entry entry : roles.entrySet()) { if (entry.getKey() <= data.getLevel()) { @@ -185,12 +185,12 @@ public static void handleChatLevelReward(Guild guild, Member member) { guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? "message.brs.autoRole.hierarchy" - : "message.brs.autoRole.missingPermission", role.getName()).thenAccept(message -> + : "message.brs.autoRole.missingPermission", role.getName()).subscribe(message -> privateChannel.sendMessage(message).queue())); } else if (role == null) { if (guild.getOwner() != null) guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - LanguageService.getByGuild(guild, "message.brs.autoRole.deleted").thenAccept(message -> + LanguageService.getByGuild(guild, "message.brs.autoRole.deleted").subscribe(message -> privateChannel.sendMessage(message).queue())); SQLSession.getSqlConnector().getSqlWorker().removeAutoRole(guild.getIdLong(), entry.getValue()); @@ -224,7 +224,7 @@ private static void addRole(Guild guild, Member member, Role role) { guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? "message.brs.autoRole.hierarchy" - : "message.brs.autoRole.missingPermission", role.getName()).thenAccept(message -> + : "message.brs.autoRole.missingPermission", role.getName()).subscribe(message -> privateChannel.sendMessage(message).queue())); } } diff --git a/src/main/java/de/presti/ree6/utils/others/ModerationUtil.java b/src/main/java/de/presti/ree6/utils/others/ModerationUtil.java index 9c0c003ce..7b7e908dc 100644 --- a/src/main/java/de/presti/ree6/utils/others/ModerationUtil.java +++ b/src/main/java/de/presti/ree6/utils/others/ModerationUtil.java @@ -2,6 +2,7 @@ import de.presti.ree6.sql.SQLSession; import de.presti.ree6.bot.BotConfig; +import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.Arrays; @@ -29,7 +30,7 @@ private ModerationUtil() { * @param guildId the ID of the Guild. * @return an {@link ArrayList} with every Blacklisted word from the Guild. */ - public static CompletableFuture> getBlacklist(long guildId) { + public static Mono> getBlacklist(long guildId) { return SQLSession.getSqlConnector().getSqlWorker().getChatProtectorWords(guildId); } @@ -40,8 +41,8 @@ public static CompletableFuture> getBlacklist(long guildId) { * @param message the Message-Content. * @return true, if there is a blacklisted for contained. */ - public static CompletableFuture checkMessage(long guildId, String message) { - return getBlacklist(guildId).thenApply(blacklist -> + public static Mono checkMessage(long guildId, String message) { + return getBlacklist(guildId).map(blacklist -> Arrays.stream(message.toLowerCase().split(" ")).anyMatch(blacklist::contains)); } @@ -50,9 +51,9 @@ public static CompletableFuture checkMessage(long guildId, String messa * * @param guildId the ID of the Guild. * @param word the word to check. - * @return true, if there is a blacklisted for contained. + * @return true, if the word is in the blacklist. */ - public static CompletableFuture checkBlacklist(long guildId, String word) { + public static Mono checkBlacklist(long guildId, String word) { return SQLSession.getSqlConnector().getSqlWorker().isChatProtectorSetup(guildId, word); } @@ -62,8 +63,9 @@ public static CompletableFuture checkBlacklist(long guildId, String wor * @param guildId the ID of the Guild. * @return true, if the Server should be moderated. */ - public static CompletableFuture shouldModerate(long guildId) { - return SQLSession.getSqlConnector().getSqlWorker().isChatProtectorSetup(guildId).thenApply(x -> x && BotConfig.isModuleActive("moderation")); + public static Mono shouldModerate(long guildId) { + if (!BotConfig.isModuleActive("moderation")) return Mono.just(false); + return SQLSession.getSqlConnector().getSqlWorker().isChatProtectorSetup(guildId); } /** @@ -73,7 +75,7 @@ public static CompletableFuture shouldModerate(long guildId) { * @param word the Word you want to blacklist. */ public static void blacklist(long guildId, String word) { - checkBlacklist(guildId, word).thenAccept(x -> { + checkBlacklist(guildId, word).subscribe(x -> { if (x) return; SQLSession.getSqlConnector().getSqlWorker().addChatProtectorWord(guildId, word); }); From 946a606659ab18027c4e2b2f87c1ff2fd7f0aa62 Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 5 Jul 2024 14:20:08 +0200 Subject: [PATCH 21/94] Fixing more stuff. --- pom.xml | 2 +- .../presti/ree6/commands/CommandManager.java | 152 +++++++------ .../commands/impl/community/Schedule.java | 7 +- .../impl/community/StreamActionCommand.java | 24 +- .../ree6/commands/impl/community/Ticket.java | 24 +- .../ree6/commands/impl/economy/Steal.java | 2 +- .../presti/ree6/commands/impl/info/Help.java | 4 +- .../presti/ree6/commands/impl/mod/Setup.java | 8 +- .../ree6/commands/interfaces/ICommand.java | 38 +++- .../de/presti/ree6/events/LoggingEvents.java | 24 +- .../de/presti/ree6/events/MenuEvents.java | 53 ++--- .../de/presti/ree6/events/OtherEvents.java | 209 +++++++++--------- .../presti/ree6/language/LanguageService.java | 9 +- src/main/java/de/presti/ree6/main/Main.java | 8 +- 14 files changed, 321 insertions(+), 243 deletions(-) diff --git a/pom.xml b/pom.xml index a6a4853f2..841679b15 100644 --- a/pom.xml +++ b/pom.xml @@ -177,7 +177,7 @@ de.ree6 Ree6-SQL - 68d594a700 + 71a8aa6a9a diff --git a/src/main/java/de/presti/ree6/commands/CommandManager.java b/src/main/java/de/presti/ree6/commands/CommandManager.java index 0b8dfb1fe..c36fe7fb9 100644 --- a/src/main/java/de/presti/ree6/commands/CommandManager.java +++ b/src/main/java/de/presti/ree6/commands/CommandManager.java @@ -40,11 +40,11 @@ import net.dv8tion.jda.internal.interactions.CommandDataImpl; import org.reflections.Reflections; import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; import java.lang.reflect.InvocationTargetException; import java.time.Duration; import java.util.*; -import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; /** @@ -222,11 +222,11 @@ public void addSlashCommand(JDA jda) { String localizedDescription = LanguageService.getByLocale(discordLocale, commandAnnotation.description()).block(); - if (localizedDescription.equals("Missing language resource!")) { + if (localizedDescription != null && localizedDescription.equals("Missing language resource!")) { localizedDescription = LanguageService.getDefault(commandAnnotation.description()).block(); } - if (!localizedDescription.equals("Missing language resource!")) { + if (localizedDescription != null && !localizedDescription.equals("Missing language resource!")) { commandData1.setDescriptionLocalization(discordLocale, localizedDescription); } @@ -236,7 +236,7 @@ public void addSlashCommand(JDA jda) { if (isValidDescription) { String localizedDescription = LanguageService.getDefault(commandAnnotation.description()).block(); - if (!localizedDescription.equals("Missing language resource!")) { + if (localizedDescription != null && !localizedDescription.equals("Missing language resource!")) { commandData1.setDescription(localizedDescription); } } @@ -272,26 +272,28 @@ public void translateSubgroups(SubcommandGroupData subcommandGroupData, DiscordL if (groupDescription.matches(RegExUtil.ALLOWED_LANGUAGE_PATHS)) { groupDescription = LanguageService.getByLocale(locale, groupDescription).block(); - if (groupDescription.equals("Missing language resource!")) { - groupDescription = LanguageService.getDefault(subcommandGroupData.getDescription()).block(); - } + if (groupDescription != null) { + if (groupDescription.equals("Missing language resource!")) { + groupDescription = LanguageService.getDefault(subcommandGroupData.getDescription()).block(); + } - if (!groupDescription.equals("Missing language resource!")) { - subcommandGroupData.setDescriptionLocalization(locale, groupDescription); + if (groupDescription != null && !groupDescription.equals("Missing language resource!")) { + subcommandGroupData.setDescriptionLocalization(locale, groupDescription); + } } } for (SubcommandData subcommandData : subcommandGroupData.getSubcommands()) { String commandDescription = subcommandData.getDescription(); - if (groupDescription.matches(RegExUtil.ALLOWED_LANGUAGE_PATHS)) { + if (groupDescription != null && groupDescription.matches(RegExUtil.ALLOWED_LANGUAGE_PATHS)) { commandDescription = LanguageService.getByLocale(locale, commandDescription).block(); - if (commandDescription.equals("Missing language resource!")) { + if (commandDescription != null && commandDescription.equals("Missing language resource!")) { commandDescription = LanguageService.getDefault(subcommandData.getDescription()).block(); } - if (!commandDescription.equals("Missing language resource!")) { + if (commandDescription != null && !commandDescription.equals("Missing language resource!")) { subcommandData.setDescriptionLocalization(locale, commandDescription); } } @@ -328,7 +330,8 @@ public void addCommand(ICommand command) throws CommandInitializerException { * @return the {@link ICommand} with the same Name. */ public ICommand getCommandByName(String name) { - return getCommands().stream().filter(command -> command.getClass().getAnnotation(Command.class).name().equalsIgnoreCase(name) || Arrays.stream(command.getAlias()).anyMatch(s -> s.equalsIgnoreCase(name))).findFirst().orElse(null); + return getCommands().stream().filter(command -> command.getClass().getAnnotation(Command.class).name().equalsIgnoreCase(name) || + Arrays.stream(command.getAlias()).anyMatch(s -> s.equalsIgnoreCase(name))).findFirst().orElse(null); } @@ -339,7 +342,8 @@ public ICommand getCommandByName(String name) { * @return the {@link ICommand} with the same Name. */ public ICommand getCommandBySlashName(String name) { - return getCommands().stream().filter(command -> (command.getCommandData() != null && command.getCommandData().getName().equalsIgnoreCase(name)) || (command.getClass().isAnnotationPresent(Command.class) && command.getClass().getAnnotation(Command.class).name().equalsIgnoreCase(name))).findFirst().orElse(null); + return getCommands().stream().filter(command -> (command.getCommandData() != null && command.getCommandData().getName().equalsIgnoreCase(name)) || + (command.getClass().isAnnotationPresent(Command.class) && command.getClass().getAnnotation(Command.class).name().equalsIgnoreCase(name))).findFirst().orElse(null); } /** @@ -365,25 +369,32 @@ public void removeCommand(ICommand command) { */ public Mono perform(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion messageChannel, SlashCommandInteractionEvent slashCommandInteractionEvent) { boolean isSlashCommand = slashCommandInteractionEvent != null; + log.info("Called perform"); // Check if the User is under Cooldown. if (isTimeout(member.getUser())) { // Check if it is a Slash Command or not. if (isSlashCommand) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.cooldown").block(), 5, messageChannel, slashCommandInteractionEvent.getHook().setEphemeral(true)); - deleteMessage(message, slashCommandInteractionEvent.getHook().setEphemeral(true)); + return LanguageService.getByGuild(guild, "command.perform.cooldown").map(messageCreateData -> { + slashCommandInteractionEvent.getHook().sendMessage(messageCreateData).queue(); + deleteMessage(message, slashCommandInteractionEvent.getHook().setEphemeral(true)); + return false; + }); } else { - SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").subscribe(setting -> { - if (setting != null && messageContent.toLowerCase().startsWith(setting.getStringValue().toLowerCase())) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.cooldown").block(), 5, messageChannel, null); - deleteMessage(message, null); + return SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").publishOn(Schedulers.boundedElastic()).mapNotNull(setting -> { + if (setting.isPresent() && messageContent.toLowerCase().startsWith(setting.get().getStringValue().toLowerCase())) { + final Mono booleanMono = LanguageService.getByGuild(guild, "command.perform.cooldown").map(translation -> { + sendMessage(String.valueOf(translation), 5, messageChannel, null); + deleteMessage(message, null); + return false; + }).thenReturn(false); + return booleanMono.block(); } + + return false; }); } - - // Return false. - return Mono.just(false); } // Check if it is a Slash Command. @@ -425,9 +436,13 @@ private Mono performMessageCommand(Member member, Guild guild, String m return Mono.just(false); } - return SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").map(setting -> { + log.info("Called performMessageCommand"); + + return SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").publishOn(Schedulers.boundedElastic()).mapNotNull(setting -> { - String currentPrefix = setting.getStringValue().toLowerCase(); + log.info("Got to prefix check."); + + String currentPrefix = setting.orElseGet(() -> new Setting(-1, "chatprefix", "Chat Prefix", BotConfig.getDefaultPrefix())).getStringValue(); // Check if the message starts with the prefix. if (!messageContent.toLowerCase().startsWith(currentPrefix)) @@ -437,59 +452,71 @@ private Mono performMessageCommand(Member member, Guild guild, String m String[] arguments = messageContent.substring(currentPrefix.length()).split("\\s+"); if (arguments.length == 0 || arguments[0].isBlank()) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.missingCommand").block(), 5, textChannel, null); - return false; + return LanguageService.getByGuild(guild, "command.perform.missingCommand").map(translated -> { + sendMessage(translated, 5, textChannel, null); + return false; + }).block(); } + log.info("Passed parsing."); + // Get the Command by the name. ICommand command = getCommandByName(arguments[0]); // Check if there is even a Command with that name. if (command == null && BotConfig.isModuleActive("customcommands")) { - CustomCommand customCommand = SQLSession.getSqlConnector().getSqlWorker().getEntity(new CustomCommand(), "FROM CustomCommand WHERE guildId=:gid AND name=:command", Map.of("gid", guild.getIdLong(), "command", arguments[0].toLowerCase())).block(); - if (customCommand != null) { - GuildMessageChannelUnion messageChannelUnion = textChannel; - - if (customCommand.getChannelId() != -1) { - messageChannelUnion = guild.getChannelById(GuildMessageChannelUnion.class, customCommand.getChannelId()); - } - - if (customCommand.getMessageResponse() != null) { - sendMessage(customCommand.getMessageResponse(), 5, messageChannelUnion, null); - } - - if (customCommand.getEmbedResponse() != null) { - EmbedBuilder embedBuilder = EmbedBuilder.fromData(DataObject.fromJson(customCommand.getEmbedResponse().toString())); - sendMessage(embedBuilder, 5, messageChannelUnion, null); - } - - return true; - } - - sendMessage(LanguageService.getByGuild(guild, "command.perform.notFound").block(), 5, textChannel, null); - return false; + return SQLSession.getSqlConnector().getSqlWorker().getEntity(new CustomCommand(), "FROM CustomCommand WHERE guildId=:gid AND name=:command", Map.of("gid", guild.getIdLong(), "command", arguments[0].toLowerCase())) + .flatMap(customCommand -> { + if (customCommand.isPresent()) { + GuildMessageChannelUnion messageChannelUnion = textChannel; + CustomCommand customCommandEntity = customCommand.get(); + if (customCommandEntity.getChannelId() != -1) { + messageChannelUnion = guild.getChannelById(GuildMessageChannelUnion.class, customCommandEntity.getChannelId()); + } + + if (customCommandEntity.getMessageResponse() != null) { + sendMessage(customCommandEntity.getMessageResponse(), 5, messageChannelUnion, null); + } + + if (customCommandEntity.getEmbedResponse() != null) { + EmbedBuilder embedBuilder = EmbedBuilder.fromData(DataObject.fromJson(customCommandEntity.getEmbedResponse().toString())); + sendMessage(embedBuilder, 5, messageChannelUnion, null); + } + + return Mono.just(true); + } + + return Mono.just(false); + }).block(); } else if (command == null) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.notFound").block(), 5, textChannel, null); - return false; + return LanguageService.getByGuild(guild, "command.perform.notFound").map(translated -> { + sendMessage(translated, 5, textChannel, null); + return false; + }).block(); } + log.info("Finished custom command."); + if (command.getClass().getAnnotation(Command.class).category() != Category.HIDDEN) { - Setting blacklistSetting = SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()).block(); + Optional blacklist = SQLSession.getSqlConnector().getSqlWorker() + .getSetting(guild.getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()).block(); // Check if the Command is blacklisted. - if (blacklistSetting != null && !blacklistSetting.getBooleanValue()) { - sendMessage(LanguageService.getByGuild(guild, "command.perform.blocked").block(), 5, textChannel, null); - return false; + if (blacklist != null && blacklist.isPresent() && !blacklist.get().getBooleanValue()) { + return LanguageService.getByGuild(guild, "command.perform.blocked").map(translated -> { + sendMessage(translated, 5, textChannel, null); + return false; + }).block(); } } + log.info("Finished blacklist."); + // Parse the arguments. String[] argumentsParsed = Arrays.copyOfRange(arguments, 1, arguments.length); // Perform the Command. - command.onASyncPerform(new CommandEvent(command.getClass().getAnnotation(Command.class).name(), member, guild, message, textChannel, argumentsParsed, null)); - - return true; + return command.onMonoPerform(new CommandEvent(command.getClass().getAnnotation(Command.class).name(), member, guild, message, textChannel, argumentsParsed, null)).block(); }); } @@ -510,15 +537,16 @@ private Mono performSlashCommand(GuildMessageChannelUnion messageChanne return Mono.just(false); } - return SQLSession.getSqlConnector().getSqlWorker().getSetting(slashCommandInteractionEvent.getGuild().getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()).map(setting -> { - if (command.getClass().getAnnotation(Command.class).category() != Category.HIDDEN && setting != null && !setting.getBooleanValue()) { + return SQLSession.getSqlConnector().getSqlWorker().getSetting(slashCommandInteractionEvent.getGuild().getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()).publishOn(Schedulers.boundedElastic()).mapNotNull(setting -> { + if (command.getClass().getAnnotation(Command.class).category() != Category.HIDDEN && setting.isPresent() && !setting.get().getBooleanValue()) { sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.blocked").block(), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); return false; } + CommandEvent commandEvent = new CommandEvent(command.getClass().getAnnotation(Command.class).name(), slashCommandInteractionEvent.getMember(), slashCommandInteractionEvent.getGuild(), null, messageChannel, null, slashCommandInteractionEvent); + // Perform the Command. - command.onASyncPerform(new CommandEvent(command.getClass().getAnnotation(Command.class).name(), slashCommandInteractionEvent.getMember(), slashCommandInteractionEvent.getGuild(), null, messageChannel, null, slashCommandInteractionEvent)); - return true; + return command.onMonoPerform(commandEvent).block(); }); } diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java b/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java index dfb39815b..948e5de9e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java @@ -114,14 +114,15 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookScheduledMessage(), "FROM WebhookScheduledMessage WHERE guildAndId.guildId = :gid AND channelId = :channel", Map.of("gid", commandEvent.getGuild().getId(), "channel", guildChannel.getIdLong())).subscribe(webhookScheduledMessage -> { - if (webhookScheduledMessage == null) { + WebhookScheduledMessage webhookScheduledMessageEntity = webhookScheduledMessage.orElse(new WebhookScheduledMessage()); + if (webhookScheduledMessage.isEmpty()) { Webhook webhook = guildChannel.asStandardGuildMessageChannel().createWebhook(BotConfig.getBotName() + "-Schedule").complete(); - webhookScheduledMessage = SQLSession.getSqlConnector().getSqlWorker() + webhookScheduledMessageEntity = SQLSession.getSqlConnector().getSqlWorker() .updateEntity(new WebhookScheduledMessage(commandEvent.getGuild().getIdLong(), guildChannel.getIdLong(), webhook.getIdLong(), webhook.getToken())).block(); } - scheduledMessage.setScheduledMessageWebhook(webhookScheduledMessage); + scheduledMessage.setScheduledMessageWebhook(webhookScheduledMessageEntity); scheduledMessage.setDelayAmount(finalFullTime); scheduledMessage.setRepeated(shouldRepeat); SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage).subscribe(x -> commandEvent.reply(commandEvent.getResource("message.schedule.added"))); diff --git a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java index 3a125db59..f22d0aa35 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java @@ -61,8 +61,9 @@ public void onPerform(CommandEvent commandEvent) { switch (subCommandGroup) { case "manage" -> - SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.name = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).subscribe(streamAction -> { - if (streamAction != null) { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.name = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).subscribe(streamActionOptional -> { + if (streamActionOptional.isPresent()) { + StreamAction streamAction = streamActionOptional.get(); switch (subCommand) { case "create" -> { OptionMapping action = commandEvent.getOption("action"); @@ -154,13 +155,13 @@ public void onPerform(CommandEvent commandEvent) { switch (subCommand) { case "create" -> - SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.actionName = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).subscribe(streamAction -> { - if (streamAction == null) { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.actionName = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).subscribe(streamActionOptional -> { + if (streamActionOptional.isEmpty()) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())) - .subscribe(twitchIntegration -> { - if (twitchIntegration != null) { + .subscribe(twitchIntegrationOptional -> { + if (twitchIntegrationOptional.isPresent()) { StreamAction newStreamAction = new StreamAction(); - newStreamAction.setIntegration(twitchIntegration); + newStreamAction.setIntegration(twitchIntegrationOptional.get()); newStreamAction.setGuildId(commandEvent.getGuild().getIdLong()); newStreamAction.setName(name.getAsString()); @@ -177,8 +178,8 @@ public void onPerform(CommandEvent commandEvent) { case "delete" -> SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.actionName = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).subscribe(streamAction -> { - if (streamAction != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(streamAction); + if (streamAction.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(streamAction.get()).block(); commandEvent.reply(commandEvent.getResource("message.stream-action.deleted", name.getAsString())); } else { commandEvent.reply(commandEvent.getResource("message.stream-action.notFound", name.getAsString())); @@ -191,8 +192,9 @@ public void onPerform(CommandEvent commandEvent) { }); case "points" -> - SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())).subscribe(twitchIntegration -> { - if (twitchIntegration != null) { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())).subscribe(twitchIntegrationOptional -> { + if (twitchIntegrationOptional.isPresent()) { + TwitchIntegration twitchIntegration = twitchIntegrationOptional.get(); StringBuilder stringBuilder = new StringBuilder(); Main.getInstance().getNotifier().getTwitchClient().getHelix().getCustomRewards(twitchIntegration.getToken(), twitchIntegration.getChannelId(), null, false).execute().getRewards().forEach(c -> stringBuilder.append(c.getId()).append(" - ").append(c.getTitle()).append("\n")); MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java b/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java index 7b10544dd..b7d6fe8ea 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java @@ -61,30 +61,26 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", commandEvent.getGuild().getId())).subscribe(tickets -> { - if (tickets != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(tickets); - } + tickets.ifPresent(value -> SQLSession.getSqlConnector().getSqlWorker().deleteEntity(value).block()); StandardGuildMessageChannel channel = logChannel.getAsChannel().asStandardGuildMessageChannel(); - tickets = new Tickets(); - tickets.setChannelId(ticketChannel.getAsChannel().getIdLong()); - tickets.setGuildId(commandEvent.getGuild().getIdLong()); - tickets.setLogChannelId(logChannel.getAsChannel().getIdLong()); - - Tickets finalTickets = tickets; + Tickets ticketEntity = new Tickets(); + ticketEntity.setChannelId(ticketChannel.getAsChannel().getIdLong()); + ticketEntity.setGuildId(commandEvent.getGuild().getIdLong()); + ticketEntity.setLogChannelId(logChannel.getAsChannel().getIdLong()); channel.createWebhook("Ticket-Log").queue(webhook -> { - finalTickets.setLogChannelWebhookId(webhook.getIdLong()); - finalTickets.setLogChannelWebhookToken(webhook.getToken()); + ticketEntity.setLogChannelWebhookId(webhook.getIdLong()); + ticketEntity.setLogChannelWebhookToken(webhook.getToken()); commandEvent.getGuild().createCategory("Tickets").addPermissionOverride(commandEvent.getGuild().getPublicRole(), null, EnumSet.of(Permission.VIEW_CHANNEL)).queue(category1 -> { - finalTickets.setTicketCategory(category1.getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(finalTickets).block(); + ticketEntity.setTicketCategory(category1.getIdLong()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(ticketEntity).block(); MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); messageCreateBuilder.setEmbeds(new EmbedBuilder() .setTitle(LanguageService.getByGuild(commandEvent.getGuild(), "label.openTicket").block()) - .setDescription(SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_ticket_menu").block().getStringValue()) + .setDescription(SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_ticket_menu").block().get().getStringValue()) .setColor(0x55ff00) .setThumbnail(commandEvent.getGuild().getIconUrl()) .setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java b/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java index e5181243c..a40a62e99 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java @@ -44,7 +44,7 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_steal_delay")).subscribe(value -> { - long delay = Long.parseLong(value.getStringValue()); + long delay = Long.parseLong(value.get().getStringValue()); if (stealTimeout.contains(entryString)) { commandEvent.reply(commandEvent.getResource("message.steal.cooldown", delay)); diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Help.java b/src/main/java/de/presti/ree6/commands/impl/info/Help.java index d2be9f245..5355e856e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Help.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Help.java @@ -85,7 +85,7 @@ public void sendHelpInformation(String categoryString, CommandEvent commandEvent if (!BotConfig.isModuleActive(cat.name().toLowerCase())) continue; String formattedName = cat.name().toUpperCase().charAt(0) + cat.name().substring(1).toLowerCase(); - em.addField("**" + formattedName + "**", setting.getStringValue() + "help " + cat.name().toLowerCase(), true); + em.addField("**" + formattedName + "**", setting.get().getStringValue() + "help " + cat.name().toLowerCase(), true); } } @@ -100,7 +100,7 @@ public void sendHelpInformation(String categoryString, CommandEvent commandEvent SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "chatprefix").subscribe(setting -> { for (ICommand cmd : Main.getInstance().getCommandManager().getCommands().stream().filter(command -> command.getClass().getAnnotation(Command.class).category() == category).toList()) { end.append("``") - .append(setting.getStringValue()) + .append(setting.get().getStringValue()) .append(cmd.getClass().getAnnotation(Command.class).name()) .append("``\n") .append(commandEvent.getResource(cmd.getClass().getAnnotation(Command.class).description())) diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java index 05cbe77b8..9fd575a2d 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java @@ -154,7 +154,7 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { if (aBoolean) { SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> { - WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), webhookEntity); + webhookEntity.ifPresent((entity) -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity)); }); } @@ -169,7 +169,7 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { if (aBoolean) { SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> { - WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), webhookEntity); + webhookEntity.ifPresent((entity) -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity)); commandEvent.reply(commandEvent.getResource("message.auditLog.deleted")); }); } else { @@ -190,7 +190,7 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { if (aBoolean) { SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> { - WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), webhookEntity); + webhookEntity.ifPresent((entity) -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity)); }); } SQLSession.getSqlConnector().getSqlWorker().setWelcomeWebhook(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong(), webhook.getIdLong(), webhook.getToken()); @@ -204,7 +204,7 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { if (aBoolean) { SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> - WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), webhookEntity)); + webhookEntity.ifPresent((entity) -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity))); commandEvent.reply(commandEvent.getResource("message.welcome.deleted")); } commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); diff --git a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java index d16db885d..ab8f85573 100644 --- a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java +++ b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java @@ -7,13 +7,16 @@ import de.presti.ree6.news.AnnouncementManager; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.bot.BotConfig; -import de.presti.ree6.utils.others.ThreadUtil; +import de.presti.ree6.sql.entities.Setting; import io.sentry.Sentry; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; +import java.util.Optional; import java.util.concurrent.CompletableFuture; /** @@ -26,6 +29,35 @@ public interface ICommand { */ Logger log = LoggerFactory.getLogger(ICommand.class); + default Mono onMonoPerform(CommandEvent commandEvent) { + return Mono.fromRunnable(() -> onPerform(commandEvent)).thenReturn(true).onErrorResume(throwable -> { + if (!throwable.getMessage().contains("Unknown Message")) { + commandEvent.reply(commandEvent.getResource("command.perform.internalError"), 5); + log.error("An error occurred while executing the command!", throwable); + Sentry.captureException(throwable); + } + return Mono.just(false); + }).publishOn(Schedulers.boundedElastic()).doOnSuccess(success -> { + if (success) { + // Update Stats. + SQLSession.getSqlConnector().getSqlWorker().addStats(commandEvent.getGuild().getIdLong(), commandEvent.getCommand()); + Optional setting = SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").block(); + if (setting.isEmpty() || !setting.get().getBooleanValue()) return; + AnnouncementManager.getAnnouncementList().forEach(a -> { + if (!AnnouncementManager.hasReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id())) { + Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder().setTitle(a.title()) + .setAuthor(BotConfig.getBotName() + "-Info") + .setDescription(a.content().replace("\\n", "\n") + "\n\n" + LanguageService.getByGuild(commandEvent.getGuild(), "message.news.notice").block()) + .setFooter(BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) + .setColor(BotWorker.randomEmbedColor()), 15, commandEvent.getChannel()); + + AnnouncementManager.addReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id()); + } + }); + } + }); + } + /** * Will be fired when the Command is called. * @@ -44,12 +76,12 @@ default void onASyncPerform(CommandEvent commandEvent) { // Update Stats. SQLSession.getSqlConnector().getSqlWorker().addStats(commandEvent.getGuild().getIdLong(), commandEvent.getCommand()); SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").subscribe(setting -> { - if (!setting.getBooleanValue()) return; + if (setting.isEmpty() || !setting.get().getBooleanValue()) return; AnnouncementManager.getAnnouncementList().forEach(a -> { if (!AnnouncementManager.hasReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id())) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder().setTitle(a.title()) .setAuthor(BotConfig.getBotName() + "-Info") - .setDescription(a.content().replace("\\n", "\n") + "\n\n" + LanguageService.getByGuild(commandEvent.getGuild(), "message.news.notice")) + .setDescription(a.content().replace("\\n", "\n") + "\n\n" + LanguageService.getByGuild(commandEvent.getGuild(), "message.news.notice").block()) .setFooter(BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) .setColor(BotWorker.randomEmbedColor()), 15, commandEvent.getChannel()); diff --git a/src/main/java/de/presti/ree6/events/LoggingEvents.java b/src/main/java/de/presti/ree6/events/LoggingEvents.java index e58e2a0bf..1ddc0f838 100644 --- a/src/main/java/de/presti/ree6/events/LoggingEvents.java +++ b/src/main/java/de/presti/ree6/events/LoggingEvents.java @@ -15,7 +15,6 @@ import de.presti.ree6.module.invite.InviteContainer; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Invite; -import de.presti.ree6.sql.entities.webhook.base.Webhook; import de.presti.ree6.utils.data.ArrayUtil; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.audit.ActionType; @@ -77,9 +76,12 @@ public void onGuildUpdateVanityCode(@NotNull GuildUpdateVanityCodeEvent event) { SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Invite(event.getGuild().getIdLong(), event.getGuild().getOwnerIdLong(), vanityInvite.getUses(), event.getNewVanityCode())).block()); } else { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Invite(), "FROM Invite WHERE guildAndCode.guildId = :gid AND guildAndCode.code = :code", - Map.of("gid", event.getGuild().getIdLong(), "code", event.getOldVanityCode())).subscribe(invite -> { - invite.setCode(event.getNewVanityCode()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(invite).block(); + Map.of("gid", event.getGuild().getIdLong(), "code", event.getOldVanityCode())).subscribe(inviteOptional -> { + if (inviteOptional.isPresent()) { + Invite invite = inviteOptional.get(); + invite.setCode(event.getNewVanityCode()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(invite).block(); + } }); } } @@ -93,7 +95,7 @@ public void onGuildBan(@Nonnull GuildBanEvent event) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberban").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -116,8 +118,8 @@ public void onGuildBan(@Nonnull GuildBanEvent event) { wm.addEmbeds(we.build()); - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(x -> { - Main.getInstance().getLoggerQueue().add(new LogMessageUser(x.getWebhookId(), x.getToken(), wm.build(), event.getGuild(), LogTyp.USER_BAN, event.getUser())); + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookOptional -> { + webhookOptional.ifPresent(webhookLog -> Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhookLog.getWebhookId(), webhookLog.getToken(), wm.build(), event.getGuild(), LogTyp.USER_BAN, event.getUser()))); }); }); }); @@ -132,7 +134,7 @@ public void onGuildUnban(@Nonnull GuildUnbanEvent event) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberunban").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -155,8 +157,8 @@ public void onGuildUnban(@Nonnull GuildUnbanEvent event) { wm.addEmbeds(we.build()); - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(x -> { - Main.getInstance().getLoggerQueue().add(new LogMessageUser(x.getWebhookId(), x.getToken(), wm.build(), event.getGuild(), LogTyp.USER_BAN, event.getUser())); + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookOptional -> { + webhookOptional.ifPresent(webhookLog -> Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhookLog.getWebhookId(), webhookLog.getToken(), wm.build(), event.getGuild(), LogTyp.USER_BAN, event.getUser()))); }); }); }); @@ -176,7 +178,7 @@ public void onGuildMemberJoin(GuildMemberJoinEvent event) { if (!isSetup) return; SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberjoin").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index abe061b31..c36453825 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -7,6 +7,7 @@ import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.bot.util.WebhookUtil; +import de.presti.ree6.commands.impl.community.Ticket; import de.presti.ree6.commands.impl.mod.Setup; import de.presti.ree6.language.Language; import de.presti.ree6.language.LanguageService; @@ -76,14 +77,14 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { if (split.length == 2) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Recording(), "FROM Recording WHERE identifier = :id AND guildId = :gid", Map.of("id", split[1], "gid", event.getGuild().getIdLong())).subscribe(recording -> { MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); - if (recording != null) { + if (recording.isPresent()) { messageEditBuilder.setEmbeds(new EmbedBuilder() .setDescription(LanguageService.getByGuild(event.getGuild(), "message.recording.inChat").block()) .setColor(Color.GREEN) .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setTitle(LanguageService.getByGuild(event.getGuild(), "label.recording.finished").block()) .build()); - messageEditBuilder.setFiles(FileUpload.fromData(recording.getRecording(), "recording.wav")); + messageEditBuilder.setFiles(FileUpload.fromData(recording.get().getRecording(), "recording.wav")); messageEditBuilder.setComponents(List.of()); } else { messageEditBuilder.setEmbeds(new EmbedBuilder() @@ -120,8 +121,9 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { case "re_ticket_open" -> { event.deferReply(true).queue(); SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(tickets -> { - if (tickets != null) { - Category category = event.getGuild().getCategoryById(tickets.getTicketCategory()); + if (tickets.isPresent()) { + Tickets ticketEntity = tickets.get(); + Category category = event.getGuild().getCategoryById(ticketEntity.getTicketCategory()); if (category != null) { if (category.getTextChannels().stream().anyMatch(c -> c.getName().contains(event.getUser().getName()))) { @@ -137,14 +139,14 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { .queue(channel -> { MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); messageCreateBuilder.setEmbeds(new EmbedBuilder().setTitle(LanguageService.getByGuild(event.getGuild(), "label.ticket").block()) - .setDescription(ticketMessage.getStringValue()) + .setDescription(ticketMessage.get().getStringValue()) .setThumbnail(event.getMember().getEffectiveAvatarUrl()).setColor(Color.GREEN).setTimestamp(Instant.now()).build()); messageCreateBuilder.addActionRow(Button.primary("re_ticket_close", LanguageService.getByGuild(event.getGuild(), "label.closeTicket").block())); Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), channel); event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.created", channel.getAsMention()).block()).queue(); }); - tickets.setTicketCount(tickets.getTicketCount() + 1); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(tickets).block(); + ticketEntity.setTicketCount(ticketEntity.getTicketCount() + 1); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(ticketEntity).block(); }); } else { event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.categoryNotFound").block()).queue(); @@ -157,9 +159,10 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { event.deferReply(true).queue(); SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(tickets -> { - if (tickets != null) { + if (tickets.isPresent()) { + Tickets ticketEntity = tickets.get(); StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(BotConfig.getBotName() + " Ticket transcript") + stringBuilder.append(BotConfig.getBotName()).append(" Ticket transcript") .append(" ") .append(ZonedDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG))) .append("\n") @@ -197,14 +200,14 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - webhookEmbedBuilder.setDescription("Here is the transcript of the ticket " + tickets.getTicketCount() + "!"); + webhookEmbedBuilder.setDescription("Here is the transcript of the ticket " + ticketEntity.getTicketCount() + "!"); webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); webhookEmbedBuilder.setColor(BotWorker.randomEmbedColor().getRGB()); webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - webhookMessageBuilder.addFile(tickets.getTicketCount() + "_transcript.txt", stringBuilder.toString().getBytes(StandardCharsets.UTF_8)); + webhookMessageBuilder.addFile(ticketEntity.getTicketCount() + "_transcript.txt", stringBuilder.toString().getBytes(StandardCharsets.UTF_8)); - WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), tickets.getLogChannelId(), tickets.getLogChannelWebhookToken(), false); + WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), ticketEntity.getLogChannelId(), ticketEntity.getLogChannelWebhookToken(), false); event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.close").block()).queue(); event.getChannel().delete().delay(2, TimeUnit.SECONDS).queue(); @@ -413,8 +416,8 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Suggestions(), "FROM Suggestions WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(suggestions -> { event.deferReply(true).queue(); - if (suggestions != null) { - MessageChannel messageChannel = (MessageChannel) event.getGuild().getGuildChannelById(suggestions.getGuildChannelId().getChannelId()); + if (suggestions.isPresent()) { + MessageChannel messageChannel = (MessageChannel) event.getGuild().getGuildChannelById(suggestions.get().getGuildChannelId().getChannelId()); if (messageChannel == null) return; @@ -463,7 +466,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { String channelId = Main.getInstance().getNotifier().getTwitchClient().getHelix().getUsers(null, null, Collections.singletonList(twitchUsername)).execute().getUsers().get(0).getId(); SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE channelId=:twitchId", Map.of("twitchId", channelId)).subscribe(twitchIntegration -> { - if (twitchIntegration == null) { + if (twitchIntegration.isPresent()) { EmbedBuilder embedBuilder = new EmbedBuilder() .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) @@ -476,21 +479,21 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.twitchCountName", Main.getInstance().getNotifier().getTwitchClient().getHelix().getChannelFollowers(null, channelId, null, 1, null).execute().getTotal()).block(), category) .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStats -> { - if (channelStats != null) { - - if (channelStats.getTwitchFollowerChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getTwitchFollowerChannelId()); + if (channelStats.isPresent()) { + ChannelStats channelStatsEntity = channelStats.get(); + if (channelStatsEntity.getTwitchFollowerChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStatsEntity.getTwitchFollowerChannelId()); if (voiceChannel3 != null) voiceChannel3.delete().queue(); } - channelStats.setTwitchFollowerChannelId(voiceChannel.getId()); - channelStats.setTwitchFollowerChannelUsername(twitchUsername); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + channelStatsEntity.setTwitchFollowerChannelId(voiceChannel.getId()); + channelStatsEntity.setTwitchFollowerChannelUsername(twitchUsername); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStatsEntity).block(); Main.getInstance().getNotifier().registerTwitchChannel(twitchUsername); } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), + ChannelStats channelStatsEntity = new ChannelStats(event.getGuild().getIdLong(), null, null, null, @@ -504,7 +507,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { null, null, null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStatsEntity).block(); Main.getInstance().getNotifier().registerTwitchChannel(twitchUsername); } }); @@ -1102,7 +1105,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.botMembersName", members.stream().filter(member -> member.getUser().isBot()).count()).block(), category).queue(voiceChannel2 -> { voiceChannel2.getManager().setUserLimit(0).queue(); SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStats -> { - if (channelStats != null) { + if (channelStats.isPresent()) { if (channelStats.getMemberStatsChannelId() != null) { VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getMemberStatsChannelId()); diff --git a/src/main/java/de/presti/ree6/events/OtherEvents.java b/src/main/java/de/presti/ree6/events/OtherEvents.java index dcee8d12a..d9583b85a 100644 --- a/src/main/java/de/presti/ree6/events/OtherEvents.java +++ b/src/main/java/de/presti/ree6/events/OtherEvents.java @@ -48,6 +48,8 @@ import net.dv8tion.jda.api.requests.restaction.MessageEditAction; import net.dv8tion.jda.internal.utils.PermissionUtil; import org.jetbrains.annotations.NotNull; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; import javax.annotation.Nonnull; import java.io.IOException; @@ -60,7 +62,6 @@ import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.IntStream; /** @@ -105,26 +106,27 @@ public void onGuildLeave(@Nonnull GuildLeaveEvent event) { public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getId())).subscribe(channelStats -> { - if (channelStats != null) { - if (channelStats.getMemberStatsChannelId() != null) { - GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStats.getMemberStatsChannelId()); + if (channelStats.isPresent()) { + ChannelStats channelStatsEntity = channelStats.get(); + if (channelStatsEntity.getMemberStatsChannelId() != null) { + GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStatsEntity.getMemberStatsChannelId()); if (guildChannel != null) { - guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.overallMembers") + ": " + event.getGuild().getMemberCount()).queue(); + guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.overallMembers").block() + ": " + event.getGuild().getMemberCount()).queue(); } } event.getGuild().loadMembers().onSuccess(members -> { - if (channelStats.getRealMemberStatsChannelId() != null) { - GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStats.getRealMemberStatsChannelId()); + if (channelStatsEntity.getRealMemberStatsChannelId() != null) { + GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStatsEntity.getRealMemberStatsChannelId()); if (guildChannel != null) { - guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.realMembers") + ": " + members.stream().filter(member -> !member.getUser().isBot()).count()).queue(); + guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.realMembers").block() + ": " + members.stream().filter(member -> !member.getUser().isBot()).count()).queue(); } } - if (channelStats.getBotMemberStatsChannelId() != null) { - GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStats.getBotMemberStatsChannelId()); + if (channelStatsEntity.getBotMemberStatsChannelId() != null) { + GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStatsEntity.getBotMemberStatsChannelId()); if (guildChannel != null) { - guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.botMembers") + ": " + members.stream().filter(member -> member.getUser().isBot()).count()).queue(); + guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.botMembers").block() + ": " + members.stream().filter(member -> member.getUser().isBot()).count()).queue(); } } }); @@ -141,31 +143,32 @@ public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { wmb.setUsername("Welcome!"); SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join").subscribe(messageSetting -> { - final String messageContent = messageSetting.getStringValue() - .replace("%user_name%", event.getMember().getUser().getName()) - .replace("%guild_name%", event.getGuild().getName()) - .replace("%guild_member_count%", String.valueOf(event.getGuild().getMemberCount())); - - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join_image").subscribe(joinImage -> { - if (!joinImage.getStringValue().isBlank()) { - try { - wmb.addFile("welcome.png", ImageCreationUtility.createJoinImage(event.getUser(), joinImage.getStringValue(), - messageContent.replace("%user_mention%", event.getMember().getUser().getName()))); - } catch (IOException e) { - wmb.setContent(messageContent); - log.error("Error while creating join image!", e); + if (messageSetting.isPresent()) { + final String messageContent = messageSetting.get().getStringValue() + .replace("%user_name%", event.getMember().getUser().getName()) + .replace("%guild_name%", event.getGuild().getName()) + .replace("%guild_member_count%", String.valueOf(event.getGuild().getMemberCount())); + + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "message_join_image").subscribe(joinImage -> { + if (joinImage.isPresent() && !joinImage.get().getStringValue().isBlank()) { + try { + wmb.addFile("welcome.png", ImageCreationUtility.createJoinImage(event.getUser(), joinImage.get().getStringValue(), + messageContent.replace("%user_mention%", event.getMember().getUser().getName()))); + } catch (IOException e) { + wmb.setContent(messageContent); + log.error("Error while creating join image!", e); + } + } else { + wmb.setContent(messageContent.replace("%user_mention%", event.getMember().getUser().getAsMention())); } - } else { - wmb.setContent(messageContent.replace("%user_mention%", event.getMember().getUser().getAsMention())); - } - SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { - if (webhook == null) return; + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + if (webhook.isEmpty()) return; - WebhookUtil.sendWebhook(wmb.build(), webhook); + WebhookUtil.sendWebhook(wmb.build(), webhook.get()); + }); }); - }); - + } }); } }); @@ -179,26 +182,27 @@ public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) { super.onGuildMemberRemove(event); SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getId())).subscribe(channelStats -> { - if (channelStats != null) { - if (channelStats.getMemberStatsChannelId() != null) { - GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStats.getMemberStatsChannelId()); + if (channelStats.isPresent()) { + ChannelStats channelStatsEntity = channelStats.get(); + if (channelStatsEntity.getMemberStatsChannelId() != null) { + GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStatsEntity.getMemberStatsChannelId()); if (guildChannel != null) { - guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.overallMembers") + ": " + event.getGuild().getMemberCount()).queue(); + guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.overallMembers").block() + ": " + event.getGuild().getMemberCount()).queue(); } } event.getGuild().loadMembers().onSuccess(members -> { - if (channelStats.getRealMemberStatsChannelId() != null) { - GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStats.getRealMemberStatsChannelId()); + if (channelStatsEntity.getRealMemberStatsChannelId() != null) { + GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStatsEntity.getRealMemberStatsChannelId()); if (guildChannel != null) { - guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.realMembers") + ": " + members.stream().filter(member -> !member.getUser().isBot()).count()).queue(); + guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.realMembers").block() + ": " + members.stream().filter(member -> !member.getUser().isBot()).count()).queue(); } } - if (channelStats.getBotMemberStatsChannelId() != null) { - GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStats.getBotMemberStatsChannelId()); + if (channelStatsEntity.getBotMemberStatsChannelId() != null) { + GuildChannel guildChannel = event.getGuild().getGuildChannelById(channelStatsEntity.getBotMemberStatsChannelId()); if (guildChannel != null) { - guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.botMembers") + ": " + members.stream().filter(member -> member.getUser().isBot()).count()).queue(); + guildChannel.getManager().setName(LanguageService.getByGuild(event.getGuild(), "label.botMembers").block() + ": " + members.stream().filter(member -> member.getUser().isBot()).count()).queue(); } } }); @@ -207,8 +211,9 @@ public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) { if (BotConfig.isModuleActive("tickets")) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(tickets -> { - if (tickets != null) { - Category category = event.getGuild().getCategoryById(tickets.getTicketCategory()); + if (tickets.isPresent()) { + Tickets ticketsEntity = tickets.get(); + Category category = event.getGuild().getCategoryById(ticketsEntity.getTicketCategory()); if (category != null) { List channels = category.getTextChannels().stream().filter(c -> c.getTopic() != null && c.getTopic().equalsIgnoreCase(event.getUser().getId())).toList(); @@ -229,7 +234,7 @@ public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) { .append(message.getTimeCreated().toZonedDateTime().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT))) .append("]") .append(" ") - .append(message.getAuthor().getAsTag()) + .append(message.getAuthor().getName()) .append(" ") .append("->") .append(" ") @@ -252,14 +257,14 @@ public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) { WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - webhookEmbedBuilder.setDescription("Here is the transcript of the ticket " + tickets.getTicketCount() + "!"); + webhookEmbedBuilder.setDescription("Here is the transcript of the ticket " + ticketsEntity.getTicketCount() + "!"); webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); webhookEmbedBuilder.setColor(BotWorker.randomEmbedColor().getRGB()); webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - webhookMessageBuilder.addFile(tickets.getTicketCount() + "_transcript.txt", stringBuilder.toString().getBytes(StandardCharsets.UTF_8)); + webhookMessageBuilder.addFile(ticketsEntity.getTicketCount() + "_transcript.txt", stringBuilder.toString().getBytes(StandardCharsets.UTF_8)); - WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), tickets.getLogChannelId(), tickets.getLogChannelWebhookToken(), false); + WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), ticketsEntity.getLogChannelId(), ticketsEntity.getLogChannelWebhookToken(), false); channel.delete().queue(); } } @@ -326,13 +331,14 @@ public void onGuildVoiceUpdate(@Nonnull GuildVoiceUpdateEvent event) { private void checkCreationChannel(Guild guild, Member member, long channelId) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", guild.getId())) .subscribe(temporalVoicechannel -> { - if (temporalVoicechannel != null) { + if (temporalVoicechannel.isPresent()) { + TemporalVoicechannel temporalVoicechannelEntity = temporalVoicechannel.get(); VoiceChannel voiceChannel = guild.getVoiceChannelById(channelId); if (voiceChannel == null) return; - if (temporalVoicechannel.getGuildChannelId().getChannelId() != voiceChannel.getIdLong()) { + if (temporalVoicechannelEntity.getGuildChannelId().getChannelId() != voiceChannel.getIdLong()) { return; } @@ -450,7 +456,7 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { if (event.isFromType(ChannelType.NEWS) && BotConfig.isModuleActive("autopublish")) { SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "configuration_autopublish").subscribe(x -> { - if (x.getBooleanValue()) + if (x.isPresent() && x.get().getBooleanValue()) event.getMessage().crosspost().queue(c -> c.addReaction(Emoji.fromUnicode("U+1F4E2")).queue()); }); } @@ -467,7 +473,7 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { ArrayUtil.messageIDwithUser.put(event.getMessageId(), event.getAuthor()); } - ModerationUtil.shouldModerate(event.getGuild().getIdLong()).subscribe(x -> { + ModerationUtil.shouldModerate(event.getGuild().getIdLong()).publishOn(Schedulers.boundedElastic()).map(x -> { log.info("Message received from {} in {} with content: {}", event.getAuthor().getGlobalName(), event.getChannel().getName(), event.getMessage().getContentRaw()); @@ -484,56 +490,59 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { log.info("Message was moderated: {}", moderated); - if (moderated) return; + return moderated; + }).flatMap((aBoolean) -> handleCommand(aBoolean, event)).publishOn(Schedulers.boundedElastic()).doOnNext(handled -> { + if (!handled) { + if (!event.getMessage().getMentions().getUsers().isEmpty() && event.getMessage().getMentions().getUsers().contains(event.getJDA().getSelfUser())) { + if (event.getMessage().getMessageReference() != null) return; - Main.getInstance().getCommandManager().perform(event.getMember(), event.getGuild(), event.getMessage().getContentRaw(), event.getMessage(), event.getGuildChannel(), null).subscribe(value -> { - if (!value) { - if (!event.getMessage().getMentions().getUsers().isEmpty() && event.getMessage().getMentions().getUsers().contains(event.getJDA().getSelfUser())) { - if (event.getMessage().getMessageReference() != null) return; + try { + String response = ChatGPTAPI.getResponse(event.getMember(), event.getMessage().getContentDisplay()); - try { - String response = ChatGPTAPI.getResponse(event.getMember(), event.getMessage().getContentDisplay()); - - if (response != null && !response.isBlank()) - Main.getInstance().getCommandManager().sendMessage(response, event.getChannel()); - } catch (Exception e) { - Sentry.captureException(e); - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError"), event.getChannel()); - } + if (response != null && !response.isBlank()) + Main.getInstance().getCommandManager().sendMessage(response, event.getChannel()); + } catch (Exception e) { + Sentry.captureException(e); + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.default.retrievalError"), event.getChannel()); } + } - if (BotConfig.isModuleActive("level")) { - if (!ArrayUtil.timeout.contains(event.getMember())) { - - SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(event.getGuild().getIdLong(), event.getMember().getIdLong()).subscribe(userLevel -> { - if (userLevel.addExperience(RandomUtils.random.nextInt(15, 26))) { - SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "level_message").subscribe(z -> { - if (z.getBooleanValue()) { - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), - "message.levelUp", userLevel.getLevel(), LanguageService.getByGuild(event.getGuild(), "label.chat") - , event.getMember().getAsMention()), event.getChannel()); - } - }); - } - - SQLSession.getSqlConnector().getSqlWorker().addChatLevelData(event.getGuild().getIdLong(), userLevel); + if (BotConfig.isModuleActive("level")) { + if (!ArrayUtil.timeout.contains(event.getMember())) { + + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(event.getGuild().getIdLong(), event.getMember().getIdLong()).subscribe(userLevel -> { + if (userLevel.addExperience(RandomUtils.random.nextInt(15, 26))) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "level_message").subscribe(z -> { + if (z.isPresent() && z.get().getBooleanValue()) { + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), + "message.levelUp", userLevel.getLevel(), LanguageService.getByGuild(event.getGuild(), "label.chat") + , event.getMember().getAsMention()), event.getChannel()); + } + }); + } - ArrayUtil.timeout.add(event.getMember()); + SQLSession.getSqlConnector().getSqlWorker().addChatLevelData(event.getGuild().getIdLong(), userLevel); - ThreadUtil.createThread(y -> ArrayUtil.timeout.remove(event.getMember()), Duration.ofSeconds(30), false, false); - }); - } + ArrayUtil.timeout.add(event.getMember()); - GuildUtil.handleChatLevelReward(event.getGuild(), event.getMember()); + ThreadUtil.createThread(y -> ArrayUtil.timeout.remove(event.getMember()), Duration.ofSeconds(30), false, false); + }); } - } else { - Main.getInstance().getCommandManager().timeoutUser(event.getAuthor()); + + GuildUtil.handleChatLevelReward(event.getGuild(), event.getMember()); } - }); - }); + } else { + Main.getInstance().getCommandManager().timeoutUser(event.getAuthor()); + } + }).subscribe(); } } + private Mono handleCommand(boolean moderated, MessageReceivedEvent event) { + if (moderated) return Mono.just(true); + return Main.getInstance().getCommandManager().perform(event.getMember(), event.getGuild(), event.getMessage().getContentRaw(), event.getMessage(), event.getGuildChannel(), null); + } + /** * @inheritDoc */ @@ -592,8 +601,9 @@ public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) { SQLSession.getSqlConnector().getSqlWorker() .getEntity(new ReactionRole(), "FROM ReactionRole WHERE guildRoleId.guildId=:gid AND emoteId=:emoteId AND messageId=:messageId", Map.of("gid", event.getGuild().getIdLong(), "emoteId", emojiId, "messageId", message.getIdLong())).subscribe(reactionRole -> { - if (reactionRole != null) { - Role role = event.getGuild().getRoleById(reactionRole.getId()); + if (reactionRole.isPresent()) { + ReactionRole reactionRoleEntity = reactionRole.get(); + Role role = event.getGuild().getRoleById(reactionRoleEntity.getId()); if (role != null) { event.getGuild().addRoleToMember(event.getMember(), role).queue(); @@ -601,18 +611,18 @@ public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) { boolean changes = false; - if (reactionRole.getChannelId() == 0) { - reactionRole.setChannelId(event.getChannel().getIdLong()); + if (reactionRoleEntity.getChannelId() == 0) { + reactionRoleEntity.setChannelId(event.getChannel().getIdLong()); changes = true; } - if (reactionRole.getFormattedEmote().isBlank()) { - reactionRole.setFormattedEmote(emojiUnion.getFormatted()); + if (reactionRoleEntity.getFormattedEmote().isBlank()) { + reactionRoleEntity.setFormattedEmote(emojiUnion.getFormatted()); changes = true; } if (changes) - SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRole).block(); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(reactionRoleEntity).block(); } }); } @@ -639,8 +649,9 @@ public void onMessageReactionRemove(@NotNull MessageReactionRemoveEvent event) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new ReactionRole(), "FROM ReactionRole WHERE guildRoleId.guildId=:gid AND emoteId=:emoteId AND messageId=:messageId", Map.of("gid", event.getGuild().getIdLong(), "emoteId", emojiId, "messageId", event.getMessageIdLong())).subscribe(reactionRole -> { - if (reactionRole != null) { - Role role = event.getGuild().getRoleById(reactionRole.getId()); + if (reactionRole.isPresent()) { + ReactionRole reactionRoleEntity = reactionRole.get(); + Role role = event.getGuild().getRoleById(reactionRoleEntity.getId()); if (role != null) { event.getGuild().removeRoleFromMember(event.getMember(), role).queue(); diff --git a/src/main/java/de/presti/ree6/language/LanguageService.java b/src/main/java/de/presti/ree6/language/LanguageService.java index 5e88eb4b5..40f98e92c 100644 --- a/src/main/java/de/presti/ree6/language/LanguageService.java +++ b/src/main/java/de/presti/ree6/language/LanguageService.java @@ -3,6 +3,7 @@ import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.Setting; import de.presti.ree6.utils.external.RequestUtility; import lombok.extern.slf4j.Slf4j; import net.dv8tion.jda.api.entities.Guild; @@ -242,9 +243,10 @@ public static void downloadLanguages() { } return SQLSession.getSqlConnector().getSqlWorker().getSetting(guildId, "configuration_language") - .mapNotNull(setting -> getByLocale(setting.getStringValue(), key, parameter).block()) + .mapNotNull(setting -> getByLocale(setting.get().getStringValue(), key, parameter).block()) .mapNotNull(resource -> SQLSession.getSqlConnector().getSqlWorker().getSetting(guildId, "chatprefix"). - map(prefix -> resource.replace("{guild_prefix}", prefix.getStringValue())).block()); + map(prefix -> resource.replace("{guild_prefix}", prefix.orElse(new Setting(-1, "chatprefix", "chatprefix", BotConfig.getDefaultPrefix())) + .getStringValue())).block()); } /** @@ -263,7 +265,8 @@ public static void downloadLanguages() { return getByLocale(interaction.getUserLocale(), key, parameter).mapNotNull(resource -> { if (resource.contains("{guild_prefix}")) { return SQLSession.getSqlConnector().getSqlWorker().getSetting(interaction.getGuild().getIdLong(), "chatprefix") - .map(prefix -> resource.replace("{guild_prefix}", prefix.getStringValue())).block(); + .map(prefix -> resource.replace("{guild_prefix}", prefix.orElse(new Setting(-1, "chatprefix", "chatprefix", BotConfig.getDefaultPrefix())) + .getStringValue())).block(); } return resource; diff --git a/src/main/java/de/presti/ree6/main/Main.java b/src/main/java/de/presti/ree6/main/Main.java index bd80e793e..6c1dec164 100644 --- a/src/main/java/de/presti/ree6/main/Main.java +++ b/src/main/java/de/presti/ree6/main/Main.java @@ -588,8 +588,8 @@ public void createCheckerThread() { LocalDate yesterday = LocalDate.now().minusDays(1); SQLSession.getSqlConnector().getSqlWorker().getStatistics(yesterday.getDayOfMonth(), yesterday.getMonthValue(), yesterday.getYear()).subscribe(statistics -> { - JsonObject jsonObject = statistics != null ? statistics.getStatsObject() : new JsonObject(); - JsonObject guildStats = statistics != null && jsonObject.has("guild") ? jsonObject.getAsJsonObject("guild") : new JsonObject(); + JsonObject jsonObject = statistics.isPresent() ? statistics.get().getStatsObject() : new JsonObject(); + JsonObject guildStats = statistics.isPresent() && jsonObject.has("guild") ? jsonObject.getAsJsonObject("guild") : new JsonObject(); guildStats.addProperty("amount", guildSize); guildStats.addProperty("users", userSize); @@ -656,10 +656,10 @@ public void createCheckerThread() { .setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()) .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage).block(); } } else { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage).block(); } } else { if (scheduledMessage.getLastUpdated() == null) { From b6bbd8aa30b11310006a0a20a413e19ee96eb77f Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 5 Jul 2024 14:30:00 +0200 Subject: [PATCH 22/94] Fixing even more classes --- .../ree6/commands/impl/economy/Work.java | 6 ++--- .../presti/ree6/commands/impl/info/Info.java | 6 +---- .../ree6/commands/impl/info/Infractions.java | 4 ++-- .../presti/ree6/commands/impl/mod/News.java | 6 +++-- .../ree6/commands/impl/mod/Suggestion.java | 11 +++++---- .../utils/data/DatabaseStorageBackend.java | 18 +++++++------- .../presti/ree6/utils/data/EconomyUtil.java | 9 +++---- .../ree6/utils/data/ImageCreationUtility.java | 24 +++++++------------ 8 files changed, 39 insertions(+), 45 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Work.java b/src/main/java/de/presti/ree6/commands/impl/economy/Work.java index 1c93bf9a9..8f5389e7d 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Work.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Work.java @@ -35,7 +35,7 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_delay")).subscribe(value -> { - long delay = Long.parseLong(value.getStringValue()); + long delay = Long.parseLong(value.get().getStringValue()); if (workTimeout.contains(entryString)) { commandEvent.reply(commandEvent.getResource("message.work.cooldown", delay)); @@ -43,10 +43,10 @@ public void onPerform(CommandEvent commandEvent) { } double min = Double.parseDouble((String) SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_min")).block().getStringValue()); + Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_min")).block().get().getStringValue()); double max = Double.parseDouble((String) SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_max")).block().getStringValue()); + Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_max")).block().get().getStringValue()); double amount = RandomUtils.round(RandomUtils.nextDouble(min, max), 2); diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Info.java b/src/main/java/de/presti/ree6/commands/impl/info/Info.java index 329de78e8..b96795217 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Info.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Info.java @@ -80,11 +80,7 @@ public void sendInfo(Member member, CommandEvent commandEvent) { em.setTitle(member.getEffectiveName() + (GuildUtil.isSupporter(member.getUser()) ? " " : "")); em.setThumbnail(member.getEffectiveAvatarUrl()); - if (member.getUser().getDiscriminator().equals("0000")) { - em.addField("**Username**", member.getUser().getName(), true); - } else { - em.addField("**UserTag**", member.getUser().getAsTag(), true); - } + em.addField("**Username**", member.getUser().getName(), true); em.addField("**Created Date**", member.getTimeCreated().toLocalDate().format(DateTimeFormatter.ofPattern("dd.MM.yyyy")), true); em.addField("**Joined Date**", member.getTimeJoined().toLocalDate().format(DateTimeFormatter.ofPattern("dd.MM.yyyy")), true); diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Infractions.java b/src/main/java/de/presti/ree6/commands/impl/info/Infractions.java index 292d1cd39..43181f576 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Infractions.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Infractions.java @@ -39,8 +39,8 @@ public void onPerform(CommandEvent commandEvent) { } SQLSession.getSqlConnector().getSqlWorker().getEntity(new Warning(), "FROM Warning WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", Map.of("gid", commandEvent.getGuild().getIdLong(), "uid", member.getIdLong())).subscribe(warning -> { - if (warning != null) { - commandEvent.reply(commandEvent.getResource("message.infractions.success", member.getAsMention(), warning.getWarnings())); + if (warning.isPresent()) { + commandEvent.reply(commandEvent.getResource("message.infractions.success", member.getAsMention(), warning.get().getWarnings())); } else { commandEvent.reply(commandEvent.getResource("message.infractions.empty", member.getAsMention())); } diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/News.java b/src/main/java/de/presti/ree6/commands/impl/mod/News.java index af1df9215..454cc708e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/News.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/News.java @@ -25,13 +25,15 @@ public void onPerform(CommandEvent commandEvent) { return; } - SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").subscribe(setting -> { - if (setting == null) { + SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").subscribe(settingOptional -> { + if (settingOptional.isEmpty()) { SQLSession.getSqlConnector().getSqlWorker().setSetting(commandEvent.getGuild().getIdLong(), "configuration_news", "Receive News", true); commandEvent.reply(commandEvent.getResource("message.news.enabled"), 5); return; } + Setting setting = settingOptional.get(); + if (setting.getBooleanValue()) { setting.setValue(false); commandEvent.reply(commandEvent.getResource("message.news.disabled"), 5); diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java b/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java index 77f2e9179..62f24952e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java @@ -21,6 +21,7 @@ import net.dv8tion.jda.api.interactions.components.buttons.Button; import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import net.dv8tion.jda.internal.interactions.CommandDataImpl; +import reactor.core.scheduler.Schedulers; import java.awt.*; import java.util.Map; @@ -75,9 +76,11 @@ public void onPerform(CommandEvent commandEvent) { public void createSuggestions(CommandEvent commandEvent, MessageChannel channel, MessageChannel messageChannel) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Suggestions(), "FROM Suggestions WHERE guildChannelId.guildId = :id", Map.of("id", commandEvent.getGuild().getIdLong())) - .map(suggestions -> { - if (suggestions != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(suggestions); + .publishOn(Schedulers.boundedElastic()) + .mapNotNull(suggestionsOptional -> { + if (suggestionsOptional.isPresent()) { + Suggestions suggestions = suggestionsOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(suggestions).block(); suggestions.getGuildChannelId().setChannelId(channel.getIdLong()); return SQLSession.getSqlConnector().getSqlWorker().updateEntity(suggestions).block(); @@ -89,7 +92,7 @@ public void createSuggestions(CommandEvent commandEvent, MessageChannel channel, EmbedBuilder embedBuilder = new EmbedBuilder(); embedBuilder.setTitle(commandEvent.getResource("label.suggestionMenu")); embedBuilder.setColor(Color.ORANGE); - embedBuilder.setDescription(setting.getStringValue()); + embedBuilder.setDescription(setting.get().getStringValue()); embedBuilder.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); messageCreateBuilder.setEmbeds(embedBuilder.build()); messageCreateBuilder.setActionRow(Button.primary("re_suggestion", commandEvent.getResource("message.suggestion.suggestionMenuPlaceholder"))); diff --git a/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java b/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java index 15c45b4b0..f0d66dab0 100644 --- a/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java +++ b/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java @@ -20,10 +20,10 @@ public class DatabaseStorageBackend implements IStorageBackend { @Override public List loadCredentials() { return SQLSession.getSqlConnector().getSqlWorker().getEntityList(new TwitchIntegration(), - "FROM TwitchIntegration", null).map(twitchIntegrations -> { + "FROM TwitchIntegration", null).map(twitchIntegrations -> { List credentials = new ArrayList<>(); - twitchIntegrations.forEach(twitchIntegration -> credentials.add(new CustomOAuth2Credential(twitchIntegration.getUserId(),"twitch", twitchIntegration.getToken(), + twitchIntegrations.forEach(twitchIntegration -> credentials.add(new CustomOAuth2Credential(twitchIntegration.getUserId(), "twitch", twitchIntegration.getToken(), twitchIntegration.getRefresh(), twitchIntegration.getChannelId(), twitchIntegration.getName(), twitchIntegration.getExpiresIn(), Collections.emptyList()))); return credentials; }).block(); @@ -39,9 +39,9 @@ public void saveCredentials(List list) { list.forEach(credential -> { if (credential instanceof CustomOAuth2Credential oAuth2Credential) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), - "FROM TwitchIntegration WHERE channelId = :userid", Map.of("userid",oAuth2Credential.getUserId())).subscribe(twitchIntegration -> { - if (twitchIntegration == null) { - twitchIntegration = new TwitchIntegration(); + "FROM TwitchIntegration WHERE channelId = :userid", Map.of("userid", oAuth2Credential.getUserId())).subscribe(twitchIntegrationOptional -> { + TwitchIntegration twitchIntegration = twitchIntegrationOptional.orElse(new TwitchIntegration()); + if (twitchIntegrationOptional.isEmpty()) { twitchIntegration.setChannelId(oAuth2Credential.getUserId()); twitchIntegration.setUserId(oAuth2Credential.getDiscordId()); } @@ -64,13 +64,13 @@ public void saveCredentials(List list) { */ @Override public Optional getCredentialByUserId(String userId) { - Optional twitchIntegration = Optional.ofNullable(SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), - "FROM TwitchIntegration WHERE channelId = :userid", Map.of("userid", userId)).block()); + Optional twitchIntegration = SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), + "FROM TwitchIntegration WHERE channelId = :userid", Map.of("userid", userId)).block(); - if (twitchIntegration.isPresent()) { + if (twitchIntegration != null && twitchIntegration.isPresent()) { TwitchIntegration twitchIntegration1 = twitchIntegration.get(); CustomOAuth2Credential oAuth2Credential - = new CustomOAuth2Credential(twitchIntegration1.getUserId(),"twitch", twitchIntegration1.getToken(), + = new CustomOAuth2Credential(twitchIntegration1.getUserId(), "twitch", twitchIntegration1.getToken(), twitchIntegration1.getRefresh(), twitchIntegration1.getChannelId(), twitchIntegration1.getName(), twitchIntegration1.getExpiresIn(), Collections.emptyList()); return Optional.of(oAuth2Credential); diff --git a/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java b/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java index 6c7febea7..0fc5e7e97 100644 --- a/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java +++ b/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java @@ -5,6 +5,7 @@ import de.presti.ree6.sql.entities.economy.MoneyTransaction; import net.dv8tion.jda.api.entities.Member; import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; import java.sql.Timestamp; import java.time.Instant; @@ -78,15 +79,15 @@ public static Mono getMoneyHolder(long guildId, long memberId) { */ public static Mono getMoneyHolder(long guildId, long memberId, boolean createIfNotExists) { return SQLSession.getSqlConnector().getSqlWorker().getEntity(new MoneyHolder(), "FROM MoneyHolder WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", - Map.of("gid", guildId, "uid", memberId)).map(moneyHolder -> { - if (moneyHolder == null && createIfNotExists) { - moneyHolder = new MoneyHolder(); + Map.of("gid", guildId, "uid", memberId)).publishOn(Schedulers.boundedElastic()).mapNotNull(moneyHolderOptional -> { + if (moneyHolderOptional.isEmpty() && createIfNotExists) { + MoneyHolder moneyHolder = new MoneyHolder(); moneyHolder.setGuildId(guildId); moneyHolder.setUserId(memberId); return SQLSession.getSqlConnector().getSqlWorker().updateEntity(moneyHolder).block(); } - return moneyHolder; + return moneyHolderOptional.get(); }); } diff --git a/src/main/java/de/presti/ree6/utils/data/ImageCreationUtility.java b/src/main/java/de/presti/ree6/utils/data/ImageCreationUtility.java index f8a10fc72..825dd8a0f 100644 --- a/src/main/java/de/presti/ree6/utils/data/ImageCreationUtility.java +++ b/src/main/java/de/presti/ree6/utils/data/ImageCreationUtility.java @@ -138,15 +138,6 @@ public static byte[] createRankImage(UserLevel userLevel) throws IOException { Main.getInstance().logAnalytic("Finished drawing User Image. ({}ms)", System.currentTimeMillis() - actionPerformance); actionPerformance = System.currentTimeMillis(); - String discriminatorText = "#" + user.getDiscriminator(); - - Font verdana60 = retrieveFont(60, discriminatorText); - Font verdana50 = retrieveFont(50, rank); - Font verdana40 = retrieveFont(40, formattedExperience + " Rank Level"); - - Main.getInstance().logAnalytic("Finished creating Fonts. ({}ms)", System.currentTimeMillis() - actionPerformance); - actionPerformance = System.currentTimeMillis(); - String username = new String(user.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); if (username.length() > 13) { @@ -156,17 +147,18 @@ public static byte[] createRankImage(UserLevel userLevel) throws IOException { Main.getInstance().logAnalytic("Finished substring on Username. ({}ms)", System.currentTimeMillis() - actionPerformance); actionPerformance = System.currentTimeMillis(); + Font verdana60 = retrieveFont(60, username); + Font verdana50 = retrieveFont(50, rank); + Font verdana40 = retrieveFont(40, formattedExperience + " Rank Level"); + + Main.getInstance().logAnalytic("Finished creating Fonts. ({}ms)", System.currentTimeMillis() - actionPerformance); + actionPerformance = System.currentTimeMillis(); + + graphics2D.setColor(BotConfig.getRankTextColor()); graphics2D.setFont(verdana60); graphics2D.drawString(username, 425, 675); - // TODO:: remove this once discord removes discriminators. - if (!user.getDiscriminator().equals("#0000")) { - graphics2D.setColor(BotConfig.getRankDetailColor()); - graphics2D.setFont(verdana40); - graphics2D.drawString(discriminatorText, 425, 675 - graphics2D.getFontMetrics(verdana60).getHeight() + 5); - } - graphics2D.setColor(BotConfig.getRankProgressbarBackgroundColor()); graphics2D.fillRoundRect(175, 705, base.getWidth() - 950, 50, 50, 50); From c1968fa5504bfe0d8a55af38dca1b1e74ef207bf Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 5 Jul 2024 14:35:00 +0200 Subject: [PATCH 23/94] Every class should be fixed except LoggingEvents and MenuEvents. --- .../de/presti/ree6/commands/impl/mod/Warn.java | 18 ++++++++++-------- .../ree6/game/impl/blackjack/Blackjack.java | 2 +- .../ree6/game/impl/musicquiz/MusicQuiz.java | 8 ++++---- .../ree6/module/giveaway/GiveawayManager.java | 10 +++++----- 4 files changed, 20 insertions(+), 18 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java b/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java index 42905bf43..44f0852f6 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java @@ -17,6 +17,7 @@ import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; import net.dv8tion.jda.api.interactions.commands.build.SubcommandGroupData; import net.dv8tion.jda.internal.interactions.CommandDataImpl; +import reactor.core.scheduler.Schedulers; import java.time.Duration; import java.util.Map; @@ -163,10 +164,10 @@ public void onPerform(CommandEvent commandEvent) { default -> { Member member = userMapping.getAsMember(); if (commandEvent.getGuild().getSelfMember().canInteract(member) && commandEvent.getMember().canInteract(member)) { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Warning(), "FROM Warning WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", Map.of("gid", commandEvent.getGuild().getIdLong(), "uid", member.getIdLong())).map(warning -> { - int warnings = warning != null ? warning.getWarnings() + 1 : 1; - if (warning == null) { - warning = new Warning(); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Warning(), "FROM Warning WHERE guildUserId.guildId = :gid AND guildUserId.userId = :uid", Map.of("gid", commandEvent.getGuild().getIdLong(), "uid", member.getIdLong())).publishOn(Schedulers.boundedElastic()).mapNotNull(warningOptional -> { + Warning warning = warningOptional.orElse(new Warning()); + int warnings = warningOptional.isPresent() ? warning.getWarnings() + 1 : 1; + if (warningOptional.isEmpty()) { warning.setUserId(member.getIdLong()); warning.setGuildId(commandEvent.getGuild().getIdLong()); } @@ -176,15 +177,16 @@ public void onPerform(CommandEvent commandEvent) { return SQLSession.getSqlConnector().getSqlWorker().updateEntity(warning).block(); }).subscribe(warning -> { commandEvent.reply(commandEvent.getResource("message.warn.success", member.getAsMention(), warning.getWarnings())); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid AND warnings = :amount", Map.of("gid", commandEvent.getGuild().getIdLong(), "amount", warning.getWarnings())).subscribe(punishment -> { - if (punishment != null) { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid AND warnings = :amount", Map.of("gid", commandEvent.getGuild().getIdLong(), "amount", warning.getWarnings())).subscribe(punishmentOptional -> { + if (punishmentOptional.isPresent()) { + Punishments punishment = punishmentOptional.get(); switch (punishment.getAction()) { case 1 -> member.timeoutFor(Duration.ofMillis(punishment.getTimeoutTime())).reason(commandEvent.getResource("message.warn.reachedWarnings", warning.getWarnings())).queue(); case 2 -> { Role role = commandEvent.getGuild().getRoleById(punishment.getRoleId()); if (role == null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment).block(); return; } @@ -193,7 +195,7 @@ public void onPerform(CommandEvent commandEvent) { case 3 -> { Role role = commandEvent.getGuild().getRoleById(punishment.getRoleId()); if (role == null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment).block(); return; } diff --git a/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java b/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java index 72978b610..8931418ec 100644 --- a/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java +++ b/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java @@ -313,7 +313,7 @@ public void stopGame(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlayer) Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), session.getChannel()); SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_blackjack_win")) - .subscribe(setting -> rewardPlayer(session, winner, setting.getValue())); + .subscribe(setting -> rewardPlayer(session, winner, setting.get().getValue())); stopGame(); } diff --git a/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java b/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java index daadd0287..0997f46cc 100644 --- a/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java +++ b/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java @@ -216,7 +216,7 @@ public void onMessageReceive(MessageReceivedEvent messageReceivedEvent) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_title")) - .subscribe(setting -> rewardPlayer(session, musicQuizPlayer, setting.getValue())); + .subscribe(setting -> rewardPlayer(session, musicQuizPlayer, setting.get().getValue())); messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundTitle", currentEntry.getTitle()).block()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); messageReceivedEvent.getMessage().delete().queue(); @@ -227,7 +227,7 @@ public void onMessageReceive(MessageReceivedEvent messageReceivedEvent) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_artist")) - .subscribe(setting -> rewardPlayer(session, musicQuizPlayer, setting.getValue())); + .subscribe(setting -> rewardPlayer(session, musicQuizPlayer, setting.get().getValue())); messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundArtists", currentEntry.getArtist()).block()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); messageReceivedEvent.getMessage().delete().queue(); @@ -238,7 +238,7 @@ public void onMessageReceive(MessageReceivedEvent messageReceivedEvent) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_feature")) - .subscribe(setting -> rewardPlayer(session, musicQuizPlayer, setting.getValue())); + .subscribe(setting -> rewardPlayer(session, musicQuizPlayer, setting.get().getValue())); messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundFeature", String.join(",", currentEntry.getFeatures())).block()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); messageReceivedEvent.getMessage().delete().queue(); @@ -288,7 +288,7 @@ public void stopGame() { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_win")) - .subscribe(setting -> rewardPlayer(session, sortedList.get(0), setting.getValue())); + .subscribe(setting -> rewardPlayer(session, sortedList.get(0), setting.get().getValue())); Main.getInstance().getMusicWorker().disconnect(session.getGuild()); } diff --git a/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java b/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java index e820be850..986fadf2a 100644 --- a/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java +++ b/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java @@ -59,10 +59,10 @@ public Giveaway get(long value) { } } - return SQLSession.getSqlConnector().getSqlWorker().getEntity(new Giveaway(), "FROM Giveaway WHERE messageId = :id", Map.of("id", value)).map(giveaway -> { - if (giveaway != null) { - giveaways.add(giveaway); - return giveaway; + return SQLSession.getSqlConnector().getSqlWorker().getEntity(new Giveaway(), "FROM Giveaway WHERE messageId = :id", Map.of("id", value)).mapNotNull(giveaway -> { + if (giveaway.isPresent()) { + giveaways.add(giveaway.get()); + return giveaway.get(); } return null; }).block(); @@ -70,7 +70,7 @@ public Giveaway get(long value) { @Override public void remove(Giveaway object) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(object); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(object).block(); IManager.super.remove(object); } From db87f5709e4184f3c6d23c2910b8cf7aa51059b5 Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 5 Jul 2024 14:56:15 +0200 Subject: [PATCH 24/94] Every class should be fixed except LoggingEvents and MenuEvents. --- .../de/presti/ree6/events/LoggingEvents.java | 159 ++++++++++++------ .../de/presti/ree6/events/MenuEvents.java | 95 +++++------ 2 files changed, 153 insertions(+), 101 deletions(-) diff --git a/src/main/java/de/presti/ree6/events/LoggingEvents.java b/src/main/java/de/presti/ree6/events/LoggingEvents.java index 1ddc0f838..adbb9ebb5 100644 --- a/src/main/java/de/presti/ree6/events/LoggingEvents.java +++ b/src/main/java/de/presti/ree6/events/LoggingEvents.java @@ -15,6 +15,7 @@ import de.presti.ree6.module.invite.InviteContainer; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Invite; +import de.presti.ree6.sql.entities.webhook.WebhookLog; import de.presti.ree6.utils.data.ArrayUtil; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.audit.ActionType; @@ -118,9 +119,8 @@ public void onGuildBan(@Nonnull GuildBanEvent event) { wm.addEmbeds(we.build()); - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookOptional -> { - webhookOptional.ifPresent(webhookLog -> Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhookLog.getWebhookId(), webhookLog.getToken(), wm.build(), event.getGuild(), LogTyp.USER_BAN, event.getUser()))); - }); + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookOptional -> + webhookOptional.ifPresent(webhookLog -> Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhookLog.getWebhookId(), webhookLog.getToken(), wm.build(), event.getGuild(), LogTyp.USER_BAN, event.getUser())))); }); }); } @@ -157,9 +157,8 @@ public void onGuildUnban(@Nonnull GuildUnbanEvent event) { wm.addEmbeds(we.build()); - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookOptional -> { - webhookOptional.ifPresent(webhookLog -> Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhookLog.getWebhookId(), webhookLog.getToken(), wm.build(), event.getGuild(), LogTyp.USER_BAN, event.getUser()))); - }); + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookOptional -> + webhookOptional.ifPresent(webhookLog -> Main.getInstance().getLoggerQueue().add(new LogMessageUser(webhookLog.getWebhookId(), webhookLog.getToken(), wm.build(), event.getGuild(), LogTyp.USER_BAN, event.getUser())))); }); }); } @@ -176,7 +175,10 @@ public void onGuildMemberJoin(GuildMemberJoinEvent event) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberjoin").subscribe(shouldLog -> { if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -198,7 +200,7 @@ public void onGuildMemberJoin(GuildMemberJoinEvent event) { if (event.getGuild().getSelfMember().hasPermission(Permission.MANAGE_SERVER)) { SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_invite").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm2 = new WebhookMessageBuilder(); wm2.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); @@ -255,9 +257,12 @@ public void onGuildMemberRemove(@Nonnull GuildMemberRemoveEvent event) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_memberleave").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); @@ -280,7 +285,7 @@ public void onGuildMemberRemove(@Nonnull GuildMemberRemoveEvent event) { auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -299,9 +304,13 @@ public void onGuildMemberUpdateTimeOut(@NotNull GuildMemberUpdateTimeOutEvent ev SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_timeout").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -350,9 +359,13 @@ public void onGuildMemberUpdateNickname(@Nonnull GuildMemberUpdateNicknameEvent SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_nickname").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); @@ -375,7 +388,7 @@ public void onGuildMemberUpdateNickname(@Nonnull GuildMemberUpdateNicknameEvent auditLogEntry.getTargetIdLong() == event.getUser().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -398,10 +411,14 @@ public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { super.onGuildVoiceUpdate(event); SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + if (event.getChannelLeft() == null) { SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicejoin").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -421,7 +438,7 @@ public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { }); } else if (event.getChannelJoined() == null) { SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voiceleave").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -439,7 +456,7 @@ public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -447,7 +464,7 @@ public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { }); } else { SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicemove").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -465,7 +482,7 @@ public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { auditLogEntry.getTargetIdLong() == event.getMember().getIdLong()).findFirst().orElse(null); if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor") + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByEvent(event, "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -488,10 +505,14 @@ public void onGenericChannel(@Nonnull GenericChannelEvent event) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + if (event.getChannelType().isAudio()) { SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_voicechannel").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); @@ -535,7 +556,7 @@ public void onGenericChannel(@Nonnull GenericChannelEvent event) { }); } else { SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_textchannel").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -562,14 +583,14 @@ public void onGenericChannel(@Nonnull GenericChannelEvent event) { entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_DELETE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); } else if (event instanceof ChannelUpdateNameEvent channelUpdateNameEvent) { - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldName") + "**", channelUpdateNameEvent.getOldValue() != null + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.oldName").block() + "**", channelUpdateNameEvent.getOldValue() != null ? ((ChannelUpdateNameEvent) event).getOldValue() : event.getChannel().getName())); - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newName") + "**", channelUpdateNameEvent.getNewValue() != null + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.newName").block() + "**", channelUpdateNameEvent.getNewValue() != null ? ((ChannelUpdateNameEvent) event).getNewValue() : event.getChannel().getName())); entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); } else if (event instanceof ChannelUpdateNSFWEvent channelUpdateNSFWEvent) { - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.nsfw") + "**", channelUpdateNSFWEvent.getNewValue() + "")); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.nsfw").block() + "**", channelUpdateNSFWEvent.getNewValue() + "")); entry = event.getGuild().retrieveAuditLogs().type(ActionType.CHANNEL_UPDATE).limit(5).stream().filter(auditLogEntry -> auditLogEntry.getTargetIdLong() == event.getChannel().getIdLong()).findFirst().orElse(null); } else { @@ -577,7 +598,7 @@ public void onGenericChannel(@Nonnull GenericChannelEvent event) { } if (entry != null && entry.getUser() != null) - we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor") + "**", entry.getUser().getAsMention())); + we.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(event.getGuild(), "label.actor").block() + "**", entry.getUser().getAsMention())); wm.addEmbeds(we.build()); @@ -600,9 +621,13 @@ public void onGuildMemberRoleAdd(@Nonnull GuildMemberRoleAddEvent event) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roleadd").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -647,9 +672,13 @@ public void onGuildMemberRoleRemove(@Nonnull GuildMemberRoleRemoveEvent event) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roleremove").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -694,9 +723,13 @@ public void onGuildMemberRoleRemove(@Nonnull GuildMemberRoleRemoveEvent event) { public void onRoleCreate(@Nonnull RoleCreateEvent event) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolecreate").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -731,9 +764,13 @@ public void onRoleCreate(@Nonnull RoleCreateEvent event) { public void onRoleDelete(@Nonnull RoleDeleteEvent event) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_roledelete").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -768,9 +805,13 @@ public void onRoleDelete(@Nonnull RoleDeleteEvent event) { public void onRoleUpdateName(@Nonnull RoleUpdateNameEvent event) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolename").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -807,9 +848,13 @@ public void onRoleUpdateName(@Nonnull RoleUpdateNameEvent event) { public void onRoleUpdateMentionable(@Nonnull RoleUpdateMentionableEvent event) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolemention").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); wm.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); @@ -845,9 +890,13 @@ public void onRoleUpdateMentionable(@Nonnull RoleUpdateMentionableEvent event) { public void onRoleUpdateHoisted(@Nonnull RoleUpdateHoistedEvent event) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolehoisted").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -886,9 +935,13 @@ public void onRoleUpdateHoisted(@Nonnull RoleUpdateHoistedEvent event) { public void onRoleUpdatePermissions(@Nonnull RoleUpdatePermissionsEvent event) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolepermission").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -952,9 +1005,13 @@ public void onRoleUpdatePermissions(@Nonnull RoleUpdatePermissionsEvent event) { public void onRoleUpdateColor(@Nonnull RoleUpdateColorEvent event) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_rolecolor").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; WebhookMessageBuilder wm = new WebhookMessageBuilder(); @@ -997,9 +1054,13 @@ public void onRoleUpdateColor(@Nonnull RoleUpdateColorEvent event) { public void onMessageDelete(@Nonnull MessageDeleteEvent event) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).subscribe(isSetup -> { if (!isSetup) return; - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhookLogOptional -> { + if (webhookLogOptional.isEmpty()) return; + + WebhookLog webhook = webhookLogOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().getSetting(event.getGuild().getIdLong(), "logging_messagedelete").subscribe(shouldLog -> { - if (!shouldLog.getBooleanValue()) return; + if (shouldLog.isEmpty() || !shouldLog.get().getBooleanValue()) return; User user = ArrayUtil.getUserFromMessageList(event.getMessageId()); diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index c36453825..973793b85 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -7,7 +7,6 @@ import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.bot.util.WebhookUtil; -import de.presti.ree6.commands.impl.community.Ticket; import de.presti.ree6.commands.impl.mod.Setup; import de.presti.ree6.language.Language; import de.presti.ree6.language.LanguageService; @@ -578,8 +577,9 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.youtubeCountName", youTubeChannel.getSubscriberCountText()).block(), category) .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStats -> { - if (channelStats != null) { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { + if (channelStatsOptional.isPresent()) { + ChannelStats channelStats = channelStatsOptional.get(); if (channelStats.getYoutubeSubscribersChannelId() != null) { VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getYoutubeSubscribersChannelId()); @@ -592,7 +592,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); Main.getInstance().getNotifier().registerYouTubeChannel(youTubeChannel.getId()); } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), null, null, null, @@ -605,8 +605,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { voiceChannel.getId(), youTubeChannel.getId(), null, - null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + null)).block(); Main.getInstance().getNotifier().registerYouTubeChannel(youTubeChannel.getId()); } }); @@ -662,8 +661,9 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.redditCountName", subreddit.getActiveUserCount()).block(), category) .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStats -> { - if (channelStats != null) { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { + if (channelStatsOptional.isPresent()) { + ChannelStats channelStats = channelStatsOptional.get(); if (channelStats.getSubredditMemberChannelId() != null) { VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getSubredditMemberChannelId()); @@ -676,7 +676,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); Main.getInstance().getNotifier().registerSubreddit(subredditName); } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), null, null, null, @@ -689,8 +689,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { null, null, voiceChannel.getId(), - subredditName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + subredditName)).block(); Main.getInstance().getNotifier().registerSubreddit(subredditName); } }); @@ -746,8 +745,9 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.twitterCountName", twitterUser.getFollowersCount()).block(), category) .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStats -> { - if (channelStats != null) { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { + if (channelStatsOptional.isPresent()) { + ChannelStats channelStats = channelStatsOptional.get(); if (channelStats.getTwitterFollowerChannelId() != null) { VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getTwitterFollowerChannelId()); @@ -760,7 +760,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); Main.getInstance().getNotifier().registerTwitterUser(twitterName); } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), null, null, null, @@ -773,8 +773,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { null, null, null, - null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + null)).block(); Main.getInstance().getNotifier().registerTwitterUser(twitterName); } }); @@ -830,9 +829,9 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.instagramCountName", instagramUser.getFollower_count()).block(), category) .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStats -> { - if (channelStats != null) { - + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { + if (channelStatsOptional.isPresent()) { + ChannelStats channelStats = channelStatsOptional.get(); if (channelStats.getInstagramFollowerChannelId() != null) { VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getInstagramFollowerChannelId()); @@ -845,7 +844,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); Main.getInstance().getNotifier().registerInstagramUser(instagramName); } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), null, null, null, @@ -858,8 +857,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { null, null, null, - null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + null)).block(); Main.getInstance().getNotifier().registerInstagramUser(instagramName); } }); @@ -1104,8 +1102,9 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even voiceChannel1.getManager().setUserLimit(0).queue(); event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.botMembersName", members.stream().filter(member -> member.getUser().isBot()).count()).block(), category).queue(voiceChannel2 -> { voiceChannel2.getManager().setUserLimit(0).queue(); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStats -> { - if (channelStats.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { + if (channelStatsOptional.isPresent()) { + ChannelStats channelStats = channelStatsOptional.get(); if (channelStats.getMemberStatsChannelId() != null) { VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getMemberStatsChannelId()); @@ -1129,7 +1128,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even channelStats.setBotMemberStatsChannelId(voiceChannel2.getId()); SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); } else { - channelStats = new ChannelStats(event.getGuild().getIdLong(), + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), voiceChannel.getId(), voiceChannel1.getId(), voiceChannel2.getId(), @@ -1142,8 +1141,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even null, null, null, - null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + null)).block(); } }); @@ -1412,15 +1410,13 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "logDelete" -> { SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { - if (webhook != null) { - event.getJDA().retrieveWebhookById(webhook.getChannelId()).queue(webhook1 -> { - webhook1.delete().queue(); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.deleted").block()); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhook); - }); - } + webhook.ifPresent(webhookLog -> event.getJDA().retrieveWebhookById(webhookLog.getChannelId()).queue(webhook1 -> { + webhook1.delete().queue(); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.deleted").block()); + embedBuilder.setColor(Color.GREEN); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookLog).block(); + })); }); } @@ -1471,10 +1467,8 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even if (textChannel != null) { textChannel.createWebhook(BotConfig.getBotName() + "-Logs").queue(webhook -> { - if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).block()) { - WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).block()); - } - + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).block().ifPresent(webhookEntity -> + WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), webhookEntity)); SQLSession.getSqlConnector().getSqlWorker().setLogWebhook(event.getGuild().getIdLong(), textChannel.getIdLong(), webhook.getIdLong(), webhook.getToken()); embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupSuccess").block()); embedBuilder.setColor(Color.GREEN); @@ -1527,15 +1521,13 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "welcomeDelete" -> { SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { - if (webhook != null) { - event.getJDA().retrieveWebhookById(webhook.getChannelId()).queue(webhook1 -> { - webhook1.delete().queue(); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.deleted").block()); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhook); - }); - } + webhook.ifPresent(webhookWelcome -> event.getJDA().retrieveWebhookById(webhookWelcome.getChannelId()).queue(webhook1 -> { + webhook1.delete().queue(); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.deleted").block()); + embedBuilder.setColor(Color.GREEN); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookWelcome).block(); + })); }); } @@ -1586,9 +1578,8 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even if (textChannel != null) { textChannel.createWebhook(BotConfig.getBotName() + "-Welcome").queue(webhook -> { // .block() can be called here because its being queued. - if (SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong()).block()) { - WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).block()); - } + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).block().ifPresent(webhookEntity -> + WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), webhookEntity)); SQLSession.getSqlConnector().getSqlWorker().setWelcomeWebhook(event.getGuild().getIdLong(), textChannel.getIdLong(), webhook.getIdLong(), webhook.getToken()); embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupSuccess").block()); From 752ba398f87ff6d37eb81f40b974a3c749c94f85 Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 5 Jul 2024 15:02:00 +0200 Subject: [PATCH 25/94] Every class should be fixed except LoggingEvents and MenuEvents. --- .../de/presti/ree6/events/MenuEvents.java | 57 ++++++++++--------- 1 file changed, 30 insertions(+), 27 deletions(-) diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index 973793b85..a4a425f95 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -913,13 +913,13 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even EmbedBuilder embedBuilder = new EmbedBuilder(event.getMessage().getEmbeds().get(0)); if (event.getSelectedOptions().isEmpty()) { roles.forEach(autoRole -> - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(autoRole)); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(autoRole).block()); } else { roles.forEach(autoRole -> { String value = String.valueOf(autoRole.getRoleId()); if (!event.getValues().contains(value)) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(autoRole); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(autoRole).block(); values.remove(value); } }); @@ -992,8 +992,9 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { optionList.add(SelectOption.of(label, "welcomeSetup")); - if (SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(event.getGuild().getIdLong()).block()) + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).block().ifPresent(welcomeWebhook -> { optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "welcomeDelete")); + }); optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setImage").block(), "welcomeImage")); @@ -1017,8 +1018,11 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { optionList.add(SelectOption.of(label, "tempVoiceSetup")); - if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).block() != null) + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", + Map.of("gid", event.getGuild().getIdLong())).block().ifPresent(temporalVoicechannel -> { optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "tempVoiceDelete")); + }); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); @@ -1049,8 +1053,9 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { optionList.add(SelectOption.of(label, "ticketsSetup")); - if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).block() != null) + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).block().ifPresent(tickets -> { optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "ticketsDelete")); + }); optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); @@ -1236,11 +1241,11 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "ticketsDelete" -> { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(tickets -> { - if (tickets != null) { + if (tickets.isPresent()) { embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.deleted").block()); embedBuilder.setColor(Color.GREEN); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(tickets); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(tickets.get()).block(); } }); } @@ -1331,11 +1336,11 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "tempVoiceDelete" -> { SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(temporalVoicechannel -> { - if (temporalVoicechannel != null) { + if (temporalVoicechannel.isPresent()) { embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.deleted").block()); embedBuilder.setColor(Color.GREEN); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel).block(); } }); } @@ -1409,15 +1414,14 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even } case "logDelete" -> { - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { - webhook.ifPresent(webhookLog -> event.getJDA().retrieveWebhookById(webhookLog.getChannelId()).queue(webhook1 -> { - webhook1.delete().queue(); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.deleted").block()); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookLog).block(); - })); - }); + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> + webhook.ifPresent(webhookLog -> event.getJDA().retrieveWebhookById(webhookLog.getChannelId()).queue(webhook1 -> { + webhook1.delete().queue(); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.deleted").block()); + embedBuilder.setColor(Color.GREEN); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookLog).block(); + }))); } default -> { @@ -1520,15 +1524,14 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even } case "welcomeDelete" -> { - SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { - webhook.ifPresent(webhookWelcome -> event.getJDA().retrieveWebhookById(webhookWelcome.getChannelId()).queue(webhook1 -> { - webhook1.delete().queue(); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.deleted").block()); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookWelcome).block(); - })); - }); + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).subscribe(webhook -> + webhook.ifPresent(webhookWelcome -> event.getJDA().retrieveWebhookById(webhookWelcome.getChannelId()).queue(webhook1 -> { + webhook1.delete().queue(); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.deleted").block()); + embedBuilder.setColor(Color.GREEN); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookWelcome).block(); + }))); } default -> { From 647a074ca022d74492cbf69c403cc60ce709d652 Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 5 Jul 2024 16:13:01 +0200 Subject: [PATCH 26/94] Everything should be fixed now. --- .../de/presti/ree6/bot/util/WebhookUtil.java | 32 +++++++++---------- .../commands/impl/community/Reactions.java | 4 +-- .../commands/impl/community/Schedule.java | 4 +-- .../presti/ree6/commands/impl/mod/Setup.java | 6 ++-- .../presti/ree6/commands/impl/mod/Warn.java | 4 +-- .../ree6/commands/impl/music/MusicPanel.java | 4 +-- .../de/presti/ree6/events/MenuEvents.java | 2 +- .../de/presti/ree6/logger/LoggerQueue.java | 20 ++++++------ .../de/presti/ree6/utils/apis/Notifier.java | 10 +++--- 9 files changed, 43 insertions(+), 43 deletions(-) diff --git a/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java b/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java index 3b291fe85..75aa9733d 100644 --- a/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java +++ b/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java @@ -13,7 +13,6 @@ import net.dv8tion.jda.api.entities.Guild; import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; /** * Class to handle Webhook sends. @@ -95,7 +94,6 @@ public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, if (!x) { // If not, inform about invalid send. log.error("[Webhook] Invalid Webhook: {} - {}", webhookId, webhookToken); - return; } else { // Check if the LoggerMessage is canceled. if ((loggerMessage == null || loggerMessage.isCanceled())) { @@ -128,49 +126,51 @@ private static void sendWebhookMessage(LogMessage loggerMessage, WebhookMessage // TODO:: this has become worst so please for the love of god find a better solution brain. SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookWelcome(), "FROM WebhookWelcome WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(welcome -> { - if (welcome != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(welcome); + if (welcome.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(welcome.get()).block(); log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookYouTube(), "FROM WebhookYouTube WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookYouTube -> { - if (webhookYouTube != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookYouTube); + if (webhookYouTube.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookYouTube.get()).block(); log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTwitter(), "FROM WebhookTwitter WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookTwitter -> { - if (webhookTwitter != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTwitter); + if (webhookTwitter.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTwitter.get()).block(); log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTwitch(), "FROM WebhookTwitch WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookTwitch -> { - if (webhookTwitch != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTwitch); + if (webhookTwitch.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTwitch.get()).block(); log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookReddit(), "FROM WebhookReddit WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookReddit -> { - if (webhookReddit != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookReddit); + if (webhookReddit.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookReddit.get()).block(); log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookInstagram(), "FROM WebhookInstagram WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookInstagram -> { - if (webhookInstagram != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookInstagram); + if (webhookInstagram.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookInstagram.get()).block(); log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTikTok(), "FROM WebhookTikTok WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookTikTok -> { - if (webhookTikTok != null) { + if (webhookTikTok.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTikTok.get()).block(); log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { SQLSession.getSqlConnector().getSqlWorker().getEntity(new RSSFeed(), "FROM WebhookTikTok WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(rssFeed -> { - if (rssFeed != null) { + if (rssFeed.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(rssFeed.get()).block(); log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else { log.error("[Webhook] Invalid Webhook: {} - {}, has not been deleted since it is not a Log-Webhook.", webhookId, webhookToken); diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java b/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java index 613526a98..de8059b6e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Reactions.java @@ -88,8 +88,8 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new ReactionRole(), "FROM ReactionRole WHERE guildRoleId.guildId=:gid AND guildRoleId.roleId=:roleId AND messageId=:messageId", Map.of("gid", commandEvent.getGuild().getIdLong(), "roleId", role.getAsRole().getIdLong(), "messageId", messageId)).subscribe(reactionRole -> { - if (reactionRole != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(reactionRole); + if (reactionRole.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(reactionRole.get()).block(); commandEvent.reply(commandEvent.getResource("message.reactions.removed", role.getAsRole().getIdLong()), 5); } diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java b/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java index 948e5de9e..7da669be3 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Schedule.java @@ -76,8 +76,8 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker() .getEntity(new ScheduledMessage(), "FROM ScheduledMessage WHERE guildAndId.guildId = :gid AND guildAndId.id = :id", Map.of("gid", commandEvent.getGuild().getIdLong(), "id", id.getAsLong())).subscribe(scheduledMessage -> { - if (scheduledMessage != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage); + if (scheduledMessage.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage.get()).block(); commandEvent.reply(commandEvent.getResource("message.schedule.delete.success")); } else { commandEvent.reply(commandEvent.getResource("message.schedule.delete.failed")); diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java index 9fd575a2d..83dd04e9f 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java @@ -222,8 +222,8 @@ public void onPerform(CommandEvent commandEvent) { } } else { SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", commandEvent.getGuild().getId())).subscribe(temporalVoicechannel -> { - if (temporalVoicechannel != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel); + if (temporalVoicechannel.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel.get()).block(); commandEvent.reply(commandEvent.getResource("message.temporalVoice.deleted")); } else { commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); @@ -265,7 +265,7 @@ public void onPerform(CommandEvent commandEvent) { if (!setting.getName().startsWith("configuration_rewards_")) continue; // TODO:: thing of how to handle this. - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Setting(commandEvent.getGuild().getIdLong(), setting.getName(), setting.getDisplayName(), setting.getValue())); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Setting(commandEvent.getGuild().getIdLong(), setting.getName(), setting.getDisplayName(), setting.getValue())).block(); } commandEvent.reply(commandEvent.getResource("message.rewards.success")); diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java b/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java index 44f0852f6..384c00565 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java @@ -150,8 +150,8 @@ public void onPerform(CommandEvent commandEvent) { case "delete" -> { int id = idMapping.getAsInt(); SQLSession.getSqlConnector().getSqlWorker().getEntity(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid AND guildAndId.id = :id", Map.of("gid", commandEvent.getGuild().getIdLong(), "id", id)).subscribe(punishment -> { - if (punishment != null) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment); + if (punishment.isPresent()) { + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(punishment.get()).block(); commandEvent.reply(commandEvent.getResource("message.warn.punishment.deleted", id)); } else { commandEvent.reply(commandEvent.getResource("message.warn.punishment.notFound", id)); diff --git a/src/main/java/de/presti/ree6/commands/impl/music/MusicPanel.java b/src/main/java/de/presti/ree6/commands/impl/music/MusicPanel.java index 4bd20d8cd..dbdfb7efc 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/MusicPanel.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/MusicPanel.java @@ -65,11 +65,11 @@ public void onMusicPlayerStateChangeEvent(MusicPlayerStateChangeEvent event) { embedBuilder1 = embedBuilder1 .setImage(audioTrackInfo1 != null && (audioTrackInfo1.artworkUrl != null && !audioTrackInfo1.artworkUrl.isBlank()) ? audioTrackInfo1.artworkUrl : "https://images.unsplash.com/photo-1546977463-943d58b78c19") .setTitle("**" + (audioTrackInfo1 != null ? LanguageService.getByGuild(event.getGuild(), "message.music.songInfoSlim", audioTrackInfo1.title, audioTrackInfo1.author) - : LanguageService.getByGuild(event.getGuild(), "message.music.notPlaying")) + "**"); + : LanguageService.getByGuild(event.getGuild(), "message.music.notPlaying")).block() + "**"); } else if (event.getState() != MusicPlayerStateChangeEvent.State.QUEUE_ADD) { embedBuilder1 = embedBuilder1 .setImage("https://images.unsplash.com/photo-1546977463-943d58b78c19") - .setTitle("**" + LanguageService.getByGuild(event.getGuild(), "message.music.notPlaying") + "**"); + .setTitle("**" + LanguageService.getByGuild(event.getGuild(), "message.music.notPlaying").block() + "**"); } messageEditBuilder.setEmbeds(embedBuilder1.build()); diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index a4a425f95..aaaf0bd67 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -1340,7 +1340,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.deleted").block()); embedBuilder.setColor(Color.GREEN); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel).block(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel.get()).block(); } }); } diff --git a/src/main/java/de/presti/ree6/logger/LoggerQueue.java b/src/main/java/de/presti/ree6/logger/LoggerQueue.java index c46a391ba..c6459b4d4 100644 --- a/src/main/java/de/presti/ree6/logger/LoggerQueue.java +++ b/src/main/java/de/presti/ree6/logger/LoggerQueue.java @@ -222,7 +222,7 @@ else if (loggerMessage.getType() == LogTyp.MEMBERROLE_CHANGE && loggerMessage in logMessageMember.getMember().getAsMention()).block()); if (!logMessageMember.getAddedRoles().isEmpty() || !logMessageMember.getRemovedRoles().isEmpty()) - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.roles") + ":**", stringBuilder.toString())); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.roles").block() + ":**", stringBuilder.toString())); modified = true; } @@ -321,8 +321,8 @@ else if (loggerMessage.getType() == LogTyp.ROLEDATA_CHANGE && loggerMessage inst if (logMessageRole.getPreviousName() != null && logMessageRole.getCurrentName() != null) { // Add new Fields with Information. - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.oldName") + "**", logMessageRole.getPreviousName())); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newName") + "**", logMessageRole.getCurrentName())); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.oldName").block() + "**", logMessageRole.getPreviousName())); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newName").block() + "**", logMessageRole.getCurrentName())); webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "** **", "** **")); } @@ -330,8 +330,8 @@ else if (loggerMessage.getType() == LogTyp.ROLEDATA_CHANGE && loggerMessage inst if (logMessageRole.isChangedMentioned()) { // Add new Fields with Information. - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.oldMentionable") + "**", String.valueOf(!logMessageRole.isMentioned()))); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newMentionable") + "**", String.valueOf(logMessageRole.isMentioned()))); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.oldMentionable").block() + "**", String.valueOf(!logMessageRole.isMentioned()))); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newMentionable").block() + "**", String.valueOf(logMessageRole.isMentioned()))); webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "** **", "** **")); } @@ -339,8 +339,8 @@ else if (loggerMessage.getType() == LogTyp.ROLEDATA_CHANGE && loggerMessage inst if (logMessageRole.isChangedHoisted()) { // Add new Fields with Information. - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.oldHoist") + "**", String.valueOf(!logMessageRole.isHoisted()))); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newHoist") + "**", String.valueOf(logMessageRole.isHoisted()))); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.oldHoist").block() + "**", String.valueOf(!logMessageRole.isHoisted()))); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newHoist").block() + "**", String.valueOf(logMessageRole.isHoisted()))); webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "** **", "** **")); } @@ -348,9 +348,9 @@ else if (loggerMessage.getType() == LogTyp.ROLEDATA_CHANGE && loggerMessage inst if (logMessageRole.getPreviousColor() != null || logMessageRole.getCurrentColor() != null) { // Add new Fields with Information. - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.oldColor") + "**", String.valueOf((logMessageRole.getPreviousColor() != null ? + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.oldColor").block() + "**", String.valueOf((logMessageRole.getPreviousColor() != null ? logMessageRole.getPreviousColor() : Color.gray).getRGB()))); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newColor") + "**", String.valueOf((logMessageRole.getCurrentColor() != null ? + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newColor").block() + "**", String.valueOf((logMessageRole.getCurrentColor() != null ? logMessageRole.getCurrentColor() : Color.gray).getRGB()))); webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "** **", "** **")); } @@ -388,7 +388,7 @@ else if (loggerMessage.getType() == LogTyp.ROLEDATA_CHANGE && loggerMessage inst // Add the String from the StringBuilder as Embed to the Message if (!stringBuilder.toString().isEmpty()) - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newPermissions") + "**", stringBuilder.toString())); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**" + LanguageService.getByGuild(loggerMessage.getGuild(), "label.newPermissions").block() + "**", stringBuilder.toString())); } else { // Check if the Role has been created. diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index 574c4e58a..c23d65269 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -655,7 +655,7 @@ public void unregisterTwitchChannel(String twitchChannel) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitchFollowerChannelUsername=:name", Map.of("name", finalTwitchChannel)) .subscribe(channelStats -> { - if (channelStats != null) return; + if (channelStats.isPresent()) return; if (isTwitchRegistered(finalTwitchChannel)) registeredTwitchChannels.remove(finalTwitchChannel); @@ -719,7 +719,7 @@ public void unregisterTwitterUser(String twitterUser) { if (!webhooks.isEmpty()) return; SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", Map.of("name", finalTwitterUser)).subscribe(x -> { - if (x != null) return; + if (x.isPresent()) return; if (isTwitterRegistered(finalTwitterUser)) { registeredTwitterUsers.remove(finalTwitterUser); @@ -880,7 +880,7 @@ public void unregisterYouTubeChannel(String youtubeChannel) { if (!webhooks.isEmpty()) return; SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", Map.of("name", youtubeChannel)).subscribe(channelStats -> { - if (channelStats != null) return; + if (channelStats.isPresent()) return; if (isYouTubeRegistered(youtubeChannel)) registeredYouTubeChannels.remove(youtubeChannel); }); @@ -1047,7 +1047,7 @@ public void unregisterSubreddit(String subreddit) { if (!webhooks.isEmpty()) return; SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", Map.of("name", subreddit)).subscribe(channelStats -> { - if (channelStats != null) return; + if (channelStats.isPresent()) return; if (isSubredditRegistered(subreddit)) registeredSubreddits.remove(subreddit); }); @@ -1193,7 +1193,7 @@ public void unregisterInstagramUser(String username) { SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(username).subscribe(webhooks -> { if (!webhooks.isEmpty()) return; - if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", Map.of("name", username)) != null) + if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", Map.of("name", username)).block().isPresent()) return; if (isInstagramUserRegistered(username)) registeredInstagramUsers.remove(username); From ee43685e699758b124741898034db749915411b1 Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 5 Jul 2024 16:17:18 +0200 Subject: [PATCH 27/94] Updating version. --- pom.xml | 4 ++-- src/main/java/de/presti/ree6/bot/BotWorker.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 841679b15..33b1455aa 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ de.presti Ree6 - 3.1.13 + 4.0.0 jar @@ -177,7 +177,7 @@ de.ree6 Ree6-SQL - 71a8aa6a9a + 79819ffcbc diff --git a/src/main/java/de/presti/ree6/bot/BotWorker.java b/src/main/java/de/presti/ree6/bot/BotWorker.java index bc9150527..52ebde78d 100644 --- a/src/main/java/de/presti/ree6/bot/BotWorker.java +++ b/src/main/java/de/presti/ree6/bot/BotWorker.java @@ -240,7 +240,7 @@ public static BotVersion getVersion() { public static String getBuild() { if (build == null) { build = Objects.requireNonNullElse(Main.class.getPackage().getImplementationVersion(), - Objects.requireNonNullElse(gitVersion, "3.1.13")); + Objects.requireNonNullElse(gitVersion, "4.0.0")); } return build; } From 71597fa14120029e8565beb4b69beac17de67ada Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 5 Jul 2024 16:49:47 +0200 Subject: [PATCH 28/94] Command stuff done, hopefully. --- .../presti/ree6/commands/CommandManager.java | 2 +- .../ree6/commands/interfaces/ICommand.java | 37 ++++++++++--------- 2 files changed, 21 insertions(+), 18 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/CommandManager.java b/src/main/java/de/presti/ree6/commands/CommandManager.java index c36fe7fb9..ad96aaf89 100644 --- a/src/main/java/de/presti/ree6/commands/CommandManager.java +++ b/src/main/java/de/presti/ree6/commands/CommandManager.java @@ -784,7 +784,7 @@ public void deleteMessage(Message message, InteractionHook interactionHook) { !message.isEphemeral() && interactionHook == null) { message.delete().onErrorMap(throwable -> { - log.error("[CommandManager] Couldn't delete a Message!", throwable); + log.error("[CommandManager] Couldn't delete a Message -> {}", throwable.getMessage()); return null; }).queue(); } diff --git a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java index ab8f85573..4271fbc68 100644 --- a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java +++ b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java @@ -1,12 +1,12 @@ package de.presti.ree6.commands.interfaces; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.news.AnnouncementManager; import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.sql.entities.Setting; import io.sentry.Sentry; import net.dv8tion.jda.api.EmbedBuilder; @@ -30,6 +30,9 @@ public interface ICommand { Logger log = LoggerFactory.getLogger(ICommand.class); default Mono onMonoPerform(CommandEvent commandEvent) { + if (BotConfig.isDebug()) + log.info("Command {} called by {} in {} ({}).", commandEvent.getCommand(), commandEvent.getMember().getUser().getName(), commandEvent.getGuild().getName(), commandEvent.getGuild().getId()); + return Mono.fromRunnable(() -> onPerform(commandEvent)).thenReturn(true).onErrorResume(throwable -> { if (!throwable.getMessage().contains("Unknown Message")) { commandEvent.reply(commandEvent.getResource("command.perform.internalError"), 5); @@ -38,23 +41,21 @@ default Mono onMonoPerform(CommandEvent commandEvent) { } return Mono.just(false); }).publishOn(Schedulers.boundedElastic()).doOnSuccess(success -> { - if (success) { - // Update Stats. - SQLSession.getSqlConnector().getSqlWorker().addStats(commandEvent.getGuild().getIdLong(), commandEvent.getCommand()); - Optional setting = SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").block(); - if (setting.isEmpty() || !setting.get().getBooleanValue()) return; - AnnouncementManager.getAnnouncementList().forEach(a -> { - if (!AnnouncementManager.hasReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id())) { - Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder().setTitle(a.title()) - .setAuthor(BotConfig.getBotName() + "-Info") - .setDescription(a.content().replace("\\n", "\n") + "\n\n" + LanguageService.getByGuild(commandEvent.getGuild(), "message.news.notice").block()) - .setFooter(BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) - .setColor(BotWorker.randomEmbedColor()), 15, commandEvent.getChannel()); + // Update Stats. + SQLSession.getSqlConnector().getSqlWorker().addStats(commandEvent.getGuild().getIdLong(), commandEvent.getCommand()); + Optional setting = SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").block(); + if (setting.isEmpty() || !setting.get().getBooleanValue()) return; + AnnouncementManager.getAnnouncementList().forEach(a -> { + if (!AnnouncementManager.hasReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id())) { + Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder().setTitle(a.title()) + .setAuthor(BotConfig.getBotName() + "-Info") + .setDescription(a.content().replace("\\n", "\n") + "\n\n" + LanguageService.getByGuild(commandEvent.getGuild(), "message.news.notice").block()) + .setFooter(BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) + .setColor(BotWorker.randomEmbedColor()), 15, commandEvent.getChannel()); - AnnouncementManager.addReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id()); - } - }); - } + AnnouncementManager.addReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id()); + } + }); }); } @@ -62,7 +63,9 @@ default Mono onMonoPerform(CommandEvent commandEvent) { * Will be fired when the Command is called. * * @param commandEvent the Event, with every needed data. + * @deprecated Use {@link #onMonoPerform(CommandEvent)} instead. */ + @Deprecated(forRemoval = true, since = "4.0.0") default void onASyncPerform(CommandEvent commandEvent) { CompletableFuture.runAsync(() -> onPerform(commandEvent)).exceptionally(throwable -> { if (!throwable.getMessage().contains("Unknown Message")) { From e7feab41763aa1b84ab8e2586b09434f292ebc55 Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 5 Jul 2024 17:12:15 +0200 Subject: [PATCH 29/94] Start of the new Sonic System. --- .../commands/impl/community/Notifier.java | 8 +- .../de/presti/ree6/events/MenuEvents.java | 4 +- src/main/java/de/presti/ree6/main/Main.java | 9 - .../ree6/module/notifications/ISonic.java | 41 +++++ .../module/notifications/SonicIdentifier.java | 14 ++ .../notifications/impl/YouTubeSonic.java | 166 +++++++++++++++++ .../de/presti/ree6/utils/apis/Notifier.java | 173 +----------------- 7 files changed, 236 insertions(+), 179 deletions(-) create mode 100644 src/main/java/de/presti/ree6/module/notifications/ISonic.java create mode 100644 src/main/java/de/presti/ree6/module/notifications/SonicIdentifier.java create mode 100644 src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java b/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java index 9fdeae148..9b380c375 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java @@ -240,8 +240,8 @@ public void onPerform(CommandEvent commandEvent) { }); commandEvent.reply(commandEvent.getResource("message.youtubeNotifier.added", name), 5); - if (!Main.getInstance().getNotifier().isYouTubeRegistered(channelResult.getId())) { - Main.getInstance().getNotifier().registerYouTubeChannel(channelResult.getId()); + if (!Main.getInstance().getNotifier().getYouTubeSonic().contains(channelResult.getId())) { + Main.getInstance().getNotifier().getYouTubeSonic().add(channelResult.getId()); } } @@ -449,8 +449,8 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().removeYouTubeWebhook(commandEvent.getGuild().getIdLong(), channelResult.getId()); commandEvent.reply(commandEvent.getResource("message.youtubeNotifier.removed", name), 5); - if (Main.getInstance().getNotifier().isYouTubeRegistered(channelResult.getId())) { - Main.getInstance().getNotifier().unregisterYouTubeChannel(channelResult.getId()); + if (Main.getInstance().getNotifier().getYouTubeSonic().contains(channelResult.getId())) { + Main.getInstance().getNotifier().getYouTubeSonic().remove(channelResult.getId()); } } diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index aaaf0bd67..28a8e4c23 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -590,7 +590,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { channelStats.setYoutubeSubscribersChannelId(voiceChannel.getId()); channelStats.setYoutubeSubscribersChannelUsername(youTubeChannel.getId()); SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); - Main.getInstance().getNotifier().registerYouTubeChannel(youTubeChannel.getId()); + Main.getInstance().getNotifier().getYouTubeSonic().add(youTubeChannel.getId()); } else { SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), null, @@ -606,7 +606,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { youTubeChannel.getId(), null, null)).block(); - Main.getInstance().getNotifier().registerYouTubeChannel(youTubeChannel.getId()); + Main.getInstance().getNotifier().getYouTubeSonic().add(youTubeChannel.getId()); } }); }); diff --git a/src/main/java/de/presti/ree6/main/Main.java b/src/main/java/de/presti/ree6/main/Main.java index 6c1dec164..eb3494520 100644 --- a/src/main/java/de/presti/ree6/main/Main.java +++ b/src/main/java/de/presti/ree6/main/Main.java @@ -366,15 +366,6 @@ public static void main(String[] args) { Sentry.captureException(exception); } - try { - // Register all YouTube channels. - SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels().subscribe(getInstance().getNotifier()::registerYouTubeChannel); - getInstance().getNotifier().registerYouTubeChannel(channelStats.stream().map(ChannelStats::getYoutubeSubscribersChannelUsername).filter(Objects::nonNull).toList()); - } catch (Exception exception) { - log.error("Error while loading YouTube data: {}", exception.getMessage()); - Sentry.captureException(exception); - } - try { // Register all Reddit Subreddits. SQLSession.getSqlConnector().getSqlWorker().getAllSubreddits().subscribe(getInstance().getNotifier()::registerSubreddit); diff --git a/src/main/java/de/presti/ree6/module/notifications/ISonic.java b/src/main/java/de/presti/ree6/module/notifications/ISonic.java new file mode 100644 index 000000000..856940ecf --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/ISonic.java @@ -0,0 +1,41 @@ +package de.presti.ree6.module.notifications; + +import de.presti.ree6.module.IManager; + +/** + * Interface for Secure Online Notification Interoperable Class Modules. + */ +public interface ISonic extends IManager { + + void load(); + void run(); + void unload(); + + default void add(long identifier) { + add(new SonicIdentifier(String.valueOf(identifier))); + } + + default void add(String identifier) { + add(new SonicIdentifier(identifier)); + } + + default boolean contains(long identifier) { + return getList().stream().anyMatch(x -> x.getIdentifierAsLong() == identifier); + } + + default boolean contains(String identifier) { + return getList().stream().anyMatch(x -> x.getIdentifier().equals(identifier)); + } + + default boolean contains(SonicIdentifier identifier) { + return getList().stream().anyMatch(x -> x.getIdentifier().equals(identifier.getIdentifier())); + } + + default void remove(long identifier) { + remove(get(identifier)); + } + + default void remove(String identifier) { + remove(get(identifier)); + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/SonicIdentifier.java b/src/main/java/de/presti/ree6/module/notifications/SonicIdentifier.java new file mode 100644 index 000000000..6a8db249a --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/SonicIdentifier.java @@ -0,0 +1,14 @@ +package de.presti.ree6.module.notifications; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class SonicIdentifier { + private String identifier; + + public long getIdentifierAsLong() { + return Long.parseLong(this.identifier); + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java new file mode 100644 index 000000000..678affebd --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java @@ -0,0 +1,166 @@ +package de.presti.ree6.module.notifications.impl; + +import club.minnced.discord.webhook.send.WebhookEmbed; +import club.minnced.discord.webhook.send.WebhookEmbedBuilder; +import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.util.WebhookUtil; +import de.presti.ree6.language.LanguageService; +import de.presti.ree6.main.Main; +import de.presti.ree6.module.notifications.ISonic; +import de.presti.ree6.module.notifications.SonicIdentifier; +import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.stats.ChannelStats; +import de.presti.ree6.utils.apis.YouTubeAPIHandler; +import de.presti.wrapper.entities.VideoResult; +import de.presti.wrapper.entities.channel.ChannelResult; +import io.sentry.Sentry; +import lombok.extern.slf4j.Slf4j; +import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; + +import java.awt.*; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Slf4j +public class YouTubeSonic implements ISonic { + ArrayList youtubeChannels = new ArrayList<>(); + + @Override + public void load() { + try { + // Register all YouTube channels. + SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels().subscribe(channel -> + channel.forEach(youtubeChannel -> + add(new SonicIdentifier(youtubeChannel)))); + } catch (Exception exception) { + log.error("Error while loading YouTube data: {}", exception.getMessage()); + Sentry.captureException(exception); + } + } + + @Override + public List getList() { + return youtubeChannels; + } + + @Override + public void run() { + for (String channel : getList().stream().map(SonicIdentifier::getIdentifier).toList()) { + SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(channel).subscribe(webhooks -> { + if (!webhooks.isEmpty()) { + try { + List playlistItemList = YouTubeAPIHandler.getInstance().getYouTubeUploads(channel); + if (!playlistItemList.isEmpty()) { + for (VideoResult playlistItem : playlistItemList) { + + Main.getInstance().logAnalytic("Video: " + playlistItem.getTitle() + " | " + playlistItem.getUploadDate() + " | " + playlistItem.getActualUploadDate() + " | " + playlistItem.getTimeAgo()); + Main.getInstance().logAnalytic("Current: " + System.currentTimeMillis() + " | " + (playlistItem.getUploadDate() > System.currentTimeMillis() - Duration.ofMinutes(5).toMillis()) + " | " + + (playlistItem.getActualUploadDate() != null && playlistItem.getActualUploadDate().before(new Date(System.currentTimeMillis() - Duration.ofDays(2).toMillis()))) + " | " + (playlistItem.getTimeAgo() > 0 && Duration.ofMinutes(5).toMillis() >= playlistItem.getTimeAgo())); + + if (playlistItem.getUploadDate() != -1 && (playlistItem.getUploadDate() > System.currentTimeMillis() - Duration.ofMinutes(5).toMillis() || + (playlistItem.getTimeAgo() > 0 && Duration.ofMinutes(5).toMillis() >= playlistItem.getTimeAgo())) && + playlistItem.getActualUploadDate() != null && !playlistItem.getActualUploadDate().before(new Date(System.currentTimeMillis() - Duration.ofDays(2).toMillis()))) { + + Main.getInstance().logAnalytic("Passed! -> " + playlistItem.getTitle() + " | " + playlistItem.getUploadDate() + " | " + playlistItem.getActualUploadDate()); + // Create a Webhook Message. + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(playlistItem.getOwnerName(), null)); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("YouTube Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + + webhookEmbedBuilder.setImageUrl(playlistItem.getThumbnail()); + + webhookEmbedBuilder.setDescription("[**" + playlistItem.getTitle() + "**](https://www.youtube.com/watch?v=" + playlistItem.getId() + ")"); + + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + webhookEmbedBuilder.setColor(Color.RED.getRGB()); + + webhooks.forEach(webhook -> { + String message = webhook.getMessage().replace("%name%", playlistItem.getOwnerName()) + .replace("%title%", playlistItem.getTitle()) + .replace("%description%", playlistItem.getDescriptionSnippet() != null ? "No Description" : playlistItem.getDescriptionSnippet()) + .replace("%url%", "https://www.youtube.com/watch?v=" + playlistItem.getId()); + + webhookMessageBuilder.setContent(message); + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); + }); + + break; + } + } + } + } catch (Exception exception) { + Sentry.captureException(exception); + log.error("Couldn't get user data of " + channel + "!", exception); + } + } + }); + + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), + "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", Map.of("name", channel)).subscribe(channelStats -> { + if (!channelStats.isEmpty()) { + ChannelResult youTubeChannel; + try { + // TODO:: change YT Tracker to use the ID instead of username. + youTubeChannel = YouTubeAPIHandler.getInstance().getYouTubeChannelById(channel); + } catch (Exception e) { + Sentry.captureException(e); + return; + } + + if (youTubeChannel == null) return; + + for (ChannelStats channelStat : channelStats) { + if (channelStat.getYoutubeSubscribersChannelId() != null) { + GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getYoutubeSubscribersChannelId()); + + if (guildChannel == null) continue; + + LanguageService.getByGuild(guildChannel.getGuild(), "label.youtubeCountName", youTubeChannel.getSubscriberCountText()).subscribe(newName -> { + if (!guildChannel.getName().equalsIgnoreCase(newName)) { + if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) + return; + + guildChannel.getManager().setName(newName).queue(); + } + }); + } + } + } + }); + } + } + + @Override + public void unload() { + + } + + @Override + public void remove(SonicIdentifier object) { + if (YouTubeAPIHandler.getInstance() == null) return; + if (!contains(object)) return; + + SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(object.getIdentifier()).subscribe(webhooks -> { + if (!webhooks.isEmpty()) return; + + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", + Map.of("name", object.getIdentifier())).subscribe(channelStats -> { + if (channelStats.isPresent()) return; + + youtubeChannels.remove(object); + }); + }); + } +} diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index c23d65269..341854096 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -36,6 +36,7 @@ import de.presti.ree6.bot.util.WebhookUtil; import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; +import de.presti.ree6.module.notifications.impl.YouTubeSonic; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.TwitchIntegration; import de.presti.ree6.sql.entities.stats.ChannelStats; @@ -118,6 +119,12 @@ public class Notifier { @Getter(AccessLevel.PUBLIC) private IGClient instagramClient; + /** + * Instance of the YouTube Sonic Manager. + */ + @Getter(AccessLevel.PUBLIC) + private YouTubeSonic youTubeSonic; + /** * Local list of registered Twitch Channels. */ @@ -129,10 +136,6 @@ public class Notifier { @Getter(AccessLevel.PUBLIC) private final HashMap twitchSubscription = new HashMap<>(); - /** - * Local list of registered YouTube Channels. - */ - private final ArrayList registeredYouTubeChannels = new ArrayList<>(); /** * Local list of registered Twitter Users. */ @@ -299,7 +302,8 @@ public Notifier() { log.info("Initializing Streams..."); log.info("Creating YouTube Streams..."); - createYTStream(); + youTubeSonic = new YouTubeSonic(); + // TODO:: Create a YouTube Stream for the Sonic Channel. log.info("Creating Twitter Streams..."); ThreadUtil.createThread(x -> { @@ -740,165 +744,6 @@ public boolean isTwitterRegistered(String twitterUser) { //endregion - //region YouTube - - /** - * Create an API Stream used to update ChannelStats and Notifier of YT. - */ - public void createYTStream() { - ThreadUtil.createThread(x -> { - for (String channel : registeredYouTubeChannels) { - SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(channel).subscribe(webhooks -> { - if (!webhooks.isEmpty()) { - try { - List playlistItemList = YouTubeAPIHandler.getInstance().getYouTubeUploads(channel); - if (!playlistItemList.isEmpty()) { - for (VideoResult playlistItem : playlistItemList) { - - Main.getInstance().logAnalytic("Video: " + playlistItem.getTitle() + " | " + playlistItem.getUploadDate() + " | " + playlistItem.getActualUploadDate() + " | " + playlistItem.getTimeAgo()); - Main.getInstance().logAnalytic("Current: " + System.currentTimeMillis() + " | " + (playlistItem.getUploadDate() > System.currentTimeMillis() - Duration.ofMinutes(5).toMillis()) + " | " - + (playlistItem.getActualUploadDate() != null && playlistItem.getActualUploadDate().before(new Date(System.currentTimeMillis() - Duration.ofDays(2).toMillis()))) + " | " + (playlistItem.getTimeAgo() > 0 && Duration.ofMinutes(5).toMillis() >= playlistItem.getTimeAgo())); - - if (playlistItem.getUploadDate() != -1 && (playlistItem.getUploadDate() > System.currentTimeMillis() - Duration.ofMinutes(5).toMillis() || - (playlistItem.getTimeAgo() > 0 && Duration.ofMinutes(5).toMillis() >= playlistItem.getTimeAgo())) && - playlistItem.getActualUploadDate() != null && !playlistItem.getActualUploadDate().before(new Date(System.currentTimeMillis() - Duration.ofDays(2).toMillis()))) { - - Main.getInstance().logAnalytic("Passed! -> " + playlistItem.getTitle() + " | " + playlistItem.getUploadDate() + " | " + playlistItem.getActualUploadDate()); - // Create a Webhook Message. - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName()); - - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(playlistItem.getOwnerName(), null)); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("YouTube Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); - - webhookEmbedBuilder.setImageUrl(playlistItem.getThumbnail()); - - webhookEmbedBuilder.setDescription("[**" + playlistItem.getTitle() + "**](https://www.youtube.com/watch?v=" + playlistItem.getId() + ")"); - - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); - webhookEmbedBuilder.setColor(Color.RED.getRGB()); - - webhooks.forEach(webhook -> { - String message = webhook.getMessage().replace("%name%", playlistItem.getOwnerName()) - .replace("%title%", playlistItem.getTitle()) - .replace("%description%", playlistItem.getDescriptionSnippet() != null ? "No Description" : playlistItem.getDescriptionSnippet()) - .replace("%url%", "https://www.youtube.com/watch?v=" + playlistItem.getId()); - - webhookMessageBuilder.setContent(message); - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); - }); - - break; - } - } - } - } catch (Exception exception) { - Sentry.captureException(exception); - log.error("Couldn't get user data of " + channel + "!", exception); - } - } - }); - - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", Map.of("name", channel)).subscribe(channelStats -> { - if (!channelStats.isEmpty()) { - ChannelResult youTubeChannel; - try { - // TODO:: change YT Tracker to use the ID instead of username. - youTubeChannel = YouTubeAPIHandler.getInstance().getYouTubeChannelById(channel); - } catch (Exception e) { - Sentry.captureException(e); - return; - } - - if (youTubeChannel == null) return; - - for (ChannelStats channelStat : channelStats) { - if (channelStat.getYoutubeSubscribersChannelId() != null) { - GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getYoutubeSubscribersChannelId()); - - if (guildChannel == null) continue; - - LanguageService.getByGuild(guildChannel.getGuild(), "label.youtubeCountName", youTubeChannel.getSubscriberCountText()).subscribe(newName -> { - if (!guildChannel.getName().equalsIgnoreCase(newName)) { - if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) - return; - - guildChannel.getManager().setName(newName).queue(); - } - }); - } - } - } - }); - } - }, x -> { - log.error("Couldn't run YT checker!", x); - Sentry.captureException(x); - // Default is 5 minutes. - }, Duration.ofMinutes(5), true, true); - } - - /** - * Used to register an Upload Event for the given YouTube Channel. - * - * @param youtubeChannel the Name of the YouTube Channel. - */ - public void registerYouTubeChannel(String youtubeChannel) { - if (YouTubeAPIHandler.getInstance() == null) return; - - if (!isYouTubeRegistered(youtubeChannel)) registeredYouTubeChannels.add(youtubeChannel); - } - - /** - * Used to register an upload Event for the given YouTube Channels. - * - * @param youtubeChannels the Names of the YouTube Channels. - */ - public void registerYouTubeChannel(List youtubeChannels) { - if (YouTubeAPIHandler.getInstance() == null) return; - - youtubeChannels.forEach(s -> { - if (!isYouTubeRegistered(s)) registeredYouTubeChannels.add(s); - }); - } - - /** - * Used to unregister an Upload Event for the given YouTube Channel - * - * @param youtubeChannel the Name of the YouTube Channel. - */ - public void unregisterYouTubeChannel(String youtubeChannel) { - if (YouTubeAPIHandler.getInstance() == null) return; - - SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(youtubeChannel).subscribe(webhooks -> { - if (!webhooks.isEmpty()) return; - - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE youtubeSubscribersChannelUsername=:name", Map.of("name", youtubeChannel)).subscribe(channelStats -> { - if (channelStats.isPresent()) return; - - if (isYouTubeRegistered(youtubeChannel)) registeredYouTubeChannels.remove(youtubeChannel); - }); - }); - } - - /** - * Check if a YouTube Channel is already being checked. - * - * @param youtubeChannel the Name of the YouTube Channel. - * @return true, if there is an Event for the Channel | false, if there isn't an Event for the Channel. - */ - public boolean isYouTubeRegistered(String youtubeChannel) { - return registeredYouTubeChannels.contains(youtubeChannel); - } - - //endregion - //region Reddit public List getSubredditPosts(String subreddit, Sorting sorting, int limit) throws AuthenticationException, IOException, InterruptedException { From 2c5bd2357007144620f863a2f13188658402fe41 Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 5 Jul 2024 18:09:52 +0200 Subject: [PATCH 30/94] Finished up the Sonic System. --- .../commands/impl/community/Notifier.java | 48 +- .../presti/ree6/commands/impl/nsfw/NSFW.java | 2 +- .../de/presti/ree6/events/MenuEvents.java | 18 +- src/main/java/de/presti/ree6/main/Main.java | 61 +- .../ree6/module/notifications/ISonic.java | 6 + .../notifications/impl/InstagramSonic.java | 163 +++ .../module/notifications/impl/RSSSonic.java | 231 ++++ .../notifications/impl/RedditSonic.java | 184 ++++ .../notifications/impl/TikTokSonic.java | 116 ++ .../notifications/impl/TwitchSonic.java | 174 +++ .../notifications/impl/TwitterSonic.java | 101 ++ .../notifications/impl/YouTubeSonic.java | 19 +- .../de/presti/ree6/utils/apis/Notifier.java | 994 +----------------- 13 files changed, 1073 insertions(+), 1044 deletions(-) create mode 100644 src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java create mode 100644 src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java create mode 100644 src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java create mode 100644 src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java create mode 100644 src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java create mode 100644 src/main/java/de/presti/ree6/module/notifications/impl/TwitterSonic.java diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java b/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java index 9b380c375..5af344937 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Notifier.java @@ -188,8 +188,8 @@ public void onPerform(CommandEvent commandEvent) { }); commandEvent.reply(commandEvent.getResource("message.instagramNotifier.added", name), 5); - if (!Main.getInstance().getNotifier().isInstagramUserRegistered(name)) { - Main.getInstance().getNotifier().registerInstagramUser(name); + if (!Main.getInstance().getNotifier().getInstagramSonic().contains(name)) { + Main.getInstance().getNotifier().getInstagramSonic().add(name); } } @@ -267,8 +267,8 @@ public void onPerform(CommandEvent commandEvent) { }); commandEvent.reply(commandEvent.getResource("message.twitchNotifier.added", name), 5); - if (!Main.getInstance().getNotifier().isTwitchRegistered(name)) { - Main.getInstance().getNotifier().registerTwitchChannel(name); + if (!Main.getInstance().getNotifier().getTwitchSonic().contains(name)) { + Main.getInstance().getNotifier().getTwitchSonic().add(name); } } @@ -301,8 +301,8 @@ public void onPerform(CommandEvent commandEvent) { }); commandEvent.reply(commandEvent.getResource("message.twitterNotifier.added", name), 5); - if (!Main.getInstance().getNotifier().isTwitterRegistered(name)) { - Main.getInstance().getNotifier().registerTwitterUser(name); + if (!Main.getInstance().getNotifier().getTwitterSonic().contains(name)) { + Main.getInstance().getNotifier().getTwitterSonic().add(name); } } @@ -337,8 +337,8 @@ public void onPerform(CommandEvent commandEvent) { }); commandEvent.reply(commandEvent.getResource("message.tiktokNotifier.added", name), 5); - if (!Main.getInstance().getNotifier().isTikTokUserRegistered(Long.parseLong(tikTokUser.getId()))) { - Main.getInstance().getNotifier().registerTikTokUser(Long.parseLong(tikTokUser.getId())); + if (!Main.getInstance().getNotifier().getTikTokSonic().contains(Long.parseLong(tikTokUser.getId()))) { + Main.getInstance().getNotifier().getTikTokSonic().add(Long.parseLong(tikTokUser.getId())); } } catch (Exception e) { commandEvent.reply(commandEvent.getResource("message.tiktokNotifier.invalidUser", name), 5); @@ -367,8 +367,8 @@ public void onPerform(CommandEvent commandEvent) { }); commandEvent.reply(commandEvent.getResource("message.redditNotifier.added", name), 5); - if (!Main.getInstance().getNotifier().isSubredditRegistered(name)) { - Main.getInstance().getNotifier().registerSubreddit(name); + if (!Main.getInstance().getNotifier().getRedditSonic().contains(name)) { + Main.getInstance().getNotifier().getRedditSonic().add(name); } } @@ -395,8 +395,8 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().addRSSWebhook(commandEvent.getGuild().getIdLong(), channel.getIdLong(), w.getIdLong(), w.getToken(), name.toLowerCase())); commandEvent.reply(commandEvent.getResource("message.rssNotifier.added", name), 5); - if (!Main.getInstance().getNotifier().isRSSRegistered(name)) { - Main.getInstance().getNotifier().registerRSS(name); + if (!Main.getInstance().getNotifier().getRssSonic().contains(name)) { + Main.getInstance().getNotifier().getRedditSonic().add(name); } } @@ -415,8 +415,8 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().removeInstagramWebhook(commandEvent.getGuild().getIdLong(), name); commandEvent.reply(commandEvent.getResource("message.instagramNotifier.removed", name), 5); - if (Main.getInstance().getNotifier().isInstagramUserRegistered(name)) { - Main.getInstance().getNotifier().unregisterInstagramUser(name); + if (Main.getInstance().getNotifier().getInstagramSonic().contains(name)) { + Main.getInstance().getNotifier().getInstagramSonic().remove(name); } } @@ -464,8 +464,8 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().removeTwitchWebhook(commandEvent.getGuild().getIdLong(), name); commandEvent.reply(commandEvent.getResource("message.twitchNotifier.removed", name), 5); - if (Main.getInstance().getNotifier().isTwitchRegistered(name)) { - Main.getInstance().getNotifier().unregisterTwitchChannel(name); + if (Main.getInstance().getNotifier().getTwitchSonic().contains(name)) { + Main.getInstance().getNotifier().getTwitchSonic().remove(name); } } @@ -479,8 +479,8 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().removeTwitterWebhook(commandEvent.getGuild().getIdLong(), name); commandEvent.reply(commandEvent.getResource("message.twitterNotifier.removed", name), 5); - if (Main.getInstance().getNotifier().isTwitterRegistered(name)) { - Main.getInstance().getNotifier().unregisterTwitterUser(name); + if (Main.getInstance().getNotifier().getTwitterSonic().contains(name)) { + Main.getInstance().getNotifier().getTwitterSonic().remove(name); } } @@ -499,8 +499,8 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.tiktokNotifier.removed", name), 5); - if (Main.getInstance().getNotifier().isTikTokUserRegistered(Long.parseLong(tikTokUser.getId()))) { - Main.getInstance().getNotifier().unregisterTikTokUser(Long.parseLong(tikTokUser.getId())); + if (Main.getInstance().getNotifier().getTikTokSonic().contains(Long.parseLong(tikTokUser.getId()))) { + Main.getInstance().getNotifier().getTikTokSonic().remove(Long.parseLong(tikTokUser.getId())); } } catch (Exception e) { commandEvent.reply(commandEvent.getResource("message.tiktokNotifier.invalidUser", name), 5); @@ -517,8 +517,8 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().removeRedditWebhook(commandEvent.getGuild().getIdLong(), name); commandEvent.reply(commandEvent.getResource("message.redditNotifier.removed", name), 5); - if (Main.getInstance().getNotifier().isSubredditRegistered(name)) { - Main.getInstance().getNotifier().unregisterSubreddit(name); + if (Main.getInstance().getNotifier().getRedditSonic().contains(name)) { + Main.getInstance().getNotifier().getRedditSonic().remove(name); } } @@ -532,8 +532,8 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().removeRSSWebhook(commandEvent.getGuild().getIdLong(), name); commandEvent.reply(commandEvent.getResource("message.rssNotifier.removed", name), 5); - if (Main.getInstance().getNotifier().isRSSRegistered(name)) { - Main.getInstance().getNotifier().unregisterRSS(name); + if (Main.getInstance().getNotifier().getRssSonic().contains(name)) { + Main.getInstance().getNotifier().getRssSonic().remove(name); } } diff --git a/src/main/java/de/presti/ree6/commands/impl/nsfw/NSFW.java b/src/main/java/de/presti/ree6/commands/impl/nsfw/NSFW.java index 367b66118..0d0733b1b 100644 --- a/src/main/java/de/presti/ree6/commands/impl/nsfw/NSFW.java +++ b/src/main/java/de/presti/ree6/commands/impl/nsfw/NSFW.java @@ -50,7 +50,7 @@ public void sendImage(CommandEvent commandEvent) { List images = new ArrayList<>(); try { - List request = Main.getInstance().getNotifier().getSubredditPosts("hentai", Sorting.HOT, 50); + List request = Main.getInstance().getNotifier().getRedditSonic().getSubredditPosts("hentai", Sorting.HOT, 50); request.forEach(x -> { String fileUrl = x.getUrl().toLowerCase(); diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index 28a8e4c23..5ab58d424 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -490,7 +490,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { channelStatsEntity.setTwitchFollowerChannelId(voiceChannel.getId()); channelStatsEntity.setTwitchFollowerChannelUsername(twitchUsername); SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStatsEntity).block(); - Main.getInstance().getNotifier().registerTwitchChannel(twitchUsername); + Main.getInstance().getNotifier().getTwitchSonic().add(twitchUsername); } else { ChannelStats channelStatsEntity = new ChannelStats(event.getGuild().getIdLong(), null, @@ -507,7 +507,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { null, null); SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStatsEntity).block(); - Main.getInstance().getNotifier().registerTwitchChannel(twitchUsername); + Main.getInstance().getNotifier().getTwitterSonic().add(twitchUsername); } }); }); @@ -648,7 +648,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { RedditSubreddit subreddit; try { - subreddit = Main.getInstance().getNotifier().getSubreddit(subredditName); + subreddit = Main.getInstance().getNotifier().getRedditSonic().getSubreddit(subredditName); } catch (IOException | InterruptedException e) { embedBuilder .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) @@ -674,7 +674,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { channelStats.setSubredditMemberChannelId(voiceChannel.getId()); channelStats.setSubredditMemberChannelSubredditName(subredditName); SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); - Main.getInstance().getNotifier().registerSubreddit(subredditName); + Main.getInstance().getNotifier().getRedditSonic().add(subredditName); } else { SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), null, @@ -690,7 +690,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { null, voiceChannel.getId(), subredditName)).block(); - Main.getInstance().getNotifier().registerSubreddit(subredditName); + Main.getInstance().getNotifier().getRedditSonic().add(subredditName); } }); }); @@ -758,7 +758,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { channelStats.setTwitterFollowerChannelId(voiceChannel.getId()); channelStats.setTwitterFollowerChannelUsername(twitterName); SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); - Main.getInstance().getNotifier().registerTwitterUser(twitterName); + Main.getInstance().getNotifier().getTwitterSonic().add(twitterName); } else { SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), null, @@ -774,7 +774,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { null, null, null)).block(); - Main.getInstance().getNotifier().registerTwitterUser(twitterName); + Main.getInstance().getNotifier().getTwitterSonic().add(twitterName); } }); }); @@ -842,7 +842,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { channelStats.setInstagramFollowerChannelId(voiceChannel.getId()); channelStats.setInstagramFollowerChannelUsername(instagramName); SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); - Main.getInstance().getNotifier().registerInstagramUser(instagramName); + Main.getInstance().getNotifier().getInstagramSonic().add(instagramName); } else { SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), null, @@ -858,7 +858,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { null, null, null)).block(); - Main.getInstance().getNotifier().registerInstagramUser(instagramName); + Main.getInstance().getNotifier().getInstagramSonic().add(instagramName); } }); diff --git a/src/main/java/de/presti/ree6/main/Main.java b/src/main/java/de/presti/ree6/main/Main.java index eb3494520..5f57f1a26 100644 --- a/src/main/java/de/presti/ree6/main/Main.java +++ b/src/main/java/de/presti/ree6/main/Main.java @@ -345,61 +345,12 @@ public static void main(String[] args) { ThreadUtil.createThread(x -> { log.info("Loading Notifier data."); SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), "FROM ChannelStats", null).subscribe(channelStats -> { - try { - // Register all Twitch Channels. - SQLSession.getSqlConnector().getSqlWorker().getAllTwitchNames().subscribe(getInstance().getNotifier()::registerTwitchChannel); - getInstance().getNotifier().registerTwitchChannel(channelStats.stream().map(ChannelStats::getTwitchFollowerChannelUsername).filter(Objects::nonNull).toList()); - - // Register the Event-handler. - getInstance().getNotifier().registerTwitchEventHandler(); - } catch (Exception exception) { - log.error("Error while loading Twitch data: {}", exception.getMessage()); - Sentry.captureException(exception); - } - - try { - // Register all Twitter Users. - SQLSession.getSqlConnector().getSqlWorker().getAllTwitterNames().subscribe(getInstance().getNotifier()::registerTwitterUser); - getInstance().getNotifier().registerTwitterUser(channelStats.stream().map(ChannelStats::getTwitterFollowerChannelUsername).filter(Objects::nonNull).toList()); - } catch (Exception exception) { - log.error("Error while loading Twitter data: {}", exception.getMessage()); - Sentry.captureException(exception); - } - - try { - // Register all Reddit Subreddits. - SQLSession.getSqlConnector().getSqlWorker().getAllSubreddits().subscribe(getInstance().getNotifier()::registerSubreddit); - getInstance().getNotifier().registerSubreddit(channelStats.stream().map(ChannelStats::getSubredditMemberChannelSubredditName).filter(Objects::nonNull).toList()); - } catch (Exception exception) { - log.error("Error while loading Reddit data: {}", exception.getMessage()); - Sentry.captureException(exception); - } - - try { - // Register all Instagram Users. - SQLSession.getSqlConnector().getSqlWorker().getAllInstagramUsers().subscribe(getInstance().getNotifier()::registerInstagramUser); - getInstance().getNotifier().registerInstagramUser(channelStats.stream().map(ChannelStats::getInstagramFollowerChannelUsername).filter(Objects::nonNull).toList()); - } catch (Exception exception) { - log.error("Error while loading Instagram data: {}", exception.getMessage()); - Sentry.captureException(exception); - } - - try { - // Register all TikTok Users. - SQLSession.getSqlConnector().getSqlWorker().getAllTikTokNames().subscribe(tiktokNames -> - tiktokNames.forEach(tikTokName -> getInstance().getNotifier().registerTikTokUser(Long.parseLong(tikTokName)))); - } catch (Exception exception) { - log.error("Error while loading TikTok data: {}", exception.getMessage()); - Sentry.captureException(exception); - } - - try { - // Register all RSS-Feeds. - SQLSession.getSqlConnector().getSqlWorker().getAllRSSUrls().subscribe(getInstance().getNotifier()::registerRSS); - } catch (Exception exception) { - log.error("Error while loading RSS data: {}", exception.getMessage()); - Sentry.captureException(exception); - } + getInstance().getNotifier().getYouTubeSonic().load(channelStats); + getInstance().getNotifier().getTwitchSonic().load(channelStats); + getInstance().getNotifier().getInstagramSonic().load(channelStats); + getInstance().getNotifier().getTwitterSonic().load(channelStats); + getInstance().getNotifier().getTikTokSonic().load(channelStats); + getInstance().getNotifier().getRssSonic().load(channelStats); }); }, t -> Sentry.captureException(t.getCause())); } diff --git a/src/main/java/de/presti/ree6/module/notifications/ISonic.java b/src/main/java/de/presti/ree6/module/notifications/ISonic.java index 856940ecf..5e0159e62 100644 --- a/src/main/java/de/presti/ree6/module/notifications/ISonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/ISonic.java @@ -1,12 +1,18 @@ package de.presti.ree6.module.notifications; import de.presti.ree6.module.IManager; +import de.presti.ree6.sql.entities.stats.ChannelStats; + +import java.util.List; /** * Interface for Secure Online Notification Interoperable Class Modules. */ public interface ISonic extends IManager { + default void load(List channelStats) { + load(); + } void load(); void run(); void unload(); diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java new file mode 100644 index 000000000..7f616b755 --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java @@ -0,0 +1,163 @@ +package de.presti.ree6.module.notifications.impl; + +import club.minnced.discord.webhook.send.WebhookEmbed; +import club.minnced.discord.webhook.send.WebhookEmbedBuilder; +import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import com.github.instagram4j.instagram4j.actions.feed.FeedIterator; +import com.github.instagram4j.instagram4j.models.media.timeline.TimelineImageMedia; +import com.github.instagram4j.instagram4j.models.media.timeline.TimelineVideoMedia; +import com.github.instagram4j.instagram4j.requests.feed.FeedUserRequest; +import com.github.instagram4j.instagram4j.responses.feed.FeedUserResponse; +import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.util.WebhookUtil; +import de.presti.ree6.language.LanguageService; +import de.presti.ree6.main.Main; +import de.presti.ree6.module.notifications.ISonic; +import de.presti.ree6.module.notifications.SonicIdentifier; +import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.stats.ChannelStats; +import de.presti.ree6.utils.apis.YouTubeAPIHandler; +import io.sentry.Sentry; +import lombok.extern.slf4j.Slf4j; +import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; + +import java.awt.*; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +@Slf4j +public class InstagramSonic implements ISonic { + + ArrayList instagramChannels = new ArrayList<>(); + + @Override + public void load(List channelStats) { + try { + channelStats.stream().map(ChannelStats::getInstagramFollowerChannelUsername).filter(Objects::nonNull).forEach(this::add); + load(); + } catch (Exception exception) { + log.error("Error while loading Instagram data: {}", exception.getMessage()); + Sentry.captureException(exception); + } + } + + @Override + public void load() { + // Register all Instagram Users. + SQLSession.getSqlConnector().getSqlWorker().getAllInstagramUsers().subscribe(instagramUsers -> + instagramUsers.forEach(this::add)); + } + + @Override + public List getList() { + return instagramChannels; + } + + @Override + public void run() { + if (!Main.getInstance().getNotifier().getInstagramClient().isLoggedIn()) return; + for (String username : getList().stream().map(SonicIdentifier::getIdentifier).toList()) { + + Main.getInstance().getNotifier().getInstagramClient().actions().users().findByUsername(username).thenAccept(userAction -> { + com.github.instagram4j.instagram4j.models.user.User user = userAction.getUser(); + + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), + "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", Map.of("name", username)).subscribe(channelStats -> { + if (!channelStats.isEmpty()) { + for (ChannelStats channelStat : channelStats) { + if (channelStat.getInstagramFollowerChannelId() != null) { + GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getInstagramFollowerChannelId()); + + if (guildChannel == null) continue; + + LanguageService.getByGuild(guildChannel.getGuild(), "label.instagramCountName", user.getFollower_count()).subscribe(newName -> { + if (!guildChannel.getName().equalsIgnoreCase(newName)) { + if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) + return; + + guildChannel.getManager().setName(newName).queue(); + } + }); + } + } + } + }); + + SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(username).subscribe(webhooks -> { + if (webhooks.isEmpty()) return; + + if (!user.is_private()) { + FeedIterator iterable = new FeedIterator<>(Main.getInstance().getNotifier().getInstagramClient(), new FeedUserRequest(user.getPk())); + + int limit = 1; + while (iterable.hasNext() && limit-- > 0) { + FeedUserResponse response = iterable.next(); + // Actions here + response.getItems().stream().filter(post -> post.getTaken_at() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())).forEach(instagramPost -> { + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(user.getUsername(), "https://www.instagram.com/" + user.getUsername())); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Instagram Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + + // Set the rest of the Information. + if (instagramPost instanceof TimelineImageMedia timelineImageMedia) { + webhookEmbedBuilder.setImageUrl(timelineImageMedia.getImage_versions2().getCandidates().get(0).getUrl()); + webhookEmbedBuilder.setDescription(timelineImageMedia.getCaption().getText()); + } else if (instagramPost instanceof TimelineVideoMedia timelineVideoMedia) { + webhookEmbedBuilder.setDescription("[Click here to watch the video](" + timelineVideoMedia.getVideo_versions().get(0).getUrl() + ")"); + } else { + webhookEmbedBuilder.setDescription(user.getUsername() + " just posted something new on Instagram!"); + } + + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + + webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); + + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + + // TODO:: add this with message. + + webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook)); + }); + } + } + }); + }).exceptionally(exception -> { + log.error("Could not get Instagram User!", exception); + Sentry.captureException(exception); + return null; + }).join(); + } + } + + @Override + public void unload() { + + } + + @Override + public void remove(SonicIdentifier object) { + if (Main.getInstance().getNotifier().getInstagramClient() == null) return; + if (!contains(object)) return; + + SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(object.getIdentifier()).subscribe(webhooks -> { + if (!webhooks.isEmpty()) return; + + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", + Map.of("name", object.getIdentifier())).subscribe(channelStats -> { + if (channelStats.isPresent()) return; + + instagramChannels.remove(object); + }); + }); + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java new file mode 100644 index 000000000..39f2b15d9 --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java @@ -0,0 +1,231 @@ +package de.presti.ree6.module.notifications.impl; + +import club.minnced.discord.webhook.send.WebhookEmbed; +import club.minnced.discord.webhook.send.WebhookEmbedBuilder; +import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import com.apptasticsoftware.rssreader.Channel; +import com.apptasticsoftware.rssreader.Image; +import com.apptasticsoftware.rssreader.Item; +import com.apptasticsoftware.rssreader.module.itunes.ItunesItem; +import com.apptasticsoftware.rssreader.module.itunes.ItunesRssReader; +import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.util.WebhookUtil; +import de.presti.ree6.module.notifications.ISonic; +import de.presti.ree6.module.notifications.SonicIdentifier; +import de.presti.ree6.sql.SQLSession; +import io.sentry.Sentry; +import lombok.extern.slf4j.Slf4j; + +import java.awt.*; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +@Slf4j +public class RSSSonic implements ISonic { + + ArrayList rssUrls = new ArrayList<>(); + + @Override + public void load() { + try { + // Register all RSS-Feeds. + SQLSession.getSqlConnector().getSqlWorker().getAllRSSUrls().subscribe(rssUrl -> + rssUrl.forEach(this::add)); + } catch (Exception exception) { + log.error("Error while loading RSS data: {}", exception.getMessage()); + Sentry.captureException(exception); + } + } + + @Override + public List getList() { + return rssUrls; + } + + @Override + public void run() { + Collection urls = getList().stream().map(SonicIdentifier::getIdentifier).toList(); + + /* + * TODO:: Either switch to RSSHub, YouTubes RSS or stay on API based. + * Issue with RSSHub is that it takes 2 hours to update, because of caching. + * Issue with YouTube is RSS that it takes over 30 minutes to update, because of idk random internal stuff. + */ + + ////Collection urls = new ArrayList<>(registeredYouTubeChannels.stream().map(c -> "https://rsshub.app/youtube/channel/" + c).toList()); + + // TODO:: Wait till Nitter has fixed their RSS Feeds. Or Twitter finally gets the stick out of their ass and stop limiting simple scraping. 05.07: Twitter still has a stick up their ass and Nitter died because of it. WoW. + ////urls.addAll(registeredTwitterUsers.stream().map(c -> "https://nitter.net/" + c + "/rss").toList()); + + ////urls.addAll(registeredRSSFeeds); + + List checkedIds = new ArrayList<>(); + + // To support Podcast RSS. + new ItunesRssReader() + .addItemExtension("media:description", Item::setDescription) + .addItemExtension("media:thumbnail", "url", (item, element) -> { + Image image = item.getChannel().getImage().orElse(new Image()); + image.setUrl(element); + item.getChannel().setImage(image); + }).addItemExtension("media:thumbnail", "width", (item, element) -> { + Image image = item.getChannel().getImage().orElse(new Image()); + image.setWidth(Integer.valueOf(element)); + item.getChannel().setImage(image); + }).addItemExtension("media:thumbnail", "height", (item, element) -> { + Image image = item.getChannel().getImage().orElse(new Image()); + image.setHeight(Integer.valueOf(element)); + item.getChannel().setImage(image); + }).addChannelExtension("published", Channel::setPubDate) + .addItemExtension("dc:creator", Item::setAuthor) + .addItemExtension("dc:date", Item::setPubDate) + .addItemExtension("yt:channelId", Item::setAuthor) + .setUserAgent("Ree6Bot/" + BotWorker.getBuild() + " (by Presti)") + .read(urls) + .sorted() + .forEach(item -> { + if (item.getPubDate().isEmpty()) return; + + String typ = "other"; + + if (item.getGuid().isPresent()) { + String guid = item.getGuid().get(); + + if (guid.contains("nitter")) { + typ = "tw"; + } else { + typ = "other"; + } + } + + + OffsetDateTime dateTime = OffsetDateTime.parse(item.getPubDate().orElse(""), DateTimeFormatter.ISO_OFFSET_DATE_TIME); + + OffsetDateTime now = OffsetDateTime.now(); + OffsetDateTime threeMinuteAgo = now.minusMinutes(3); + + if (dateTime.isBefore(threeMinuteAgo)) return; + + if (item.getChannel() != null) { + + String id = ""; + + switch (typ) { + case "tw" -> id = item.getChannel().getLink().replace("https://nitter.net/", ""); + + case "other" -> id = item.getChannel().getLink(); + } + + if (checkedIds.contains(id)) { + return; + } + + + if (typ.equals("tw")) { + SQLSession.getSqlConnector().getSqlWorker().getTwitterWebhooksByName(item.getChannel().getLink().replace("https://nitter.net/", "")).subscribe(webhooks -> { + + if (webhooks.isEmpty()) return; + + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + + webhookMessageBuilder.setUsername(BotConfig.getBotName()); + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + item.getChannel().getImage().ifPresentOrElse(image -> + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), + URLDecoder.decode(image.getUrl().replace("nitter.net/pic/", ""), StandardCharsets.UTF_8), null)), + () -> webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), null, null))); + + + webhookEmbedBuilder.setDescription(item.getTitle() + "\n"); + + item.getDescription().ifPresent(description -> { + if (description.contains(" { + String message = webhook.getMessage() + .replace("%name%", item.getChannel().getTitle()); + + if (item.getLink().isPresent()) { + message = message.replace("%url%", item.getLink().get() + .replace("nitter.net", "twitter.com")) + .replace("#m", ""); + } + webhookMessageBuilder.setContent(message); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); + }); + }); + } else { + try { + SQLSession.getSqlConnector().getSqlWorker().getRSSWebhooksByUrl(id).subscribe(webhooks -> { + if (webhooks.isEmpty()) return; + + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + + webhookMessageBuilder.setUsername(BotConfig.getBotName()); + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + item.getChannel().getImage().ifPresentOrElse(image -> + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), + URLDecoder.decode(image.getUrl(), StandardCharsets.UTF_8), null)), + () -> webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), null, null))); + + item.getDescription().ifPresent(description -> webhookEmbedBuilder.setDescription(description + "\n")); + + if (item instanceof ItunesItem itunesItem) { + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(itunesItem.getItunesTitle().orElse("No Title"), item.getLink().orElse("No Link"))); + itunesItem.getItunesImage().ifPresent(webhookEmbedBuilder::setThumbnailUrl); + } else { + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(item.getTitle().orElse("No Title"), item.getLink().orElse("No Link"))); + } + + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("RSS Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl(), null)); + + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); + webhookEmbedBuilder.setTimestamp(Instant.now()); + webhookEmbedBuilder.setColor(Color.CYAN.getRGB()); + + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + + webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook)); + }); + } catch (Exception exception) { + Sentry.captureException(exception); + } + } + + checkedIds.add(id); + } + }); + } + + @Override + public void unload() { + + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java new file mode 100644 index 000000000..cb0b2a8a3 --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java @@ -0,0 +1,184 @@ +package de.presti.ree6.module.notifications.impl; + +import club.minnced.discord.webhook.send.WebhookEmbed; +import club.minnced.discord.webhook.send.WebhookEmbedBuilder; +import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import cn.hutool.core.exceptions.ValidateException; +import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.util.WebhookUtil; +import de.presti.ree6.main.Main; +import de.presti.ree6.module.notifications.ISonic; +import de.presti.ree6.module.notifications.SonicIdentifier; +import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.stats.ChannelStats; +import io.sentry.Sentry; +import lombok.extern.slf4j.Slf4j; +import masecla.reddit4j.exceptions.AuthenticationException; +import masecla.reddit4j.objects.RedditPost; +import masecla.reddit4j.objects.Sorting; +import masecla.reddit4j.objects.subreddit.RedditSubreddit; +import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; + +import java.awt.*; +import java.io.IOException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.*; + +@Slf4j +public class RedditSonic implements ISonic { + + ArrayList subreddits = new ArrayList<>(); + + @Override + public void load(List channelStats) { + try { + channelStats.stream().map(ChannelStats::getSubredditMemberChannelSubredditName).filter(Objects::nonNull).forEach(this::add); + load(); + } catch (Exception exception) { + log.error("Error while loading Reddit data: {}", exception.getMessage()); + Sentry.captureException(exception); + } + } + + @Override + public void load() { + // Register all Reddit Subreddits. + SQLSession.getSqlConnector().getSqlWorker().getAllSubreddits().subscribe(channel -> + channel.forEach(this::add)); + } + + @Override + public List getList() { + return subreddits; + } + + @Override + public void run() { + try { + for (String subreddit : subreddits.stream().map(SonicIdentifier::getIdentifier).toList()) { + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), + "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", Map.of("name", subreddit)).subscribe(channelStats -> { + if (!channelStats.isEmpty()) { + RedditSubreddit subredditEntity; + try { + subredditEntity = getSubreddit(subreddit); + } catch (IOException | InterruptedException e) { + return; + } + + for (ChannelStats channelStat : channelStats) { + if (channelStat.getSubredditMemberChannelId() != null) { + GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getSubredditMemberChannelId()); + String newName = "Subreddit Members: " + subredditEntity.getActiveUserCount(); + if (guildChannel != null && + !guildChannel.getName().equalsIgnoreCase(newName)) { + + if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) + continue; + + guildChannel.getManager().setName(newName).queue(); + } + } + } + } + }); + + getSubredditPosts(subreddit, Sorting.NEW, 50).stream().filter(redditPost -> redditPost.getCreated() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())).forEach(redditPost -> { + SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit).subscribe(webhooks -> { + if (webhooks.isEmpty()) return; + + // Create Webhook Message. + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(redditPost.getTitle(), redditPost.getUrl())); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Reddit Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + + + if (!redditPost.getThumbnail().equalsIgnoreCase("self")) + webhookEmbedBuilder.setImageUrl(redditPost.getThumbnail()); + + // Set rest of the Information. + webhookEmbedBuilder.setDescription(URLDecoder.decode(redditPost.getSelftext(), StandardCharsets.UTF_8)); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Author**", redditPost.getAuthor())); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Subreddit**", redditPost.getSubreddit())); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + + webhookEmbedBuilder.setColor(Color.ORANGE.getRGB()); + + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + + webhooks.forEach(webhook -> { + String message = webhook.getMessage() + .replace("%title%", redditPost.getTitle()) + .replace("%author%", redditPost.getAuthor()) + .replace("%name%", redditPost.getSubreddit()) + .replace("%url%", redditPost.getUrl()); + webhookMessageBuilder.setContent(message); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); + }); + }); + }); + } + } catch (Exception exception) { + log.error("Could not get Reddit Posts!", exception); + Sentry.captureException(exception); + } + } + + /** + * Used to get a Subreddit. + * + * @param subreddit the Name of the Subreddit. + * @return the Subreddit. + * @throws IOException if the Subreddit couldn't be found. + * @throws InterruptedException if the Thread was interrupted. + */ + public RedditSubreddit getSubreddit(String subreddit) throws IOException, InterruptedException { + return Main.getInstance().getNotifier().getRedditClient().getSubreddit(subreddit); + } + + + public List getSubredditPosts(String subreddit, Sorting sorting, int limit) throws AuthenticationException, IOException, InterruptedException { + try { + return Main.getInstance().getNotifier().getRedditClient().getSubredditPosts(subreddit, sorting).limit(limit).submit(); + } catch (ValidateException exception) { + if (exception.getMessage().startsWith("The parameter")) { + Main.getInstance().getNotifier().getRedditClient().userlessConnect(); + return Main.getInstance().getNotifier().getRedditClient().getSubredditPosts(subreddit, sorting).limit(limit).submit(); + } + } + + return Collections.emptyList(); + } + + @Override + public void unload() { + + } + + @Override + public void remove(SonicIdentifier object) { + if (Main.getInstance().getNotifier().getRedditClient() == null) return; + if (!contains(object)) return; + + SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(object.getIdentifier()).subscribe(webhooks -> { + if (!webhooks.isEmpty()) return; + + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", + Map.of("name", object.getIdentifier())).subscribe(channelStats -> { + if (channelStats.isPresent()) return; + + subreddits.remove(object); + }); + }); + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java new file mode 100644 index 000000000..34cc3bbd8 --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java @@ -0,0 +1,116 @@ +package de.presti.ree6.module.notifications.impl; + +import club.minnced.discord.webhook.send.WebhookEmbed; +import club.minnced.discord.webhook.send.WebhookEmbedBuilder; +import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.util.WebhookUtil; +import de.presti.ree6.module.notifications.ISonic; +import de.presti.ree6.module.notifications.SonicIdentifier; +import de.presti.ree6.sql.SQLSession; +import de.presti.wrapper.tiktok.TikTokWrapper; +import de.presti.wrapper.tiktok.entities.TikTokUser; +import io.sentry.Sentry; +import lombok.extern.slf4j.Slf4j; +import org.jsoup.HttpStatusException; + +import java.awt.*; +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +@Slf4j +public class TikTokSonic implements ISonic { + + ArrayList tiktokChannels = new ArrayList<>(); + + @Override + public void load() { + try { + // Register all TikTok Users. + SQLSession.getSqlConnector().getSqlWorker().getAllTikTokNames().subscribe(tiktokNames -> + tiktokNames.forEach(this::add)); + } catch (Exception exception) { + log.error("Error while loading TikTok data: {}", exception.getMessage()); + Sentry.captureException(exception); + } + } + + @Override + public List getList() { + return tiktokChannels; + } + + @Override + public void run() { + for (long id : getList().stream().map(SonicIdentifier::getIdentifierAsLong).toList()) { + try { + TikTokUser user = TikTokWrapper.getUser(id); + + SQLSession.getSqlConnector().getSqlWorker().getTikTokWebhooksByName(user.getId()).subscribe(webhooks -> { + if (webhooks.isEmpty()) { + return; + } + + AtomicInteger limit = new AtomicInteger(); + + user.getPosts().forEach(post -> { + if (limit.get() > 3) return; + + if (post.getCreationTime() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())) { + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(user.getDisplayName(), "https://www.tiktok.com/@" + user.getName())); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("TikTok Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + + // Set rest of the Information. + if (post.getCover() != null) { + webhookEmbedBuilder.setImageUrl(post.getCover().getMediumUrl()); + webhookEmbedBuilder.setDescription("[Click here to watch the video](https://tiktok.com/share/video/" + post.getId() + ")"); + } else { + webhookEmbedBuilder.setDescription(user.getDisplayName() + " just posted something new on TikTok!"); + } + + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + + webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); + + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + + webhooks.forEach(webhook -> { + String message = webhook.getMessage() + .replace("%description%", post.getDescription()) + .replace("%author%", user.getName()) + .replace("%name%", user.getDisplayName()) + .replace("%url%", "https://tiktok.com/share/video/" + post.getId()); + webhookMessageBuilder.setContent(message); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); + }); + } + limit.incrementAndGet(); + }); + }); + } catch (IOException e) { + if (e instanceof HttpStatusException httpStatusException) { + if (httpStatusException.getStatusCode() == 404) return; + // TODO:: check, maybe delete on 404? + } + + Sentry.captureException(e); + } + } + } + + @Override + public void unload() { + + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java new file mode 100644 index 000000000..140cbaf20 --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java @@ -0,0 +1,174 @@ +package de.presti.ree6.module.notifications.impl; + +import club.minnced.discord.webhook.send.WebhookEmbed; +import club.minnced.discord.webhook.send.WebhookEmbedBuilder; +import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import com.github.twitch4j.events.ChannelFollowCountUpdateEvent; +import com.github.twitch4j.events.ChannelGoLiveEvent; +import com.github.twitch4j.helix.domain.User; +import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.util.WebhookUtil; +import de.presti.ree6.language.LanguageService; +import de.presti.ree6.main.Main; +import de.presti.ree6.module.notifications.ISonic; +import de.presti.ree6.module.notifications.SonicIdentifier; +import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.stats.ChannelStats; +import io.sentry.Sentry; +import lombok.extern.slf4j.Slf4j; +import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; + +import java.awt.*; +import java.util.*; +import java.util.List; + +@Slf4j +public class TwitchSonic implements ISonic { + + ArrayList twitchChannels = new ArrayList<>(); + + @Override + public void load(List channelStats) { + try { + channelStats.stream().map(ChannelStats::getTwitchFollowerChannelUsername).filter(Objects::nonNull).forEach(this::add); + load(); + + // Register the Event-handler. + run(); + } catch (Exception exception) { + log.error("Error while loading Twitch data: {}", exception.getMessage()); + Sentry.captureException(exception); + } + } + + @Override + public void load() { + // Register all Twitch Channels. + SQLSession.getSqlConnector().getSqlWorker().getAllTwitchNames().subscribe(channel -> + channel.forEach(this::add)); + } + + @Override + public List getList() { + return twitchChannels; + } + + @Override + public void run() { + Main.getInstance().getNotifier().getTwitchClient().getEventManager().onEvent(ChannelGoLiveEvent.class, channelGoLiveEvent -> { + + SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(channelGoLiveEvent.getChannel().getName()).subscribe(webhooks -> { + if (webhooks.isEmpty()) { + return; + } + + String twitchUrl = "https://twitch.tv/" + channelGoLiveEvent.getChannel().getName(); + + // Create a Webhook Message. + WebhookMessageBuilder wmb = new WebhookMessageBuilder(); + + wmb.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); + wmb.setUsername(BotConfig.getBotName()); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(channelGoLiveEvent.getStream().getUserName(), twitchUrl)); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Twitch Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl(), null)); + + // Try getting the User. + Optional twitchUserRequest = Main.getInstance().getNotifier().getTwitchClient().getHelix().getUsers(null, null, Collections.singletonList(channelGoLiveEvent.getStream().getUserName())).execute().getUsers().stream().findFirst(); + if (twitchUserRequest.isPresent()) { + webhookEmbedBuilder.setThumbnailUrl(twitchUserRequest.orElseThrow().getProfileImageUrl()); + } + webhookEmbedBuilder.setImageUrl(channelGoLiveEvent.getStream().getThumbnailUrl()); + + // Set rest of the Information. + webhookEmbedBuilder.setDescription("**" + channelGoLiveEvent.getStream().getTitle() + "**\n[Watch Stream](" + twitchUrl + ")"); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Game**", channelGoLiveEvent.getStream().getGameName())); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Viewer**", String.valueOf(channelGoLiveEvent.getStream().getViewerCount()))); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); + webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); + + wmb.addEmbeds(webhookEmbedBuilder.build()); + + // Go through every Webhook that is registered for the Twitch Channel + webhooks.forEach(webhook -> { + String message = webhook.getMessage() + .replace("%name%", channelGoLiveEvent.getStream().getUserName()) + .replace("%url%", twitchUrl); + wmb.setContent(message); + WebhookUtil.sendWebhook(wmb.build(), webhook); + }); + }); + }); + + Main.getInstance().getNotifier().getTwitchClient().getEventManager().onEvent(ChannelFollowCountUpdateEvent.class, channelFollowCountUpdateEvent -> { + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), + "FROM ChannelStats WHERE LOWER(twitchFollowerChannelUsername) = :name", + Map.of("name", channelFollowCountUpdateEvent.getChannel().getName().toLowerCase())).subscribe(channelStats -> { + if (!channelStats.isEmpty()) { + for (ChannelStats channelStat : channelStats) { + if (channelStat.getTwitchFollowerChannelId() != null) { + GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getTwitchFollowerChannelId()); + if (guildChannel != null) { + if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) + continue; + + LanguageService.getByGuild(guildChannel.getGuild(), "label.twitchCountName", channelFollowCountUpdateEvent.getFollowCount()).subscribe(newName -> { + if (!guildChannel.getName().equalsIgnoreCase(newName)) { + guildChannel.getManager().setName(newName).queue(); + } + }); + } + } + } + } + }); + }); + } + + @Override + public void unload() { + + } + + @Override + public void add(SonicIdentifier object) { + if (Main.getInstance().getNotifier().getTwitchClient() == null) return; + if (contains(object)) return; + + String twitchChannel = object.getIdentifier().toLowerCase(); + + twitchChannels.add(new SonicIdentifier(twitchChannel)); + + Main.getInstance().getNotifier().getTwitchClient().getClientHelper().enableStreamEventListener(twitchChannel); + Main.getInstance().getNotifier().getTwitchClient().getClientHelper().enableFollowEventListener(twitchChannel); + } + + @Override + public boolean contains(String identifier) { + return ISonic.super.contains(identifier.toLowerCase()); + } + + @Override + public void remove(SonicIdentifier object) { + if (Main.getInstance().getNotifier().getTwitchClient() == null) return; + + String twitchChannel = object.getIdentifier().toLowerCase(); + + SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(twitchChannel).subscribe(webhooks -> { + if (!webhooks.isEmpty()) return; + + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitchFollowerChannelUsername=:name", Map.of("name", twitchChannel)) + .subscribe(channelStats -> { + if (channelStats.isPresent()) return; + + twitchChannels.remove(object); + + Main.getInstance().getNotifier().getTwitchClient().getClientHelper().disableStreamEventListener(twitchChannel); + Main.getInstance().getNotifier().getTwitchClient().getClientHelper().disableFollowEventListener(twitchChannel); + }); + }); + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/TwitterSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/TwitterSonic.java new file mode 100644 index 000000000..270ef0c9a --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/impl/TwitterSonic.java @@ -0,0 +1,101 @@ +package de.presti.ree6.module.notifications.impl; + +import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.language.LanguageService; +import de.presti.ree6.main.Main; +import de.presti.ree6.module.notifications.ISonic; +import de.presti.ree6.module.notifications.SonicIdentifier; +import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.stats.ChannelStats; +import io.github.redouane59.twitter.dto.user.UserV2; +import io.sentry.Sentry; +import lombok.extern.slf4j.Slf4j; +import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; + +import java.util.*; + +@Slf4j +public class TwitterSonic implements ISonic { + + ArrayList twitterChannels = new ArrayList<>(); + + @Override + public void load(List channelStats) { + try { + channelStats.stream().map(ChannelStats::getTwitterFollowerChannelUsername).filter(Objects::nonNull).forEach(this::add); + load(); + } catch (Exception exception) { + log.error("Error while loading Twitter data: {}", exception.getMessage()); + Sentry.captureException(exception); + } + } + + @Override + public void load() { + // Register all Twitter Users. + SQLSession.getSqlConnector().getSqlWorker().getAllTwitterNames().subscribe(twitterNames -> + twitterNames.forEach(this::add)); + } + + @Override + public List getList() { + return twitterChannels; + } + + @Override + public void run() { + for (String twitterName : getList().stream().map(SonicIdentifier::getIdentifier).toList()) { + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), + "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", Map.of("name", twitterName)).subscribe(channelStats -> { + if (!channelStats.isEmpty()) { + UserV2 twitterUser; + try { + twitterUser = Main.getInstance().getNotifier().getTwitterClient().getUserFromUserName(twitterName); + } catch (NoSuchElementException e) { + return; + } + + if (twitterUser.getData() == null) return; + + for (ChannelStats channelStat : channelStats) { + if (channelStat.getTwitterFollowerChannelUsername() != null) { + GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getTwitchFollowerChannelId()); + if (guildChannel == null) continue; + + LanguageService.getByGuild(guildChannel.getGuild(), "label.twitterCountName", twitterUser.getFollowersCount()).subscribe(newName -> { + if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) + return; + + if (!guildChannel.getName().equalsIgnoreCase(newName)) { + guildChannel.getManager().setName(newName).queue(); + } + }); + } + } + } + }); + } + } + + @Override + public void unload() { + + } + + @Override + public void remove(SonicIdentifier object) { + if (Main.getInstance().getNotifier().getTwitterClient() == null) return; + if (!contains(object)) return; + + SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(object.getIdentifier()).subscribe(webhooks -> { + if (!webhooks.isEmpty()) return; + + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", + Map.of("name", object.getIdentifier())).subscribe(channelStats -> { + if (channelStats.isPresent()) return; + + twitterChannels.remove(object); + }); + }); + } +} diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java index 678affebd..701859d5e 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java @@ -21,28 +21,31 @@ import java.awt.*; import java.time.Duration; -import java.util.ArrayList; -import java.util.Date; import java.util.List; -import java.util.Map; +import java.util.*; @Slf4j public class YouTubeSonic implements ISonic { ArrayList youtubeChannels = new ArrayList<>(); @Override - public void load() { + public void load(List channelStats) { try { - // Register all YouTube channels. - SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels().subscribe(channel -> - channel.forEach(youtubeChannel -> - add(new SonicIdentifier(youtubeChannel)))); + channelStats.stream().map(ChannelStats::getYoutubeSubscribersChannelUsername).filter(Objects::nonNull).forEach(this::add); + load(); } catch (Exception exception) { log.error("Error while loading YouTube data: {}", exception.getMessage()); Sentry.captureException(exception); } } + @Override + public void load() { + // Register all YouTube channels. + SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels().subscribe(channel -> + channel.forEach(this::add)); + } + @Override public List getList() { return youtubeChannels; diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index 341854096..210d84803 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -1,20 +1,6 @@ package de.presti.ree6.utils.apis; -import club.minnced.discord.webhook.send.WebhookEmbed; -import club.minnced.discord.webhook.send.WebhookEmbedBuilder; -import club.minnced.discord.webhook.send.WebhookMessageBuilder; -import cn.hutool.core.exceptions.ValidateException; -import com.apptasticsoftware.rssreader.Channel; -import com.apptasticsoftware.rssreader.Image; -import com.apptasticsoftware.rssreader.Item; -import com.apptasticsoftware.rssreader.module.itunes.ItunesItem; -import com.apptasticsoftware.rssreader.module.itunes.ItunesRssReader; import com.github.instagram4j.instagram4j.IGClient; -import com.github.instagram4j.instagram4j.actions.feed.FeedIterator; -import com.github.instagram4j.instagram4j.models.media.timeline.TimelineImageMedia; -import com.github.instagram4j.instagram4j.models.media.timeline.TimelineVideoMedia; -import com.github.instagram4j.instagram4j.requests.feed.FeedUserRequest; -import com.github.instagram4j.instagram4j.responses.feed.FeedUserResponse; import com.github.instagram4j.instagram4j.utils.IGChallengeUtils; import com.github.philippheuer.credentialmanager.CredentialManager; import com.github.philippheuer.credentialmanager.CredentialManagerBuilder; @@ -24,30 +10,19 @@ import com.github.twitch4j.auth.TwitchAuth; import com.github.twitch4j.auth.providers.TwitchIdentityProvider; import com.github.twitch4j.chat.events.channel.FollowEvent; -import com.github.twitch4j.events.ChannelFollowCountUpdateEvent; -import com.github.twitch4j.events.ChannelGoLiveEvent; import com.github.twitch4j.eventsub.events.ChannelSubscribeEvent; -import com.github.twitch4j.helix.domain.User; import com.github.twitch4j.pubsub.PubSubSubscription; import com.github.twitch4j.pubsub.events.RewardRedeemedEvent; import de.presti.ree6.actions.streamtools.container.StreamActionContainerCreator; import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; -import de.presti.ree6.bot.util.WebhookUtil; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; -import de.presti.ree6.module.notifications.impl.YouTubeSonic; +import de.presti.ree6.module.notifications.impl.*; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.TwitchIntegration; -import de.presti.ree6.sql.entities.stats.ChannelStats; import de.presti.ree6.utils.data.DatabaseStorageBackend; import de.presti.ree6.utils.others.ThreadUtil; -import de.presti.wrapper.entities.VideoResult; -import de.presti.wrapper.entities.channel.ChannelResult; -import de.presti.wrapper.tiktok.TikTokWrapper; -import de.presti.wrapper.tiktok.entities.TikTokUser; import io.github.redouane59.twitter.TwitterClient; -import io.github.redouane59.twitter.dto.user.UserV2; import io.github.redouane59.twitter.signature.TwitterCredentials; import io.sentry.Sentry; import lombok.AccessLevel; @@ -55,24 +30,11 @@ import lombok.extern.slf4j.Slf4j; import masecla.reddit4j.client.Reddit4J; import masecla.reddit4j.exceptions.AuthenticationException; -import masecla.reddit4j.objects.RedditPost; -import masecla.reddit4j.objects.Sorting; -import masecla.reddit4j.objects.subreddit.RedditSubreddit; -import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; -import org.jsoup.HttpStatusException; -import java.awt.*; -import java.io.IOException; -import java.net.URLDecoder; -import java.nio.charset.StandardCharsets; import java.time.Duration; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.List; -import java.util.*; +import java.util.HashMap; +import java.util.Scanner; import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicInteger; // TODO:: translate // TODO:: fix the Twitter Stream handler, wait for responses via https://github.com/redouane59/twittered/issues/447 @@ -126,40 +88,46 @@ public class Notifier { private YouTubeSonic youTubeSonic; /** - * Local list of registered Twitch Channels. + * Instance of the Twitch Sonic Manager. */ - private final ArrayList registeredTwitchChannels = new ArrayList<>(); + @Getter(AccessLevel.PUBLIC) + private TwitchSonic twitchSonic; /** - * A list with all the Twitch Subscription for the Streaming Tools. + * Instance of the Instagram Sonic Manager. */ @Getter(AccessLevel.PUBLIC) - private final HashMap twitchSubscription = new HashMap<>(); + private InstagramSonic instagramSonic; /** - * Local list of registered Twitter Users. + * Instance of the TikTok Sonic Manager. */ - private final ArrayList registeredTwitterUsers = new ArrayList<>(); + @Getter(AccessLevel.PUBLIC) + private TikTokSonic tikTokSonic; /** - * Local list of registered Subreddits. + * Instance of the Twitter Sonic Manager. */ - private final ArrayList registeredSubreddits = new ArrayList<>(); + @Getter(AccessLevel.PUBLIC) + private TwitterSonic twitterSonic; /** - * Local list of registered Instagram Users. + * Instance of the Reddit Sonic Manager. */ - private final ArrayList registeredInstagramUsers = new ArrayList<>(); + @Getter(AccessLevel.PUBLIC) + private RedditSonic redditSonic; /** - * Local list of registered RSS-Feeds. + * Instance of the RSS Sonic Manager. */ - private final ArrayList registeredRSSFeeds = new ArrayList<>(); + @Getter(AccessLevel.PUBLIC) + private RSSSonic rssSonic; /** - * Local list of registered TikTok Users. + * A list with all the Twitch Subscription for the Streaming Tools. */ - private final ArrayList registeredTikTokUsers = new ArrayList<>(); + @Getter(AccessLevel.PUBLIC) + private final HashMap twitchSubscription = new HashMap<>(); /** * Constructor used to created instance of the API Clients. @@ -257,7 +225,6 @@ public Notifier() { .setUserAgent("Ree6Bot/" + BotWorker.getBuild() + " (by /u/PrestiSchmesti)"); redditClient.userlessConnect(); - createRedditPostStream(); } catch (Exception exception) { if (exception instanceof AuthenticationException) { log.warn("Reddit Credentials are invalid, you can ignore this if you don't use Reddit."); @@ -291,922 +258,55 @@ public Notifier() { log.error("Failed to login to Instagram API, you can ignore this if you don't use Instagram.", throwable); } else { log.error("Failed to login to Instagram API, you can ignore this if you don't use Instagram."); - log.error("Error Message: " + throwable.getMessage() + log.error("Error Message: {}", throwable.getMessage() .replace("com.github.instagram4j.instagram4j.exceptions.IGResponseException: ", "") .replace("'", "'")); } return null; }); - createInstagramPostStream(); log.info("Initializing Streams..."); log.info("Creating YouTube Streams..."); youTubeSonic = new YouTubeSonic(); - // TODO:: Create a YouTube Stream for the Sonic Channel. + ThreadUtil.createThread(x -> youTubeSonic.run(), x -> { + log.error("Failed to run YouTube Stream!", x); + Sentry.captureException(x); + }, Duration.ofMinutes(5), true, true); log.info("Creating Twitter Streams..."); - ThreadUtil.createThread(x -> { - for (String twitterName : registeredTwitterUsers) { - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", Map.of("name", twitterName)).subscribe(channelStats -> { - if (!channelStats.isEmpty()) { - UserV2 twitterUser; - try { - twitterUser = Main.getInstance().getNotifier().getTwitterClient().getUserFromUserName(twitterName); - } catch (NoSuchElementException e) { - return; - } - - if (twitterUser.getData() == null) return; - - for (ChannelStats channelStat : channelStats) { - if (channelStat.getTwitterFollowerChannelUsername() != null) { - GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getTwitchFollowerChannelId()); - if (guildChannel == null) continue; - - LanguageService.getByGuild(guildChannel.getGuild(), "label.twitterCountName", twitterUser.getFollowersCount()).subscribe(newName -> { - if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) - return; - - if (!guildChannel.getName().equalsIgnoreCase(newName)) { - guildChannel.getManager().setName(newName).queue(); - } - }); - } - } - } - }); - } - }, x -> { + twitterSonic = new TwitterSonic(); + ThreadUtil.createThread(x -> twitterSonic.run(), x -> { log.error("Failed to run Twitter Follower count checker!", x); Sentry.captureException(x); }, Duration.ofMinutes(5), true, true); log.info("Creating RSS Streams..."); - createRssStream(); - - log.info("Creating TikTok Streams..."); - createTikTokStream(); - } - - /** - * Creates an RSS Stream. - */ - public void createRssStream() { - ThreadUtil.createThread(x -> { - - Collection urls = new ArrayList<>(registeredRSSFeeds); - - /* - * TODO:: Either switch to RSSHub, YouTubes RSS or stay on API based. - * Issue with RSSHub is that it takes 2 hours to update, because of caching. - * Issue with YouTube is that it takes over 30 minutes to update, because of idk random internal stuff. - */ - - ////Collection urls = new ArrayList<>(registeredYouTubeChannels.stream().map(c -> "https://rsshub.app/youtube/channel/" + c).toList()); - - // TODO:: Wait till Nitter has fixed their RSS Feeds. Or Twitter finally gets the stick out of their ass and stop limiting simple scraping. - ////urls.addAll(registeredTwitterUsers.stream().map(c -> "https://nitter.net/" + c + "/rss").toList()); - - ////urls.addAll(registeredRSSFeeds); - - List checkedIds = new ArrayList<>(); - - // To support Podcast RSS. - new ItunesRssReader() - .addItemExtension("media:description", Item::setDescription) - .addItemExtension("media:thumbnail", "url", (item, element) -> { - Image image = item.getChannel().getImage().orElse(new Image()); - image.setUrl(element); - item.getChannel().setImage(image); - }).addItemExtension("media:thumbnail", "width", (item, element) -> { - Image image = item.getChannel().getImage().orElse(new Image()); - image.setWidth(Integer.valueOf(element)); - item.getChannel().setImage(image); - }).addItemExtension("media:thumbnail", "height", (item, element) -> { - Image image = item.getChannel().getImage().orElse(new Image()); - image.setHeight(Integer.valueOf(element)); - item.getChannel().setImage(image); - }).addChannelExtension("published", Channel::setPubDate) - .addItemExtension("dc:creator", Item::setAuthor) - .addItemExtension("dc:date", Item::setPubDate) - .addItemExtension("yt:channelId", Item::setAuthor) - .setUserAgent("Ree6Bot/" + BotWorker.getBuild() + " (by Presti)") - .read(urls) - .sorted() - .forEach(item -> { - if (item.getPubDate().isEmpty()) return; - - String typ = "other"; - - if (item.getGuid().isPresent()) { - String guid = item.getGuid().get(); - - if (guid.contains("nitter")) { - typ = "tw"; - } else { - typ = "other"; - } - } - - - OffsetDateTime dateTime = OffsetDateTime.parse(item.getPubDate().orElse(""), DateTimeFormatter.ISO_OFFSET_DATE_TIME); - - OffsetDateTime now = OffsetDateTime.now(); - OffsetDateTime threeMinuteAgo = now.minusMinutes(3); - - if (dateTime.isBefore(threeMinuteAgo)) return; - - if (item.getChannel() != null) { - - String id = ""; - - switch (typ) { - case "tw" -> id = item.getChannel().getLink().replace("https://nitter.net/", ""); - - case "other" -> id = item.getChannel().getLink(); - } - - if (checkedIds.contains(id)) { - return; - } - - - if (typ.equals("tw")) { - SQLSession.getSqlConnector().getSqlWorker().getTwitterWebhooksByName(item.getChannel().getLink().replace("https://nitter.net/", "")).subscribe(webhooks -> { - - if (webhooks.isEmpty()) return; - - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - - webhookMessageBuilder.setUsername(BotConfig.getBotName()); - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); - - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - item.getChannel().getImage().ifPresentOrElse(image -> - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), - URLDecoder.decode(image.getUrl().replace("nitter.net/pic/", ""), StandardCharsets.UTF_8), null)), - () -> webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), null, null))); - - - webhookEmbedBuilder.setDescription(item.getTitle() + "\n"); - - item.getDescription().ifPresent(description -> { - if (description.contains(" { - String message = webhook.getMessage() - .replace("%name%", item.getChannel().getTitle()); - - if (item.getLink().isPresent()) { - message = message.replace("%url%", item.getLink().get() - .replace("nitter.net", "twitter.com")) - .replace("#m", ""); - } - webhookMessageBuilder.setContent(message); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); - }); - }); - } else { - try { - SQLSession.getSqlConnector().getSqlWorker().getRSSWebhooksByUrl(id).subscribe(webhooks -> { - if (webhooks.isEmpty()) return; - - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - - webhookMessageBuilder.setUsername(BotConfig.getBotName()); - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); - - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - item.getChannel().getImage().ifPresentOrElse(image -> - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), - URLDecoder.decode(image.getUrl(), StandardCharsets.UTF_8), null)), - () -> webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(item.getChannel().getTitle(), null, null))); - - item.getDescription().ifPresent(description -> webhookEmbedBuilder.setDescription(description + "\n")); - - if (item instanceof ItunesItem itunesItem) { - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(itunesItem.getItunesTitle().orElse("No Title"), item.getLink().orElse("No Link"))); - itunesItem.getItunesImage().ifPresent(webhookEmbedBuilder::setThumbnailUrl); - } else { - - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(item.getTitle().orElse("No Title"), item.getLink().orElse("No Link"))); - } - - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("RSS Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl(), null)); - - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); - webhookEmbedBuilder.setTimestamp(Instant.now()); - webhookEmbedBuilder.setColor(Color.CYAN.getRGB()); - - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - - webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook)); - }); - } catch (Exception exception) { - Sentry.captureException(exception); - } - } - - checkedIds.add(id); - } - }); + rssSonic = new RSSSonic(); + ThreadUtil.createThread(x -> rssSonic.run(), x -> { + log.error("Failed to run RSS Feed Stream!", x); + Sentry.captureException(x); }, Duration.ofMinutes(3), true, true); - } - - //region Twitch - - /** - * Register an EventHandler for the Twitch Livestream Event. - */ - public void registerTwitchEventHandler() { - getTwitchClient().getEventManager().onEvent(ChannelGoLiveEvent.class, channelGoLiveEvent -> { - - SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(channelGoLiveEvent.getChannel().getName()).subscribe(webhooks -> { - if (webhooks.isEmpty()) { - return; - } - - String twitchUrl = "https://twitch.tv/" + channelGoLiveEvent.getChannel().getName(); - - // Create a Webhook Message. - WebhookMessageBuilder wmb = new WebhookMessageBuilder(); - - wmb.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); - wmb.setUsername(BotConfig.getBotName()); - - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(channelGoLiveEvent.getStream().getUserName(), twitchUrl)); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Twitch Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl(), null)); - - // Try getting the User. - Optional twitchUserRequest = getTwitchClient().getHelix().getUsers(null, null, Collections.singletonList(channelGoLiveEvent.getStream().getUserName())).execute().getUsers().stream().findFirst(); - if (twitchUserRequest.isPresent()) { - webhookEmbedBuilder.setThumbnailUrl(twitchUserRequest.orElseThrow().getProfileImageUrl()); - } - webhookEmbedBuilder.setImageUrl(channelGoLiveEvent.getStream().getThumbnailUrl()); - - // Set rest of the Information. - webhookEmbedBuilder.setDescription("**" + channelGoLiveEvent.getStream().getTitle() + "**\n[Watch Stream](" + twitchUrl + ")"); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Game**", channelGoLiveEvent.getStream().getGameName())); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Viewer**", String.valueOf(channelGoLiveEvent.getStream().getViewerCount()))); - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); - webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); - - wmb.addEmbeds(webhookEmbedBuilder.build()); - - // Go through every Webhook that is registered for the Twitch Channel - webhooks.forEach(webhook -> { - String message = webhook.getMessage() - .replace("%name%", channelGoLiveEvent.getStream().getUserName()) - .replace("%url%", twitchUrl); - wmb.setContent(message); - WebhookUtil.sendWebhook(wmb.build(), webhook); - }); - }); - }); - - getTwitchClient().getEventManager().onEvent(ChannelFollowCountUpdateEvent.class, channelFollowCountUpdateEvent -> { - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE LOWER(twitchFollowerChannelUsername) = :name", - Map.of("name", channelFollowCountUpdateEvent.getChannel().getName().toLowerCase())).subscribe(channelStats -> { - if (!channelStats.isEmpty()) { - for (ChannelStats channelStat : channelStats) { - if (channelStat.getTwitchFollowerChannelId() != null) { - GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getTwitchFollowerChannelId()); - if (guildChannel != null) { - if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) - continue; - - LanguageService.getByGuild(guildChannel.getGuild(), "label.twitchCountName", channelFollowCountUpdateEvent.getFollowCount()).subscribe(newName -> { - if (!guildChannel.getName().equalsIgnoreCase(newName)) { - guildChannel.getManager().setName(newName).queue(); - } - }); - } - } - } - } - }); - }); - } - - /** - * Used to Register a Livestream Event for the given Twitch Channel - * - * @param twitchChannel the Name of the Twitch Channel. - */ - public void registerTwitchChannel(String twitchChannel) { - if (getTwitchClient() == null) return; - - twitchChannel = twitchChannel.toLowerCase(); - - if (!isTwitchRegistered(twitchChannel)) registeredTwitchChannels.add(twitchChannel); - - getTwitchClient().getClientHelper().enableStreamEventListener(twitchChannel); - getTwitchClient().getClientHelper().enableFollowEventListener(twitchChannel); - } - - /** - * Used to Register a Livestream Event for the given Twitch Channels - * - * @param twitchChannels the Names of the Twitch Channels. - */ - public void registerTwitchChannel(List twitchChannels) { - if (getTwitchClient() == null) return; - - twitchChannels.forEach(s -> { - if (s == null) return; - - s = s.toLowerCase(); - if (!isTwitchRegistered(s)) registeredTwitchChannels.add(s); - }); - - getTwitchClient().getClientHelper().enableStreamEventListener(twitchChannels); - getTwitchClient().getClientHelper().enableFollowEventListener(twitchChannels); - } - - /** - * Used to Unregister a Livestream Event for the given Twitch Channel - * - * @param twitchChannel the Name of the Twitch Channel. - */ - public void unregisterTwitchChannel(String twitchChannel) { - if (getTwitchClient() == null) return; - - twitchChannel = twitchChannel.toLowerCase(); - - String finalTwitchChannel = twitchChannel; - SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(twitchChannel).subscribe(webhooks -> { - if (!webhooks.isEmpty()) return; - - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitchFollowerChannelUsername=:name", Map.of("name", finalTwitchChannel)) - .subscribe(channelStats -> { - if (channelStats.isPresent()) return; - - if (isTwitchRegistered(finalTwitchChannel)) - registeredTwitchChannels.remove(finalTwitchChannel); - - getTwitchClient().getClientHelper().disableStreamEventListener(finalTwitchChannel); - getTwitchClient().getClientHelper().disableFollowEventListener(finalTwitchChannel); - }); - }); - } - - /** - * Check if a Twitch Channel is already being checked. - * - * @param twitchChannel the Name of the Twitch Channel. - * @return true, if there is an Event for the Channel | false, if there isn't an Event for the Channel. - */ - public boolean isTwitchRegistered(String twitchChannel) { - return registeredTwitchChannels.contains(twitchChannel.toLowerCase()); - } - - //endregion - - //region Twitter - - /** - * Used to Register a Tweet Event for the given Twitter Users - * - * @param twitterUsers the Names of the Twitter Users. - */ - public void registerTwitterUser(List twitterUsers) { - twitterUsers.forEach(this::registerTwitterUser); - } - - /** - * Used to Register a Tweet Event for the given Twitter User - * - * @param twitterUser the Name of the Twitter User. - */ - public void registerTwitterUser(String twitterUser) { - if (getTwitterClient() == null) return; - - twitterUser = twitterUser.toLowerCase(); - - if (!isTwitterRegistered(twitterUser)) { - registeredTwitterUsers.add(twitterUser); - } - } - - /** - * Used to Unregister a Tweet Event for the given Twitter User - * - * @param twitterUser the Name of the Twitter User. - */ - public void unregisterTwitterUser(String twitterUser) { - if (getTwitterClient() == null) return; - - twitterUser = twitterUser.toLowerCase(); - - String finalTwitterUser = twitterUser; - SQLSession.getSqlConnector().getSqlWorker().getTwitterWebhooksByName(twitterUser).subscribe(webhooks -> { - if (!webhooks.isEmpty()) return; - - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", Map.of("name", finalTwitterUser)).subscribe(x -> { - if (x.isPresent()) return; - - if (isTwitterRegistered(finalTwitterUser)) { - registeredTwitterUsers.remove(finalTwitterUser); - } - }); - }); - } - - /** - * Check if a Twitter User is already being checked. - * - * @param twitterUser the Name of the Twitter User. - * @return true, if there is an Event for the User | false, if there isn't an Event for the User. - */ - public boolean isTwitterRegistered(String twitterUser) { - return registeredTwitterUsers.contains(twitterUser.toLowerCase()); - } - - //endregion - - //region Reddit - - public List getSubredditPosts(String subreddit, Sorting sorting, int limit) throws AuthenticationException, IOException, InterruptedException { - try { - return redditClient.getSubredditPosts(subreddit, sorting).limit(limit).submit(); - } catch (ValidateException exception) { - if (exception.getMessage().startsWith("The parameter")) { - redditClient.userlessConnect(); - return redditClient.getSubredditPosts(subreddit, sorting).limit(limit).submit(); - } - } - - return Collections.emptyList(); - } - - /** - * Used to register a Reddit-Post Event for all Subreddits. - */ - public void createRedditPostStream() { - ThreadUtil.createThread(x -> { - try { - for (String subreddit : registeredSubreddits) { - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", Map.of("name", subreddit)).subscribe(channelStats -> { - if (!channelStats.isEmpty()) { - RedditSubreddit subredditEntity; - try { - subredditEntity = Main.getInstance().getNotifier().getSubreddit(subreddit); - } catch (IOException | InterruptedException e) { - return; - } - - for (ChannelStats channelStat : channelStats) { - if (channelStat.getSubredditMemberChannelId() != null) { - GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getSubredditMemberChannelId()); - String newName = "Subreddit Members: " + subredditEntity.getActiveUserCount(); - if (guildChannel != null && - !guildChannel.getName().equalsIgnoreCase(newName)) { - - if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) - continue; - - guildChannel.getManager().setName(newName).queue(); - } - } - } - } - }); - - getSubredditPosts(subreddit, Sorting.NEW, 50).stream().filter(redditPost -> redditPost.getCreated() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())).forEach(redditPost -> { - SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit).subscribe(webhooks -> { - if (webhooks.isEmpty()) return; - - // Create Webhook Message. - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName()); - - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(redditPost.getTitle(), redditPost.getUrl())); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Reddit Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); - - - if (!redditPost.getThumbnail().equalsIgnoreCase("self")) - webhookEmbedBuilder.setImageUrl(redditPost.getThumbnail()); - - // Set rest of the Information. - webhookEmbedBuilder.setDescription(URLDecoder.decode(redditPost.getSelftext(), StandardCharsets.UTF_8)); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Author**", redditPost.getAuthor())); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Subreddit**", redditPost.getSubreddit())); - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); - - webhookEmbedBuilder.setColor(Color.ORANGE.getRGB()); - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - - webhooks.forEach(webhook -> { - String message = webhook.getMessage() - .replace("%title%", redditPost.getTitle()) - .replace("%author%", redditPost.getAuthor()) - .replace("%name%", redditPost.getSubreddit()) - .replace("%url%", redditPost.getUrl()); - webhookMessageBuilder.setContent(message); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); - }); - }); - }); - } - } catch (Exception exception) { - log.error("Could not get Reddit Posts!", exception); - Sentry.captureException(exception); - } - }, x -> { - log.error("Couldn't start Reddit Stream!"); + log.info("Creating TikTok Streams..."); + tikTokSonic = new TikTokSonic(); + ThreadUtil.createThread(x -> tikTokSonic.run(), x -> { + log.error("Failed to run TikTok Stream!", x); Sentry.captureException(x); }, Duration.ofMinutes(5), true, true); - } - - /** - * Used to get a Subreddit. - * - * @param subreddit the Name of the Subreddit. - * @return the Subreddit. - * @throws IOException if the Subreddit couldn't be found. - * @throws InterruptedException if the Thread was interrupted. - */ - public RedditSubreddit getSubreddit(String subreddit) throws IOException, InterruptedException { - return redditClient.getSubreddit(subreddit); - } - /** - * Used to register a Reddit-Post Event for the given Subreddit - * - * @param subreddit the Names of the Subreddit. - */ - public void registerSubreddit(String subreddit) { - if (getRedditClient() == null) return; - - if (!isSubredditRegistered(subreddit)) registeredSubreddits.add(subreddit); - } - - /** - * Used to register a Reddit-Post Event for the Subreddit. - * - * @param subreddits the Names of the Subreddits. - */ - public void registerSubreddit(List subreddits) { - if (getRedditClient() == null) return; - - subreddits.forEach(s -> { - if (!isSubredditRegistered(s)) registeredSubreddits.add(s); - }); - } - - /** - * Used to unregister a Reddit-Post Event for the given Subreddit. - * - * @param subreddit the Names of the Subreddit. - */ - public void unregisterSubreddit(String subreddit) { - if (getRedditClient() == null) return; - - SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit).subscribe(webhooks -> { - if (!webhooks.isEmpty()) return; - - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", Map.of("name", subreddit)).subscribe(channelStats -> { - if (channelStats.isPresent()) return; - - if (isSubredditRegistered(subreddit)) registeredSubreddits.remove(subreddit); - }); - }); - } - - /** - * Check if a Subreddit is already being checked. - * - * @param subreddit the Names of the Subreddit. - * @return true, if there is an Event for the Channel | false, if there isn't an Event for the Channel. - */ - public boolean isSubredditRegistered(String subreddit) { - return registeredSubreddits.contains(subreddit); - } - - //endregion - - //region Instagram - - /** - * Used to register an Instagram-Post Event for all Insta-Users. - */ - public void createInstagramPostStream() { - ThreadUtil.createThread(x -> { - if (!instagramClient.isLoggedIn()) return; - - for (String username : registeredInstagramUsers) { - - instagramClient.actions().users().findByUsername(username).thenAccept(userAction -> { - com.github.instagram4j.instagram4j.models.user.User user = userAction.getUser(); - - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", Map.of("name", username)).subscribe(channelStats -> { - if (!channelStats.isEmpty()) { - for (ChannelStats channelStat : channelStats) { - if (channelStat.getInstagramFollowerChannelId() != null) { - GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getInstagramFollowerChannelId()); - - if (guildChannel == null) continue; - - LanguageService.getByGuild(guildChannel.getGuild(), "label.instagramCountName", user.getFollower_count()).subscribe(newName -> { - if (!guildChannel.getName().equalsIgnoreCase(newName)) { - if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) - return; - - guildChannel.getManager().setName(newName).queue(); - } - }); - } - } - } - }); - - SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(username).subscribe(webhooks -> { - if (webhooks.isEmpty()) return; - - if (!user.is_private()) { - FeedIterator iterable = new FeedIterator<>(instagramClient, new FeedUserRequest(user.getPk())); - - int limit = 1; - while (iterable.hasNext() && limit-- > 0) { - FeedUserResponse response = iterable.next(); - // Actions here - response.getItems().stream().filter(post -> post.getTaken_at() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())).forEach(instagramPost -> { - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName()); - - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(user.getUsername(), "https://www.instagram.com/" + user.getUsername())); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Instagram Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); - - // Set the rest of the Information. - if (instagramPost instanceof TimelineImageMedia timelineImageMedia) { - webhookEmbedBuilder.setImageUrl(timelineImageMedia.getImage_versions2().getCandidates().get(0).getUrl()); - webhookEmbedBuilder.setDescription(timelineImageMedia.getCaption().getText()); - } else if (instagramPost instanceof TimelineVideoMedia timelineVideoMedia) { - webhookEmbedBuilder.setDescription("[Click here to watch the video](" + timelineVideoMedia.getVideo_versions().get(0).getUrl() + ")"); - } else { - webhookEmbedBuilder.setDescription(user.getUsername() + " just posted something new on Instagram!"); - } - - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); - - webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); - - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - - // TODO:: add this with message. - - webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook)); - }); - } - } - }); - }).exceptionally(exception -> { - log.error("Could not get Instagram User!", exception); - Sentry.captureException(exception); - return null; - }).join(); - } - }, x -> { - log.error("Couldn't start Instagram Stream!"); + log.info("Creating Instagram Streams..."); + instagramSonic = new InstagramSonic(); + ThreadUtil.createThread(x -> instagramSonic.run(), x -> { + log.error("Failed to run Instagram Stream!", x); Sentry.captureException(x); }, Duration.ofMinutes(5), true, true); - } - - /** - * Used to register an Instagram-Post Event for all Insta-Users. - * - * @param username the Names of the User. - */ - public void registerInstagramUser(String username) { - if (getInstagramClient() == null) return; - - if (!isInstagramUserRegistered(username)) registeredInstagramUsers.add(username); - } - - /** - * Used to register an Instagram-Post Event for all Insta-Users. - * - * @param usernames the Names of the Users. - */ - public void registerInstagramUser(List usernames) { - if (getInstagramClient() == null) return; - - usernames.forEach(s -> { - if (!isInstagramUserRegistered(s)) registeredInstagramUsers.add(s); - }); - } - - /** - * Used to unregister an Instagram-Post Event for all Insta-Users. - * - * @param username the Names of the User. - */ - public void unregisterInstagramUser(String username) { - if (getInstagramClient() == null) return; - - SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(username).subscribe(webhooks -> { - if (!webhooks.isEmpty()) return; - - if (SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", Map.of("name", username)).block().isPresent()) - return; - - if (isInstagramUserRegistered(username)) registeredInstagramUsers.remove(username); - }); - } - - /** - * Check if a User is already being checked. - * - * @param username the Names of the User. - * @return true, if there is an Event for the Channel | false, if there isn't an Event for the Channel. - */ - public boolean isInstagramUserRegistered(String username) { - return registeredInstagramUsers.contains(username); - } - - //endregion - - //region TikTok - - /** - * Used to create a Thread that handles TikTok notifications. - */ - public void createTikTokStream() { - ThreadUtil.createThread(x -> { - for (long id : registeredTikTokUsers) { - try { - TikTokUser user = TikTokWrapper.getUser(id); - - SQLSession.getSqlConnector().getSqlWorker().getTikTokWebhooksByName(user.getId()).subscribe(webhooks -> { - if (webhooks.isEmpty()) { - return; - } - - AtomicInteger limit = new AtomicInteger(); - - user.getPosts().forEach(post -> { - if (limit.get() > 3) return; - - if (post.getCreationTime() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())) { - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName()); - - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(user.getDisplayName(), "https://www.tiktok.com/@" + user.getName())); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("TikTok Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); - - // Set rest of the Information. - if (post.getCover() != null) { - webhookEmbedBuilder.setImageUrl(post.getCover().getMediumUrl()); - webhookEmbedBuilder.setDescription("[Click here to watch the video](https://tiktok.com/share/video/" + post.getId() + ")"); - } else { - webhookEmbedBuilder.setDescription(user.getDisplayName() + " just posted something new on TikTok!"); - } - - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); - - webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); - - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - webhooks.forEach(webhook -> { - String message = webhook.getMessage() - .replace("%description%", post.getDescription()) - .replace("%author%", user.getName()) - .replace("%name%", user.getDisplayName()) - .replace("%url%", "https://tiktok.com/share/video/" + post.getId()); - webhookMessageBuilder.setContent(message); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); - }); - } - limit.incrementAndGet(); - }); - }); - } catch (IOException e) { - if (e instanceof HttpStatusException httpStatusException) { - if (httpStatusException.getStatusCode() == 404) return; - // TODO:: check, maybe delete on 404? - } - - Sentry.captureException(e); - } - } + log.info("Creating Reddit Streams..."); + redditSonic = new RedditSonic(); + ThreadUtil.createThread(x -> redditSonic.run(), x -> { + log.error("Failed to run Reddit Stream!", x); + Sentry.captureException(x); }, Duration.ofMinutes(5), true, true); } - - /** - * Used to register a TikTok User. - * - * @param id the ID of the TikTok User. - */ - public void registerTikTokUser(long id) { - if (!isTikTokUserRegistered(id)) registeredTikTokUsers.add(id); - } - - /** - * Used to register multiple TikTok Users. - * - * @param users the ID of the TikTok Users. - */ - public void registerTikTokUser(List users) { - users.forEach(this::registerTikTokUser); - } - - /** - * Used to unregister a TikTok User. - * - * @param id the ID of the TikTok User. - */ - public void unregisterTikTokUser(long id) { - if (isTikTokUserRegistered(id)) registeredTikTokUsers.remove(id); - } - - /** - * Check if a TikTok User is already being checked. - * - * @param id the Name of the TikTok User. - * @return true, if there is a User | false, if there isn't a User. - */ - public boolean isTikTokUserRegistered(long id) { - return registeredTikTokUsers.contains(id); - } - - //endregion - - //region RSS - - /** - * Used to register an RSS Feed. - * - * @param rssUrl the Url of the RSS-Feed. - */ - public void registerRSS(String rssUrl) { - if (!isRSSRegistered(rssUrl)) registeredRSSFeeds.add(rssUrl); - } - - /** - * Used to register an RSS Feed. - * - * @param rssUrls the Urls of the RSS-Feeds. - */ - public void registerRSS(List rssUrls) { - rssUrls.forEach(s -> { - if (!isRSSRegistered(s)) registeredRSSFeeds.add(s); - }); - } - - /** - * Used to unregister an RSS Feed. - * - * @param rssUrl the Url of the RSS-Feed. - */ - public void unregisterRSS(String rssUrl) { - if (isRSSRegistered(rssUrl)) registeredRSSFeeds.remove(rssUrl); - } - - /** - * Check if an RSS-Feed is already being checked. - * - * @param rssUrl the Url of the RSS-Feed. - * @return true, if there is an Url | false, if there isn't an Url. - */ - public boolean isRSSRegistered(String rssUrl) { - return registeredRSSFeeds.contains(rssUrl); - } - - //endregion } From 503f35a01335dc905b835b7e9edd3e3831409b00 Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 5 Jul 2024 18:25:14 +0200 Subject: [PATCH 31/94] Preventing output outside of debug env. --- .../presti/ree6/commands/CommandManager.java | 19 +++++++++++++------ .../presti/ree6/commands/impl/info/Stats.java | 10 +++++++++- .../de/presti/ree6/events/OtherEvents.java | 6 ++++-- .../de/presti/ree6/utils/apis/Notifier.java | 10 ++++------ 4 files changed, 30 insertions(+), 15 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/CommandManager.java b/src/main/java/de/presti/ree6/commands/CommandManager.java index ad96aaf89..b5cf60b3d 100644 --- a/src/main/java/de/presti/ree6/commands/CommandManager.java +++ b/src/main/java/de/presti/ree6/commands/CommandManager.java @@ -369,7 +369,9 @@ public void removeCommand(ICommand command) { */ public Mono perform(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion messageChannel, SlashCommandInteractionEvent slashCommandInteractionEvent) { boolean isSlashCommand = slashCommandInteractionEvent != null; - log.info("Called perform"); + + if (BotConfig.isDebug()) + log.info("Called perform"); // Check if the User is under Cooldown. if (isTimeout(member.getUser())) { @@ -436,11 +438,13 @@ private Mono performMessageCommand(Member member, Guild guild, String m return Mono.just(false); } - log.info("Called performMessageCommand"); + if (BotConfig.isDebug()) + log.info("Called performMessageCommand"); return SQLSession.getSqlConnector().getSqlWorker().getSetting(guild.getIdLong(), "chatprefix").publishOn(Schedulers.boundedElastic()).mapNotNull(setting -> { - log.info("Got to prefix check."); + if (BotConfig.isDebug()) + log.info("Got to prefix check."); String currentPrefix = setting.orElseGet(() -> new Setting(-1, "chatprefix", "Chat Prefix", BotConfig.getDefaultPrefix())).getStringValue(); @@ -458,7 +462,8 @@ private Mono performMessageCommand(Member member, Guild guild, String m }).block(); } - log.info("Passed parsing."); + if (BotConfig.isDebug()) + log.info("Passed parsing."); // Get the Command by the name. ICommand command = getCommandByName(arguments[0]); @@ -495,7 +500,8 @@ private Mono performMessageCommand(Member member, Guild guild, String m }).block(); } - log.info("Finished custom command."); + if (BotConfig.isDebug()) + log.info("Finished custom command."); if (command.getClass().getAnnotation(Command.class).category() != Category.HIDDEN) { Optional blacklist = SQLSession.getSqlConnector().getSqlWorker() @@ -510,7 +516,8 @@ private Mono performMessageCommand(Member member, Guild guild, String m } } - log.info("Finished blacklist."); + if (BotConfig.isDebug()) + log.info("Finished blacklist."); // Parse the arguments. String[] argumentsParsed = Arrays.copyOfRange(arguments, 1, arguments.length); diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java index bfc13d9c9..ed5cab733 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java @@ -42,7 +42,7 @@ public void onPerform(CommandEvent commandEvent) { : commandEvent.getChannel().sendMessage(commandEvent.getResource("label.loading")).complete(); long ping = System.currentTimeMillis() - start; - + long computeTimeStart = System.currentTimeMillis(); EmbedBuilder em = new EmbedBuilder(); em.setAuthor(commandEvent.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), @@ -94,6 +94,14 @@ public void onPerform(CommandEvent commandEvent) { MessageEditBuilder messageEditBuilder = new MessageEditBuilder(); messageEditBuilder.setContent(""); + + long computeTime = System.currentTimeMillis() - computeTimeStart; + + if (BotConfig.isDebug()) { + em.addField("**DEV ONLY**", "", true); + em.addField("**Compute Time**", computeTime + "ms", true); + } + messageEditBuilder.setEmbeds(em.build()); commandEvent.update(message, messageEditBuilder.build()); diff --git a/src/main/java/de/presti/ree6/events/OtherEvents.java b/src/main/java/de/presti/ree6/events/OtherEvents.java index d9583b85a..d1f5bb75b 100644 --- a/src/main/java/de/presti/ree6/events/OtherEvents.java +++ b/src/main/java/de/presti/ree6/events/OtherEvents.java @@ -475,7 +475,8 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { ModerationUtil.shouldModerate(event.getGuild().getIdLong()).publishOn(Schedulers.boundedElastic()).map(x -> { - log.info("Message received from {} in {} with content: {}", event.getAuthor().getGlobalName(), event.getChannel().getName(), event.getMessage().getContentRaw()); + if (BotConfig.isDebug()) + log.info("Message received from {} in {} with content: {}", event.getAuthor().getGlobalName(), event.getChannel().getName(), event.getMessage().getContentRaw()); boolean moderated = false; if (x) { @@ -488,7 +489,8 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { } } - log.info("Message was moderated: {}", moderated); + if (BotConfig.isDebug()) + log.info("Message was moderated: {}", moderated); return moderated; }).flatMap((aBoolean) -> handleCommand(aBoolean, event)).publishOn(Schedulers.boundedElastic()).doOnNext(handled -> { diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index 210d84803..b6a03c759 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -136,6 +136,7 @@ public Notifier() { if (!BotConfig.isModuleActive("notifier")) return; log.info("Initializing Twitch Client..."); + twitchSonic = new TwitchSonic(); try { credentialManager = CredentialManagerBuilder.builder() .withStorageBackend(new DatabaseStorageBackend()) @@ -207,7 +208,7 @@ public Notifier() { } log.info("Initializing Twitter Client..."); - + twitterSonic = new TwitterSonic(); try { twitterClient = new TwitterClient(TwitterCredentials.builder() .bearerToken(Main.getInstance().getConfig().getConfiguration().getString("twitter.bearer")).build()); @@ -216,7 +217,7 @@ public Notifier() { } log.info("Initializing Reddit Client..."); - + redditSonic = new RedditSonic(); try { redditClient = Reddit4J .rateLimited() @@ -235,7 +236,7 @@ public Notifier() { } log.info("Initializing Instagram Client..."); - + instagramSonic = new InstagramSonic(); // Callable that returns inputted code from System.in Callable inputCode = () -> { Scanner scanner = new Scanner(System.in); @@ -275,7 +276,6 @@ public Notifier() { }, Duration.ofMinutes(5), true, true); log.info("Creating Twitter Streams..."); - twitterSonic = new TwitterSonic(); ThreadUtil.createThread(x -> twitterSonic.run(), x -> { log.error("Failed to run Twitter Follower count checker!", x); Sentry.captureException(x); @@ -296,14 +296,12 @@ public Notifier() { }, Duration.ofMinutes(5), true, true); log.info("Creating Instagram Streams..."); - instagramSonic = new InstagramSonic(); ThreadUtil.createThread(x -> instagramSonic.run(), x -> { log.error("Failed to run Instagram Stream!", x); Sentry.captureException(x); }, Duration.ofMinutes(5), true, true); log.info("Creating Reddit Streams..."); - redditSonic = new RedditSonic(); ThreadUtil.createThread(x -> redditSonic.run(), x -> { log.error("Failed to run Reddit Stream!", x); Sentry.captureException(x); From 687cb85d7320dc05cd360a1c3332983034851099 Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 5 Jul 2024 18:30:34 +0200 Subject: [PATCH 32/94] Revert bad merge. --- .../de/presti/ree6/commands/impl/info/Stats.java | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java index 0e5f5c5e3..dcdd5c97c 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java @@ -1,5 +1,6 @@ package de.presti.ree6.commands.impl.info; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; @@ -9,7 +10,6 @@ import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.stats.CommandStats; import de.presti.ree6.sql.entities.stats.GuildCommandStats; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.TimeUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Message; @@ -37,12 +37,9 @@ public void onPerform(CommandEvent commandEvent) { long start = System.currentTimeMillis(); - Message message = null; - if (commandEvent.isSlashCommand()) { - message = commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("label.loading")).complete(); - } else { - message = commandEvent.getChannel().sendMessage(commandEvent.getResource("label.loading")).complete(); - } + Message message = commandEvent.isSlashCommand() + ? commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("label.loading")).complete() + : commandEvent.getChannel().sendMessage(commandEvent.getResource("label.loading")).complete(); long ping = System.currentTimeMillis() - start; long computeTimeStart = System.currentTimeMillis(); @@ -68,7 +65,7 @@ public void onPerform(CommandEvent commandEvent) { em.addField("**" + commandEvent.getResource("label.discordStats") + ":**", "", true); em.addField("**" + commandEvent.getResource("label.gatewayTime") + "**", BotWorker.getShardManager().getAverageGatewayPing() + "ms", true); - em.addField("**" + commandEvent.getResource("label.shardAmount") + "**", BotWorker.getShardManager().getShards().size() + " " + commandEvent.getResource("label.shards"), true); + em.addField("**" + commandEvent.getResource("label.shardAmount") + "**", BotWorker.getShardManager().getShards().size() + " " + commandEvent.getResource("label.shards"), true); em.addField("**" + commandEvent.getResource("label.networkStats") + ":**", "", true); em.addField("**" + commandEvent.getResource("label.responseTime") + "**", (Integer.parseInt((ping) + "")) + "ms", true); From 1f9da8f0eeb23e60b85aeec7368f35bd9ec825d8 Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 5 Jul 2024 18:32:12 +0200 Subject: [PATCH 33/94] Fix typo. --- src/main/java/de/presti/ree6/commands/impl/info/Stats.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java index dcdd5c97c..f015795c5 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java @@ -100,7 +100,7 @@ public void onPerform(CommandEvent commandEvent) { if (BotConfig.isDebug()) { em.addField("**DEV ONLY**", "", true); em.addField("**Compute Time**", computeTime + "ms", true); - em.addField("**DEV ONLY*", "", true); + em.addField("**DEV ONLY**", "", true); } messageEditBuilder.setEmbeds(em.build()); From 69371d331629f922667638d5ec3d0b36e9753226 Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 8 Aug 2024 12:10:49 +0200 Subject: [PATCH 34/94] Fixing a conditional lock of operation. --- .../presti/ree6/bot/version/BotVersion.java | 15 ++++-- .../de/presti/ree6/commands/CommandEvent.java | 18 +++++-- .../presti/ree6/commands/CommandManager.java | 49 ++++++++++++++++--- .../presti/ree6/commands/impl/fun/Cringe.java | 2 +- .../presti/ree6/commands/impl/info/Stats.java | 5 +- .../de/presti/ree6/commands/impl/mod/Ban.java | 2 +- .../ree6/commands/impl/mod/Blacklist.java | 2 +- .../presti/ree6/commands/impl/mod/Clear.java | 2 +- .../presti/ree6/commands/impl/mod/Kick.java | 2 +- .../presti/ree6/commands/impl/mod/Mute.java | 2 +- .../presti/ree6/commands/impl/mod/Setup.java | 2 +- .../presti/ree6/commands/impl/mod/Unban.java | 2 +- .../presti/ree6/commands/impl/mod/Unmute.java | 2 +- .../ree6/commands/interfaces/ICommand.java | 18 +++++-- .../de/presti/ree6/events/OtherEvents.java | 4 +- .../ree6/game/impl/blackjack/Blackjack.java | 2 +- .../de/presti/ree6/language/Language.java | 46 +++-------------- .../de/presti/ree6/utils/apis/Notifier.java | 4 +- .../de/presti/ree6/utils/data/ArrayUtil.java | 12 ++--- 19 files changed, 110 insertions(+), 81 deletions(-) diff --git a/src/main/java/de/presti/ree6/bot/version/BotVersion.java b/src/main/java/de/presti/ree6/bot/version/BotVersion.java index 1639be0f0..e66f9e432 100644 --- a/src/main/java/de/presti/ree6/bot/version/BotVersion.java +++ b/src/main/java/de/presti/ree6/bot/version/BotVersion.java @@ -13,19 +13,28 @@ public enum BotVersion { /** * Version for Development tests. */ - DEVELOPMENT("bot.tokens.dev"), + DEVELOPMENT("Dev","bot.tokens.dev"), /** * Version for a not yet fully stable release. */ - BETA("bot.tokens.beta"), + BETA("Beta", "bot.tokens.beta"), /** * Version for a stable release. */ - RELEASE("bot.tokens.release"); + RELEASE("Release", "bot.tokens.release"); + + /** + * The name of the Version. + */ + final String name; /** * The Token-Path in the config file. */ final String tokenPath; + @Override + public String toString() { + return name; + } } diff --git a/src/main/java/de/presti/ree6/commands/CommandEvent.java b/src/main/java/de/presti/ree6/commands/CommandEvent.java index 5eedfb857..5d2ac90b4 100644 --- a/src/main/java/de/presti/ree6/commands/CommandEvent.java +++ b/src/main/java/de/presti/ree6/commands/CommandEvent.java @@ -3,10 +3,10 @@ import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import lombok.Getter; +import lombok.extern.java.Log; import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.entities.channel.unions.GuildMessageChannelUnion; -import net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.InteractionHook; import net.dv8tion.jda.api.interactions.commands.OptionMapping; @@ -20,6 +20,7 @@ /** * Event class used to parse and provide Information about a command execution. */ +@Log public class CommandEvent { /** @@ -152,7 +153,8 @@ public void reply(MessageCreateData message, int deleteSecond) { /** * Update a Message that has been sent. - * @param message the Message that has been sent. + * + * @param message the Message that has been sent. * @param messageEditData the Message Edit that is being used to update the message. */ public void update(@Nullable Message message, MessageEditData messageEditData) { @@ -167,6 +169,7 @@ public void update(@Nullable Message message, MessageEditData messageEditData) { /** * If the message default should be ephemeral or not. + * * @param ephemeral if the message should be ephemeral. */ public void setEphemeral(boolean ephemeral) { @@ -175,6 +178,13 @@ public void setEphemeral(boolean ephemeral) { } } + /** + * Delete the Message that has been sent. + */ + public void delete() { + Main.getInstance().getCommandManager().deleteMessageWithoutException(message, getInteractionHook()); + } + /** * Get a Message from the Guild specific Language Setting. * @@ -249,7 +259,6 @@ public String[] getArguments() { * Get the Arguments associated with the Event. * * @param parseFromSlash if the Arguments should be parsed from the SlashCommandInteractionEvent. - * * @return the Arguments. */ public String[] getArguments(boolean parseFromSlash) { @@ -280,6 +289,7 @@ public String[] getArguments(boolean parseFromSlash) { /** * Get an option from the slash command! + * * @param name The option name. * @return the {@link OptionMapping} of the option | or null. */ @@ -291,6 +301,7 @@ public String[] getArguments(boolean parseFromSlash) { /** * Get the Subcommand of the Slash Command. + * * @return the Subcommand. */ public String getSubcommand() { @@ -303,6 +314,7 @@ public String getSubcommand() { /** * Get the Subcommand Group of the Slash Command. + * * @return the Subcommand Group. */ public String getSubcommandGroup() { diff --git a/src/main/java/de/presti/ree6/commands/CommandManager.java b/src/main/java/de/presti/ree6/commands/CommandManager.java index b5cf60b3d..f4fc2b0a2 100644 --- a/src/main/java/de/presti/ree6/commands/CommandManager.java +++ b/src/main/java/de/presti/ree6/commands/CommandManager.java @@ -434,6 +434,8 @@ public void timeoutUser(User user) { private Mono performMessageCommand(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion textChannel) { // Check if the Message is null. if (message == null) { + if (BotConfig.isDebug()) + log.info("Message is null."); sendMessage(LanguageService.getByGuild(guild, "command.perform.error").block(), 5, textChannel, null); return Mono.just(false); } @@ -449,8 +451,11 @@ private Mono performMessageCommand(Member member, Guild guild, String m String currentPrefix = setting.orElseGet(() -> new Setting(-1, "chatprefix", "Chat Prefix", BotConfig.getDefaultPrefix())).getStringValue(); // Check if the message starts with the prefix. - if (!messageContent.toLowerCase().startsWith(currentPrefix)) + if (!messageContent.toLowerCase().startsWith(currentPrefix)) { + if (BotConfig.isDebug()) + log.info("Wrong prefix"); return false; + } // Split all Arguments. String[] arguments = messageContent.substring(currentPrefix.length()).split("\\s+"); @@ -458,6 +463,8 @@ private Mono performMessageCommand(Member member, Guild guild, String m if (arguments.length == 0 || arguments[0].isBlank()) { return LanguageService.getByGuild(guild, "command.perform.missingCommand").map(translated -> { sendMessage(translated, 5, textChannel, null); + if (BotConfig.isDebug()) + log.info("Missing command from string."); return false; }).block(); } @@ -470,9 +477,15 @@ private Mono performMessageCommand(Member member, Guild guild, String m // Check if there is even a Command with that name. if (command == null && BotConfig.isModuleActive("customcommands")) { - return SQLSession.getSqlConnector().getSqlWorker().getEntity(new CustomCommand(), "FROM CustomCommand WHERE guildId=:gid AND name=:command", Map.of("gid", guild.getIdLong(), "command", arguments[0].toLowerCase())) + return SQLSession.getSqlConnector().getSqlWorker().getEntity(new CustomCommand(), "FROM CustomCommand WHERE guildId=:gid AND name=:command", + Map.of("gid", guild.getIdLong(), "command", arguments[0].toLowerCase())) .flatMap(customCommand -> { + if (BotConfig.isDebug()) + log.info("Got custom command."); + if (customCommand.isPresent()) { + if (BotConfig.isDebug()) + log.info("Custom command is present."); GuildMessageChannelUnion messageChannelUnion = textChannel; CustomCommand customCommandEntity = customCommand.get(); if (customCommandEntity.getChannelId() != -1) { @@ -491,7 +504,13 @@ private Mono performMessageCommand(Member member, Guild guild, String m return Mono.just(true); } - return Mono.just(false); + if (BotConfig.isDebug()) + log.info("Custom command is not present."); + + return LanguageService.getByGuild(guild, "command.perform.notFound").map(translated -> { + sendMessage(translated, 5, textChannel, null); + return false; + }); }).block(); } else if (command == null) { return LanguageService.getByGuild(guild, "command.perform.notFound").map(translated -> { @@ -501,11 +520,13 @@ private Mono performMessageCommand(Member member, Guild guild, String m } if (BotConfig.isDebug()) - log.info("Finished custom command."); + log.info("Finished command check."); - if (command.getClass().getAnnotation(Command.class).category() != Category.HIDDEN) { + Command commandAnnotation = command.getClass().getAnnotation(Command.class); + + if (commandAnnotation.category() != Category.HIDDEN) { Optional blacklist = SQLSession.getSqlConnector().getSqlWorker() - .getSetting(guild.getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()).block(); + .getSetting(guild.getIdLong(), "command_" + commandAnnotation.name().toLowerCase()).block(); // Check if the Command is blacklisted. if (blacklist != null && blacklist.isPresent() && !blacklist.get().getBooleanValue()) { @@ -523,7 +544,7 @@ private Mono performMessageCommand(Member member, Guild guild, String m String[] argumentsParsed = Arrays.copyOfRange(arguments, 1, arguments.length); // Perform the Command. - return command.onMonoPerform(new CommandEvent(command.getClass().getAnnotation(Command.class).name(), member, guild, message, textChannel, argumentsParsed, null)).block(); + return command.onMonoPerform(new CommandEvent(commandAnnotation.name(), member, guild, message, textChannel, argumentsParsed, null)).block(); }); } @@ -797,4 +818,18 @@ public void deleteMessage(Message message, InteractionHook interactionHook) { } } + /** + * Delete a specific message. + * + * @param message the {@link Message} entity. + * @param interactionHook the Interaction-hook, if it is a slash event. + */ + public void deleteMessageWithoutException(Message message, InteractionHook interactionHook) { + try { + deleteMessage(message, interactionHook); + } catch (Exception e) { + log.error("[CommandManager] Couldn't delete a Message -> {}", e.getMessage()); + } + } + } \ No newline at end of file diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Cringe.java b/src/main/java/de/presti/ree6/commands/impl/fun/Cringe.java index 9a6cdd7ab..d42c9f301 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Cringe.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Cringe.java @@ -27,7 +27,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getChannel().getHistoryBefore(commandEvent.getMessage().getIdLong(), 1).complete().getRetrievedHistory().get(0).reply("https://images.ree6.de/cringe.gif").queue(); } - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java index f015795c5..f673a7d6d 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java @@ -32,8 +32,7 @@ public class Stats implements ICommand { */ @Override public void onPerform(CommandEvent commandEvent) { - - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); long start = System.currentTimeMillis(); @@ -59,7 +58,7 @@ public void onPerform(CommandEvent commandEvent) { em.addField("**" + commandEvent.getResource("label.users") + "**", String.valueOf(memberCount), true); em.addField("**" + commandEvent.getResource("label.botStats") + ":**", "", true); - em.addField("**" + commandEvent.getResource("label.version") + "**", BotWorker.getBuild() + "-" + BotWorker.getVersion().name().toUpperCase() + em.addField("**" + commandEvent.getResource("label.version") + "**", BotWorker.getBuild() + "-" + BotWorker.getVersion().getName().toUpperCase() + " [[" + BotWorker.getCommit() + "](" + BotWorker.getRepository().replace(".git", "") + "/commit/" + BotWorker.getCommit() + ")]", true); em.addField("**" + commandEvent.getResource("label.uptime") + "**", TimeUtil.getTime(BotWorker.getStartTime()), true); diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Ban.java b/src/main/java/de/presti/ree6/commands/impl/mod/Ban.java index 3d1a749ff..cb6ff5846 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Ban.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Ban.java @@ -74,7 +74,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", Permission.ADMINISTRATOR.name()), 5); } - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java b/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java index 1d08fff6e..8d32145bb 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java @@ -139,7 +139,7 @@ public void onPerform(CommandEvent commandEvent) { } else { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", Permission.ADMINISTRATOR.name()), 5); } - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Clear.java b/src/main/java/de/presti/ree6/commands/impl/mod/Clear.java index e887abe47..e39993e49 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Clear.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Clear.java @@ -92,7 +92,7 @@ public void deleteMessages(CommandEvent commandEvent, int amount) { if (amount <= 200 && amount >= 2) { try { - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); commandEvent.getChannel().getIterableHistory().takeAsync(amount).thenAccept(messages -> { commandEvent.getChannel().purgeMessages(messages); commandEvent.reply(commandEvent.getResource("message.clear.success", amount), 5); diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Kick.java b/src/main/java/de/presti/ree6/commands/impl/mod/Kick.java index 1f2d51d26..bd1e62650 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Kick.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Kick.java @@ -62,7 +62,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", Permission.KICK_MEMBERS.name()), 5); } - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Mute.java b/src/main/java/de/presti/ree6/commands/impl/mod/Mute.java index a8a8e60e2..9efef0411 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Mute.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Mute.java @@ -80,7 +80,7 @@ public void onPerform(CommandEvent commandEvent) { } else { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", Permission.MODERATE_MEMBERS.name()), 5); } - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java index 83dd04e9f..09056be2f 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java @@ -276,8 +276,8 @@ public void onPerform(CommandEvent commandEvent) { } else { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", Permission.ADMINISTRATOR.name() + "/" + Permission.MANAGE_SERVER.name())); } - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); } public static EmbedBuilder createAutoRoleSetupMessage(Guild guild, InteractionHook interactionHook) { diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Unban.java b/src/main/java/de/presti/ree6/commands/impl/mod/Unban.java index 48464732c..6f3a54c22 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Unban.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Unban.java @@ -62,7 +62,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", Permission.BAN_MEMBERS.name()), 5); } - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Unmute.java b/src/main/java/de/presti/ree6/commands/impl/mod/Unmute.java index ab84f3640..4870638e6 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Unmute.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Unmute.java @@ -60,7 +60,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", Permission.MODERATE_MEMBERS.name()), 5); } - Main.getInstance().getCommandManager().deleteMessage(commandEvent.getMessage(), commandEvent.getInteractionHook()); + commandEvent.delete(); } /** diff --git a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java index 4271fbc68..266d01acd 100644 --- a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java +++ b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java @@ -33,18 +33,20 @@ default Mono onMonoPerform(CommandEvent commandEvent) { if (BotConfig.isDebug()) log.info("Command {} called by {} in {} ({}).", commandEvent.getCommand(), commandEvent.getMember().getUser().getName(), commandEvent.getGuild().getName(), commandEvent.getGuild().getId()); - return Mono.fromRunnable(() -> onPerform(commandEvent)).thenReturn(true).onErrorResume(throwable -> { + return Mono.fromRunnable(() -> onPerformWithLog(commandEvent)).thenReturn(true).onErrorResume(throwable -> { if (!throwable.getMessage().contains("Unknown Message")) { commandEvent.reply(commandEvent.getResource("command.perform.internalError"), 5); log.error("An error occurred while executing the command!", throwable); Sentry.captureException(throwable); } return Mono.just(false); - }).publishOn(Schedulers.boundedElastic()).doOnSuccess(success -> { + }).doOnSuccess(success -> { + if (BotConfig.isDebug()) + log.info("Updating Stats {} in {} ({}).", commandEvent.getCommand(), commandEvent.getGuild().getName(), commandEvent.getGuild().getId()); // Update Stats. SQLSession.getSqlConnector().getSqlWorker().addStats(commandEvent.getGuild().getIdLong(), commandEvent.getCommand()); Optional setting = SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").block(); - if (setting.isEmpty() || !setting.get().getBooleanValue()) return; + if (setting == null || setting.isEmpty() || !setting.get().getBooleanValue()) return; AnnouncementManager.getAnnouncementList().forEach(a -> { if (!AnnouncementManager.hasReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id())) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder().setTitle(a.title()) @@ -62,7 +64,7 @@ default Mono onMonoPerform(CommandEvent commandEvent) { /** * Will be fired when the Command is called. * - * @param commandEvent the Event, with every needed data. + * @param commandEvent the Event, with every necessary data. * @deprecated Use {@link #onMonoPerform(CommandEvent)} instead. */ @Deprecated(forRemoval = true, since = "4.0.0") @@ -94,10 +96,16 @@ default void onASyncPerform(CommandEvent commandEvent) { }); } + default void onPerformWithLog(CommandEvent commandEvent) { + onPerform(commandEvent); + if (BotConfig.isDebug()) + log.info("Command {} has ended, called by {} in {} ({}).", commandEvent.getCommand(), commandEvent.getMember().getUser().getName(), commandEvent.getGuild().getName(), commandEvent.getGuild().getId()); + } + /** * Will be fired when the Command is called. * - * @param commandEvent the Event, with every needed data. + * @param commandEvent the Event, with every necessary data. */ void onPerform(CommandEvent commandEvent); diff --git a/src/main/java/de/presti/ree6/events/OtherEvents.java b/src/main/java/de/presti/ree6/events/OtherEvents.java index d1f5bb75b..bbfbc7527 100644 --- a/src/main/java/de/presti/ree6/events/OtherEvents.java +++ b/src/main/java/de/presti/ree6/events/OtherEvents.java @@ -483,7 +483,7 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { moderated = Boolean.TRUE.equals(ModerationUtil.checkMessage(event.getGuild().getIdLong(), event.getMessage().getContentRaw()).block()); if (moderated) { - Main.getInstance().getCommandManager().deleteMessage(event.getMessage(), null); + Main.getInstance().getCommandManager().deleteMessageWithoutException(event.getMessage(), null); Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.blacklisted"), event.getChannel(), null); } @@ -493,7 +493,7 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { log.info("Message was moderated: {}", moderated); return moderated; - }).flatMap((aBoolean) -> handleCommand(aBoolean, event)).publishOn(Schedulers.boundedElastic()).doOnNext(handled -> { + }).flatMap((aBoolean) -> handleCommand(aBoolean, event)).doOnNext(handled -> { if (!handled) { if (!event.getMessage().getMentions().getUsers().isEmpty() && event.getMessage().getMentions().getUsers().contains(event.getJDA().getSelfUser())) { if (event.getMessage().getMessageReference() != null) return; diff --git a/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java b/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java index 8931418ec..0a5a9bcf2 100644 --- a/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java +++ b/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java @@ -117,7 +117,7 @@ public void startGame() { playerTwo.getHand().add(getRandomCard()); updateViews(player, playerTwo); - Main.getInstance().getCommandManager().deleteMessage(menuMessage, null); + Main.getInstance().getCommandManager().deleteMessageWithoutException(menuMessage, null); currentPlayer = player; } diff --git a/src/main/java/de/presti/ree6/language/Language.java b/src/main/java/de/presti/ree6/language/Language.java index b8b904258..4d5a6c7f3 100644 --- a/src/main/java/de/presti/ree6/language/Language.java +++ b/src/main/java/de/presti/ree6/language/Language.java @@ -4,6 +4,7 @@ import io.sentry.SentryEvent; import io.sentry.SentryLevel; import io.sentry.protocol.Message; +import lombok.Getter; import lombok.extern.slf4j.Slf4j; import net.dv8tion.jda.api.interactions.DiscordLocale; import org.jetbrains.annotations.NotNull; @@ -21,26 +22,31 @@ public class Language { /** * The Locale-Tag of the Language. */ + @Getter private final String locale; /** * The Name of the Language. */ + @Getter private final String name; /** * The Author of the Language-File. */ + @Getter private final String author; /** * The corresponding Ree6 Version. */ + @Getter private final String version; /** * The DiscordLocale of the Language. */ + @Getter private final DiscordLocale discordLocale; /** @@ -84,46 +90,6 @@ public Language(@NotNull String locale, @NotNull String name, @NotNull String au discordLocale = DiscordLocale.from(locale); } - /** - * Called to get the Locale-Tag of the Language. - * @return The Locale-Tag. - */ - public String getLocale() { - return locale; - } - - /** - * Called to get the Name of the Language. - * @return The Name. - */ - public String getName() { - return name; - } - - /** - * Called to get the Author of the Language-File. - * @return The Author. - */ - public String getAuthor() { - return author; - } - - /** - * Called to get the corresponding Ree6 Version. - * @return The Version. - */ - public String getVersion() { - return version; - } - - /** - * Called to get the DiscordLocale of the Language. - * @return The DiscordLocale. - */ - public DiscordLocale getDiscordLocale() { - return discordLocale; - } - /** * Called to get the entry of the Language. * @param key The key of the entry. diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index b6a03c759..f9ca582a3 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -130,7 +130,7 @@ public class Notifier { private final HashMap twitchSubscription = new HashMap<>(); /** - * Constructor used to created instance of the API Clients. + * Constructor used to create instance of the API Clients. */ public Notifier() { if (!BotConfig.isModuleActive("notifier")) return; @@ -143,7 +143,7 @@ public Notifier() { .build(); TwitchAuth.registerIdentityProvider(credentialManager, Main.getInstance().getConfig().getConfiguration().getString("twitch.client.id"), - Main.getInstance().getConfig().getConfiguration().getString("twitch.client.secret"), BotConfig.getTwitchAuth()); + Main.getInstance().getConfig().getConfiguration().getString("twitch.client.secret"), BotConfig.getTwitchAuth(), false); twitchIdentityProvider = (TwitchIdentityProvider) credentialManager.getIdentityProviderByName("twitch").orElse(null); diff --git a/src/main/java/de/presti/ree6/utils/data/ArrayUtil.java b/src/main/java/de/presti/ree6/utils/data/ArrayUtil.java index 9812dc865..6f6543095 100644 --- a/src/main/java/de/presti/ree6/utils/data/ArrayUtil.java +++ b/src/main/java/de/presti/ree6/utils/data/ArrayUtil.java @@ -27,10 +27,10 @@ private ArrayUtil() { } /** - * HashMap used to store conversations between the user and the Chat-GPT implementation. + * HashMap used to store conversations between the user and the ChatGPT implementation. * These are being stored guild specific so Ree6 will not continue a conversation in another guild. - * While at the same time we store them in memory to protect users privacy, since there is no actual - * reason for us to keep these longer then the current application uptime. + * While at the same time we store them in memory to protect users' privacy, since there is no actual + * reason for us to keep these longer than the current application uptime. */ public static final Map> chatGPTMessages = new HashMap<>(); @@ -40,7 +40,7 @@ private ArrayUtil() { public static final Map messageIDwithMessage = new HashMap<>(); /** - * HashMap used to store user Ids that are associated with a message, to show the content when the message gets deleted. + * HashMap used to store user Ids that are associated with a message to show the content when the message gets deleted. */ public static final Map messageIDwithUser = new HashMap<>(); @@ -55,12 +55,12 @@ private ArrayUtil() { public static final Map musicPanelList = new HashMap<>(); /** - * HashMap used to store a users Ids, to keep them from spamming commands. + * HashMap used to store a user's Ids, to keep them from spamming commands. */ public static final List commandCooldown = new ArrayList<>(); /** - * HashMap used to store a users Ids, to keep them from earning XP with every message. + * HashMap used to store a user's Ids, to keep them from earning XP with every message. */ public static final List timeout = new ArrayList<>(); From 8f361d3ead6d76a74270d32c7974923681ace6fe Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 8 Aug 2024 14:45:37 +0200 Subject: [PATCH 35/94] Use new repository for languages. --- src/main/java/de/presti/ree6/language/LanguageService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/de/presti/ree6/language/LanguageService.java b/src/main/java/de/presti/ree6/language/LanguageService.java index 40f98e92c..57809241d 100644 --- a/src/main/java/de/presti/ree6/language/LanguageService.java +++ b/src/main/java/de/presti/ree6/language/LanguageService.java @@ -79,7 +79,7 @@ public static void downloadLanguages() { } try { - RequestUtility.requestJson(RequestUtility.Request.builder().url("https://api.github.com/repos/Ree6-Applications/Ree6/contents/languages").build()).getAsJsonArray().forEach(jsonElement -> { + RequestUtility.requestJson(RequestUtility.Request.builder().url("https://api.github.com/repos/Ree6-Applications/Language/contents/languages").build()).getAsJsonArray().forEach(jsonElement -> { String language = jsonElement.getAsJsonObject().get("name").getAsString().replace(".yml", ""); String download = jsonElement.getAsJsonObject().get("download_url").getAsString(); From 46e646350c946240e6db58d0b825934b5bcfa926 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 14 Aug 2024 11:50:20 +0200 Subject: [PATCH 36/94] New Addon System. --- pom.xml | 14 +- .../java/de/presti/ree6/addons/Addon.java | 106 --------- .../de/presti/ree6/addons/AddonInterface.java | 17 -- .../de/presti/ree6/addons/AddonLoader.java | 207 ------------------ .../de/presti/ree6/addons/AddonManager.java | 123 ----------- .../java/de/presti/ree6/addons/ReePlugin.java | 17 ++ .../presti/ree6/addons/ReePluginContext.java | 15 ++ .../presti/ree6/addons/ReePluginFactory.java | 25 +++ .../presti/ree6/addons/ReePluginManager.java | 36 +++ .../addons/YamlPluginDescriptorFinder.java | 117 ++++++++++ .../ree6/addons/utils/AddonClassLoader.java | 45 ---- .../ree6/commands/impl/hidden/Addon.java | 40 ++-- .../ree6/commands/interfaces/ICommand.java | 3 +- src/main/java/de/presti/ree6/main/Main.java | 37 +++- 14 files changed, 271 insertions(+), 531 deletions(-) delete mode 100644 src/main/java/de/presti/ree6/addons/Addon.java delete mode 100644 src/main/java/de/presti/ree6/addons/AddonInterface.java delete mode 100644 src/main/java/de/presti/ree6/addons/AddonLoader.java delete mode 100644 src/main/java/de/presti/ree6/addons/AddonManager.java create mode 100644 src/main/java/de/presti/ree6/addons/ReePlugin.java create mode 100644 src/main/java/de/presti/ree6/addons/ReePluginContext.java create mode 100644 src/main/java/de/presti/ree6/addons/ReePluginFactory.java create mode 100644 src/main/java/de/presti/ree6/addons/ReePluginManager.java create mode 100644 src/main/java/de/presti/ree6/addons/YamlPluginDescriptorFinder.java delete mode 100644 src/main/java/de/presti/ree6/addons/utils/AddonClassLoader.java diff --git a/pom.xml b/pom.xml index 235311822..42534f675 100644 --- a/pom.xml +++ b/pom.xml @@ -260,7 +260,6 @@ 3.1.8 - org.apache.httpcomponents.client5 @@ -286,6 +285,19 @@ gson 2.11.0 + + + + org.pf4j + pf4j + 3.12.0 + + + org.slf4j + slf4j-simple + + + diff --git a/src/main/java/de/presti/ree6/addons/Addon.java b/src/main/java/de/presti/ree6/addons/Addon.java deleted file mode 100644 index 0777379d6..000000000 --- a/src/main/java/de/presti/ree6/addons/Addon.java +++ /dev/null @@ -1,106 +0,0 @@ -package de.presti.ree6.addons; - -import java.io.File; - -/** - * Created a new Local-Addon - * - * @param addonInterface AddonInterface. - * @param name Add-on Name. - * @param author Add-on Author. - * @param version Add-on Version. - * @param apiVersion Ree6 Version used for the Addon. - * @param classPath Path to the Main-Class in the JAR. - * @param file The actual JAR as File. - */ -public record Addon(AddonInterface addonInterface, String name, String author, String version, - String apiVersion, String classPath, File file) { - - /** - * Get the AddonInterface. - * - * @return AddonInterface. - */ - public AddonInterface getAddonInterface() { - return addonInterface; - } - - /** - * Get the Add-on Name. - * - * @return Add-on Name. - */ - public String getName() { - return name; - } - - /** - * Get the Author Name. - * - * @return Author Name. - */ - public String getAuthor() { - return author; - } - - /** - * Get the Add-on Version. - * - * @return Add-on Version. - */ - public String getVersion() { - return version; - } - - /** - * Get the Ree6 Version used for the Addon. - * - * @return used Ree6 Version. - */ - public String getApiVersion() { - return apiVersion; - } - - /** - * Get the Path to the Main class. - * - * @return Main class Path. - */ - public String getClassPath() { - return classPath; - } - - /** - * Get the actual File. - * - * @return File. - */ - public File getFile() { - return file; - } - - /** - * Get the ClassLoader of the Addon. - * @return ClassLoader. - */ - public ClassLoader getClassLoader() { - return addonInterface.getClass().getClassLoader(); - } - - /** - * Get everything in a single String. - * - * @return a String with every data. - */ - @Override - public String toString() { - return "Addon{" + - "name='" + getName() + '\'' + - ", author='" + getAuthor() + '\'' + - ", version='" + getVersion() + '\'' + - ", api='" + getApiVersion() + '\'' + - ", path='" + getClassPath() + '\'' + - ", file=" + getFile().getAbsolutePath() + - '}'; - } -} diff --git a/src/main/java/de/presti/ree6/addons/AddonInterface.java b/src/main/java/de/presti/ree6/addons/AddonInterface.java deleted file mode 100644 index 7de4ffb9b..000000000 --- a/src/main/java/de/presti/ree6/addons/AddonInterface.java +++ /dev/null @@ -1,17 +0,0 @@ -package de.presti.ree6.addons; - -/** - * The Interface used for the Addons. - */ -public interface AddonInterface { - - /** - * Called methode when the Addon gets started (What a surprise isn't it :)) - */ - void onEnable(); - - /** - * Called methode when the Addon get stopped. - */ - void onDisable(); -} diff --git a/src/main/java/de/presti/ree6/addons/AddonLoader.java b/src/main/java/de/presti/ree6/addons/AddonLoader.java deleted file mode 100644 index 6557e7794..000000000 --- a/src/main/java/de/presti/ree6/addons/AddonLoader.java +++ /dev/null @@ -1,207 +0,0 @@ -package de.presti.ree6.addons; - -import de.presti.ree6.addons.utils.AddonClassLoader; -import de.presti.ree6.main.Main; -import lombok.extern.slf4j.Slf4j; -import org.simpleyaml.configuration.file.FileConfiguration; -import org.simpleyaml.configuration.file.YamlConfiguration; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.charset.StandardCharsets; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -/** - * The actual Addon-Loader which Loads every single Addon from the Addon Folder. - */ -@Slf4j -@SuppressWarnings("ResultOfMethodCallIgnored") -public class AddonLoader { - - /** - * Constructor should not be called, since it is a utility class that doesn't need an instance. - * - * @throws IllegalStateException it is a utility class. - */ - private AddonLoader() { - throw new IllegalStateException("Utility class"); - } - - /** - * Create the Folder if not existing. - */ - private static void createFolders() { - if (!new File("addons/").exists()) { - new File("addons/").mkdir(); - } - - if (!new File("addons/tmp/").exists()) { - new File("addons/tmp/").mkdir(); - } - } - - /** - * Load every Addon. - */ - public static void loadAllAddons() { - - // Create Folder if not existing. - createFolders(); - - // Get every single File from the Folder. - File[] files = new File("addons/").listFiles(); - - // Check if there are any Files. - assert files != null; - for (File file : files) { - - // Check if it's a jar File. - if (file.getName().endsWith("jar")) { - try { - // Try creating a Local-Addon and adding it into the loaded Addon List. - Addon addon = loadAddon(file.getName()); - - if (addon == null) { - log.error("Couldn't pre-load the addon {}", file.getName()); - } - - Main.getInstance().getAddonManager().loadAddon(addon); - } catch (Exception ex) { - // If the Methode loadAddon fails notify. - log.error("[AddonManager] Couldn't load the Addon {}\nException: {}", file.getName(), ex.getMessage()); - } - } - } - - } - - /** - * Actually load a Addon. - * - * @param fileName Name of the File. - * @return a Local-Addon. - * @throws IOException If it is an invalid Addon. - */ - public static Addon loadAddon(String fileName) throws IOException { - - // Initialize local Variables to save Information about the Addon. - String name = null, author = null, version = null, apiVersion = null, classPath = null; - - - // Create a ZipInputStream to get every single class inside the JAR. I'm pretty sure there is a faster and more efficient way, but I didn't have the time to find it. - try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream("addons/" + fileName))) { - ZipEntry entry; - - // While there a still Classes inside the JAR, it should check them. - while ((entry = zipInputStream.getNextEntry()) != null) { - try { - // Get the current name of the class. - String entryName = entry.getName(); - - // Check if it is a Directory if so don't do anything and skip. - // If it is the addon.yml then get the Data from it. - if (!entry.isDirectory() && entryName.equalsIgnoreCase("addon.yml")) { - String content; - // Create a FileOutputStream of the temporal File and write every bite from the File inside the JAR. - try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { - - for (int c = zipInputStream.read(); c != -1; c = zipInputStream.read()) { - os.write(c); - } - - content = os.toString(StandardCharsets.UTF_8); - } - - if (content == null) { - log.info("Error while trying to pre-load the Addon {}\nException: {}", fileName, "Content is null"); - continue; - } - - // Load it as a YAML-Config and fill the Variables. - FileConfiguration conf = YamlConfiguration.loadConfigurationFromString(content); - - name = conf.getString("name"); - author = conf.getString("author"); - version = conf.getString("version"); - apiVersion = conf.getString("api-version"); - classPath = conf.getString("main"); - break; - } - } catch (Exception e) { - log.error("Error while trying to pre-load the Addon {}\nException: {}", fileName, e.getMessage()); - zipInputStream.closeEntry(); - } finally { - zipInputStream.closeEntry(); - } - } - } - - // Check if there is any data core data if not throw this error. - if (name == null && classPath == null) { - log.error("Error while trying to pre-load the Addon {}, no addon.yml given.", fileName); - } else { - File addonFile = new File("addons/" + fileName); - AddonInterface addonInterface = null; - // Try loading the Class with a URL Class Loader. - try (AddonClassLoader urlClassLoader = new AddonClassLoader(new URL[] { addonFile.toURI().toURL() }, AddonLoader.class.getClassLoader())) { - - // Get the Addon Class. - Class addonClass = getClass(urlClassLoader, classPath); - - // If valid, call the onEnable methode. - if (addonClass != null) { - log.info("[AddonManager] Loaded {} ({}) by {}", name, version, author); - addonInterface = (AddonInterface) addonClass.getDeclaredConstructor().newInstance(); - } else { - // If not inform about an invalid Addon. - log.error("[AddonManager] Couldn't load the Addon {}({}) by {}", name, version, author); - log.error("[AddonManager] The given Main class doesn't not implement our AddonInterface!"); - } - } catch (Exception e) { - log.error("[AddonManager] Couldn't start the Addon {}({}) by {}", name, version, author); - log.error("[AddonManager] Exception: {}", e.getMessage()); - } - - if (addonInterface == null) { - log.error("Error while trying to pre-load the Addon {}\nException: {}", fileName, "AddonInterface is null"); - return null; - } - - return new Addon(addonInterface, name, author, version, apiVersion, classPath, new File("addons/" + fileName)); - } - - return null; - } - - /** - * Get the Addon Class from the Class-Loader and its path. - * - * @param classLoader the Class Loader of the File. - * @param classPath the Path to the Main class. - * @return the Main class of the Addon. - * @throws ClassNotFoundException if there is no file with the given Path. - */ - private static Class getClass(AddonClassLoader classLoader, String classPath) throws ClassNotFoundException { - // Class from the loader. - Class urlCl = classLoader.loadClass(classPath); - - // Get the Interfaces. - Class[] ifs = urlCl.getInterfaces(); - - // Check if any of the Interfaces is the AddonInterface. - for (Class anIf : ifs) { - - // If it has the AddonInterface mark it as valid. - if (anIf.getName().equalsIgnoreCase("de.presti.ree6.addons.AddonInterface")) { - return urlCl; - } - } - - return null; - } -} diff --git a/src/main/java/de/presti/ree6/addons/AddonManager.java b/src/main/java/de/presti/ree6/addons/AddonManager.java deleted file mode 100644 index ad53246b1..000000000 --- a/src/main/java/de/presti/ree6/addons/AddonManager.java +++ /dev/null @@ -1,123 +0,0 @@ -package de.presti.ree6.addons; - -import de.presti.ree6.bot.BotWorker; -import de.presti.ree6.utils.others.VersionUtil; -import lombok.extern.slf4j.Slf4j; - -import java.util.ArrayList; - -/** - * The AddonManager has been created to save every Addon in a List to keep track of them - * and to unload them if wanted/needed. - */ -@Slf4j -public class AddonManager { - /** - * The actual List with the Addons. - */ - public final ArrayList addons = new ArrayList<>(); - - /** - * Reload the AddonManager by stopping every Addon and reading them. - */ - public void reload() { - stopAddons(); - - addons.clear(); - - AddonLoader.loadAllAddons(); - - startAddons(); - } - - /** - * Try starting an Addon by calling the Class with a URL-Class Loader. - * - * @param addon the Local-Addon. - */ - public void startAddon(Addon addon) { - log.info("[AddonManager] Loading {} ({}) by {}", addon.getName(), addon.getVersion(), addon.getAuthor()); - - // Check if it's made for the current Ree6 Version if not inform. - if (!addon.getApiVersion().equalsIgnoreCase(BotWorker.getBuild())) { - - VersionUtil.VersionType difference = VersionUtil.compareVersion(BotWorker.getBuild(), addon.getApiVersion()); - - boolean isAddonForOlder = true; - - if (difference == VersionUtil.VersionType.NONE) { - VersionUtil.VersionType reverseDifference = VersionUtil.compareVersion(addon.getApiVersion(), BotWorker.getBuild()); - if (reverseDifference != VersionUtil.VersionType.NONE) { - isAddonForOlder = false; - difference = reverseDifference; - } - } - - if (isAddonForOlder) { - log.warn("[AddonManager] The Addon {}({}) by {} is made for an older version of Ree6. Ree6 is on Version {} and the Addon is made for Version {}.", addon.getName(), addon.getVersion(), addon.getAuthor(), BotWorker.getBuild(), addon.getApiVersion()); - } else { - log.warn("[AddonManager] The Addon {}({}) by {} is made for a newer version of Ree6. Ree6 is on Version {} and the Addon is made for Version {}.", addon.getName(), addon.getVersion(), addon.getAuthor().toLowerCase(), BotWorker.getBuild(), addon.getApiVersion()); - } - - if (difference == VersionUtil.VersionType.MAYOR) { - log.warn("[AddonManager] Version difference is at least one mayor version, be advised this will most likely cause Issues or not work at all!"); - } else if (difference == VersionUtil.VersionType.MINOR || difference == VersionUtil.VersionType.PATCH) { - log.warn("[AddonManager] Version difference is at least one " + difference.name().toLowerCase() + " version, be advised this might cause Issues!"); - } - } - - try { - addon.getAddonInterface().onEnable(); - } catch (Exception ex) { - // Throw an error if the Addon is invalid or corrupted. - log.error("[AddonManager] Couldn't start the Addon {}({}) by {}", addon.getName(), addon.getVersion(), addon.getAuthor()); - log.error("[AddonManager] Information: {}, {}, {}", addon.getClassPath(), addon.getVersion(), addon.getApiVersion()); - log.error("[AddonManager] Exception: ", ex); - } - } - - /** - * Start every Addon from the AddonList. - */ - public void startAddons() { - for (Addon addon : addons) { - startAddon(addon); - } - } - - /** - * Try stopping the Addon by calling the Main-Class methode onDisable. - * - * @param addon The Local-Addon. - */ - public void stopAddon(Addon addon) { - log.info("[AddonManager] Unloading {} ({}) by {}", addon.getName(), addon.getVersion(), addon.getAuthor()); - - try { - addon.getAddonInterface().onDisable(); - } catch (Exception ex) { - // Throw an error if the Addon is invalid or corrupted. - log.error("[AddonManager] Couldn't stop the Addon {}({}) by {}", addon.getName(), addon.getVersion(), addon.getAuthor()); - log.error("[AddonManager] Information: {}, {}, {}", addon.getClassPath(), addon.getVersion(), addon.getApiVersion()); - log.error("[AddonManager] Exception: ", ex); - } - } - - /** - * Stop every Addon. - */ - public void stopAddons() { - for (Addon addon : addons) { - stopAddon(addon); - } - } - - /** - * "Load" an Addon. - * - * @param addon the Local-Addon. - */ - public void loadAddon(Addon addon) { - addons.add(addon); - } -} diff --git a/src/main/java/de/presti/ree6/addons/ReePlugin.java b/src/main/java/de/presti/ree6/addons/ReePlugin.java new file mode 100644 index 000000000..78d152dec --- /dev/null +++ b/src/main/java/de/presti/ree6/addons/ReePlugin.java @@ -0,0 +1,17 @@ +package de.presti.ree6.addons; + +import org.apache.commons.digester.plugins.PluginContext; +import org.pf4j.Plugin; + +/** + * The Interface used for the Addons. + */ +public abstract class ReePlugin extends Plugin { + + protected final PluginContext context; + + protected ReePlugin(PluginContext context) { + super(); + this.context = context; + } +} diff --git a/src/main/java/de/presti/ree6/addons/ReePluginContext.java b/src/main/java/de/presti/ree6/addons/ReePluginContext.java new file mode 100644 index 000000000..c1e0d72a6 --- /dev/null +++ b/src/main/java/de/presti/ree6/addons/ReePluginContext.java @@ -0,0 +1,15 @@ +package de.presti.ree6.addons; + +import lombok.Getter; +import org.pf4j.RuntimeMode; + +@Getter +public class ReePluginContext { + + private final RuntimeMode runtimeMode; + + public ReePluginContext(RuntimeMode runtimeMode) { + this.runtimeMode = runtimeMode; + } + +} diff --git a/src/main/java/de/presti/ree6/addons/ReePluginFactory.java b/src/main/java/de/presti/ree6/addons/ReePluginFactory.java new file mode 100644 index 000000000..c41e31436 --- /dev/null +++ b/src/main/java/de/presti/ree6/addons/ReePluginFactory.java @@ -0,0 +1,25 @@ +package de.presti.ree6.addons; + +import lombok.extern.slf4j.Slf4j; +import org.pf4j.DefaultPluginFactory; +import org.pf4j.Plugin; +import org.pf4j.PluginWrapper; + +import java.lang.reflect.Constructor; + +@Slf4j +public class ReePluginFactory extends DefaultPluginFactory { + + @Override + protected Plugin createInstance(Class pluginClass, PluginWrapper pluginWrapper) { + ReePluginContext context = new ReePluginContext(pluginWrapper.getRuntimeMode()); + try { + Constructor constructor = pluginClass.getConstructor(ReePluginContext.class); + return (Plugin) constructor.newInstance(context); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + + return null; + } +} diff --git a/src/main/java/de/presti/ree6/addons/ReePluginManager.java b/src/main/java/de/presti/ree6/addons/ReePluginManager.java new file mode 100644 index 000000000..06bd13166 --- /dev/null +++ b/src/main/java/de/presti/ree6/addons/ReePluginManager.java @@ -0,0 +1,36 @@ +package de.presti.ree6.addons; + +import lombok.extern.slf4j.Slf4j; +import org.pf4j.DefaultPluginManager; +import org.pf4j.PluginDescriptorFinder; +import org.pf4j.PluginFactory; + +@Slf4j +public class ReePluginManager extends DefaultPluginManager { + + + public ReePluginManager() { + super(); + addPluginStateListener(x -> { + switch (x.getPluginState()) { + case STARTED -> log.info("Plugin '{}' started", x.getPlugin().getPluginId()); + case FAILED -> log.error("Plugin '{}' failed", x.getPlugin().getPluginId()); + case STOPPED -> log.info("Plugin '{}' stopped", x.getPlugin().getPluginId()); + case DISABLED -> log.info("Plugin '{}' disabled", x.getPlugin().getPluginId()); + case UNLOADED -> log.info("Plugin '{}' unloading", x.getPlugin().getPluginId()); + case CREATED -> log.info("Plugin '{}' created", x.getPlugin().getPluginId()); + case RESOLVED -> log.info("Plugin '{}' resolved", x.getPlugin().getPluginId()); + } + }); + } + + @Override + protected PluginDescriptorFinder createPluginDescriptorFinder() { + return new YamlPluginDescriptorFinder(); + } + + @Override + protected PluginFactory createPluginFactory() { + return new ReePluginFactory(); + } +} diff --git a/src/main/java/de/presti/ree6/addons/YamlPluginDescriptorFinder.java b/src/main/java/de/presti/ree6/addons/YamlPluginDescriptorFinder.java new file mode 100644 index 000000000..dbada1f1b --- /dev/null +++ b/src/main/java/de/presti/ree6/addons/YamlPluginDescriptorFinder.java @@ -0,0 +1,117 @@ +package de.presti.ree6.addons; + +import lombok.extern.slf4j.Slf4j; +import org.pf4j.*; +import org.pf4j.util.FileUtils; +import org.pf4j.util.StringUtils; +import org.simpleyaml.configuration.file.YamlConfiguration; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +@Slf4j +public class YamlPluginDescriptorFinder implements PluginDescriptorFinder { + + public static final String DEFAULT_PROPERTIES_FILE_NAME = "plugin.yml"; + + public static final String PLUGIN_ID = "id"; + public static final String PLUGIN_DESCRIPTION = "description"; + public static final String PLUGIN_CLASS = "class"; + public static final String PLUGIN_VERSION = "version"; + public static final String PLUGIN_PROVIDER = "provider"; + public static final String PLUGIN_DEPENDENCIES = "dependencies"; + public static final String PLUGIN_REQUIRES = "requires"; + public static final String PLUGIN_LICENSE = "license"; + + protected String propertiesFileName; + + public YamlPluginDescriptorFinder() { + this(DEFAULT_PROPERTIES_FILE_NAME); + } + + public YamlPluginDescriptorFinder(String propertiesFileName) { + this.propertiesFileName = propertiesFileName; + } + + @Override + public boolean isApplicable(Path pluginPath) { + return Files.exists(pluginPath) && (Files.isDirectory(pluginPath) || FileUtils.isZipOrJarFile(pluginPath)); + } + + @Override + public PluginDescriptor find(Path pluginPath) { + YamlConfiguration properties = readYaml(pluginPath); + + return createPluginDescriptor(properties); + } + + protected YamlConfiguration readYaml(Path pluginPath) { + Path yamlPath = getYamlPath(pluginPath, propertiesFileName); + if (yamlPath == null) { + throw new PluginRuntimeException("Cannot find the properties path"); + } + + YamlConfiguration yamlConfiguration = null; + try { + log.debug("Lookup plugin descriptor in '{}'", yamlPath); + if (Files.notExists(yamlPath)) { + throw new PluginRuntimeException("Cannot find '{}' path", yamlPath); + } + + try (InputStream input = Files.newInputStream(yamlPath)) { + yamlConfiguration = YamlConfiguration.loadConfiguration(input); + } catch (IOException e) { + throw new PluginRuntimeException(e); + } + } finally { + FileUtils.closePath(yamlPath); + } + + return yamlConfiguration; + } + + protected Path getYamlPath(Path pluginPath, String propertiesFileName) { + if (Files.isDirectory(pluginPath)) { + return pluginPath.resolve(Paths.get(propertiesFileName)); + } + + // it's a zip or jar file + try { + return FileUtils.getPath(pluginPath, propertiesFileName); + } catch (IOException e) { + throw new PluginRuntimeException(e); + } + } + + protected PluginDescriptor createPluginDescriptor(YamlConfiguration yamlConfiguration) { + String id = yamlConfiguration.getString(PLUGIN_ID); + + String description = yamlConfiguration.getString(PLUGIN_DESCRIPTION); + if (StringUtils.isNullOrEmpty(description)) { + description = ""; + } + + String clazz = yamlConfiguration.getString(PLUGIN_CLASS); + String version = yamlConfiguration.getString(PLUGIN_VERSION); + String provider = yamlConfiguration.getString(PLUGIN_PROVIDER); + List dependencies = yamlConfiguration.getStringList(PLUGIN_DEPENDENCIES); + String requires = yamlConfiguration.getString(PLUGIN_REQUIRES); + String license = yamlConfiguration.getString(PLUGIN_LICENSE); + + DefaultPluginDescriptor pluginDescriptor = createPluginDescriptorInstance(id, description, clazz, version, requires, provider, license); + + for (String dependency : dependencies) { + pluginDescriptor.addDependency(new PluginDependency(dependency)); + } + + return pluginDescriptor; + } + + protected DefaultPluginDescriptor createPluginDescriptorInstance(String id, String description, String clazz, String version, String requires, String provider, String license) { + return new DefaultPluginDescriptor(id, description, clazz, version, requires, provider, license); + } +} diff --git a/src/main/java/de/presti/ree6/addons/utils/AddonClassLoader.java b/src/main/java/de/presti/ree6/addons/utils/AddonClassLoader.java deleted file mode 100644 index cd9284af0..000000000 --- a/src/main/java/de/presti/ree6/addons/utils/AddonClassLoader.java +++ /dev/null @@ -1,45 +0,0 @@ -package de.presti.ree6.addons.utils; - -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Arrays; -import java.util.List; - -public class AddonClassLoader extends URLClassLoader { - - public static final List SHARED_PACKAGES = Arrays.asList( - "de.ree6.sql", - "de.presti.ree6.commands", - "de.presti.ree6.bot.util", - "de.presti.ree6.utils", - "de.presti.ree6.module", - "de.presti.ree6.main", - "de.presti.ree6.language", - "de.presti.ree6.game", - "de.presti.ree6.audio" - ); - - public AddonClassLoader(URL[] urls, ClassLoader parent) { - super(urls, parent); - } - - @Override - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { - // has the class loaded already? - Class loadedClass = findLoadedClass(name); - if (loadedClass == null) { - final boolean isSharedClass = SHARED_PACKAGES.stream().anyMatch(name::startsWith); - if (isSharedClass) { - loadedClass = getParent().loadClass(name); - } else { - loadedClass = super.loadClass(name, resolve); - } - } - - if (resolve) { // marked to resolve - resolveClass(loadedClass); - } - return loadedClass; - } -} diff --git a/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java b/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java index caf997154..26e977d4d 100644 --- a/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java +++ b/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java @@ -1,6 +1,5 @@ package de.presti.ree6.commands.impl.hidden; -import de.presti.ree6.addons.AddonLoader; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; @@ -12,6 +11,10 @@ import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; import net.dv8tion.jda.internal.interactions.CommandDataImpl; +import org.pf4j.PluginState; +import org.pf4j.PluginWrapper; + +import java.nio.file.Path; /** * A command to either reload all Addons or list all of them. @@ -41,15 +44,14 @@ public void onPerform(CommandEvent commandEvent) { switch (subcommand) { case "reload" -> { commandEvent.reply(commandEvent.getResource("message.addon.reloadAll")); - Main.getInstance().getAddonManager().reload(); + //Main.getInstance().getPluginManager().reload(); commandEvent.reply(commandEvent.getResource("message.addon.reloadedAll")); } case "list" -> { StringBuilder stringBuilder = new StringBuilder("```"); - for (de.presti.ree6.addons.Addon addon : Main.getInstance().getAddonManager().addons) { - stringBuilder.append(addon.getName()).append("v").append(addon.getVersion()) - .append(" ").append("for").append(" ").append("by").append(" ").append(addon.getAuthor()).append("\n"); + for (PluginWrapper addon : Main.getInstance().getPluginManager().getPlugins()) { + stringBuilder.append(addon.getPluginId()).append("v").append(addon.getDescriptor().getVersion()).append(" ").append("by").append(" ").append(addon.getDescriptor().getProvider()).append("\n"); } stringBuilder.append("```"); commandEvent.reply(commandEvent.getResource("message.addon.list") + " " + (stringBuilder.length() == 6 ? "None" : stringBuilder)); @@ -59,13 +61,10 @@ public void onPerform(CommandEvent commandEvent) { String addonName = commandEvent.getOption("addon").getAsString(); try { - de.presti.ree6.addons.Addon addon = AddonLoader.loadAddon(addonName); - if (addon == null) { - commandEvent.reply("Couldn't find a addon called " + addonName, 5); - return; - } - Main.getInstance().getAddonManager().loadAddon(addon); - Main.getInstance().getAddonManager().startAddon(addon); + String id = Main.getInstance().getPluginManager().loadPlugin(Path.of("plugins", addonName)); + PluginState state = Main.getInstance().getPluginManager().startPlugin(id); + + commandEvent.reply("Loading attempt for addon with the name " + addonName + " and id " + id + " resulted in: " + state); } catch (Exception exception) { commandEvent.reply("Couldn't load the addon called " + addonName, 5); Sentry.captureException(exception); @@ -73,13 +72,16 @@ public void onPerform(CommandEvent commandEvent) { } case "stop" -> { - de.presti.ree6.addons.Addon addon = Main.getInstance().getAddonManager().addons.stream() - .filter(a -> a.getName().equalsIgnoreCase(commandEvent.getOption("addon").getAsString())).findFirst().orElse(null); - - if (addon != null) { - Main.getInstance().getAddonManager().stopAddon(addon); - Main.getInstance().getAddonManager().addons.remove(addon); - commandEvent.reply("Stopped addon with the name " + addon.getName() + "!"); + String addonName = commandEvent.getOption("addon").getAsString(); + try { + if (Main.getInstance().getPluginManager().unloadPlugin(addonName)) { + commandEvent.reply("Unloaded addon with the name " + addonName + "!"); + } else { + commandEvent.reply("Couldn't unload the addon called " + addonName, 5); + } + } catch (Exception exception) { + commandEvent.reply("Couldn't unload the addon called " + addonName, 5); + Sentry.captureException(exception); } } diff --git a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java index 266d01acd..ce93a4d38 100644 --- a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java +++ b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java @@ -11,6 +11,7 @@ import io.sentry.Sentry; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; +import org.pf4j.ExtensionPoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; @@ -22,7 +23,7 @@ /** * An Interface class, used to make it easier for the creation of Commands. */ -public interface ICommand { +public interface ICommand extends ExtensionPoint { /** * The Logger for this class. diff --git a/src/main/java/de/presti/ree6/main/Main.java b/src/main/java/de/presti/ree6/main/Main.java index 5f57f1a26..d27e4ae9a 100644 --- a/src/main/java/de/presti/ree6/main/Main.java +++ b/src/main/java/de/presti/ree6/main/Main.java @@ -6,8 +6,7 @@ import com.github.twitch4j.pubsub.PubSubSubscription; import com.google.gson.JsonObject; import de.presti.ree6.actions.streamtools.container.StreamActionContainerCreator; -import de.presti.ree6.addons.AddonLoader; -import de.presti.ree6.addons.AddonManager; +import de.presti.ree6.addons.ReePluginManager; import de.presti.ree6.audio.music.MusicWorker; import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; @@ -15,6 +14,8 @@ import de.presti.ree6.bot.version.BotState; import de.presti.ree6.bot.version.BotVersion; import de.presti.ree6.commands.CommandManager; +import de.presti.ree6.commands.exceptions.CommandInitializerException; +import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.events.*; import de.presti.ree6.game.core.GameManager; import de.presti.ree6.game.impl.musicquiz.util.MusicQuizUtil; @@ -52,6 +53,7 @@ import net.dv8tion.jda.api.entities.channel.unions.GuildMessageChannelUnion; import net.dv8tion.jda.api.entities.emoji.Emoji; import net.dv8tion.jda.api.utils.messages.MessageEditBuilder; +import org.pf4j.PluginManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -98,9 +100,9 @@ public class Main { CommandManager commandManager; /** - * Addon Manager, used to manage the Addons. + * Instance of the PluginManager, used to manage the Plugins. */ - AddonManager addonManager; + PluginManager pluginManager; /** * Instance of the GiveawayManager, used to manage the Giveaways. @@ -361,16 +363,27 @@ public static void main(String[] args) { // Set the start Time for stats. BotWorker.setStartTime(System.currentTimeMillis()); - log.info("Loading AddonManager"); - // Initialize the Addon-Manager. - getInstance().setAddonManager(new AddonManager()); + log.info("Loading PluginManager"); + // Initialize the Plugin-Manager. + getInstance().setPluginManager(new ReePluginManager()); if (BotConfig.isModuleActive("addons")) { - // Initialize the Addon-Loader. - AddonLoader.loadAllAddons(); + log.info("Loading all Plugins."); + getInstance().getPluginManager().loadPlugins(); - // Start all Addons. - getInstance().getAddonManager().startAddons(); + log.info("Starting all Plugins."); + getInstance().getPluginManager().startPlugins(); + + log.info("Registering all Commands of plugins."); + List commands = getInstance().getPluginManager().getExtensions(ICommand.class); + log.info("Found {} commands in all plugins.", commands.size()); + commands.forEach(command -> { + try { + getInstance().getCommandManager().addCommand(command); + } catch (CommandInitializerException e) { + log.warn("Failed to initialize command: {}", command.getClass().getSimpleName(), e); + } + }); } // Create checker Thread. @@ -436,7 +449,7 @@ private void shutdown() { if (BotConfig.isModuleActive("addons")) { // Shutdown every Addon. log.info("[Main] Disabling every Addon!"); - getAddonManager().stopAddons(); + getPluginManager().unloadPlugins(); log.info("[Main] Every Addon has been disabled!"); } From 2aee4f8dbcf10977b08ebf06726a938ff290ea66 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 14 Aug 2024 12:08:48 +0200 Subject: [PATCH 37/94] New Addon System fix. --- src/main/java/de/presti/ree6/addons/ReePlugin.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/de/presti/ree6/addons/ReePlugin.java b/src/main/java/de/presti/ree6/addons/ReePlugin.java index 78d152dec..7fb8766fa 100644 --- a/src/main/java/de/presti/ree6/addons/ReePlugin.java +++ b/src/main/java/de/presti/ree6/addons/ReePlugin.java @@ -1,6 +1,5 @@ package de.presti.ree6.addons; -import org.apache.commons.digester.plugins.PluginContext; import org.pf4j.Plugin; /** @@ -8,9 +7,9 @@ */ public abstract class ReePlugin extends Plugin { - protected final PluginContext context; + protected final ReePluginContext context; - protected ReePlugin(PluginContext context) { + protected ReePlugin(ReePluginContext context) { super(); this.context = context; } From 30f806bb47d975baf9fe1d61d4c383daeebbc48f Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 14 Aug 2024 13:02:46 +0200 Subject: [PATCH 38/94] Fix missing git properties and improve a few checks. --- src/main/java/de/presti/ree6/commands/CommandEvent.java | 9 +++++++++ .../presti/ree6/commands/impl/hidden/Announcement.java | 2 +- .../java/de/presti/ree6/commands/impl/hidden/Debug.java | 7 +++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/main/java/de/presti/ree6/commands/CommandEvent.java b/src/main/java/de/presti/ree6/commands/CommandEvent.java index 5d2ac90b4..f60c49851 100644 --- a/src/main/java/de/presti/ree6/commands/CommandEvent.java +++ b/src/main/java/de/presti/ree6/commands/CommandEvent.java @@ -1,5 +1,6 @@ package de.presti.ree6.commands; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import lombok.Getter; @@ -218,6 +219,14 @@ public String getResource(String key, Object... parameters) { return member; } + /** + * Check if the Member is the Bot Owner. + * @return true, if the Member is the Bot Owner. | false, if not. + */ + public boolean isBotOwner() { + return BotConfig.getBotOwner().equals(member.getId()); + } + /** * Get the {@link Guild} Entity associated with the Event. * diff --git a/src/main/java/de/presti/ree6/commands/impl/hidden/Announcement.java b/src/main/java/de/presti/ree6/commands/impl/hidden/Announcement.java index dca874b72..00e9f52a1 100644 --- a/src/main/java/de/presti/ree6/commands/impl/hidden/Announcement.java +++ b/src/main/java/de/presti/ree6/commands/impl/hidden/Announcement.java @@ -26,7 +26,7 @@ public class Announcement implements ICommand { @Override public void onPerform(CommandEvent commandEvent) { - if (!commandEvent.getMember().getUser().getId().equalsIgnoreCase(BotConfig.getBotOwner())) { + if (!commandEvent.isBotOwner()) { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", "BE DEVELOPER"), 5); return; } diff --git a/src/main/java/de/presti/ree6/commands/impl/hidden/Debug.java b/src/main/java/de/presti/ree6/commands/impl/hidden/Debug.java index 33e54b7ff..92c34ca97 100644 --- a/src/main/java/de/presti/ree6/commands/impl/hidden/Debug.java +++ b/src/main/java/de/presti/ree6/commands/impl/hidden/Debug.java @@ -5,6 +5,7 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; +import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -13,6 +14,11 @@ public class Debug implements ICommand { @Override public void onPerform(CommandEvent commandEvent) { + if (!commandEvent.isBotOwner()) { + commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", "BE DEVELOPER"), 5); + return; + } + StringBuilder debugInfo = new StringBuilder("```") .append("Build:").append(" ").append(BotWorker.getBuild()).append("\n") .append("Version:").append(" ").append(BotWorker.getVersion()).append("\n") @@ -27,6 +33,7 @@ public void onPerform(CommandEvent commandEvent) { .append("Java:").append(" ").append(System.getProperty("java.version")).append("\n") .append("OS:").append(" ").append(System.getProperty("os.name")).append("\n") .append("OS-Version:").append(" ").append(System.getProperty("os.version")).append("\n") + .append("Addons: ").append(" ").append(Main.getInstance().getPluginManager().getPlugins().size()).append("\n") .append("```"); commandEvent.reply(debugInfo.toString(), 5); From b2df1a99bdf060705e98d4a03210ad3ed2108f53 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 14 Aug 2024 13:03:08 +0200 Subject: [PATCH 39/94] Fix missing git properties and improve a few checks. --- pom.xml | 3 +++ .../java/de/presti/ree6/commands/impl/hidden/Addon.java | 2 +- src/main/java/de/presti/ree6/commands/impl/hidden/Test.java | 2 +- src/main/java/de/presti/ree6/commands/impl/mod/Setup.java | 6 ++---- src/main/java/de/presti/ree6/utils/others/GuildUtil.java | 2 +- 5 files changed, 8 insertions(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index 42534f675..f4573238a 100644 --- a/pom.xml +++ b/pom.xml @@ -363,6 +363,9 @@ ^git.build.(time|version)$ ^git.commit.id.(abbrev|full)$ + ^git.dirty$ + ^git.branch$ + ^git.remote.origin.url$ full ddMMyyyy diff --git a/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java b/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java index 26e977d4d..e9a3912f6 100644 --- a/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java +++ b/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java @@ -29,7 +29,7 @@ public class Addon implements ICommand { */ @Override public void onPerform(CommandEvent commandEvent) { - if (!commandEvent.getMember().getUser().getId().equalsIgnoreCase(BotConfig.getBotOwner())) { + if (!commandEvent.isBotOwner()) { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", "BE DEVELOPER"), 5); return; } diff --git a/src/main/java/de/presti/ree6/commands/impl/hidden/Test.java b/src/main/java/de/presti/ree6/commands/impl/hidden/Test.java index f00405560..4ef9bbf8c 100644 --- a/src/main/java/de/presti/ree6/commands/impl/hidden/Test.java +++ b/src/main/java/de/presti/ree6/commands/impl/hidden/Test.java @@ -19,7 +19,7 @@ public class Test implements ICommand { */ @Override public void onPerform(CommandEvent commandEvent) { - if (!commandEvent.getMember().getUser().getId().equalsIgnoreCase(BotConfig.getBotOwner())) { + if (!commandEvent.isBotOwner()) { commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", "BE DEVELOPER"), 5); return; } diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java index 09056be2f..6e7222df3 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java @@ -7,7 +7,6 @@ import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Setting; import de.presti.ree6.sql.entities.TemporalVoicechannel; @@ -41,7 +40,6 @@ import java.util.Base64; import java.util.List; import java.util.Map; -import java.util.concurrent.CompletableFuture; /** * A command to set Ree6 up. @@ -281,7 +279,7 @@ public void onPerform(CommandEvent commandEvent) { } public static EmbedBuilder createAutoRoleSetupMessage(Guild guild, InteractionHook interactionHook) { - boolean hasRoles = !GuildUtil.getManagableRoles(guild).isEmpty(); + boolean hasRoles = !GuildUtil.getManageableRoles(guild).isEmpty(); return new EmbedBuilder() .setTitle(LanguageService.getByGuildOrInteractionHook(guild, interactionHook, "label.setup").block()) @@ -293,7 +291,7 @@ public static EmbedBuilder createAutoRoleSetupMessage(Guild guild, InteractionHo public static Mono createAutoRoleSetupSelectMenu(Guild guild, InteractionHook interactionHook) { List optionList = new ArrayList<>(); - for (Role role : GuildUtil.getManagableRoles(guild)) { + for (Role role : GuildUtil.getManageableRoles(guild)) { optionList.add(SelectOption.of(role.getName(), role.getId())); } diff --git a/src/main/java/de/presti/ree6/utils/others/GuildUtil.java b/src/main/java/de/presti/ree6/utils/others/GuildUtil.java index 16cbe9e79..56fab2013 100644 --- a/src/main/java/de/presti/ree6/utils/others/GuildUtil.java +++ b/src/main/java/de/presti/ree6/utils/others/GuildUtil.java @@ -235,7 +235,7 @@ private static void addRole(Guild guild, Member member, Role role) { * @param guild the Guild to get the roles from. * @return a List of Roles that Ree6 can manage. */ - public static List getManagableRoles(Guild guild) { + public static List getManageableRoles(Guild guild) { return guild.getRoles().stream().filter(role -> guild.getSelfMember().canInteract(role) && !role.isManaged() && !role.isPublicRole()).toList(); } From 588c7dcd600d7ecb4895dd7e8233ae8abb8d2dfe Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 29 Aug 2024 13:15:04 +0200 Subject: [PATCH 40/94] Added support for custom Rank Images. --- pom.xml | 2 +- .../ree6/commands/impl/level/Level.java | 23 +++++++++---------- .../ree6/utils/data/ImageCreationUtility.java | 11 ++++++--- 3 files changed, 20 insertions(+), 16 deletions(-) diff --git a/pom.xml b/pom.xml index c9ef19d98..3698d1df2 100644 --- a/pom.xml +++ b/pom.xml @@ -182,7 +182,7 @@ de.ree6 Ree6-SQL - 79819ffcbc + 0586650f02 diff --git a/src/main/java/de/presti/ree6/commands/impl/level/Level.java b/src/main/java/de/presti/ree6/commands/impl/level/Level.java index f353cbf0b..2ec08ff93 100644 --- a/src/main/java/de/presti/ree6/commands/impl/level/Level.java +++ b/src/main/java/de/presti/ree6/commands/impl/level/Level.java @@ -4,9 +4,7 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.sql.entities.level.UserLevel; import de.presti.ree6.utils.data.ImageCreationUtility; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.interactions.commands.OptionMapping; @@ -82,16 +80,17 @@ public String[] getAlias() { public void sendLevel(Member member, CommandEvent commandEvent, String type) { (type.equalsIgnoreCase("voice") ? SQLSession.getSqlConnector().getSqlWorker().getVoiceLevelData(commandEvent.getGuild().getIdLong(), member.getIdLong()) : - SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), member.getIdLong())).subscribe(userLevel -> { - try { - MessageCreateBuilder createBuilder = new MessageCreateBuilder(); - createBuilder.addFiles(FileUpload.fromData(ImageCreationUtility.createRankImage(userLevel), "rank.png")); + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), member.getIdLong())).subscribe(userLevel -> + SQLSession.getSqlConnector().getSqlWorker().getUserRankCard(member.getIdLong()).subscribe(rankCard -> { + try { + MessageCreateBuilder createBuilder = new MessageCreateBuilder(); + createBuilder.addFiles(FileUpload.fromData(ImageCreationUtility.createRankImage(userLevel, rankCard), "rank.png")); - commandEvent.reply(createBuilder.build()); - } catch (Exception exception) { - commandEvent.reply(commandEvent.getResource("command.perform.error")); - log.error("Couldn't generated Rank Image!", exception); - } - }); + commandEvent.reply(createBuilder.build()); + } catch (Exception exception) { + commandEvent.reply(commandEvent.getResource("command.perform.error")); + log.error("Couldn't generated Rank Image!", exception); + } + })); } } diff --git a/src/main/java/de/presti/ree6/utils/data/ImageCreationUtility.java b/src/main/java/de/presti/ree6/utils/data/ImageCreationUtility.java index 825dd8a0f..c95015bcf 100644 --- a/src/main/java/de/presti/ree6/utils/data/ImageCreationUtility.java +++ b/src/main/java/de/presti/ree6/utils/data/ImageCreationUtility.java @@ -3,6 +3,7 @@ import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.main.Main; +import de.presti.ree6.sql.entities.UserRankCard; import de.presti.ree6.sql.entities.level.UserLevel; import lombok.extern.slf4j.Slf4j; import net.dv8tion.jda.api.entities.User; @@ -19,6 +20,7 @@ import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.HashMap; +import java.util.Optional; // TODO:: translate. @@ -53,7 +55,7 @@ private ImageCreationUtility() { * @return the bytes of the Image. * @throws IOException when URL-Format is Invalid or the URL is not a valid Image. */ - public static byte[] createRankImage(UserLevel userLevel) throws IOException { + public static byte[] createRankImage(UserLevel userLevel, Optional card) throws IOException { long start = System.currentTimeMillis(); long actionPerformance = System.currentTimeMillis(); @@ -88,8 +90,11 @@ public static byte[] createRankImage(UserLevel userLevel) throws IOException { Main.getInstance().logAnalytic("Loading and creating Background base. ({}ms)", System.currentTimeMillis() - actionPerformance); actionPerformance = System.currentTimeMillis(); - // Generate a 885x211 Image Background. + // Generate a 1920x1080 Image Background. Dog what is this? if (rankBackgroundBase == null) rankBackgroundBase = ImageIO.read(new File("storage/images/base.png")); + + BufferedImage background = card.isPresent() ? ImageIO.read(new ByteArrayInputStream(card.get().getRankCard())) : rankBackgroundBase; + BufferedImage base = new BufferedImage(1920, 1080, BufferedImage.TYPE_INT_ARGB); Main.getInstance().logAnalytic("Loaded and created Background base. ({}ms)", System.currentTimeMillis() - actionPerformance); @@ -122,7 +127,7 @@ public static byte[] createRankImage(UserLevel userLevel) throws IOException { actionPerformance = System.currentTimeMillis(); // Draw Background art. graphics2D.setComposite(AlphaComposite.Src); - graphics2D.drawImage(rankBackgroundBase, null, 0, 0); + graphics2D.drawImage(background, null, 0, 0); graphics2D.setColor(Color.WHITE); graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Main.getInstance().logAnalytic("Finished drawing Background Image. ({}ms)", System.currentTimeMillis() - actionPerformance); From 83b10c44a530e6323109a69ea69b3e63775acc34 Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 30 Aug 2024 10:21:41 +0200 Subject: [PATCH 41/94] Change Ticket Transcript to be an HTML page instead of a TXT file. --- .../de/presti/ree6/events/MenuEvents.java | 38 ++------- .../de/presti/ree6/events/OtherEvents.java | 37 ++------ .../ree6/utils/data/TranscriptUtil.java | 84 +++++++++++++++++++ 3 files changed, 94 insertions(+), 65 deletions(-) create mode 100644 src/main/java/de/presti/ree6/utils/data/TranscriptUtil.java diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index e8c6b74c3..ce822285e 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -18,6 +18,7 @@ import de.presti.ree6.sql.entities.webhook.base.Webhook; import de.presti.ree6.utils.apis.YouTubeAPIHandler; import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.utils.data.TranscriptUtil; import de.presti.wrapper.entities.channel.ChannelResult; import io.github.redouane59.twitter.dto.user.UserV2; import masecla.reddit4j.objects.subreddit.RedditSubreddit; @@ -162,38 +163,6 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(tickets -> { if (tickets.isPresent()) { Tickets ticketEntity = tickets.get(); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(BotConfig.getBotName()).append(" Ticket transcript") - .append(" ") - .append(ZonedDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG))) - .append("\n") - .append("\n"); - - - for (Message message : event.getChannel().asTextChannel().getIterableHistory().reverse()) { - stringBuilder - .append("[") - .append(message.getTimeCreated().toZonedDateTime().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT))) - .append("]") - .append(" ") - .append(message.getAuthor().getName()) - .append(" ") - .append("->") - .append(" ") - .append(message.getContentRaw()); - - if (!message.getAttachments().isEmpty()) { - for (Message.Attachment attachment : message.getAttachments()) { - stringBuilder.append("\n").append(attachment.getUrl()); - } - } - - stringBuilder.append("\n"); - } - - // TODO:: translate and fix the date being shown as UTC+1 and instead use the current server region. - - stringBuilder.append("\n").append("Closed by").append(" ").append(event.getUser().getName()); WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); webhookMessageBuilder.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); @@ -206,7 +175,10 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { webhookEmbedBuilder.setColor(BotWorker.randomEmbedColor().getRGB()); webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - webhookMessageBuilder.addFile(ticketEntity.getTicketCount() + "_transcript.txt", stringBuilder.toString().getBytes(StandardCharsets.UTF_8)); + webhookMessageBuilder.addFile(event.getGuild().getId() + "_" + ticketEntity.getTicketCount() + "_transcript.html", + TranscriptUtil.generateTranscript(event.getJDA(), event.getChannel().asTextChannel().getIterableHistory().reverse().stream().toList(), + event.getChannel().getTimeCreated().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)).replace("T", " "), + ZonedDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)).replace("T", " ")).getBytes(StandardCharsets.UTF_8)); WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), ticketEntity.getLogChannelWebhookId(), ticketEntity.getLogChannelWebhookToken(), false); diff --git a/src/main/java/de/presti/ree6/events/OtherEvents.java b/src/main/java/de/presti/ree6/events/OtherEvents.java index bbfbc7527..2ecf85d1c 100644 --- a/src/main/java/de/presti/ree6/events/OtherEvents.java +++ b/src/main/java/de/presti/ree6/events/OtherEvents.java @@ -18,6 +18,7 @@ import de.presti.ree6.utils.apis.ChatGPTAPI; import de.presti.ree6.utils.data.ArrayUtil; import de.presti.ree6.utils.data.ImageCreationUtility; +import de.presti.ree6.utils.data.TranscriptUtil; import de.presti.ree6.utils.others.*; import io.sentry.Sentry; import lombok.extern.slf4j.Slf4j; @@ -219,37 +220,6 @@ public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) { List channels = category.getTextChannels().stream().filter(c -> c.getTopic() != null && c.getTopic().equalsIgnoreCase(event.getUser().getId())).toList(); if (!channels.isEmpty()) { TextChannel channel = channels.get(0); - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(BotConfig.getBotName()) - .append(" Ticket transcript") - .append(" ") - .append(ZonedDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG))) - .append("\n") - .append("\n"); - - - for (Message message : channel.getIterableHistory().reverse()) { - stringBuilder - .append("[") - .append(message.getTimeCreated().toZonedDateTime().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT))) - .append("]") - .append(" ") - .append(message.getAuthor().getName()) - .append(" ") - .append("->") - .append(" ") - .append(message.getContentRaw()); - - if (!message.getAttachments().isEmpty()) { - for (Message.Attachment attachment : message.getAttachments()) { - stringBuilder.append("\n").append(attachment.getUrl()); - } - } - - stringBuilder.append("\n"); - } - - stringBuilder.append("\n").append("Closed by").append(" ").append(event.getUser().getEffectiveName()); WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); webhookMessageBuilder.setAvatarUrl(event.getJDA().getSelfUser().getEffectiveAvatarUrl()); @@ -262,7 +232,10 @@ public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) { webhookEmbedBuilder.setColor(BotWorker.randomEmbedColor().getRGB()); webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - webhookMessageBuilder.addFile(ticketsEntity.getTicketCount() + "_transcript.txt", stringBuilder.toString().getBytes(StandardCharsets.UTF_8)); + webhookMessageBuilder.addFile(event.getGuild().getId() + "_" + ticketsEntity.getTicketCount() + "_transcript.html", + TranscriptUtil.generateTranscript(event.getJDA(), channel.getIterableHistory().reverse().stream().toList(), + channel.getTimeCreated().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)).replace("T", " "), + ZonedDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)).replace("T", " ")).getBytes(StandardCharsets.UTF_8)); WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), ticketsEntity.getLogChannelId(), ticketsEntity.getLogChannelWebhookToken(), false); channel.delete().queue(); diff --git a/src/main/java/de/presti/ree6/utils/data/TranscriptUtil.java b/src/main/java/de/presti/ree6/utils/data/TranscriptUtil.java new file mode 100644 index 000000000..a443d41e8 --- /dev/null +++ b/src/main/java/de/presti/ree6/utils/data/TranscriptUtil.java @@ -0,0 +1,84 @@ +package de.presti.ree6.utils.data; + +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.entities.Message; + +import java.util.List; + +public class TranscriptUtil { + + /** + * The HTML template that should be used for the transcripts. + */ + public static final String template = """ + + + + + + + + +
+
+
+ +
+
+
Opened: %opened%
+
Transcript Generated: %closed%
+
Total Messages: %messages_count%
+
+
+
+ %messages% +
+
+ + + """; + + /** + * The Message template to be inserted into the HTML template. + */ + public static final String messageTemplate = """ +
+
%name%%time%
+
+ %message% +
+ """; + + /** + * Generates a Transcript based on the templates. + * @param selfUser The Bot Self User to use as an Icon. + * @param messages The messages that should be put into the transcript. + * @param opened When the Ticket was opened. + * @param closed When the Ticket was closed. + * @return A filled-out template as {@link String} + */ + public static String generateTranscript(JDA selfUser, List messages, String opened, String closed) { + String icon = selfUser.getSelfUser().getEffectiveAvatarUrl(); + StringBuilder messageBuilder = new StringBuilder(); + for (Message message : messages) { + messageBuilder.append(messageTemplate + .replace("%name%", message.getAuthor().getName()) + .replace("%time%", message.getTimeCreated().toString()) + .replace("%message%", message.getContentRaw())); + } + + return template + .replace("%icon%", icon) + .replace("%opened%", opened) + .replace("%closed%", closed) + .replace("%messages_count%", String.valueOf(messages.size())) + .replace("%messages%", messageBuilder.toString()); + } + +} From e9620e4a6793cc6b5b3df0985b1165a989c2cfad Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 13 Sep 2024 12:49:45 +0200 Subject: [PATCH 42/94] Updated Twitch Notification for better clarity and easier use. --- pom.xml | 5 +++-- .../notifications/impl/TwitchSonic.java | 19 ++++++++++++++----- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index 3698d1df2..3b4edf287 100644 --- a/pom.xml +++ b/pom.xml @@ -18,6 +18,7 @@ UTF-8 dxssucuk https://sonarcloud.io + 3.4.2 @@ -81,9 +82,9 @@ 1.1.2 - club.minnced + de.ree6 discord-webhooks - 0.8.4 + f67bf93e5f diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java index 140cbaf20..3625e4293 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java @@ -3,8 +3,12 @@ import club.minnced.discord.webhook.send.WebhookEmbed; import club.minnced.discord.webhook.send.WebhookEmbedBuilder; import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import club.minnced.discord.webhook.send.component.ComponentElement; +import club.minnced.discord.webhook.send.component.button.Button; +import club.minnced.discord.webhook.send.component.layout.ActionRow; import com.github.twitch4j.events.ChannelFollowCountUpdateEvent; import com.github.twitch4j.events.ChannelGoLiveEvent; +import com.github.twitch4j.helix.domain.GameList; import com.github.twitch4j.helix.domain.User; import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; @@ -81,15 +85,20 @@ public void run() { if (twitchUserRequest.isPresent()) { webhookEmbedBuilder.setThumbnailUrl(twitchUserRequest.orElseThrow().getProfileImageUrl()); } - webhookEmbedBuilder.setImageUrl(channelGoLiveEvent.getStream().getThumbnailUrl()); // Set rest of the Information. - webhookEmbedBuilder.setDescription("**" + channelGoLiveEvent.getStream().getTitle() + "**\n[Watch Stream](" + twitchUrl + ")"); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Game**", channelGoLiveEvent.getStream().getGameName())); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Viewer**", String.valueOf(channelGoLiveEvent.getStream().getViewerCount()))); - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); + webhookEmbedBuilder.setDescription("**" + channelGoLiveEvent.getStream().getTitle() + "**"); + GameList gameList = Main.getInstance().getNotifier().getTwitchClient().getClientHelper().getTwitchHelix().getGames(null, List.of(channelGoLiveEvent.getStream().getGameId()), null, null).execute(); + if (!gameList.getGames().isEmpty()) { + webhookEmbedBuilder.setThumbnailUrl(gameList.getGames().get(0).getBoxArtUrl()); + } + + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(channelGoLiveEvent.getStream().getUserName(), twitchUserRequest.map(User::getProfileImageUrl).orElse(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()), twitchUrl)); + webhookEmbedBuilder.setImageUrl(channelGoLiveEvent.getStream().getThumbnailUrlTemplate()); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(channelGoLiveEvent.getStream().getGameName(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); + wmb.addComponents(ActionRow.of(new Button(Button.Style.LINK, twitchUrl).setLabel(twitchUserRequest.isPresent() ? twitchUserRequest.get().getDisplayName() : "Watch Stream"))); wmb.addEmbeds(webhookEmbedBuilder.build()); // Go through every Webhook that is registered for the Twitch Channel From 8e6bde542a420f3059a25ade4e5a2c04f470404d Mon Sep 17 00:00:00 2001 From: Presti Date: Mon, 23 Sep 2024 16:42:35 +0200 Subject: [PATCH 43/94] Starting #565 --- .../notifications/impl/SpotifySonic.java | 57 +++++++++++++++++++ .../ree6/utils/apis/SpotifyAPIHandler.java | 57 ++++++++++++++++++- 2 files changed, 113 insertions(+), 1 deletion(-) create mode 100644 src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java new file mode 100644 index 000000000..7f20dd4d5 --- /dev/null +++ b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java @@ -0,0 +1,57 @@ +package de.presti.ree6.module.notifications.impl; + +import de.presti.ree6.module.notifications.ISonic; +import de.presti.ree6.module.notifications.SonicIdentifier; +import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.stats.ChannelStats; +import de.presti.ree6.utils.apis.SpotifyAPIHandler; +import lombok.extern.slf4j.Slf4j; + +import java.util.List; +import java.util.*; + +@Slf4j +public class SpotifySonic implements ISonic { + ArrayList spotifyArtist = new ArrayList<>(); + ArrayList spotifyPodcasts = new ArrayList<>(); + + @Override + public void load(List channelStats) { + // No need for this. + } + + @Override + public void load() { + // Register all YouTube channels. + SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels().subscribe(channel -> + channel.forEach(this::add)); + } + + @Override + public List getList() { + return spotifyArtist; + } + + @Override + public void run() { + for (String artistId : spotifyArtist.stream().map(SonicIdentifier::getIdentifier).toList()) { + // SpotifyAPIHandler.getInstance().getArtistAlbums(artistId); + } + + for (String podcastId : spotifyPodcasts.stream().map(SonicIdentifier::getIdentifier).toList()) { + // SpotifyAPIHandler.getInstance().getPodcastEpisodes(podcastId); + } + } + + @Override + public void unload() { + + } + + @Override + public void remove(SonicIdentifier object) { + if (SpotifyAPIHandler.getInstance() == null) return; + if (!contains(object)) return; + + } +} diff --git a/src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java b/src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java index 6d840e837..dd76dec61 100644 --- a/src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java +++ b/src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java @@ -15,7 +15,6 @@ import se.michaelthelin.spotify.requests.authorization.client_credentials.ClientCredentialsRequest; import se.michaelthelin.spotify.requests.data.albums.GetAlbumsTracksRequest; import se.michaelthelin.spotify.requests.data.playlists.GetPlaylistRequest; -import se.michaelthelin.spotify.requests.data.tracks.GetTrackRequest; import java.io.IOException; import java.util.ArrayList; @@ -228,6 +227,62 @@ public ArrayList getTracks(String playlistId) { return tracks; } + /** + * Get the Artist based on their ID. + * + * @param artistId The Artist ID. + * @return The Artist. + * @throws ParseException if the response is not a Valid JSON. + * @throws SpotifyWebApiException if an error occurs. + * @throws IOException if there was a network error. + */ + public Artist getArtist(String artistId) throws ParseException, SpotifyWebApiException, IOException { + if (!isSpotifyConnected) return null; + return spotifyApi.getArtist(artistId).build().execute(); + } + + /** + * Get the Albums of an Artist. + * + * @param artistId The Artist ID. + * @return All Albums of the Artist. + * @throws ParseException if the response is not a Valid JSON. + * @throws SpotifyWebApiException if an error occurs. + * @throws IOException if there was a network error. + */ + public Paging getArtistAlbums(String artistId) throws ParseException, SpotifyWebApiException, IOException { + if (!isSpotifyConnected) return null; + return spotifyApi.getArtistsAlbums(artistId).build().execute(); + } + + /** + * Get a Podcast. + * + * @param podcastId The Podcast ID. + * @return The Podcast. + * @throws ParseException if the response is not a Valid JSON. + * @throws SpotifyWebApiException if an error occurs. + * @throws IOException if there was a network error. + */ + public Show getPodcast(String podcastId) throws ParseException, SpotifyWebApiException, IOException { + if (!isSpotifyConnected) return null; + return spotifyApi.getShow(podcastId).build().execute(); + } + + /** + * Get all Podcast Episodes. + * + * @param podcastId The Podcast ID. + * @return The Podcast episodes. + * @throws ParseException if the response is not a Valid JSON. + * @throws SpotifyWebApiException if an error occurs. + * @throws IOException if there was a network error. + */ + public Paging getPodcastEpisodes(String podcastId) throws ParseException, SpotifyWebApiException, IOException { + if (!isSpotifyConnected) return null; + return spotifyApi.getShowEpisodes(podcastId).build().execute(); + } + /** * Get the Artist and Track Name of a Track. * From 920f840510d2191aacb5eddbba925423fa4687ea Mon Sep 17 00:00:00 2001 From: Presti Date: Mon, 23 Sep 2024 16:45:40 +0200 Subject: [PATCH 44/94] Fix Album get request. --- src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java b/src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java index dd76dec61..67e064849 100644 --- a/src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java +++ b/src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java @@ -252,7 +252,7 @@ public Artist getArtist(String artistId) throws ParseException, SpotifyWebApiExc */ public Paging getArtistAlbums(String artistId) throws ParseException, SpotifyWebApiException, IOException { if (!isSpotifyConnected) return null; - return spotifyApi.getArtistsAlbums(artistId).build().execute(); + return spotifyApi.getArtistsAlbums(artistId).album_type("album,single").build().execute(); } /** From 5bad41054a1159da400af77efa2d090bdd5082dc Mon Sep 17 00:00:00 2001 From: Presti Date: Mon, 23 Sep 2024 17:05:38 +0200 Subject: [PATCH 45/94] Fix Album get request. Signed-off-by: Presti --- src/main/java/de/presti/ree6/utils/data/Config.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/de/presti/ree6/utils/data/Config.java b/src/main/java/de/presti/ree6/utils/data/Config.java index c20c78048..e6027be7c 100644 --- a/src/main/java/de/presti/ree6/utils/data/Config.java +++ b/src/main/java/de/presti/ree6/utils/data/Config.java @@ -15,6 +15,7 @@ import java.util.List; import java.util.Map; +// TODO:: Rework the Config System to make the Config class be the actual config structure and use it to serialize and deserialize while making a new ConfigManager class that loads and saves the config. /** * Config. */ From a8ac3056e2b91bc9d3f4324c393186f81ef27851 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 25 Sep 2024 12:29:22 +0200 Subject: [PATCH 46/94] Refactor. Signed-off-by: Presti --- src/main/java/de/presti/ree6/main/Main.java | 6 ++++-- src/main/java/de/presti/ree6/utils/apis/Notifier.java | 2 +- .../java/de/presti/ree6/utils/{data => config}/Config.java | 4 ++-- .../ree6/utils/{data => oauth}/CustomOAuth2Credential.java | 3 +-- .../presti/ree6/utils/{data => oauth}/CustomOAuth2Util.java | 2 +- .../ree6/utils/{data => oauth}/DatabaseStorageBackend.java | 2 +- 6 files changed, 10 insertions(+), 9 deletions(-) rename src/main/java/de/presti/ree6/utils/{data => config}/Config.java (99%) rename src/main/java/de/presti/ree6/utils/{data => oauth}/CustomOAuth2Credential.java (98%) rename src/main/java/de/presti/ree6/utils/{data => oauth}/CustomOAuth2Util.java (98%) rename src/main/java/de/presti/ree6/utils/{data => oauth}/DatabaseStorageBackend.java (99%) diff --git a/src/main/java/de/presti/ree6/main/Main.java b/src/main/java/de/presti/ree6/main/Main.java index 9987d272a..575d30f97 100644 --- a/src/main/java/de/presti/ree6/main/Main.java +++ b/src/main/java/de/presti/ree6/main/Main.java @@ -30,14 +30,16 @@ import de.presti.ree6.sql.entities.Setting; import de.presti.ree6.sql.entities.TwitchIntegration; import de.presti.ree6.sql.entities.stats.ChannelStats; -import de.presti.ree6.sql.entities.stats.Statistics; import de.presti.ree6.sql.util.SQLConfig; import de.presti.ree6.sql.util.SettingsManager; import de.presti.ree6.utils.apis.ChatGPTAPI; import de.presti.ree6.utils.apis.Notifier; import de.presti.ree6.utils.apis.SpotifyAPIHandler; -import de.presti.ree6.utils.data.*; +import de.presti.ree6.utils.config.Config; +import de.presti.ree6.utils.data.ArrayUtil; import de.presti.ree6.utils.external.RequestUtility; +import de.presti.ree6.utils.oauth.CustomOAuth2Credential; +import de.presti.ree6.utils.oauth.CustomOAuth2Util; import de.presti.ree6.utils.others.ThreadUtil; import io.sentry.Sentry; import lavalink.client.io.jda.JdaLavalink; diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index f9ca582a3..dd4a9d267 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -20,7 +20,7 @@ import de.presti.ree6.module.notifications.impl.*; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.TwitchIntegration; -import de.presti.ree6.utils.data.DatabaseStorageBackend; +import de.presti.ree6.utils.oauth.DatabaseStorageBackend; import de.presti.ree6.utils.others.ThreadUtil; import io.github.redouane59.twitter.TwitterClient; import io.github.redouane59.twitter.signature.TwitterCredentials; diff --git a/src/main/java/de/presti/ree6/utils/data/Config.java b/src/main/java/de/presti/ree6/utils/config/Config.java similarity index 99% rename from src/main/java/de/presti/ree6/utils/data/Config.java rename to src/main/java/de/presti/ree6/utils/config/Config.java index e6027be7c..0cbe82bfb 100644 --- a/src/main/java/de/presti/ree6/utils/data/Config.java +++ b/src/main/java/de/presti/ree6/utils/config/Config.java @@ -1,4 +1,4 @@ -package de.presti.ree6.utils.data; +package de.presti.ree6.utils.config; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.utils.others.VersionUtil; @@ -35,7 +35,7 @@ public class Config { /** * The config version. */ - private final String version = "3.1.12"; + private final String version = "4.0.0"; /** * Initialize the Configuration. diff --git a/src/main/java/de/presti/ree6/utils/data/CustomOAuth2Credential.java b/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Credential.java similarity index 98% rename from src/main/java/de/presti/ree6/utils/data/CustomOAuth2Credential.java rename to src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Credential.java index 28b27553e..53b06d530 100644 --- a/src/main/java/de/presti/ree6/utils/data/CustomOAuth2Credential.java +++ b/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Credential.java @@ -1,8 +1,7 @@ -package de.presti.ree6.utils.data; +package de.presti.ree6.utils.oauth; import com.github.philippheuer.credentialmanager.domain.Credential; import com.github.philippheuer.credentialmanager.domain.OAuth2Credential; -import io.sentry.MeasurementUnit; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/de/presti/ree6/utils/data/CustomOAuth2Util.java b/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Util.java similarity index 98% rename from src/main/java/de/presti/ree6/utils/data/CustomOAuth2Util.java rename to src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Util.java index d79917df7..0ae4db667 100644 --- a/src/main/java/de/presti/ree6/utils/data/CustomOAuth2Util.java +++ b/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Util.java @@ -1,4 +1,4 @@ -package de.presti.ree6.utils.data; +package de.presti.ree6.utils.oauth; import com.github.philippheuer.credentialmanager.domain.OAuth2Credential; import com.github.philippheuer.credentialmanager.identityprovider.OAuth2IdentityProvider; diff --git a/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java b/src/main/java/de/presti/ree6/utils/oauth/DatabaseStorageBackend.java similarity index 99% rename from src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java rename to src/main/java/de/presti/ree6/utils/oauth/DatabaseStorageBackend.java index f0d66dab0..917f263af 100644 --- a/src/main/java/de/presti/ree6/utils/data/DatabaseStorageBackend.java +++ b/src/main/java/de/presti/ree6/utils/oauth/DatabaseStorageBackend.java @@ -1,4 +1,4 @@ -package de.presti.ree6.utils.data; +package de.presti.ree6.utils.oauth; import com.github.philippheuer.credentialmanager.api.IStorageBackend; import com.github.philippheuer.credentialmanager.domain.Credential; From 3fa9df44a178242fc8a6f8593a7d4ab8241dff4e Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 25 Sep 2024 16:03:29 +0200 Subject: [PATCH 47/94] Gang Gang Signed-off-by: Presti --- pom.xml | 2 +- .../notifications/impl/SpotifySonic.java | 54 ++++++++++--- .../de/presti/ree6/utils/apis/Notifier.java | 13 +++ .../ree6/utils/apis/SpotifyAPIHandler.java | 79 +++++++++++++++++-- 4 files changed, 130 insertions(+), 18 deletions(-) diff --git a/pom.xml b/pom.xml index ef38e9fdd..819b55ce1 100644 --- a/pom.xml +++ b/pom.xml @@ -183,7 +183,7 @@ de.ree6 Ree6-SQL - 0586650f02 + bc06476620 diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java index 7f20dd4d5..8f91d2837 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java @@ -4,16 +4,19 @@ import de.presti.ree6.module.notifications.SonicIdentifier; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.stats.ChannelStats; +import de.presti.ree6.sql.entities.webhook.WebhookSpotify; import de.presti.ree6.utils.apis.SpotifyAPIHandler; import lombok.extern.slf4j.Slf4j; +import se.michaelthelin.spotify.model_objects.specification.AlbumSimplified; +import se.michaelthelin.spotify.model_objects.specification.EpisodeSimplified; +import java.util.ArrayList; import java.util.List; -import java.util.*; +import java.util.Map; @Slf4j public class SpotifySonic implements ISonic { - ArrayList spotifyArtist = new ArrayList<>(); - ArrayList spotifyPodcasts = new ArrayList<>(); + ArrayList spotifyEntries = new ArrayList<>(); @Override public void load(List channelStats) { @@ -23,24 +26,53 @@ public void load(List channelStats) { @Override public void load() { // Register all YouTube channels. - SQLSession.getSqlConnector().getSqlWorker().getAllYouTubeChannels().subscribe(channel -> - channel.forEach(this::add)); + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new WebhookSpotify(), "FROM WebhookSpotify", Map.of()).subscribe(spotifyNotify -> { + spotifyNotify.forEach(x -> { + if (x.getEntityTyp() == 0) { + add("art:" + x.getEntityId()); + } else { + add("pot:" + x.getEntityId()); + } + }); + }); } @Override public List getList() { - return spotifyArtist; + return spotifyEntries; } @Override public void run() { - for (String artistId : spotifyArtist.stream().map(SonicIdentifier::getIdentifier).toList()) { + for (String entry : spotifyEntries.stream().map(SonicIdentifier::getIdentifier).toList()) { + String actualId = entry.substring(entry.lastIndexOf(':') + 1); + try { + if (entry.startsWith("art")) { + ArrayList albums = SpotifyAPIHandler.getInstance().getArtistAlbums(actualId); + if (albums.isEmpty()) return; + AlbumSimplified album = albums.get(0); + if (album == null) return; + if (album.getReleaseDatePrecision().precision.equals("year")) continue; + if (album.getReleaseDatePrecision().precision.equals("month")) continue; + if (album.getReleaseDate().equals("d")) { + // TODO:: add actual check and webhook send + } + } else { + ArrayList episodes = SpotifyAPIHandler.getInstance().getPodcastEpisodes(actualId); + if (episodes.isEmpty()) continue; + EpisodeSimplified episode = episodes.get(0); + if (episode == null) continue; + if (episode.getReleaseDatePrecision().precision.equals("year")) continue; + if (episode.getReleaseDatePrecision().precision.equals("month")) continue; + if (episode.getReleaseDate().equals("d")) { + // TODO:: add actual check and webhook send + } + } + } catch (Exception exception) { + // TODO:: handle this shit + } // SpotifyAPIHandler.getInstance().getArtistAlbums(artistId); } - - for (String podcastId : spotifyPodcasts.stream().map(SonicIdentifier::getIdentifier).toList()) { - // SpotifyAPIHandler.getInstance().getPodcastEpisodes(podcastId); - } } @Override diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index dd4a9d267..8bbb9da85 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -123,6 +123,12 @@ public class Notifier { @Getter(AccessLevel.PUBLIC) private RSSSonic rssSonic; + /** + * Instance of the Spotify Sonic Manager. + */ + @Getter(AccessLevel.PUBLIC) + private SpotifySonic spotifySonic; + /** * A list with all the Twitch Subscription for the Streaming Tools. */ @@ -306,5 +312,12 @@ public Notifier() { log.error("Failed to run Reddit Stream!", x); Sentry.captureException(x); }, Duration.ofMinutes(5), true, true); + + log.info("Creating Spotify Streams..."); + spotifySonic = new SpotifySonic(); + ThreadUtil.createThread(x -> spotifySonic.run(), x -> { + log.error("Failed to run Spotify Stream!", x); + Sentry.captureException(x); + }, Duration.ofMinutes(5), true, true); } } diff --git a/src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java b/src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java index 67e064849..95fe3e789 100644 --- a/src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java +++ b/src/main/java/de/presti/ree6/utils/apis/SpotifyAPIHandler.java @@ -14,7 +14,9 @@ import se.michaelthelin.spotify.model_objects.specification.*; import se.michaelthelin.spotify.requests.authorization.client_credentials.ClientCredentialsRequest; import se.michaelthelin.spotify.requests.data.albums.GetAlbumsTracksRequest; +import se.michaelthelin.spotify.requests.data.artists.GetArtistsAlbumsRequest; import se.michaelthelin.spotify.requests.data.playlists.GetPlaylistRequest; +import se.michaelthelin.spotify.requests.data.shows.GetShowsEpisodesRequest; import java.io.IOException; import java.util.ArrayList; @@ -250,9 +252,42 @@ public Artist getArtist(String artistId) throws ParseException, SpotifyWebApiExc * @throws SpotifyWebApiException if an error occurs. * @throws IOException if there was a network error. */ - public Paging getArtistAlbums(String artistId) throws ParseException, SpotifyWebApiException, IOException { - if (!isSpotifyConnected) return null; - return spotifyApi.getArtistsAlbums(artistId).album_type("album,single").build().execute(); + public ArrayList getArtistAlbums(String artistId) throws ParseException, SpotifyWebApiException, IOException { + if (!isSpotifyConnected) return new ArrayList<>(); + ArrayList albums = new ArrayList<>(); + + if (retries.getOrDefault(artistId, 0) >= 3) return albums; + + GetArtistsAlbumsRequest request = spotifyApi.getArtistsAlbums(artistId).build(); + try { + Paging albumList = request.execute(); + + for (AlbumSimplified album : albumList.getItems()) { + if (album == null) continue; + + albums.add(album); + } + retries.remove(artistId); + } catch (UnauthorizedException unauthorizedException) { + if (spotifyApi.getClientId() != null) { + + try { + isSpotifyConnected = false; + retries.put(artistId, retries.getOrDefault(artistId, 0) + 1); + initSpotify(); + } catch (Exception exception) { + Sentry.captureException(exception); + } + + return getArtistAlbums(artistId); + } else { + log.error("Couldn't get Album from Artist", unauthorizedException); + } + } catch (ParseException | SpotifyWebApiException | IOException e) { + log.error("Couldn't get Album from Artist", e); + } + + return albums; } /** @@ -278,9 +313,41 @@ public Show getPodcast(String podcastId) throws ParseException, SpotifyWebApiExc * @throws SpotifyWebApiException if an error occurs. * @throws IOException if there was a network error. */ - public Paging getPodcastEpisodes(String podcastId) throws ParseException, SpotifyWebApiException, IOException { - if (!isSpotifyConnected) return null; - return spotifyApi.getShowEpisodes(podcastId).build().execute(); + public ArrayList getPodcastEpisodes(String podcastId) throws ParseException, SpotifyWebApiException, IOException { + if (!isSpotifyConnected) return new ArrayList<>(); + ArrayList episodes = new ArrayList<>(); + + if (retries.getOrDefault(podcastId, 0) >= 3) return episodes; + + GetShowsEpisodesRequest request = spotifyApi.getShowEpisodes(podcastId).build(); + try { + Paging albumList = request.execute(); + + for (EpisodeSimplified episode : albumList.getItems()) { + if (episode == null) continue; + + episodes.add(episode); + } + retries.remove(podcastId); + } catch (UnauthorizedException unauthorizedException) { + if (spotifyApi.getClientId() != null) { + + try { + isSpotifyConnected = false; + retries.put(podcastId, retries.getOrDefault(podcastId, 0) + 1); + initSpotify(); + } catch (Exception exception) { + Sentry.captureException(exception); + } + + return getPodcastEpisodes(podcastId); + } else { + log.error("Couldn't get Episodes from Podcast", unauthorizedException); + } + } catch (ParseException | SpotifyWebApiException | IOException e) { + log.error("Couldn't get Episodes from Podcast", e); + } + return episodes; } /** From 44aac15f4dea643d6f088d615aaa6b6fa959240d Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 25 Sep 2024 16:51:25 +0200 Subject: [PATCH 48/94] Gang Gang Signed-off-by: Presti --- .../notifications/impl/SpotifySonic.java | 95 ++++++++++++++----- 1 file changed, 69 insertions(+), 26 deletions(-) diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java index 8f91d2837..bfcd8f378 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java @@ -1,5 +1,11 @@ package de.presti.ree6.module.notifications.impl; +import club.minnced.discord.webhook.send.WebhookEmbed; +import club.minnced.discord.webhook.send.WebhookEmbedBuilder; +import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.util.WebhookUtil; import de.presti.ree6.module.notifications.ISonic; import de.presti.ree6.module.notifications.SonicIdentifier; import de.presti.ree6.sql.SQLSession; @@ -10,6 +16,7 @@ import se.michaelthelin.spotify.model_objects.specification.AlbumSimplified; import se.michaelthelin.spotify.model_objects.specification.EpisodeSimplified; +import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -44,35 +51,71 @@ public List getList() { @Override public void run() { - for (String entry : spotifyEntries.stream().map(SonicIdentifier::getIdentifier).toList()) { - String actualId = entry.substring(entry.lastIndexOf(':') + 1); - try { - if (entry.startsWith("art")) { - ArrayList albums = SpotifyAPIHandler.getInstance().getArtistAlbums(actualId); - if (albums.isEmpty()) return; - AlbumSimplified album = albums.get(0); - if (album == null) return; - if (album.getReleaseDatePrecision().precision.equals("year")) continue; - if (album.getReleaseDatePrecision().precision.equals("month")) continue; - if (album.getReleaseDate().equals("d")) { - // TODO:: add actual check and webhook send - } - } else { - ArrayList episodes = SpotifyAPIHandler.getInstance().getPodcastEpisodes(actualId); - if (episodes.isEmpty()) continue; - EpisodeSimplified episode = episodes.get(0); - if (episode == null) continue; - if (episode.getReleaseDatePrecision().precision.equals("year")) continue; - if (episode.getReleaseDatePrecision().precision.equals("month")) continue; - if (episode.getReleaseDate().equals("d")) { - // TODO:: add actual check and webhook send + // TODO:: fix the actual checks. + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new WebhookSpotify(), "FROM WebhookSpotify", Map.of()).subscribe(spotifyNotify -> { + for (String entry : spotifyEntries.stream().map(SonicIdentifier::getIdentifier).toList()) { + String actualId = entry.substring(entry.lastIndexOf(':') + 1); + try { + if (entry.startsWith("art")) { + ArrayList albums = SpotifyAPIHandler.getInstance().getArtistAlbums(actualId); + if (albums.isEmpty()) return; + AlbumSimplified album = albums.get(0); + if (album == null) return; + if (album.getReleaseDatePrecision().precision.equals("year")) continue; + if (album.getReleaseDatePrecision().precision.equals("month")) continue; + if (album.getReleaseDate().equals("d")) { + sendWebhooks(album.getArtists()[0].getName(), album.getArtists()[0].getHref(), + album.getImages()[0].getUrl(), album.getHref(), album.getName(), + spotifyNotify.stream().filter(x -> x.getEntityTyp() == 0).toList()); + } + } else { + ArrayList episodes = SpotifyAPIHandler.getInstance().getPodcastEpisodes(actualId); + if (episodes.isEmpty()) continue; + EpisodeSimplified episode = episodes.get(0); + if (episode == null) continue; + if (episode.getReleaseDatePrecision().precision.equals("year")) continue; + if (episode.getReleaseDatePrecision().precision.equals("month")) continue; + if (episode.getReleaseDate().equals("d")) { + sendWebhooks(episode.getName(), episode.getAudioPreviewUrl(), + episode.getImages()[0].getUrl(), episode.getHref(), episode.getDescription(), + spotifyNotify.stream().filter(x -> x.getEntityTyp() == 0).toList()); + } } + } catch (Exception exception) { + // TODO:: handle this shit } - } catch (Exception exception) { - // TODO:: handle this shit } - // SpotifyAPIHandler.getInstance().getArtistAlbums(artistId); - } + }); + } + + public void sendWebhooks(String authorName, String authorUrl, String imageUrl, String redirectUrl, String description, List webhooks) { + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(authorName, authorUrl)); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Spotify Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + + webhookEmbedBuilder.setImageUrl(imageUrl); + + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + + webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); + + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + + webhooks.forEach(webhook -> { + String message = webhook.getMessage() + .replace("%description%", description) + .replace("%author%", authorName) + .replace("%name%", authorName) + .replace("%url%", redirectUrl); + webhookMessageBuilder.setContent(message); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); + }); } @Override From 6bb10a4a00daee29c9c6c60fb21aed379b888f49 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 25 Sep 2024 17:20:43 +0200 Subject: [PATCH 49/94] Just need to make the actual time check, design the embed and add the commands. Signed-off-by: Presti --- src/main/java/de/presti/ree6/main/Main.java | 1 + .../ree6/module/notifications/impl/SpotifySonic.java | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/src/main/java/de/presti/ree6/main/Main.java b/src/main/java/de/presti/ree6/main/Main.java index 575d30f97..ce9e192c4 100644 --- a/src/main/java/de/presti/ree6/main/Main.java +++ b/src/main/java/de/presti/ree6/main/Main.java @@ -346,6 +346,7 @@ public static void main(String[] args) { getInstance().setNotifier(new Notifier()); if (BotConfig.isModuleActive("notifier")) { + getInstance().getNotifier().getSpotifySonic().load(); ThreadUtil.createThread(x -> { log.info("Loading Notifier data."); SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), "FROM ChannelStats", null).subscribe(channelStats -> { diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java index bfcd8f378..f53a16ad0 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java @@ -127,6 +127,13 @@ public void unload() { public void remove(SonicIdentifier object) { if (SpotifyAPIHandler.getInstance() == null) return; if (!contains(object)) return; + String actualId = object.getIdentifier(); + actualId = actualId.substring(actualId.lastIndexOf(':') + 1); + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new WebhookSpotify(), "FROM WebhookSpotify WHERE entityId=:id", Map.of("id", actualId)).subscribe(webhooks -> { + if (!webhooks.isEmpty()) return; + + spotifyEntries.remove(object); + }); } } From 149035e4aa4ea03267202c3f8ce606a77f1f1f67 Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 27 Sep 2024 12:40:00 +0200 Subject: [PATCH 50/94] Spotify Notifications should now work. I have not tested this yet. Signed-off-by: Presti --- .../notifications/impl/SpotifySonic.java | 56 +++++++++++-------- .../de/presti/ree6/utils/apis/Notifier.java | 3 +- 2 files changed, 36 insertions(+), 23 deletions(-) diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java index f53a16ad0..6747552ca 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java @@ -14,10 +14,15 @@ import de.presti.ree6.utils.apis.SpotifyAPIHandler; import lombok.extern.slf4j.Slf4j; import se.michaelthelin.spotify.model_objects.specification.AlbumSimplified; +import se.michaelthelin.spotify.model_objects.specification.ArtistSimplified; import se.michaelthelin.spotify.model_objects.specification.EpisodeSimplified; import java.awt.*; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; +import java.util.Date; import java.util.List; import java.util.Map; @@ -25,6 +30,8 @@ public class SpotifySonic implements ISonic { ArrayList spotifyEntries = new ArrayList<>(); + SimpleDateFormat spotifyTimestamp = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ssZ"); + @Override public void load(List channelStats) { // No need for this. @@ -51,8 +58,8 @@ public List getList() { @Override public void run() { - // TODO:: fix the actual checks. SQLSession.getSqlConnector().getSqlWorker().getEntityList(new WebhookSpotify(), "FROM WebhookSpotify", Map.of()).subscribe(spotifyNotify -> { + Date yesterday = Date.from(Instant.now().minus(1, ChronoUnit.DAYS)); for (String entry : spotifyEntries.stream().map(SonicIdentifier::getIdentifier).toList()) { String actualId = entry.substring(entry.lastIndexOf(':') + 1); try { @@ -63,10 +70,16 @@ public void run() { if (album == null) return; if (album.getReleaseDatePrecision().precision.equals("year")) continue; if (album.getReleaseDatePrecision().precision.equals("month")) continue; - if (album.getReleaseDate().equals("d")) { - sendWebhooks(album.getArtists()[0].getName(), album.getArtists()[0].getHref(), - album.getImages()[0].getUrl(), album.getHref(), album.getName(), - spotifyNotify.stream().filter(x -> x.getEntityTyp() == 0).toList()); + + Date date = spotifyTimestamp.parse(album.getReleaseDate()); + + if (date.after(yesterday)) { + ArtistSimplified artistSimplified = album.getArtists()[0]; + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(artistSimplified.getName(), artistSimplified.getHref())); + webhookEmbedBuilder.setImageUrl(album.getImages()[0].getUrl()); + + sendWebhooks(webhookEmbedBuilder, album.getName(), artistSimplified.getName(), album.getHref(), spotifyNotify); } } else { ArrayList episodes = SpotifyAPIHandler.getInstance().getPodcastEpisodes(actualId); @@ -75,10 +88,16 @@ public void run() { if (episode == null) continue; if (episode.getReleaseDatePrecision().precision.equals("year")) continue; if (episode.getReleaseDatePrecision().precision.equals("month")) continue; - if (episode.getReleaseDate().equals("d")) { - sendWebhooks(episode.getName(), episode.getAudioPreviewUrl(), - episode.getImages()[0].getUrl(), episode.getHref(), episode.getDescription(), - spotifyNotify.stream().filter(x -> x.getEntityTyp() == 0).toList()); + + Date date = spotifyTimestamp.parse(episode.getReleaseDate()); + + if (date.after(yesterday)) { + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(episode.getName(), episode.getHref())); + webhookEmbedBuilder.setImageUrl(episode.getImages()[0].getUrl()); + + sendWebhooks(webhookEmbedBuilder, episode.getDescription(), episode.getName(), episode.getHref(), spotifyNotify); } } } catch (Exception exception) { @@ -88,31 +107,24 @@ public void run() { }); } - public void sendWebhooks(String authorName, String authorUrl, String imageUrl, String redirectUrl, String description, List webhooks) { + public void sendWebhooks(WebhookEmbedBuilder webhookEmbed, String description, String authorName, String redirect, List webhooks) { WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); webhookMessageBuilder.setUsername(BotConfig.getBotName()); - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(authorName, authorUrl)); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Spotify Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); - - webhookEmbedBuilder.setImageUrl(imageUrl); - - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); - - webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); + webhookEmbed.setAuthor(new WebhookEmbed.EmbedAuthor("Spotify Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + webhookEmbed.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + webhookEmbed.setColor(Color.GREEN.getRGB()); - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + webhookMessageBuilder.addEmbeds(webhookEmbed.build()); webhooks.forEach(webhook -> { String message = webhook.getMessage() .replace("%description%", description) .replace("%author%", authorName) .replace("%name%", authorName) - .replace("%url%", redirectUrl); + .replace("%url%", redirect); webhookMessageBuilder.setContent(message); WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); }); diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index 8bbb9da85..3a3107d00 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -313,11 +313,12 @@ public Notifier() { Sentry.captureException(x); }, Duration.ofMinutes(5), true, true); + // Use 1 day instead of minutes, because Spotify release date is at max precise to the day log.info("Creating Spotify Streams..."); spotifySonic = new SpotifySonic(); ThreadUtil.createThread(x -> spotifySonic.run(), x -> { log.error("Failed to run Spotify Stream!", x); Sentry.captureException(x); - }, Duration.ofMinutes(5), true, true); + }, Duration.ofDays(1), true, true); } } From fd1be269dd68f7c0eaa7752e9d7a09793132f99f Mon Sep 17 00:00:00 2001 From: Presti Date: Mon, 30 Sep 2024 12:03:05 +0200 Subject: [PATCH 51/94] Fix up Signed-off-by: Presti --- .../ree6/module/notifications/impl/TwitchSonic.java | 8 +++----- src/main/java/de/presti/ree6/utils/apis/Notifier.java | 4 +++- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java index 3625e4293..edca65045 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java @@ -3,7 +3,6 @@ import club.minnced.discord.webhook.send.WebhookEmbed; import club.minnced.discord.webhook.send.WebhookEmbedBuilder; import club.minnced.discord.webhook.send.WebhookMessageBuilder; -import club.minnced.discord.webhook.send.component.ComponentElement; import club.minnced.discord.webhook.send.component.button.Button; import club.minnced.discord.webhook.send.component.layout.ActionRow; import com.github.twitch4j.events.ChannelFollowCountUpdateEvent; @@ -24,8 +23,8 @@ import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; import java.awt.*; -import java.util.*; import java.util.List; +import java.util.*; @Slf4j public class TwitchSonic implements ISonic { @@ -37,9 +36,6 @@ public void load(List channelStats) { try { channelStats.stream().map(ChannelStats::getTwitchFollowerChannelUsername).filter(Objects::nonNull).forEach(this::add); load(); - - // Register the Event-handler. - run(); } catch (Exception exception) { log.error("Error while loading Twitch data: {}", exception.getMessage()); Sentry.captureException(exception); @@ -51,6 +47,8 @@ public void load() { // Register all Twitch Channels. SQLSession.getSqlConnector().getSqlWorker().getAllTwitchNames().subscribe(channel -> channel.forEach(this::add)); + // Register the Event-handler. + run(); } @Override diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index 3a3107d00..59563ed6a 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -272,6 +272,9 @@ public Notifier() { return null; }); + log.info("Initializing Spotify Client..."); + spotifySonic = new SpotifySonic(); + log.info("Initializing Streams..."); log.info("Creating YouTube Streams..."); @@ -315,7 +318,6 @@ public Notifier() { // Use 1 day instead of minutes, because Spotify release date is at max precise to the day log.info("Creating Spotify Streams..."); - spotifySonic = new SpotifySonic(); ThreadUtil.createThread(x -> spotifySonic.run(), x -> { log.error("Failed to run Spotify Stream!", x); Sentry.captureException(x); From e89815f64248232ef32ce704bb1b0fcde2e20db7 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 9 Oct 2024 15:19:37 +0200 Subject: [PATCH 52/94] Fix typos. Signed-off-by: Presti --- src/main/java/de/presti/ree6/main/Main.java | 2 +- .../presti/ree6/module/notifications/impl/SpotifySonic.java | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/de/presti/ree6/main/Main.java b/src/main/java/de/presti/ree6/main/Main.java index ce9e192c4..131be5d04 100644 --- a/src/main/java/de/presti/ree6/main/Main.java +++ b/src/main/java/de/presti/ree6/main/Main.java @@ -346,10 +346,10 @@ public static void main(String[] args) { getInstance().setNotifier(new Notifier()); if (BotConfig.isModuleActive("notifier")) { - getInstance().getNotifier().getSpotifySonic().load(); ThreadUtil.createThread(x -> { log.info("Loading Notifier data."); SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), "FROM ChannelStats", null).subscribe(channelStats -> { + getInstance().getNotifier().getSpotifySonic().load(channelStats); getInstance().getNotifier().getYouTubeSonic().load(channelStats); getInstance().getNotifier().getTwitchSonic().load(channelStats); getInstance().getNotifier().getInstagramSonic().load(channelStats); diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java index 6747552ca..cd6fae9b1 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java @@ -12,6 +12,7 @@ import de.presti.ree6.sql.entities.stats.ChannelStats; import de.presti.ree6.sql.entities.webhook.WebhookSpotify; import de.presti.ree6.utils.apis.SpotifyAPIHandler; +import io.sentry.Sentry; import lombok.extern.slf4j.Slf4j; import se.michaelthelin.spotify.model_objects.specification.AlbumSimplified; import se.michaelthelin.spotify.model_objects.specification.ArtistSimplified; @@ -34,12 +35,13 @@ public class SpotifySonic implements ISonic { @Override public void load(List channelStats) { + load(); // No need for this. } @Override public void load() { - // Register all YouTube channels. + // Register all Spotify artists and podcasts. SQLSession.getSqlConnector().getSqlWorker().getEntityList(new WebhookSpotify(), "FROM WebhookSpotify", Map.of()).subscribe(spotifyNotify -> { spotifyNotify.forEach(x -> { if (x.getEntityTyp() == 0) { @@ -101,6 +103,7 @@ public void run() { } } } catch (Exception exception) { + Sentry.captureException(exception); // TODO:: handle this shit } } From 61e8612a6dedd9dda9f6400eac4eb8b91766e953 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 9 Oct 2024 15:21:18 +0200 Subject: [PATCH 53/94] Bump Signed-off-by: Presti --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 62f7a6eba..74bd273ec 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ de.presti Ree6 - 4.0.0 + 4.0.0-alpha.1 jar From b0bc2bc67321e47ca64bfae0fb00f2ec344aea07 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 9 Oct 2024 15:42:30 +0200 Subject: [PATCH 54/94] Big refactor. Signed-off-by: Presti --- .../de/presti/ree6/bot/util/WebhookUtil.java | 2 +- .../impl/community/StreamActionCommand.java | 4 ++-- .../presti/ree6/commands/impl/fun/Game.java | 11 +++++----- .../commands/impl/hidden/Announcement.java | 8 +++----- .../ree6/commands/interfaces/ICommand.java | 3 +-- .../de/presti/ree6/events/CustomEvents.java | 3 +-- .../de/presti/ree6/events/GameEvents.java | 8 ++++---- .../de/presti/ree6/events/LoggingEvents.java | 12 +++++------ src/main/java/de/presti/ree6/main/Main.java | 8 ++++---- .../{ => module}/actions/ActionEvent.java | 2 +- .../ree6/{ => module}/actions/ActionInfo.java | 2 +- .../actions/ActionRunContainer.java | 2 +- .../ree6/{ => module}/actions/IAction.java | 2 +- .../customevents/CustomEventActionEvent.java | 4 ++-- .../actions/customevents/IEventAction.java | 6 +++--- .../container/CustomEventContainer.java | 8 ++++---- .../CustomEventContainerCreator.java | 6 +++--- .../actions/streamtools/IStreamAction.java | 6 +++--- .../streamtools/StreamActionEvent.java | 5 ++--- .../action/PlayBlerpStreamAction.java | 8 ++++---- .../action/PlayTTSStreamAction.java | 8 ++++---- .../action/PlayUrlStreamAction.java | 8 ++++---- .../streamtools/action/SayStreamAction.java | 8 ++++---- .../action/VoiceJoinStreamAction.java | 8 ++++---- .../action/VoiceLeaveStreamAction.java | 8 ++++---- .../container/StreamActionContainer.java | 8 ++++---- .../StreamActionContainerCreator.java | 9 ++++----- .../{ => module}/game/core/GameManager.java | 10 +++++----- .../{ => module}/game/core/GameSession.java | 7 +++---- .../{ => module}/game/core/base/GameInfo.java | 2 +- .../game/core/base/GamePlayer.java | 2 +- .../game/core/base/GameState.java | 2 +- .../{ => module}/game/core/base/IGame.java | 4 ++-- .../game/impl/blackjack/Blackjack.java | 20 +++++++++---------- .../blackjack/entities/BlackJackCard.java | 2 +- .../blackjack/entities/BlackJackPlayer.java | 4 ++-- .../blackjack/util/BlackJackCardUtility.java | 4 ++-- .../game/impl/musicquiz/MusicQuiz.java | 18 ++++++++--------- .../musicquiz/entities/MusicQuizEntry.java | 2 +- .../musicquiz/entities/MusicQuizPlayer.java | 5 ++--- .../impl/musicquiz/util/MusicQuizUtil.java | 4 ++-- .../ree6/{ => module}/logger/LogMessage.java | 2 +- .../ree6/{ => module}/logger/LogTyp.java | 2 +- .../ree6/{ => module}/logger/LoggerQueue.java | 10 +++++----- .../logger/events/LogMessageMember.java | 6 +++--- .../logger/events/LogMessageRole.java | 6 +++--- .../logger/events/LogMessageUser.java | 6 +++--- .../logger/events/LogMessageVoice.java | 6 +++--- .../ree6/{ => module}/news/Announcement.java | 2 +- .../news/AnnouncementManager.java | 3 +-- .../de/presti/ree6/utils/apis/Notifier.java | 2 +- 51 files changed, 144 insertions(+), 154 deletions(-) rename src/main/java/de/presti/ree6/{ => module}/actions/ActionEvent.java (91%) rename src/main/java/de/presti/ree6/{ => module}/actions/ActionInfo.java (95%) rename src/main/java/de/presti/ree6/{ => module}/actions/ActionRunContainer.java (91%) rename src/main/java/de/presti/ree6/{ => module}/actions/IAction.java (89%) rename src/main/java/de/presti/ree6/{ => module}/actions/customevents/CustomEventActionEvent.java (88%) rename src/main/java/de/presti/ree6/{ => module}/actions/customevents/IEventAction.java (81%) rename src/main/java/de/presti/ree6/{ => module}/actions/customevents/container/CustomEventContainer.java (91%) rename src/main/java/de/presti/ree6/{ => module}/actions/customevents/container/CustomEventContainerCreator.java (94%) rename src/main/java/de/presti/ree6/{ => module}/actions/streamtools/IStreamAction.java (88%) rename src/main/java/de/presti/ree6/{ => module}/actions/streamtools/StreamActionEvent.java (88%) rename src/main/java/de/presti/ree6/{ => module}/actions/streamtools/action/PlayBlerpStreamAction.java (89%) rename src/main/java/de/presti/ree6/{ => module}/actions/streamtools/action/PlayTTSStreamAction.java (86%) rename src/main/java/de/presti/ree6/{ => module}/actions/streamtools/action/PlayUrlStreamAction.java (78%) rename src/main/java/de/presti/ree6/{ => module}/actions/streamtools/action/SayStreamAction.java (83%) rename src/main/java/de/presti/ree6/{ => module}/actions/streamtools/action/VoiceJoinStreamAction.java (87%) rename src/main/java/de/presti/ree6/{ => module}/actions/streamtools/action/VoiceLeaveStreamAction.java (76%) rename src/main/java/de/presti/ree6/{ => module}/actions/streamtools/container/StreamActionContainer.java (93%) rename src/main/java/de/presti/ree6/{ => module}/actions/streamtools/container/StreamActionContainerCreator.java (92%) rename src/main/java/de/presti/ree6/{ => module}/game/core/GameManager.java (96%) rename src/main/java/de/presti/ree6/{ => module}/game/core/GameSession.java (95%) rename src/main/java/de/presti/ree6/{ => module}/game/core/base/GameInfo.java (93%) rename src/main/java/de/presti/ree6/{ => module}/game/core/base/GamePlayer.java (97%) rename src/main/java/de/presti/ree6/{ => module}/game/core/base/GameState.java (82%) rename src/main/java/de/presti/ree6/{ => module}/game/core/base/IGame.java (96%) rename src/main/java/de/presti/ree6/{ => module}/game/impl/blackjack/Blackjack.java (96%) rename src/main/java/de/presti/ree6/{ => module}/game/impl/blackjack/entities/BlackJackCard.java (96%) rename src/main/java/de/presti/ree6/{ => module}/game/impl/blackjack/entities/BlackJackPlayer.java (96%) rename src/main/java/de/presti/ree6/{ => module}/game/impl/blackjack/util/BlackJackCardUtility.java (98%) rename src/main/java/de/presti/ree6/{ => module}/game/impl/musicquiz/MusicQuiz.java (96%) rename src/main/java/de/presti/ree6/{ => module}/game/impl/musicquiz/entities/MusicQuizEntry.java (98%) rename src/main/java/de/presti/ree6/{ => module}/game/impl/musicquiz/entities/MusicQuizPlayer.java (84%) rename src/main/java/de/presti/ree6/{ => module}/game/impl/musicquiz/util/MusicQuizUtil.java (97%) rename src/main/java/de/presti/ree6/{ => module}/logger/LogMessage.java (98%) rename src/main/java/de/presti/ree6/{ => module}/logger/LogTyp.java (97%) rename src/main/java/de/presti/ree6/{ => module}/logger/LoggerQueue.java (99%) rename src/main/java/de/presti/ree6/{ => module}/logger/events/LogMessageMember.java (98%) rename src/main/java/de/presti/ree6/{ => module}/logger/events/LogMessageRole.java (99%) rename src/main/java/de/presti/ree6/{ => module}/logger/events/LogMessageUser.java (89%) rename src/main/java/de/presti/ree6/{ => module}/logger/events/LogMessageVoice.java (96%) rename src/main/java/de/presti/ree6/{ => module}/news/Announcement.java (95%) rename src/main/java/de/presti/ree6/{ => module}/news/AnnouncementManager.java (97%) diff --git a/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java b/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java index 75aa9733d..f54d849ee 100644 --- a/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java +++ b/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java @@ -3,7 +3,7 @@ import club.minnced.discord.webhook.WebhookClient; import club.minnced.discord.webhook.send.WebhookMessage; import de.presti.ree6.bot.BotWorker; -import de.presti.ree6.logger.LogMessage; +import de.presti.ree6.module.logger.LogMessage; import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.webhook.*; diff --git a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java index f22d0aa35..de5fb6650 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java @@ -2,8 +2,8 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.streamtools.container.StreamActionContainer; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.container.StreamActionContainer; import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Game.java b/src/main/java/de/presti/ree6/commands/impl/fun/Game.java index 6ce727f04..c768acf72 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Game.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Game.java @@ -4,12 +4,11 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.game.core.GameManager; -import de.presti.ree6.game.core.GameSession; -import de.presti.ree6.game.core.base.GameInfo; -import de.presti.ree6.game.core.base.GamePlayer; -import de.presti.ree6.game.core.base.GameState; -import de.presti.ree6.language.LanguageService; +import de.presti.ree6.module.game.core.GameManager; +import de.presti.ree6.module.game.core.GameSession; +import de.presti.ree6.module.game.core.base.GameInfo; +import de.presti.ree6.module.game.core.base.GamePlayer; +import de.presti.ree6.module.game.core.base.GameState; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; diff --git a/src/main/java/de/presti/ree6/commands/impl/hidden/Announcement.java b/src/main/java/de/presti/ree6/commands/impl/hidden/Announcement.java index 00e9f52a1..242fa59f0 100644 --- a/src/main/java/de/presti/ree6/commands/impl/hidden/Announcement.java +++ b/src/main/java/de/presti/ree6/commands/impl/hidden/Announcement.java @@ -4,9 +4,7 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.news.AnnouncementManager; -import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.module.news.AnnouncementManager; import de.presti.ree6.utils.others.RandomUtils; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; @@ -41,8 +39,8 @@ public void onPerform(CommandEvent commandEvent) { OptionMapping toDeleteId = commandEvent.getOption("id"); if (title != null && content != null) { - de.presti.ree6.news.Announcement announcement = - new de.presti.ree6.news.Announcement(RandomUtils.randomString(16, false), title.getAsString(), + de.presti.ree6.module.news.Announcement announcement = + new de.presti.ree6.module.news.Announcement(RandomUtils.randomString(16, false), title.getAsString(), content.getAsString()); AnnouncementManager.addAnnouncement(announcement); diff --git a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java index ce93a4d38..67a158b64 100644 --- a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java +++ b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java @@ -5,7 +5,7 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; -import de.presti.ree6.news.AnnouncementManager; +import de.presti.ree6.module.news.AnnouncementManager; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Setting; import io.sentry.Sentry; @@ -15,7 +15,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; -import reactor.core.scheduler.Schedulers; import java.util.Optional; import java.util.concurrent.CompletableFuture; diff --git a/src/main/java/de/presti/ree6/events/CustomEvents.java b/src/main/java/de/presti/ree6/events/CustomEvents.java index 9487955b8..c158ab225 100644 --- a/src/main/java/de/presti/ree6/events/CustomEvents.java +++ b/src/main/java/de/presti/ree6/events/CustomEvents.java @@ -1,11 +1,10 @@ package de.presti.ree6.events; -import de.presti.ree6.actions.customevents.container.CustomEventContainer; +import de.presti.ree6.module.actions.customevents.container.CustomEventContainer; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.custom.CustomEventAction; import de.presti.ree6.sql.entities.custom.CustomEventTyp; import de.presti.ree6.utils.data.CustomEventMapper; -import de.presti.ree6.utils.others.ThreadUtil; import net.dv8tion.jda.api.events.GenericEvent; import net.dv8tion.jda.api.events.guild.GenericGuildEvent; import net.dv8tion.jda.api.events.message.GenericMessageEvent; diff --git a/src/main/java/de/presti/ree6/events/GameEvents.java b/src/main/java/de/presti/ree6/events/GameEvents.java index 068a1bda0..e810113e0 100644 --- a/src/main/java/de/presti/ree6/events/GameEvents.java +++ b/src/main/java/de/presti/ree6/events/GameEvents.java @@ -1,9 +1,9 @@ package de.presti.ree6.events; -import de.presti.ree6.game.core.GameManager; -import de.presti.ree6.game.core.GameSession; -import de.presti.ree6.game.core.base.GamePlayer; -import de.presti.ree6.game.core.base.GameState; +import de.presti.ree6.module.game.core.GameManager; +import de.presti.ree6.module.game.core.GameSession; +import de.presti.ree6.module.game.core.base.GamePlayer; +import de.presti.ree6.module.game.core.base.GameState; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.react.GenericMessageReactionEvent; diff --git a/src/main/java/de/presti/ree6/events/LoggingEvents.java b/src/main/java/de/presti/ree6/events/LoggingEvents.java index adbb9ebb5..b6bb3903c 100644 --- a/src/main/java/de/presti/ree6/events/LoggingEvents.java +++ b/src/main/java/de/presti/ree6/events/LoggingEvents.java @@ -5,12 +5,12 @@ import club.minnced.discord.webhook.send.WebhookMessageBuilder; import de.presti.ree6.bot.BotConfig; import de.presti.ree6.language.LanguageService; -import de.presti.ree6.logger.LogMessage; -import de.presti.ree6.logger.LogTyp; -import de.presti.ree6.logger.events.LogMessageMember; -import de.presti.ree6.logger.events.LogMessageRole; -import de.presti.ree6.logger.events.LogMessageUser; -import de.presti.ree6.logger.events.LogMessageVoice; +import de.presti.ree6.module.logger.LogMessage; +import de.presti.ree6.module.logger.LogTyp; +import de.presti.ree6.module.logger.events.LogMessageMember; +import de.presti.ree6.module.logger.events.LogMessageRole; +import de.presti.ree6.module.logger.events.LogMessageUser; +import de.presti.ree6.module.logger.events.LogMessageVoice; import de.presti.ree6.main.Main; import de.presti.ree6.module.invite.InviteContainer; import de.presti.ree6.sql.SQLSession; diff --git a/src/main/java/de/presti/ree6/main/Main.java b/src/main/java/de/presti/ree6/main/Main.java index 131be5d04..37e9888da 100644 --- a/src/main/java/de/presti/ree6/main/Main.java +++ b/src/main/java/de/presti/ree6/main/Main.java @@ -5,7 +5,7 @@ import com.github.philippheuer.credentialmanager.domain.OAuth2Credential; import com.github.twitch4j.pubsub.PubSubSubscription; import com.google.gson.JsonObject; -import de.presti.ree6.actions.streamtools.container.StreamActionContainerCreator; +import de.presti.ree6.module.actions.streamtools.container.StreamActionContainerCreator; import de.presti.ree6.addons.ReePluginManager; import de.presti.ree6.audio.music.MusicWorker; import de.presti.ree6.bot.BotConfig; @@ -17,10 +17,10 @@ import de.presti.ree6.commands.exceptions.CommandInitializerException; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.events.*; -import de.presti.ree6.game.core.GameManager; -import de.presti.ree6.game.impl.musicquiz.util.MusicQuizUtil; +import de.presti.ree6.module.game.core.GameManager; +import de.presti.ree6.module.game.impl.musicquiz.util.MusicQuizUtil; import de.presti.ree6.language.LanguageService; -import de.presti.ree6.logger.LoggerQueue; +import de.presti.ree6.module.logger.LoggerQueue; import de.presti.ree6.module.giveaway.GiveawayManager; import de.presti.ree6.module.invite.InviteContainerManager; import de.presti.ree6.sql.DatabaseTyp; diff --git a/src/main/java/de/presti/ree6/actions/ActionEvent.java b/src/main/java/de/presti/ree6/module/actions/ActionEvent.java similarity index 91% rename from src/main/java/de/presti/ree6/actions/ActionEvent.java rename to src/main/java/de/presti/ree6/module/actions/ActionEvent.java index de018c9de..2ca8ace5b 100644 --- a/src/main/java/de/presti/ree6/actions/ActionEvent.java +++ b/src/main/java/de/presti/ree6/module/actions/ActionEvent.java @@ -1,4 +1,4 @@ -package de.presti.ree6.actions; +package de.presti.ree6.module.actions; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/src/main/java/de/presti/ree6/actions/ActionInfo.java b/src/main/java/de/presti/ree6/module/actions/ActionInfo.java similarity index 95% rename from src/main/java/de/presti/ree6/actions/ActionInfo.java rename to src/main/java/de/presti/ree6/module/actions/ActionInfo.java index ee24945ed..cf2812d4c 100644 --- a/src/main/java/de/presti/ree6/actions/ActionInfo.java +++ b/src/main/java/de/presti/ree6/module/actions/ActionInfo.java @@ -1,4 +1,4 @@ -package de.presti.ree6.actions; +package de.presti.ree6.module.actions; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/java/de/presti/ree6/actions/ActionRunContainer.java b/src/main/java/de/presti/ree6/module/actions/ActionRunContainer.java similarity index 91% rename from src/main/java/de/presti/ree6/actions/ActionRunContainer.java rename to src/main/java/de/presti/ree6/module/actions/ActionRunContainer.java index 01698f1ce..6f0477d5b 100644 --- a/src/main/java/de/presti/ree6/actions/ActionRunContainer.java +++ b/src/main/java/de/presti/ree6/module/actions/ActionRunContainer.java @@ -1,4 +1,4 @@ -package de.presti.ree6.actions; +package de.presti.ree6.module.actions; import lombok.AccessLevel; import lombok.AllArgsConstructor; diff --git a/src/main/java/de/presti/ree6/actions/IAction.java b/src/main/java/de/presti/ree6/module/actions/IAction.java similarity index 89% rename from src/main/java/de/presti/ree6/actions/IAction.java rename to src/main/java/de/presti/ree6/module/actions/IAction.java index 423258deb..f6f70c5b0 100644 --- a/src/main/java/de/presti/ree6/actions/IAction.java +++ b/src/main/java/de/presti/ree6/module/actions/IAction.java @@ -1,4 +1,4 @@ -package de.presti.ree6.actions; +package de.presti.ree6.module.actions; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/de/presti/ree6/actions/customevents/CustomEventActionEvent.java b/src/main/java/de/presti/ree6/module/actions/customevents/CustomEventActionEvent.java similarity index 88% rename from src/main/java/de/presti/ree6/actions/customevents/CustomEventActionEvent.java rename to src/main/java/de/presti/ree6/module/actions/customevents/CustomEventActionEvent.java index 659d1fb67..20f05452f 100644 --- a/src/main/java/de/presti/ree6/actions/customevents/CustomEventActionEvent.java +++ b/src/main/java/de/presti/ree6/module/actions/customevents/CustomEventActionEvent.java @@ -1,6 +1,6 @@ -package de.presti.ree6.actions.customevents; +package de.presti.ree6.module.actions.customevents; -import de.presti.ree6.actions.ActionEvent; +import de.presti.ree6.module.actions.ActionEvent; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; diff --git a/src/main/java/de/presti/ree6/actions/customevents/IEventAction.java b/src/main/java/de/presti/ree6/module/actions/customevents/IEventAction.java similarity index 81% rename from src/main/java/de/presti/ree6/actions/customevents/IEventAction.java rename to src/main/java/de/presti/ree6/module/actions/customevents/IEventAction.java index 0b092117e..fe9968c0c 100644 --- a/src/main/java/de/presti/ree6/actions/customevents/IEventAction.java +++ b/src/main/java/de/presti/ree6/module/actions/customevents/IEventAction.java @@ -1,7 +1,7 @@ -package de.presti.ree6.actions.customevents; +package de.presti.ree6.module.actions.customevents; -import de.presti.ree6.actions.ActionEvent; -import de.presti.ree6.actions.IAction; +import de.presti.ree6.module.actions.ActionEvent; +import de.presti.ree6.module.actions.IAction; import org.jetbrains.annotations.NotNull; /** diff --git a/src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainer.java b/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainer.java similarity index 91% rename from src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainer.java rename to src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainer.java index cc29d8df2..b2c3cd5f0 100644 --- a/src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainer.java +++ b/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainer.java @@ -1,11 +1,11 @@ -package de.presti.ree6.actions.customevents.container; +package de.presti.ree6.module.actions.customevents.container; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import de.presti.ree6.actions.ActionRunContainer; -import de.presti.ree6.actions.customevents.CustomEventActionEvent; -import de.presti.ree6.actions.customevents.IEventAction; +import de.presti.ree6.module.actions.ActionRunContainer; +import de.presti.ree6.module.actions.customevents.CustomEventActionEvent; +import de.presti.ree6.module.actions.customevents.IEventAction; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.sql.entities.custom.CustomEventAction; import lombok.AccessLevel; diff --git a/src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainerCreator.java b/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java similarity index 94% rename from src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainerCreator.java rename to src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java index d38e84a19..f6607659d 100644 --- a/src/main/java/de/presti/ree6/actions/customevents/container/CustomEventContainerCreator.java +++ b/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java @@ -1,7 +1,7 @@ -package de.presti.ree6.actions.customevents.container; +package de.presti.ree6.module.actions.customevents.container; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.customevents.IEventAction; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.customevents.IEventAction; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.custom.CustomEventAction; import de.presti.ree6.sql.entities.custom.CustomEventTyp; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/IStreamAction.java b/src/main/java/de/presti/ree6/module/actions/streamtools/IStreamAction.java similarity index 88% rename from src/main/java/de/presti/ree6/actions/streamtools/IStreamAction.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/IStreamAction.java index 52f3c8907..d5fcd2cfe 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/IStreamAction.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/IStreamAction.java @@ -1,8 +1,8 @@ -package de.presti.ree6.actions.streamtools; +package de.presti.ree6.module.actions.streamtools; import com.github.twitch4j.common.events.TwitchEvent; -import de.presti.ree6.actions.ActionEvent; -import de.presti.ree6.actions.IAction; +import de.presti.ree6.module.actions.ActionEvent; +import de.presti.ree6.module.actions.IAction; import net.dv8tion.jda.api.entities.Guild; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/StreamActionEvent.java b/src/main/java/de/presti/ree6/module/actions/streamtools/StreamActionEvent.java similarity index 88% rename from src/main/java/de/presti/ree6/actions/streamtools/StreamActionEvent.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/StreamActionEvent.java index c0619c821..4aed81384 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/StreamActionEvent.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/StreamActionEvent.java @@ -1,8 +1,7 @@ -package de.presti.ree6.actions.streamtools; +package de.presti.ree6.module.actions.streamtools; import com.github.philippheuer.events4j.core.domain.Event; -import com.github.twitch4j.common.events.TwitchEvent; -import de.presti.ree6.actions.ActionEvent; +import de.presti.ree6.module.actions.ActionEvent; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/action/PlayBlerpStreamAction.java b/src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayBlerpStreamAction.java similarity index 89% rename from src/main/java/de/presti/ree6/actions/streamtools/action/PlayBlerpStreamAction.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayBlerpStreamAction.java index 05167b7c7..1e5e5b81b 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/action/PlayBlerpStreamAction.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayBlerpStreamAction.java @@ -1,9 +1,9 @@ -package de.presti.ree6.actions.streamtools.action; +package de.presti.ree6.module.actions.streamtools.action; import com.github.twitch4j.pubsub.events.RewardRedeemedEvent; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.streamtools.IStreamAction; -import de.presti.ree6.actions.streamtools.StreamActionEvent; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.IStreamAction; +import de.presti.ree6.module.actions.streamtools.StreamActionEvent; import de.presti.ree6.main.Main; import de.presti.ree6.utils.data.RegExUtil; import de.presti.ree6.utils.external.RequestUtility; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/action/PlayTTSStreamAction.java b/src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayTTSStreamAction.java similarity index 86% rename from src/main/java/de/presti/ree6/actions/streamtools/action/PlayTTSStreamAction.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayTTSStreamAction.java index 9f1c279da..53bd66ccb 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/action/PlayTTSStreamAction.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayTTSStreamAction.java @@ -1,8 +1,8 @@ -package de.presti.ree6.actions.streamtools.action; +package de.presti.ree6.module.actions.streamtools.action; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.streamtools.IStreamAction; -import de.presti.ree6.actions.streamtools.StreamActionEvent; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.IStreamAction; +import de.presti.ree6.module.actions.streamtools.StreamActionEvent; import de.presti.ree6.main.Main; import lombok.NoArgsConstructor; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/action/PlayUrlStreamAction.java b/src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayUrlStreamAction.java similarity index 78% rename from src/main/java/de/presti/ree6/actions/streamtools/action/PlayUrlStreamAction.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayUrlStreamAction.java index 8f0c7a5a0..1d54bee31 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/action/PlayUrlStreamAction.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/action/PlayUrlStreamAction.java @@ -1,8 +1,8 @@ -package de.presti.ree6.actions.streamtools.action; +package de.presti.ree6.module.actions.streamtools.action; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.streamtools.IStreamAction; -import de.presti.ree6.actions.streamtools.StreamActionEvent; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.IStreamAction; +import de.presti.ree6.module.actions.streamtools.StreamActionEvent; import de.presti.ree6.main.Main; import lombok.NoArgsConstructor; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/action/SayStreamAction.java b/src/main/java/de/presti/ree6/module/actions/streamtools/action/SayStreamAction.java similarity index 83% rename from src/main/java/de/presti/ree6/actions/streamtools/action/SayStreamAction.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/action/SayStreamAction.java index 04313aecc..4bae87958 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/action/SayStreamAction.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/action/SayStreamAction.java @@ -1,8 +1,8 @@ -package de.presti.ree6.actions.streamtools.action; +package de.presti.ree6.module.actions.streamtools.action; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.streamtools.IStreamAction; -import de.presti.ree6.actions.streamtools.StreamActionEvent; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.IStreamAction; +import de.presti.ree6.module.actions.streamtools.StreamActionEvent; import de.presti.ree6.main.Main; import lombok.NoArgsConstructor; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/action/VoiceJoinStreamAction.java b/src/main/java/de/presti/ree6/module/actions/streamtools/action/VoiceJoinStreamAction.java similarity index 87% rename from src/main/java/de/presti/ree6/actions/streamtools/action/VoiceJoinStreamAction.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/action/VoiceJoinStreamAction.java index 5b8ba08da..544ca90d2 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/action/VoiceJoinStreamAction.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/action/VoiceJoinStreamAction.java @@ -1,8 +1,8 @@ -package de.presti.ree6.actions.streamtools.action; +package de.presti.ree6.module.actions.streamtools.action; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.streamtools.IStreamAction; -import de.presti.ree6.actions.streamtools.StreamActionEvent; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.IStreamAction; +import de.presti.ree6.module.actions.streamtools.StreamActionEvent; import de.presti.ree6.main.Main; import io.sentry.Sentry; import lombok.NoArgsConstructor; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/action/VoiceLeaveStreamAction.java b/src/main/java/de/presti/ree6/module/actions/streamtools/action/VoiceLeaveStreamAction.java similarity index 76% rename from src/main/java/de/presti/ree6/actions/streamtools/action/VoiceLeaveStreamAction.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/action/VoiceLeaveStreamAction.java index f4cfa6569..5b606a769 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/action/VoiceLeaveStreamAction.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/action/VoiceLeaveStreamAction.java @@ -1,8 +1,8 @@ -package de.presti.ree6.actions.streamtools.action; +package de.presti.ree6.module.actions.streamtools.action; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.streamtools.IStreamAction; -import de.presti.ree6.actions.streamtools.StreamActionEvent; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.IStreamAction; +import de.presti.ree6.module.actions.streamtools.StreamActionEvent; import de.presti.ree6.main.Main; import lombok.NoArgsConstructor; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainer.java b/src/main/java/de/presti/ree6/module/actions/streamtools/container/StreamActionContainer.java similarity index 93% rename from src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainer.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/container/StreamActionContainer.java index 89d0a6c19..db4c9dba4 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainer.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/container/StreamActionContainer.java @@ -1,12 +1,12 @@ -package de.presti.ree6.actions.streamtools.container; +package de.presti.ree6.module.actions.streamtools.container; import com.github.philippheuer.events4j.core.domain.Event; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import de.presti.ree6.actions.ActionRunContainer; -import de.presti.ree6.actions.streamtools.IStreamAction; -import de.presti.ree6.actions.streamtools.StreamActionEvent; +import de.presti.ree6.module.actions.ActionRunContainer; +import de.presti.ree6.module.actions.streamtools.IStreamAction; +import de.presti.ree6.module.actions.streamtools.StreamActionEvent; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.sql.entities.StreamAction; import de.presti.ree6.utils.others.ThreadUtil; diff --git a/src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainerCreator.java b/src/main/java/de/presti/ree6/module/actions/streamtools/container/StreamActionContainerCreator.java similarity index 92% rename from src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainerCreator.java rename to src/main/java/de/presti/ree6/module/actions/streamtools/container/StreamActionContainerCreator.java index 10af29a83..6b84ee6c6 100644 --- a/src/main/java/de/presti/ree6/actions/streamtools/container/StreamActionContainerCreator.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/container/StreamActionContainerCreator.java @@ -1,8 +1,8 @@ -package de.presti.ree6.actions.streamtools.container; +package de.presti.ree6.module.actions.streamtools.container; -import de.presti.ree6.actions.ActionInfo; -import de.presti.ree6.actions.streamtools.IStreamAction; -import de.presti.ree6.actions.streamtools.action.*; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.IStreamAction; +import de.presti.ree6.module.actions.streamtools.action.*; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.StreamAction; import org.reflections.Reflections; @@ -14,7 +14,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.concurrent.CompletableFuture; /** * A Utility class used to create StreamActionContainers. diff --git a/src/main/java/de/presti/ree6/game/core/GameManager.java b/src/main/java/de/presti/ree6/module/game/core/GameManager.java similarity index 96% rename from src/main/java/de/presti/ree6/game/core/GameManager.java rename to src/main/java/de/presti/ree6/module/game/core/GameManager.java index c6725847f..21da79f08 100644 --- a/src/main/java/de/presti/ree6/game/core/GameManager.java +++ b/src/main/java/de/presti/ree6/module/game/core/GameManager.java @@ -1,7 +1,7 @@ -package de.presti.ree6.game.core; +package de.presti.ree6.module.game.core; -import de.presti.ree6.game.core.base.GameInfo; -import de.presti.ree6.game.core.base.IGame; +import de.presti.ree6.module.game.core.base.GameInfo; +import de.presti.ree6.module.game.core.base.IGame; import de.presti.ree6.utils.others.RandomUtils; import lombok.Getter; import lombok.extern.slf4j.Slf4j; @@ -37,7 +37,7 @@ public class GameManager { * Should be called to load all Games into the cache. */ public static void loadAllGames() { - Reflections reflections = new Reflections("de.presti.ree6.game.impl"); + Reflections reflections = new Reflections("de.presti.ree6.module.game.impl"); Set> classes = reflections.getSubTypesOf(IGame.class); for (Class aClass : classes) { @@ -99,7 +99,7 @@ public static IGame getGame(String gameName, GameSession gameSession) { } } - Reflections reflections = new Reflections("de.presti.ree6.game.impl"); + Reflections reflections = new Reflections("de.presti.ree6.module.game.impl"); Set> classes = reflections.getSubTypesOf(IGame.class); for (Class aClass : classes) { diff --git a/src/main/java/de/presti/ree6/game/core/GameSession.java b/src/main/java/de/presti/ree6/module/game/core/GameSession.java similarity index 95% rename from src/main/java/de/presti/ree6/game/core/GameSession.java rename to src/main/java/de/presti/ree6/module/game/core/GameSession.java index ae7a6522b..353991e89 100644 --- a/src/main/java/de/presti/ree6/game/core/GameSession.java +++ b/src/main/java/de/presti/ree6/module/game/core/GameSession.java @@ -1,13 +1,12 @@ -package de.presti.ree6.game.core; +package de.presti.ree6.module.game.core; -import de.presti.ree6.game.core.base.GameState; -import de.presti.ree6.game.core.base.IGame; +import de.presti.ree6.module.game.core.base.GameState; +import de.presti.ree6.module.game.core.base.IGame; import lombok.Getter; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.channel.unions.GuildMessageChannelUnion; -import net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion; import java.util.ArrayList; diff --git a/src/main/java/de/presti/ree6/game/core/base/GameInfo.java b/src/main/java/de/presti/ree6/module/game/core/base/GameInfo.java similarity index 93% rename from src/main/java/de/presti/ree6/game/core/base/GameInfo.java rename to src/main/java/de/presti/ree6/module/game/core/base/GameInfo.java index e233316ca..29dd09f79 100644 --- a/src/main/java/de/presti/ree6/game/core/base/GameInfo.java +++ b/src/main/java/de/presti/ree6/module/game/core/base/GameInfo.java @@ -1,4 +1,4 @@ -package de.presti.ree6.game.core.base; +package de.presti.ree6.module.game.core.base; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; diff --git a/src/main/java/de/presti/ree6/game/core/base/GamePlayer.java b/src/main/java/de/presti/ree6/module/game/core/base/GamePlayer.java similarity index 97% rename from src/main/java/de/presti/ree6/game/core/base/GamePlayer.java rename to src/main/java/de/presti/ree6/module/game/core/base/GamePlayer.java index bbd924d9a..5bb1466b6 100644 --- a/src/main/java/de/presti/ree6/game/core/base/GamePlayer.java +++ b/src/main/java/de/presti/ree6/module/game/core/base/GamePlayer.java @@ -1,4 +1,4 @@ -package de.presti.ree6.game.core.base; +package de.presti.ree6.module.game.core.base; import de.presti.ree6.bot.BotWorker; import lombok.Getter; diff --git a/src/main/java/de/presti/ree6/game/core/base/GameState.java b/src/main/java/de/presti/ree6/module/game/core/base/GameState.java similarity index 82% rename from src/main/java/de/presti/ree6/game/core/base/GameState.java rename to src/main/java/de/presti/ree6/module/game/core/base/GameState.java index 087e3f84e..32b16e387 100644 --- a/src/main/java/de/presti/ree6/game/core/base/GameState.java +++ b/src/main/java/de/presti/ree6/module/game/core/base/GameState.java @@ -1,4 +1,4 @@ -package de.presti.ree6.game.core.base; +package de.presti.ree6.module.game.core.base; /** * Enum used to store the current Game State. diff --git a/src/main/java/de/presti/ree6/game/core/base/IGame.java b/src/main/java/de/presti/ree6/module/game/core/base/IGame.java similarity index 96% rename from src/main/java/de/presti/ree6/game/core/base/IGame.java rename to src/main/java/de/presti/ree6/module/game/core/base/IGame.java index 1c0525595..392f14474 100644 --- a/src/main/java/de/presti/ree6/game/core/base/IGame.java +++ b/src/main/java/de/presti/ree6/module/game/core/base/IGame.java @@ -1,6 +1,6 @@ -package de.presti.ree6.game.core.base; +package de.presti.ree6.module.game.core.base; -import de.presti.ree6.game.core.GameSession; +import de.presti.ree6.module.game.core.GameSession; import de.presti.ree6.utils.data.EconomyUtil; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; diff --git a/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java b/src/main/java/de/presti/ree6/module/game/impl/blackjack/Blackjack.java similarity index 96% rename from src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java rename to src/main/java/de/presti/ree6/module/game/impl/blackjack/Blackjack.java index 0a5a9bcf2..bb4324dd3 100644 --- a/src/main/java/de/presti/ree6/game/impl/blackjack/Blackjack.java +++ b/src/main/java/de/presti/ree6/module/game/impl/blackjack/Blackjack.java @@ -1,15 +1,15 @@ -package de.presti.ree6.game.impl.blackjack; +package de.presti.ree6.module.game.impl.blackjack; import de.presti.ree6.bot.BotWorker; -import de.presti.ree6.game.core.GameManager; -import de.presti.ree6.game.core.GameSession; -import de.presti.ree6.game.core.base.GameInfo; -import de.presti.ree6.game.core.base.GamePlayer; -import de.presti.ree6.game.core.base.GameState; -import de.presti.ree6.game.core.base.IGame; -import de.presti.ree6.game.impl.blackjack.entities.BlackJackCard; -import de.presti.ree6.game.impl.blackjack.entities.BlackJackPlayer; -import de.presti.ree6.game.impl.blackjack.util.BlackJackCardUtility; +import de.presti.ree6.module.game.core.GameManager; +import de.presti.ree6.module.game.core.GameSession; +import de.presti.ree6.module.game.core.base.GameInfo; +import de.presti.ree6.module.game.core.base.GamePlayer; +import de.presti.ree6.module.game.core.base.GameState; +import de.presti.ree6.module.game.core.base.IGame; +import de.presti.ree6.module.game.impl.blackjack.entities.BlackJackCard; +import de.presti.ree6.module.game.impl.blackjack.entities.BlackJackPlayer; +import de.presti.ree6.module.game.impl.blackjack.util.BlackJackCardUtility; import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; diff --git a/src/main/java/de/presti/ree6/game/impl/blackjack/entities/BlackJackCard.java b/src/main/java/de/presti/ree6/module/game/impl/blackjack/entities/BlackJackCard.java similarity index 96% rename from src/main/java/de/presti/ree6/game/impl/blackjack/entities/BlackJackCard.java rename to src/main/java/de/presti/ree6/module/game/impl/blackjack/entities/BlackJackCard.java index 5a0948833..22d66f09b 100644 --- a/src/main/java/de/presti/ree6/game/impl/blackjack/entities/BlackJackCard.java +++ b/src/main/java/de/presti/ree6/module/game/impl/blackjack/entities/BlackJackCard.java @@ -1,4 +1,4 @@ -package de.presti.ree6.game.impl.blackjack.entities; +package de.presti.ree6.module.game.impl.blackjack.entities; import net.dv8tion.jda.api.entities.emoji.CustomEmoji; diff --git a/src/main/java/de/presti/ree6/game/impl/blackjack/entities/BlackJackPlayer.java b/src/main/java/de/presti/ree6/module/game/impl/blackjack/entities/BlackJackPlayer.java similarity index 96% rename from src/main/java/de/presti/ree6/game/impl/blackjack/entities/BlackJackPlayer.java rename to src/main/java/de/presti/ree6/module/game/impl/blackjack/entities/BlackJackPlayer.java index 7dbcbb359..14681d852 100644 --- a/src/main/java/de/presti/ree6/game/impl/blackjack/entities/BlackJackPlayer.java +++ b/src/main/java/de/presti/ree6/module/game/impl/blackjack/entities/BlackJackPlayer.java @@ -1,6 +1,6 @@ -package de.presti.ree6.game.impl.blackjack.entities; +package de.presti.ree6.module.game.impl.blackjack.entities; -import de.presti.ree6.game.core.base.GamePlayer; +import de.presti.ree6.module.game.core.base.GamePlayer; import net.dv8tion.jda.api.entities.User; import java.util.ArrayList; diff --git a/src/main/java/de/presti/ree6/game/impl/blackjack/util/BlackJackCardUtility.java b/src/main/java/de/presti/ree6/module/game/impl/blackjack/util/BlackJackCardUtility.java similarity index 98% rename from src/main/java/de/presti/ree6/game/impl/blackjack/util/BlackJackCardUtility.java rename to src/main/java/de/presti/ree6/module/game/impl/blackjack/util/BlackJackCardUtility.java index 91474d224..f44e5a86a 100644 --- a/src/main/java/de/presti/ree6/game/impl/blackjack/util/BlackJackCardUtility.java +++ b/src/main/java/de/presti/ree6/module/game/impl/blackjack/util/BlackJackCardUtility.java @@ -1,6 +1,6 @@ -package de.presti.ree6.game.impl.blackjack.util; +package de.presti.ree6.module.game.impl.blackjack.util; -import de.presti.ree6.game.impl.blackjack.entities.BlackJackCard; +import de.presti.ree6.module.game.impl.blackjack.entities.BlackJackCard; import de.presti.ree6.utils.others.RandomUtils; import net.dv8tion.jda.api.entities.emoji.Emoji; diff --git a/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/MusicQuiz.java similarity index 96% rename from src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java rename to src/main/java/de/presti/ree6/module/game/impl/musicquiz/MusicQuiz.java index 0997f46cc..7193238d8 100644 --- a/src/main/java/de/presti/ree6/game/impl/musicquiz/MusicQuiz.java +++ b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/MusicQuiz.java @@ -1,14 +1,14 @@ -package de.presti.ree6.game.impl.musicquiz; +package de.presti.ree6.module.game.impl.musicquiz; import de.presti.ree6.bot.BotWorker; -import de.presti.ree6.game.core.GameSession; -import de.presti.ree6.game.core.base.GameInfo; -import de.presti.ree6.game.core.base.GamePlayer; -import de.presti.ree6.game.core.base.GameState; -import de.presti.ree6.game.core.base.IGame; -import de.presti.ree6.game.impl.musicquiz.entities.MusicQuizEntry; -import de.presti.ree6.game.impl.musicquiz.entities.MusicQuizPlayer; -import de.presti.ree6.game.impl.musicquiz.util.MusicQuizUtil; +import de.presti.ree6.module.game.core.GameSession; +import de.presti.ree6.module.game.core.base.GameInfo; +import de.presti.ree6.module.game.core.base.GamePlayer; +import de.presti.ree6.module.game.core.base.GameState; +import de.presti.ree6.module.game.core.base.IGame; +import de.presti.ree6.module.game.impl.musicquiz.entities.MusicQuizEntry; +import de.presti.ree6.module.game.impl.musicquiz.entities.MusicQuizPlayer; +import de.presti.ree6.module.game.impl.musicquiz.util.MusicQuizUtil; import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; diff --git a/src/main/java/de/presti/ree6/game/impl/musicquiz/entities/MusicQuizEntry.java b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/entities/MusicQuizEntry.java similarity index 98% rename from src/main/java/de/presti/ree6/game/impl/musicquiz/entities/MusicQuizEntry.java rename to src/main/java/de/presti/ree6/module/game/impl/musicquiz/entities/MusicQuizEntry.java index 3d7430eb6..f795dd291 100644 --- a/src/main/java/de/presti/ree6/game/impl/musicquiz/entities/MusicQuizEntry.java +++ b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/entities/MusicQuizEntry.java @@ -1,4 +1,4 @@ -package de.presti.ree6.game.impl.musicquiz.entities; +package de.presti.ree6.module.game.impl.musicquiz.entities; import lombok.Getter; diff --git a/src/main/java/de/presti/ree6/game/impl/musicquiz/entities/MusicQuizPlayer.java b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/entities/MusicQuizPlayer.java similarity index 84% rename from src/main/java/de/presti/ree6/game/impl/musicquiz/entities/MusicQuizPlayer.java rename to src/main/java/de/presti/ree6/module/game/impl/musicquiz/entities/MusicQuizPlayer.java index 5338e622c..ef61bb966 100644 --- a/src/main/java/de/presti/ree6/game/impl/musicquiz/entities/MusicQuizPlayer.java +++ b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/entities/MusicQuizPlayer.java @@ -1,8 +1,7 @@ -package de.presti.ree6.game.impl.musicquiz.entities; +package de.presti.ree6.module.game.impl.musicquiz.entities; -import de.presti.ree6.game.core.base.GamePlayer; +import de.presti.ree6.module.game.core.base.GamePlayer; import lombok.Getter; -import net.dv8tion.jda.api.hooks.ListenerAdapter; /** * Class used to store information about a player in the music quiz game. diff --git a/src/main/java/de/presti/ree6/game/impl/musicquiz/util/MusicQuizUtil.java b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/util/MusicQuizUtil.java similarity index 97% rename from src/main/java/de/presti/ree6/game/impl/musicquiz/util/MusicQuizUtil.java rename to src/main/java/de/presti/ree6/module/game/impl/musicquiz/util/MusicQuizUtil.java index 42edee100..ec9c45132 100644 --- a/src/main/java/de/presti/ree6/game/impl/musicquiz/util/MusicQuizUtil.java +++ b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/util/MusicQuizUtil.java @@ -1,6 +1,6 @@ -package de.presti.ree6.game.impl.musicquiz.util; +package de.presti.ree6.module.game.impl.musicquiz.util; -import de.presti.ree6.game.impl.musicquiz.entities.MusicQuizEntry; +import de.presti.ree6.module.game.impl.musicquiz.entities.MusicQuizEntry; import de.presti.ree6.utils.apis.SpotifyAPIHandler; import de.presti.ree6.utils.apis.YouTubeAPIHandler; import de.presti.ree6.utils.others.RandomUtils; diff --git a/src/main/java/de/presti/ree6/logger/LogMessage.java b/src/main/java/de/presti/ree6/module/logger/LogMessage.java similarity index 98% rename from src/main/java/de/presti/ree6/logger/LogMessage.java rename to src/main/java/de/presti/ree6/module/logger/LogMessage.java index d54c3a17c..55ecfa6f7 100644 --- a/src/main/java/de/presti/ree6/logger/LogMessage.java +++ b/src/main/java/de/presti/ree6/module/logger/LogMessage.java @@ -1,4 +1,4 @@ -package de.presti.ree6.logger; +package de.presti.ree6.module.logger; import club.minnced.discord.webhook.send.WebhookMessage; import net.dv8tion.jda.api.entities.Guild; diff --git a/src/main/java/de/presti/ree6/logger/LogTyp.java b/src/main/java/de/presti/ree6/module/logger/LogTyp.java similarity index 97% rename from src/main/java/de/presti/ree6/logger/LogTyp.java rename to src/main/java/de/presti/ree6/module/logger/LogTyp.java index 8752dbdaa..4e6a9ec16 100644 --- a/src/main/java/de/presti/ree6/logger/LogTyp.java +++ b/src/main/java/de/presti/ree6/module/logger/LogTyp.java @@ -1,4 +1,4 @@ -package de.presti.ree6.logger; +package de.presti.ree6.module.logger; /** * The used Log-Types. diff --git a/src/main/java/de/presti/ree6/logger/LoggerQueue.java b/src/main/java/de/presti/ree6/module/logger/LoggerQueue.java similarity index 99% rename from src/main/java/de/presti/ree6/logger/LoggerQueue.java rename to src/main/java/de/presti/ree6/module/logger/LoggerQueue.java index c6459b4d4..a0e2b71e5 100644 --- a/src/main/java/de/presti/ree6/logger/LoggerQueue.java +++ b/src/main/java/de/presti/ree6/module/logger/LoggerQueue.java @@ -1,14 +1,14 @@ -package de.presti.ree6.logger; +package de.presti.ree6.module.logger; import club.minnced.discord.webhook.send.WebhookEmbed; import club.minnced.discord.webhook.send.WebhookEmbedBuilder; import club.minnced.discord.webhook.send.WebhookMessageBuilder; import de.presti.ree6.bot.util.WebhookUtil; import de.presti.ree6.language.LanguageService; -import de.presti.ree6.logger.events.LogMessageMember; -import de.presti.ree6.logger.events.LogMessageRole; -import de.presti.ree6.logger.events.LogMessageUser; -import de.presti.ree6.logger.events.LogMessageVoice; +import de.presti.ree6.module.logger.events.LogMessageMember; +import de.presti.ree6.module.logger.events.LogMessageRole; +import de.presti.ree6.module.logger.events.LogMessageUser; +import de.presti.ree6.module.logger.events.LogMessageVoice; import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.ThreadUtil; import net.dv8tion.jda.api.Permission; diff --git a/src/main/java/de/presti/ree6/logger/events/LogMessageMember.java b/src/main/java/de/presti/ree6/module/logger/events/LogMessageMember.java similarity index 98% rename from src/main/java/de/presti/ree6/logger/events/LogMessageMember.java rename to src/main/java/de/presti/ree6/module/logger/events/LogMessageMember.java index bea7787ea..dad949d30 100644 --- a/src/main/java/de/presti/ree6/logger/events/LogMessageMember.java +++ b/src/main/java/de/presti/ree6/module/logger/events/LogMessageMember.java @@ -1,8 +1,8 @@ -package de.presti.ree6.logger.events; +package de.presti.ree6.module.logger.events; import club.minnced.discord.webhook.send.WebhookMessage; -import de.presti.ree6.logger.LogMessage; -import de.presti.ree6.logger.LogTyp; +import de.presti.ree6.module.logger.LogMessage; +import de.presti.ree6.module.logger.LogTyp; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Role; diff --git a/src/main/java/de/presti/ree6/logger/events/LogMessageRole.java b/src/main/java/de/presti/ree6/module/logger/events/LogMessageRole.java similarity index 99% rename from src/main/java/de/presti/ree6/logger/events/LogMessageRole.java rename to src/main/java/de/presti/ree6/module/logger/events/LogMessageRole.java index f0d94e40a..251f8e385 100644 --- a/src/main/java/de/presti/ree6/logger/events/LogMessageRole.java +++ b/src/main/java/de/presti/ree6/module/logger/events/LogMessageRole.java @@ -1,8 +1,8 @@ -package de.presti.ree6.logger.events; +package de.presti.ree6.module.logger.events; import club.minnced.discord.webhook.send.WebhookMessage; -import de.presti.ree6.logger.LogMessage; -import de.presti.ree6.logger.LogTyp; +import de.presti.ree6.module.logger.LogMessage; +import de.presti.ree6.module.logger.LogTyp; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Role; diff --git a/src/main/java/de/presti/ree6/logger/events/LogMessageUser.java b/src/main/java/de/presti/ree6/module/logger/events/LogMessageUser.java similarity index 89% rename from src/main/java/de/presti/ree6/logger/events/LogMessageUser.java rename to src/main/java/de/presti/ree6/module/logger/events/LogMessageUser.java index bf011fc8f..1272a4571 100644 --- a/src/main/java/de/presti/ree6/logger/events/LogMessageUser.java +++ b/src/main/java/de/presti/ree6/module/logger/events/LogMessageUser.java @@ -1,8 +1,8 @@ -package de.presti.ree6.logger.events; +package de.presti.ree6.module.logger.events; import club.minnced.discord.webhook.send.WebhookMessage; -import de.presti.ree6.logger.LogMessage; -import de.presti.ree6.logger.LogTyp; +import de.presti.ree6.module.logger.LogMessage; +import de.presti.ree6.module.logger.LogTyp; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.User; diff --git a/src/main/java/de/presti/ree6/logger/events/LogMessageVoice.java b/src/main/java/de/presti/ree6/module/logger/events/LogMessageVoice.java similarity index 96% rename from src/main/java/de/presti/ree6/logger/events/LogMessageVoice.java rename to src/main/java/de/presti/ree6/module/logger/events/LogMessageVoice.java index b38dda8d8..82caf869f 100644 --- a/src/main/java/de/presti/ree6/logger/events/LogMessageVoice.java +++ b/src/main/java/de/presti/ree6/module/logger/events/LogMessageVoice.java @@ -1,8 +1,8 @@ -package de.presti.ree6.logger.events; +package de.presti.ree6.module.logger.events; import club.minnced.discord.webhook.send.WebhookMessage; -import de.presti.ree6.logger.LogMessage; -import de.presti.ree6.logger.LogTyp; +import de.presti.ree6.module.logger.LogMessage; +import de.presti.ree6.module.logger.LogTyp; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.channel.middleman.AudioChannel; diff --git a/src/main/java/de/presti/ree6/news/Announcement.java b/src/main/java/de/presti/ree6/module/news/Announcement.java similarity index 95% rename from src/main/java/de/presti/ree6/news/Announcement.java rename to src/main/java/de/presti/ree6/module/news/Announcement.java index 7a9094446..2b1d1dfd4 100644 --- a/src/main/java/de/presti/ree6/news/Announcement.java +++ b/src/main/java/de/presti/ree6/module/news/Announcement.java @@ -1,4 +1,4 @@ -package de.presti.ree6.news; +package de.presti.ree6.module.news; /** * Announcement entity class to store information about an announcement. diff --git a/src/main/java/de/presti/ree6/news/AnnouncementManager.java b/src/main/java/de/presti/ree6/module/news/AnnouncementManager.java similarity index 97% rename from src/main/java/de/presti/ree6/news/AnnouncementManager.java rename to src/main/java/de/presti/ree6/module/news/AnnouncementManager.java index 13606d088..4387ec864 100644 --- a/src/main/java/de/presti/ree6/news/AnnouncementManager.java +++ b/src/main/java/de/presti/ree6/module/news/AnnouncementManager.java @@ -1,7 +1,6 @@ -package de.presti.ree6.news; +package de.presti.ree6.module.news; import de.presti.ree6.bot.BotConfig; -import lombok.AccessLevel; import lombok.Getter; import java.util.ArrayList; diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index 59563ed6a..9556b8959 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -13,7 +13,7 @@ import com.github.twitch4j.eventsub.events.ChannelSubscribeEvent; import com.github.twitch4j.pubsub.PubSubSubscription; import com.github.twitch4j.pubsub.events.RewardRedeemedEvent; -import de.presti.ree6.actions.streamtools.container.StreamActionContainerCreator; +import de.presti.ree6.module.actions.streamtools.container.StreamActionContainerCreator; import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.main.Main; From 4797d32f8fc342df6be59c1554ff555a0221269c Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 9 Oct 2024 16:44:54 +0200 Subject: [PATCH 55/94] Fix. Signed-off-by: Presti --- .../de/presti/ree6/commands/impl/community/Birthday.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java b/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java index 506796516..33490e779 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.sql.SQLSession; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; @@ -18,8 +17,7 @@ import java.text.DecimalFormat; import java.text.NumberFormat; -import java.time.Instant; -import java.time.temporal.ChronoField; +import java.util.Calendar; /** * This command is used to let the bot remember your Birthday. @@ -107,7 +105,7 @@ public CommandData getCommandData() { new SubcommandData("add", "Add a Birthday entry!") .addOptions(new OptionData(OptionType.INTEGER, "day", "The day of the month.", true).setMinValue(1).setMaxValue(31), new OptionData(OptionType.INTEGER, "month", "Your birth month.", true).setMinValue(1).setMaxValue(12), - new OptionData(OptionType.INTEGER, "year", "Your birth year.", false).setMinValue(1900).setMaxValue(Instant.now().get(ChronoField.YEAR)), + new OptionData(OptionType.INTEGER, "year", "Your birth year.", false).setMinValue(1900).setMaxValue(Calendar.getInstance().get(Calendar.YEAR)), new OptionData(OptionType.USER, "user", "The User which should get their birthday entry added.", false))); } From 25d2cdcd1f7d1fdf7b43365b47c99ec253859e1b Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 13:58:21 +0200 Subject: [PATCH 56/94] V4 Userapp (#655) Adding support for Userapps. --- pom.xml | 4 +- .../de/presti/ree6/commands/Category.java | 70 ++++++------------- .../de/presti/ree6/commands/CommandEvent.java | 8 +++ .../presti/ree6/commands/CommandManager.java | 43 +++++++++--- .../presti/ree6/commands/impl/fun/Anime.java | 10 +-- .../presti/ree6/commands/impl/fun/Cringe.java | 4 +- .../presti/ree6/commands/impl/fun/Game.java | 2 +- .../ree6/commands/impl/fun/HornyJail.java | 13 ++-- .../de/presti/ree6/commands/impl/fun/Hug.java | 16 +++-- .../presti/ree6/commands/impl/fun/Kiss.java | 16 +++-- .../presti/ree6/commands/impl/fun/Manga.java | 5 +- .../commands/impl/fun/PremiumCommand.java | 2 +- .../presti/ree6/commands/impl/fun/Record.java | 8 +-- .../ree6/commands/impl/fun/ShibaImage.java | 6 +- .../presti/ree6/commands/impl/fun/Slap.java | 16 +++-- .../ree6/commands/impl/fun/Twitter.java | 18 +++-- .../presti/ree6/commands/impl/info/Stats.java | 2 +- .../ree6/commands/interfaces/Command.java | 6 ++ .../ree6/commands/interfaces/ICommand.java | 4 +- .../presti/ree6/language/LanguageService.java | 4 +- src/main/java/de/presti/ree6/main/Main.java | 14 ++-- .../presti/ree6/utils/others/GuildUtil.java | 3 + 22 files changed, 158 insertions(+), 116 deletions(-) diff --git a/pom.xml b/pom.xml index 74bd273ec..326782eab 100644 --- a/pom.xml +++ b/pom.xml @@ -56,9 +56,9 @@ - net.dv8tion + io.github.JDA-Fork JDA - 5.1.2 + 55d824408c diff --git a/src/main/java/de/presti/ree6/commands/Category.java b/src/main/java/de/presti/ree6/commands/Category.java index b8de7dd43..6405c8a17 100644 --- a/src/main/java/de/presti/ree6/commands/Category.java +++ b/src/main/java/de/presti/ree6/commands/Category.java @@ -1,46 +1,49 @@ package de.presti.ree6.commands; +import lombok.Getter; + /** * Different Categories for the commands. */ +@Getter public enum Category { /** - * Category used for informativ Commands. + * Category used for information Commands. */ - INFO("re_icon_info", 1019221661070917632L, false, "category.info"), + INFO("re_icon_info", 1019221661070917632L, false, "category.info", true), /** - * Category used for moderativ Commands. + * Category used for moderate Commands. */ - MOD("re_icon_mod", 1019221710932803624L, false, "category.moderation"), + MOD("re_icon_mod", 1019221710932803624L, false, "category.moderation", true), /** * Category used for music Commands. */ - MUSIC("re_icon_music", 1019221781762023575L, false, "category.music"), + MUSIC("re_icon_music", 1019221781762023575L, false, "category.music", true), /** * Category used for fun Commands. */ - FUN("re_icon_fun", 1019221814670532628L, false, "category.fun"), + FUN("re_icon_fun", 1019221814670532628L, false, "category.fun", false), /** * Category used for level Commands. */ - LEVEL("re_icon_level", 1019221845972635809L, false, "category.level"), + LEVEL("re_icon_level", 1019221845972635809L, false, "category.level", true), /** * Category used for community Commands. */ - COMMUNITY("re_icon_community", 1019221884686057552L, false, "category.community"), + COMMUNITY("re_icon_community", 1019221884686057552L, false, "category.community", true), /** * Category used for economy Commands. */ - ECONOMY("re_icon_economy", 0L, false, "category.economy"), + ECONOMY("re_icon_economy", 0L, false, "category.economy", true), /** * Category used for NSFW Commands. */ - NSFW("re_icon_nsfw", 1019221923466584166L, false, "category.nsfw"), + NSFW("re_icon_nsfw", 1019221923466584166L, false, "category.nsfw", false), /** * Category used for admin Commands. */ - HIDDEN("re_icon_hidden", 1019221957817933865L, false, "category.hidden"); + HIDDEN("re_icon_hidden", 1019221957817933865L, false, "category.hidden", true); /** * The Name of the Icon. @@ -62,6 +65,11 @@ public enum Category { */ private final String description; + /** + * Value for knowledge about the Command being Guild only or not. + */ + private final boolean guildOnly; + /** * Constructor. * @@ -69,47 +77,13 @@ public enum Category { * @param iconId the Icon ID. * @param iconAnimated the info if the Icon is animated. * @param description a short description. + * @param guildOnly the info if the Command is Guild only. */ - Category(String icon, long iconId, boolean iconAnimated, String description) { + Category(String icon, long iconId, boolean iconAnimated, String description, boolean guildOnly) { this.icon = icon; this.iconId = iconId; this.iconAnimated = iconAnimated; this.description = description; - } - - /** - * The Icon Name for the Category. - * - * @return the Name. - */ - public String getIcon() { - return icon; - } - - /** - * The Icon ID for the Category. - * - * @return the Icon ID. - */ - public long getIconId() { - return iconId; - } - - /** - * The Information if the Icon is animated. - * - * @return true, if yes | false, if not. - */ - public boolean isIconAnimated() { - return iconAnimated; - } - - /** - * Short description of the Category. - * - * @return the short description. - */ - public String getDescription() { - return description; + this.guildOnly = guildOnly; } } diff --git a/src/main/java/de/presti/ree6/commands/CommandEvent.java b/src/main/java/de/presti/ree6/commands/CommandEvent.java index f60c49851..905e5d39d 100644 --- a/src/main/java/de/presti/ree6/commands/CommandEvent.java +++ b/src/main/java/de/presti/ree6/commands/CommandEvent.java @@ -227,6 +227,14 @@ public boolean isBotOwner() { return BotConfig.getBotOwner().equals(member.getId()); } + /** + * Check if the command event is run via App-Command. + * @return true, if it has been run via App-Command. + */ + public boolean isDetached() { + return getGuild().isDetached(); + } + /** * Get the {@link Guild} Entity associated with the Event. * diff --git a/src/main/java/de/presti/ree6/commands/CommandManager.java b/src/main/java/de/presti/ree6/commands/CommandManager.java index f4fc2b0a2..f74b7d13f 100644 --- a/src/main/java/de/presti/ree6/commands/CommandManager.java +++ b/src/main/java/de/presti/ree6/commands/CommandManager.java @@ -27,6 +27,7 @@ import net.dv8tion.jda.api.entities.channel.unions.GuildMessageChannelUnion; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.DiscordLocale; +import net.dv8tion.jda.api.interactions.IntegrationType; import net.dv8tion.jda.api.interactions.InteractionHook; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -210,6 +211,16 @@ public void addSlashCommand(JDA jda) { commandData.setNSFW(true); } + if (commandAnnotation.category().isGuildOnly()) { + commandData.setIntegrationTypes(IntegrationType.GUILD_INSTALL); + } else { + if (commandAnnotation.allowAppInstall()) { + commandData.setIntegrationTypes(IntegrationType.ALL); + } else { + commandData.setIntegrationTypes(IntegrationType.GUILD_INSTALL); + } + } + if (commandData instanceof CommandDataImpl commandData1) { boolean isValidDescription = commandAnnotation.description().matches(RegExUtil.ALLOWED_LANGUAGE_PATHS); @@ -370,6 +381,10 @@ public void removeCommand(ICommand command) { public Mono perform(Member member, Guild guild, String messageContent, Message message, GuildMessageChannelUnion messageChannel, SlashCommandInteractionEvent slashCommandInteractionEvent) { boolean isSlashCommand = slashCommandInteractionEvent != null; + if (!isSlashCommand && guild.isDetached()) { + return Mono.just(false); + } + if (BotConfig.isDebug()) log.info("Called perform"); @@ -565,17 +580,27 @@ private Mono performSlashCommand(GuildMessageChannelUnion messageChanne return Mono.just(false); } - return SQLSession.getSqlConnector().getSqlWorker().getSetting(slashCommandInteractionEvent.getGuild().getIdLong(), "command_" + command.getClass().getAnnotation(Command.class).name().toLowerCase()).publishOn(Schedulers.boundedElastic()).mapNotNull(setting -> { - if (command.getClass().getAnnotation(Command.class).category() != Category.HIDDEN && setting.isPresent() && !setting.get().getBooleanValue()) { - sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.blocked").block(), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); - return false; - } + Command annotation = command.getClass().getAnnotation(Command.class); - CommandEvent commandEvent = new CommandEvent(command.getClass().getAnnotation(Command.class).name(), slashCommandInteractionEvent.getMember(), slashCommandInteractionEvent.getGuild(), null, messageChannel, null, slashCommandInteractionEvent); + Guild guild = slashCommandInteractionEvent.getGuild(); - // Perform the Command. - return command.onMonoPerform(commandEvent).block(); - }); + if (!annotation.allowAppInstall() && guild.isDetached()) return Mono.just(false); + + CommandEvent commandEvent = new CommandEvent(annotation.name(), slashCommandInteractionEvent.getMember(), guild, null, messageChannel, null, slashCommandInteractionEvent); + + if (guild.isDetached()) { + return command.onMonoPerform(commandEvent); + } else { + return SQLSession.getSqlConnector().getSqlWorker().getSetting(slashCommandInteractionEvent.getGuild().getIdLong(), "command_" + annotation.name().toLowerCase()).publishOn(Schedulers.boundedElastic()).mapNotNull(setting -> { + if (annotation.category() != Category.HIDDEN && setting.isPresent() && !setting.get().getBooleanValue()) { + sendMessage(LanguageService.getByGuild(slashCommandInteractionEvent.getGuild(), "command.perform.blocked").block(), 5, null, slashCommandInteractionEvent.getHook().setEphemeral(true)); + return false; + } + + // Perform the Command. + return command.onMonoPerform(commandEvent).block(); + }); + } } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java b/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java index 1f77d24d6..8bf6e06b6 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java @@ -3,13 +3,12 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Message; @@ -61,9 +60,10 @@ public void onPerform(CommandEvent commandEvent) { /** * Send the anime to the channel. + * * @param commandEvent the CommandEvent. - * @param message the Message. - * @param query the query. + * @param message the Message. + * @param query the query. */ public void sendAnime(CommandEvent commandEvent, Message message, String query) { RequestUtility.Request request = RequestUtility.Request.builder() @@ -141,7 +141,7 @@ public void sendAnime(CommandEvent commandEvent, Message message, String query) em.addField(":trophy: **" + commandEvent.getResource("label.rank") + "**", "**TOP " + rank + "**", true); em.setFooter(commandEvent.getMember().getEffectiveName() + " - " + BotConfig.getAdvertisement(), commandEvent.getMember().getEffectiveAvatarUrl()); - if (commandEvent.isSlashCommand()) { + if (commandEvent.isSlashCommand() && !commandEvent.isDetached()) { message.editMessage(commandEvent.getResource("message.anime.found")).queue(); Main.getInstance().getCommandManager().sendMessage(em, commandEvent.getChannel(), null); } else { diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Cringe.java b/src/main/java/de/presti/ree6/commands/impl/fun/Cringe.java index d42c9f301..4d134239a 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Cringe.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Cringe.java @@ -4,15 +4,13 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.internal.interactions.CommandDataImpl; /** * A command to let the bot response to the last Message with a cringe Image. */ -@Command(name = "cringe", description = "command.description.cringe", category = Category.FUN) +@Command(name = "cringe", description = "command.description.cringe", category = Category.FUN, allowAppInstall = false) public class Cringe implements ICommand { /** diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Game.java b/src/main/java/de/presti/ree6/commands/impl/fun/Game.java index c768acf72..da3d2ef41 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Game.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Game.java @@ -22,7 +22,7 @@ /** * Command used to access the Game System. */ -@Command(name = "game", description = "command.description.game", category = Category.FUN) +@Command(name = "game", description = "command.description.game", category = Category.FUN, allowAppInstall = false) public class Game implements ICommand { /** diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/HornyJail.java b/src/main/java/de/presti/ree6/commands/impl/fun/HornyJail.java index 4ed524cca..6bdd8b5c1 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/HornyJail.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/HornyJail.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.utils.data.ImageCreationUtility; import net.dv8tion.jda.api.entities.Member; @@ -74,9 +73,15 @@ public void sendHornyJail(Member member, CommandEvent commandEvent) { try { MessageCreateBuilder createBuilder = new MessageCreateBuilder(); createBuilder.addFiles(FileUpload.fromData(ImageCreationUtility.createHornyJailImage(member.getUser()), "hornyjail.png")); - Main.getInstance().getCommandManager().sendMessage(commandEvent.getResource("message.hornyJail", member.getAsMention()), commandEvent.getChannel(), commandEvent.getInteractionHook()); - commandEvent.getChannel().sendMessage(createBuilder.build()).queue(); - if (commandEvent.isSlashCommand()) commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + String messageContent = commandEvent.getResource("message.hornyJail", member.getAsMention()); + if (commandEvent.isDetached()) { + createBuilder.setContent(messageContent); + commandEvent.reply(createBuilder.build()); + } else { + Main.getInstance().getCommandManager().sendMessage(messageContent, commandEvent.getChannel(), commandEvent.getInteractionHook()); + commandEvent.getChannel().sendMessage(createBuilder.build()).queue(); + if (commandEvent.isSlashCommand()) commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + } } catch (Exception ex) { Main.getInstance().getCommandManager().sendMessage(commandEvent.getResource("command.perform.error"), commandEvent.getChannel(), commandEvent.getInteractionHook()); log.error("Error while sending Horny-jail!", ex); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Hug.java b/src/main/java/de/presti/ree6/commands/impl/fun/Hug.java index 913c6f251..0da6b4e89 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Hug.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Hug.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.utils.apis.Neko4JsAPI; import net.dv8tion.jda.api.entities.Member; @@ -12,6 +11,7 @@ import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.interactions.commands.build.OptionData; +import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import net.dv8tion.jda.internal.interactions.CommandDataImpl; import pw.aru.api.nekos4j.image.Image; import pw.aru.api.nekos4j.image.ImageProvider; @@ -72,7 +72,6 @@ public String[] getAlias() { * @param commandEvent The CommandEvent. */ public void sendHug(Member member, CommandEvent commandEvent) { - Main.getInstance().getCommandManager().sendMessage(commandEvent.getResource("message.hug", member.getAsMention(), commandEvent.getMember().getAsMention()), commandEvent.getChannel(), null); ImageProvider ip = Neko4JsAPI.imageAPI.getImageProvider(); @@ -82,8 +81,17 @@ public void sendHug(Member member, CommandEvent commandEvent) { } catch (Exception ignored) { } - Main.getInstance().getCommandManager().sendMessage((im != null ? im.getUrl() : "https://images.ree6.de/notfound.png"), commandEvent.getChannel(), null); - if (commandEvent.isSlashCommand()) commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + if (!commandEvent.isDetached()) { + Main.getInstance().getCommandManager().sendMessage(commandEvent.getResource("message.hug", member.getAsMention(), commandEvent.getMember().getAsMention()), commandEvent.getChannel(), null); + + Main.getInstance().getCommandManager().sendMessage((im != null ? im.getUrl() : "https://images.ree6.de/notfound.png"), commandEvent.getChannel(), null); + if (commandEvent.isSlashCommand()) + commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + } else { + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); + messageCreateBuilder.setContent(commandEvent.getResource("message.hug", member.getAsMention(), commandEvent.getMember().getAsMention()) + "\n" + (im != null ? im.getUrl() : "https://images.ree6.de/notfound.png")); + commandEvent.reply(messageCreateBuilder.build()); + } } } diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Kiss.java b/src/main/java/de/presti/ree6/commands/impl/fun/Kiss.java index 1da4e09ac..9d3bb8bea 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Kiss.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Kiss.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.utils.apis.Neko4JsAPI; import net.dv8tion.jda.api.entities.Member; @@ -12,6 +11,7 @@ import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.interactions.commands.build.OptionData; +import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import net.dv8tion.jda.internal.interactions.CommandDataImpl; import pw.aru.api.nekos4j.image.Image; import pw.aru.api.nekos4j.image.ImageProvider; @@ -72,7 +72,6 @@ public String[] getAlias() { * @param commandEvent The command event. */ public void sendKiss(Member member, CommandEvent commandEvent) { - Main.getInstance().getCommandManager().sendMessage(commandEvent.getResource("message.kiss", member.getAsMention(), commandEvent.getMember().getAsMention()), commandEvent.getChannel(), null); ImageProvider ip = Neko4JsAPI.imageAPI.getImageProvider(); @@ -82,7 +81,16 @@ public void sendKiss(Member member, CommandEvent commandEvent) { } catch (Exception ignored) { } - Main.getInstance().getCommandManager().sendMessage((im != null ? im.getUrl() : "https://images.ree6.de/notfound.png"), commandEvent.getChannel(), null); - if (commandEvent.isSlashCommand()) commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + if (!commandEvent.isDetached()) { + Main.getInstance().getCommandManager().sendMessage(commandEvent.getResource("message.kiss", member.getAsMention(), commandEvent.getMember().getAsMention()), commandEvent.getChannel(), null); + + Main.getInstance().getCommandManager().sendMessage(im != null ? im.getUrl() : "https://images.ree6.de/notfound.png", commandEvent.getChannel(), null); + if (commandEvent.isSlashCommand()) + commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + } else { + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); + messageCreateBuilder.setContent(commandEvent.getResource("message.kiss", member.getAsMention(), commandEvent.getMember().getAsMention()) + "\n" + (im != null ? im.getUrl() : "https://images.ree6.de/notfound.png")); + commandEvent.reply(messageCreateBuilder.build()); + } } } diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java b/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java index e5cbadd06..884586c0f 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java @@ -3,13 +3,12 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Message; @@ -141,7 +140,7 @@ public void sendManga(CommandEvent commandEvent, Message message, String query) em.addField(":trophy: **" + commandEvent.getResource("label.rank") + "**", "**TOP " + rank + "**", true); em.setFooter(commandEvent.getMember().getEffectiveName() + " - " + BotConfig.getAdvertisement(), commandEvent.getMember().getEffectiveAvatarUrl()); - if (commandEvent.isSlashCommand()) { + if (commandEvent.isSlashCommand() && !commandEvent.isDetached()) { message.editMessage(commandEvent.getResource("message.manga.found")).queue(); Main.getInstance().getCommandManager().sendMessage(em, commandEvent.getChannel(), null); } else { diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/PremiumCommand.java b/src/main/java/de/presti/ree6/commands/impl/fun/PremiumCommand.java index 724bcaa4d..87c083b69 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/PremiumCommand.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/PremiumCommand.java @@ -14,7 +14,7 @@ public class PremiumCommand implements ICommand { @Override public void onPerform(CommandEvent commandEvent) { - if (GuildUtil.isSupporter(commandEvent.getMember().getUser())) { + if (GuildUtil.isSupporter(commandEvent.getUser())) { commandEvent.setEphemeral(false); commandEvent.reply("Thank you for helping with funding Ree6 " + commandEvent.getMember().getAsMention() + "!"); } else { diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Record.java b/src/main/java/de/presti/ree6/commands/impl/fun/Record.java index 19994dd86..99f8134e4 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Record.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Record.java @@ -6,20 +6,18 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; -import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.GuildVoiceState; import net.dv8tion.jda.api.entities.channel.ChannelType; -import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel; import net.dv8tion.jda.api.entities.channel.unions.AudioChannelUnion; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.managers.AudioManager; +import net.dv8tion.jda.internal.interactions.CommandDataImpl; /** * A command used to record the conversation of a voice channel. */ -@Command(name = "record", description = "command.description.record", category = Category.FUN) +@Command(name = "record", description = "command.description.record", category = Category.FUN, allowAppInstall = false) public class Record implements ICommand { /** @@ -86,7 +84,7 @@ public void connectAndRecord(CommandEvent commandEvent) { */ @Override public CommandData getCommandData() { - return null; + return new CommandDataImpl("record", "command.description.record"); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/ShibaImage.java b/src/main/java/de/presti/ree6/commands/impl/fun/ShibaImage.java index d85c6cd56..ac5f8ef29 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/ShibaImage.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/ShibaImage.java @@ -2,13 +2,12 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -39,8 +38,7 @@ public void onPerform(CommandEvent commandEvent) { em.setColor(BotWorker.randomEmbedColor()); em.setImage(js.get(0).getAsString()); em.setFooter(commandEvent.getResource("label.footerMessage", commandEvent.getMember().getEffectiveName(), BotConfig.getAdvertisement()), commandEvent.getMember().getEffectiveAvatarUrl()); - - Main.getInstance().getCommandManager().sendMessage(em, commandEvent.getChannel(), commandEvent.getInteractionHook()); + commandEvent.reply(em.build()); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Slap.java b/src/main/java/de/presti/ree6/commands/impl/fun/Slap.java index 03a6af716..cb3dbd806 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Slap.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Slap.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.utils.apis.Neko4JsAPI; import net.dv8tion.jda.api.entities.Member; @@ -12,6 +11,7 @@ import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.interactions.commands.build.OptionData; +import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import net.dv8tion.jda.internal.interactions.CommandDataImpl; import pw.aru.api.nekos4j.image.Image; import pw.aru.api.nekos4j.image.ImageProvider; @@ -72,8 +72,6 @@ public String[] getAlias() { * @param commandEvent The CommandEvent. */ public void sendSlap(Member member, CommandEvent commandEvent) { - Main.getInstance().getCommandManager().sendMessage(commandEvent.getResource("message.slap", member.getAsMention(), commandEvent.getMember().getAsMention()), commandEvent.getChannel(), null); - ImageProvider ip = Neko4JsAPI.imageAPI.getImageProvider(); Image im = null; @@ -83,7 +81,15 @@ public void sendSlap(Member member, CommandEvent commandEvent) { log.error("Failed to get Image from Neko4J API!", exception); } - Main.getInstance().getCommandManager().sendMessage((im != null ? im.getUrl() : "https://images.ree6.de/notfound.png"), commandEvent.getChannel(), null); - if (commandEvent.isSlashCommand()) commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + if (!commandEvent.isDetached()) { + Main.getInstance().getCommandManager().sendMessage(commandEvent.getResource("message.slap", member.getAsMention(), commandEvent.getMember().getAsMention()), commandEvent.getChannel(), null); + Main.getInstance().getCommandManager().sendMessage(im != null ? im.getUrl() : "https://images.ree6.de/notfound.png", commandEvent.getChannel(), null); + if (commandEvent.isSlashCommand()) + commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + } else { + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); + messageCreateBuilder.setContent(commandEvent.getResource("message.slap", member.getAsMention(), commandEvent.getMember().getAsMention()) + "\n" + (im != null ? im.getUrl() : "https://images.ree6.de/notfound.png")); + commandEvent.reply(messageCreateBuilder.build()); + } } } diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Twitter.java b/src/main/java/de/presti/ree6/commands/impl/fun/Twitter.java index 19d2edc4a..98f142d3b 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Twitter.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Twitter.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.interactions.commands.OptionMapping; @@ -61,7 +60,7 @@ public void onPerform(CommandEvent commandEvent) { sendTwitterTweet(commandEvent.getMessage().getMentions().getMembers().get(0), stringBuilder.toString(), commandEvent); } } else { - commandEvent.reply(commandEvent.getResource("message.default.usage","twitter @User Yourtexthere"), 5); + commandEvent.reply(commandEvent.getResource("message.default.usage", "twitter @User Yourtexthere"), 5); } } } @@ -86,8 +85,9 @@ public String[] getAlias() { /** * The method to create the Tweet. - * @param member The Member that should tweet. - * @param content The content of the Tweet. + * + * @param member The Member that should tweet. + * @param content The content of the Tweet. * @param commandEvent The CommandEvent. */ public void sendTwitterTweet(Member member, String content, CommandEvent commandEvent) { @@ -102,10 +102,14 @@ public void sendTwitterTweet(Member member, String content, CommandEvent command MessageCreateBuilder createBuilder = new MessageCreateBuilder(); createBuilder.addFiles(FileUpload.fromData(response.getEntity().getContent().readAllBytes(), "twitter.png")); - commandEvent.getChannel().sendMessage(createBuilder.build()).queue(); + if (!commandEvent.isDetached()) { + commandEvent.getChannel().sendMessage(createBuilder.build()).queue(); - if (commandEvent.isSlashCommand()) - commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + if (commandEvent.isSlashCommand()) + commandEvent.getInteractionHook().sendMessage(commandEvent.getResource("message.default.checkBelow")).queue(); + } else { + commandEvent.reply(createBuilder.build()); + } } catch (Exception ex) { commandEvent.reply(commandEvent.getResource("message.perform.error")); log.error("An error occurred while creating a Tweet!", ex); diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java index f673a7d6d..4a21b0e6e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java @@ -99,7 +99,7 @@ public void onPerform(CommandEvent commandEvent) { if (BotConfig.isDebug()) { em.addField("**DEV ONLY**", "", true); em.addField("**Compute Time**", computeTime + "ms", true); - em.addField("**DEV ONLY**", "", true); + em.addField("**App Installs**", "" + BotWorker.getShardManager().retrieveApplicationInfo().complete().getUserInstallCount(), true); } messageEditBuilder.setEmbeds(em.build()); diff --git a/src/main/java/de/presti/ree6/commands/interfaces/Command.java b/src/main/java/de/presti/ree6/commands/interfaces/Command.java index ad2c37e6d..b6e52639e 100644 --- a/src/main/java/de/presti/ree6/commands/interfaces/Command.java +++ b/src/main/java/de/presti/ree6/commands/interfaces/Command.java @@ -34,4 +34,10 @@ * @return retrieve the category of the Command. */ Category category(); + + /** + * Allow a command to be used as app command. + * @return if the command is allowed to be used via command. + */ + boolean allowAppInstall() default true; } diff --git a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java index 67a158b64..cd26b705b 100644 --- a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java +++ b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java @@ -31,7 +31,7 @@ public interface ICommand extends ExtensionPoint { default Mono onMonoPerform(CommandEvent commandEvent) { if (BotConfig.isDebug()) - log.info("Command {} called by {} in {} ({}).", commandEvent.getCommand(), commandEvent.getMember().getUser().getName(), commandEvent.getGuild().getName(), commandEvent.getGuild().getId()); + log.info("Command {} called by {} in {} ({}).", commandEvent.getCommand(), commandEvent.getUser().getName(), commandEvent.getGuild().getName(), commandEvent.getGuild().getId()); return Mono.fromRunnable(() -> onPerformWithLog(commandEvent)).thenReturn(true).onErrorResume(throwable -> { if (!throwable.getMessage().contains("Unknown Message")) { @@ -41,6 +41,7 @@ default Mono onMonoPerform(CommandEvent commandEvent) { } return Mono.just(false); }).doOnSuccess(success -> { + if (commandEvent.getGuild().isDetached()) return; if (BotConfig.isDebug()) log.info("Updating Stats {} in {} ({}).", commandEvent.getCommand(), commandEvent.getGuild().getName(), commandEvent.getGuild().getId()); // Update Stats. @@ -77,6 +78,7 @@ default void onASyncPerform(CommandEvent commandEvent) { } return null; }); + if (commandEvent.getGuild().isDetached()) return; // Update Stats. SQLSession.getSqlConnector().getSqlWorker().addStats(commandEvent.getGuild().getIdLong(), commandEvent.getCommand()); diff --git a/src/main/java/de/presti/ree6/language/LanguageService.java b/src/main/java/de/presti/ree6/language/LanguageService.java index 1c18dc85e..6730412a5 100644 --- a/src/main/java/de/presti/ree6/language/LanguageService.java +++ b/src/main/java/de/presti/ree6/language/LanguageService.java @@ -36,7 +36,7 @@ public class LanguageService { /** - * A Hashmap containing the locale as key and the YamlConfiguration as value. + * A Hashmap containing the locale as a key and the YamlConfiguration as value. */ public static final HashMap languageResources = new HashMap<>(); @@ -226,7 +226,7 @@ public static void downloadLanguages() { * @return The String. */ public static @NotNull Mono getByGuild(Guild guild, @NotNull String key, @Nullable Object... parameter) { - return getByGuild(guild != null ? guild.getIdLong() : -1, key, parameter); + return getByGuild(guild != null && !guild.isDetached() ? guild.getIdLong() : -1, key, parameter); } /** diff --git a/src/main/java/de/presti/ree6/main/Main.java b/src/main/java/de/presti/ree6/main/Main.java index 37e9888da..7f8043c94 100644 --- a/src/main/java/de/presti/ree6/main/Main.java +++ b/src/main/java/de/presti/ree6/main/Main.java @@ -5,7 +5,6 @@ import com.github.philippheuer.credentialmanager.domain.OAuth2Credential; import com.github.twitch4j.pubsub.PubSubSubscription; import com.google.gson.JsonObject; -import de.presti.ree6.module.actions.streamtools.container.StreamActionContainerCreator; import de.presti.ree6.addons.ReePluginManager; import de.presti.ree6.audio.music.MusicWorker; import de.presti.ree6.bot.BotConfig; @@ -17,12 +16,13 @@ import de.presti.ree6.commands.exceptions.CommandInitializerException; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.events.*; +import de.presti.ree6.language.LanguageService; +import de.presti.ree6.module.actions.streamtools.container.StreamActionContainerCreator; import de.presti.ree6.module.game.core.GameManager; import de.presti.ree6.module.game.impl.musicquiz.util.MusicQuizUtil; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.module.logger.LoggerQueue; import de.presti.ree6.module.giveaway.GiveawayManager; import de.presti.ree6.module.invite.InviteContainerManager; +import de.presti.ree6.module.logger.LoggerQueue; import de.presti.ree6.sql.DatabaseTyp; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Giveaway; @@ -398,10 +398,10 @@ public static void main(String[] args) { log.info("Any previous messages about \"Error executing DDL\" can be most likely ignored."); log.info("Initialization finished."); log.info("Bot is ready to use."); - log.info("You are running on: v" + BotWorker.getBuild()); - log.info("You are running on: " + BotWorker.getShardManager().getShardsTotal() + " Shards."); - log.info("You are running on: " + BotWorker.getShardManager().getGuilds().size() + " Guilds."); - log.info("You are running on: " + BotWorker.getShardManager().getUsers().size() + " Users."); + log.info("You are running on: v{}", BotWorker.getBuild()); + log.info("You are running on: {} Shards.", BotWorker.getShardManager().getShardsTotal()); + log.info("You are running on: {} Guilds.", BotWorker.getShardManager().getGuilds().size()); + log.info("You are running on: {} Users.", BotWorker.getShardManager().getUsers().size()); log.info("Have fun!"); } diff --git a/src/main/java/de/presti/ree6/utils/others/GuildUtil.java b/src/main/java/de/presti/ree6/utils/others/GuildUtil.java index 56fab2013..0d8e07284 100644 --- a/src/main/java/de/presti/ree6/utils/others/GuildUtil.java +++ b/src/main/java/de/presti/ree6/utils/others/GuildUtil.java @@ -1,5 +1,6 @@ package de.presti.ree6.utils.others; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.language.LanguageService; import de.presti.ree6.sql.SQLSession; @@ -246,6 +247,8 @@ public static List getManageableRoles(Guild guild) { * @return true if the User has supported Ree6 via Donations, false if not. */ public static boolean isSupporter(User member) { + if (member.getId().equalsIgnoreCase(BotConfig.getBotOwner())) return true; + if (!member.getJDA().retrieveEntitlements().excludeEnded(true).skuIds(1165934495447384144L).complete().isEmpty()) { return true; } From bb1fae0d5267efcb7855a62f33c6cc3c659a793c Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 15:57:37 +0200 Subject: [PATCH 57/94] Code clean up. Signed-off-by: Presti --- .../ree6/addons/YamlPluginDescriptorFinder.java | 2 +- .../presti/ree6/audio/AudioPlayerReceiveHandler.java | 12 +++++------- .../de/presti/ree6/audio/music/TrackScheduler.java | 1 - .../java/de/presti/ree6/commands/CommandManager.java | 3 ++- .../ree6/commands/impl/community/Giveaway.java | 1 - .../de/presti/ree6/commands/impl/hidden/Addon.java | 1 - .../de/presti/ree6/commands/impl/hidden/Test.java | 1 - .../de/presti/ree6/commands/impl/info/Avatar.java | 1 - .../java/de/presti/ree6/commands/impl/info/Help.java | 1 - .../java/de/presti/ree6/commands/impl/info/Info.java | 1 - .../de/presti/ree6/commands/impl/info/Stats.java | 1 - .../presti/ree6/commands/impl/level/LevelRole.java | 1 - .../java/de/presti/ree6/commands/impl/mod/Ban.java | 2 -- .../de/presti/ree6/commands/impl/mod/Blacklist.java | 1 - .../java/de/presti/ree6/commands/impl/mod/Clear.java | 2 -- .../presti/ree6/commands/impl/mod/EmbedSender.java | 1 - .../de/presti/ree6/commands/impl/mod/Import.java | 1 - .../java/de/presti/ree6/commands/impl/mod/Kick.java | 2 -- .../java/de/presti/ree6/commands/impl/mod/Mute.java | 2 -- .../de/presti/ree6/commands/impl/mod/Prefix.java | 1 - .../de/presti/ree6/commands/impl/mod/Suggestion.java | 1 - .../java/de/presti/ree6/commands/impl/mod/Unban.java | 2 -- .../de/presti/ree6/commands/impl/mod/Unmute.java | 2 -- .../de/presti/ree6/commands/impl/music/Play.java | 1 - .../de/presti/ree6/commands/impl/music/Seek.java | 1 - .../de/presti/ree6/commands/impl/music/Skip.java | 1 - .../de/presti/ree6/commands/impl/music/Volume.java | 1 - .../de/presti/ree6/commands/impl/nsfw/Rule34.java | 1 - src/main/java/de/presti/ree6/events/MenuEvents.java | 3 --- .../presti/ree6/module/giveaway/GiveawayManager.java | 1 - .../module/notifications/impl/InstagramSonic.java | 1 - .../java/de/presti/ree6/utils/data/EconomyUtil.java | 1 - .../de/presti/ree6/utils/oauth/CustomOAuth2Util.java | 2 +- .../de/presti/ree6/utils/others/ModerationUtil.java | 2 -- 34 files changed, 9 insertions(+), 49 deletions(-) diff --git a/src/main/java/de/presti/ree6/addons/YamlPluginDescriptorFinder.java b/src/main/java/de/presti/ree6/addons/YamlPluginDescriptorFinder.java index dbada1f1b..6b56a3dc4 100644 --- a/src/main/java/de/presti/ree6/addons/YamlPluginDescriptorFinder.java +++ b/src/main/java/de/presti/ree6/addons/YamlPluginDescriptorFinder.java @@ -63,7 +63,7 @@ protected YamlConfiguration readYaml(Path pluginPath) { } try (InputStream input = Files.newInputStream(yamlPath)) { - yamlConfiguration = YamlConfiguration.loadConfiguration(input); + yamlConfiguration = YamlConfiguration.loadConfiguration(() -> input); } catch (IOException e) { throw new PluginRuntimeException(e); } diff --git a/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java b/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java index 830d2dafe..c67144970 100644 --- a/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java +++ b/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java @@ -68,7 +68,6 @@ public class AudioPlayerReceiveHandler implements AudioReceiveHandler { /** * The first sent message which should be edited. */ - // TODO:: make this async one day, and thread safe. Message message; /** @@ -90,9 +89,8 @@ public AudioPlayerReceiveHandler(Member member, AudioChannelUnion audioChannelUn audioChannelUnion.asVoiceChannel().canTalk(); if (canTalk) { - LanguageService.getByGuild(member.getGuild(), "message.default.nameChangeFailed").subscribe(message -> { - audioChannelUnion.asGuildMessageChannel().sendMessage(message).queue(); - }); + LanguageService.getByGuild(member.getGuild(), "message.default.nameChangeFailed").subscribe(message -> + audioChannelUnion.asGuildMessageChannel().sendMessage(message).queue()); } return null; }).queue())); @@ -194,9 +192,9 @@ public void endReceiving() { Recording recording = new Recording(audioChannelUnion.getGuild().getIdLong(), audioChannelUnion.getIdLong(), creatorId, AudioUtil.convertPCMtoWAV(byteBuffer), JsonParser.parseString(new Gson().toJson(participants)).getAsJsonArray()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(recording).doOnError(x -> { - audioChannelUnion.asGuildMessageChannel().sendMessage(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.error", "Upload failed").block()).setFiles(FileUpload.fromData(recording.getRecording(), "recording.wav")); - }).subscribe(newRecording -> { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(recording).doOnError(x -> + audioChannelUnion.asGuildMessageChannel().sendMessage(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.error", "Upload failed").block()).setFiles(FileUpload.fromData(recording.getRecording(), "recording.wav"))) + .subscribe(newRecording -> { if (canTalk) { message.editMessageEmbeds(new EmbedBuilder() .setDescription(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.stopped").block()) diff --git a/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java b/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java index cd7e72d3a..9051f0c3d 100644 --- a/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java +++ b/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java @@ -16,7 +16,6 @@ import lombok.extern.slf4j.Slf4j; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.channel.unions.GuildMessageChannelUnion; -import net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion; import net.dv8tion.jda.api.interactions.InteractionHook; import java.awt.*; diff --git a/src/main/java/de/presti/ree6/commands/CommandManager.java b/src/main/java/de/presti/ree6/commands/CommandManager.java index f74b7d13f..8656a4198 100644 --- a/src/main/java/de/presti/ree6/commands/CommandManager.java +++ b/src/main/java/de/presti/ree6/commands/CommandManager.java @@ -28,6 +28,7 @@ import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.DiscordLocale; import net.dv8tion.jda.api.interactions.IntegrationType; +import net.dv8tion.jda.api.interactions.InteractionContextType; import net.dv8tion.jda.api.interactions.InteractionHook; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -265,7 +266,7 @@ public void addSlashCommand(JDA jda) { commandData.setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.ADMINISTRATOR)); } - commandData.setGuildOnly(true); + commandData.setContexts(InteractionContextType.GUILD); //noinspection ResultOfMethodCallIgnored listUpdateAction.addCommands(commandData); diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java b/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java index 587cfd77f..9543df983 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Giveaway.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.utils.data.RegExUtil; diff --git a/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java b/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java index e9a3912f6..867cfe5a7 100644 --- a/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java +++ b/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java @@ -5,7 +5,6 @@ import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import io.sentry.Sentry; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.CommandData; diff --git a/src/main/java/de/presti/ree6/commands/impl/hidden/Test.java b/src/main/java/de/presti/ree6/commands/impl/hidden/Test.java index 4ef9bbf8c..caf2517f1 100644 --- a/src/main/java/de/presti/ree6/commands/impl/hidden/Test.java +++ b/src/main/java/de/presti/ree6/commands/impl/hidden/Test.java @@ -5,7 +5,6 @@ import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.utils.data.ArrayUtil; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.interactions.commands.build.CommandData; /** diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java b/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java index 50e61f901..32f4164b2 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java @@ -5,7 +5,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.utils.others.GuildUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.User; diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Help.java b/src/main/java/de/presti/ree6/commands/impl/info/Help.java index 5355e856e..d1ca27d33 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Help.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Help.java @@ -5,7 +5,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.bot.BotConfig; diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Info.java b/src/main/java/de/presti/ree6/commands/impl/info/Info.java index b96795217..2873a0a71 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Info.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Info.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.GuildUtil; import net.dv8tion.jda.api.EmbedBuilder; diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java index 4a21b0e6e..ff766b4d5 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java @@ -6,7 +6,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.stats.CommandStats; import de.presti.ree6.sql.entities.stats.GuildCommandStats; diff --git a/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java b/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java index 0dbef764d..19cee1c10 100644 --- a/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java +++ b/src/main/java/de/presti/ree6/commands/impl/level/LevelRole.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.sql.SQLSession; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Role; diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Ban.java b/src/main/java/de/presti/ree6/commands/impl/mod/Ban.java index cb6ff5846..0147ba78b 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Ban.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Ban.java @@ -4,8 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java b/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java index 8d32145bb..dcf1c38ba 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.main.Main; import de.presti.ree6.utils.others.ModerationUtil; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.interactions.commands.OptionMapping; diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Clear.java b/src/main/java/de/presti/ree6/commands/impl/mod/Clear.java index e39993e49..26abda5e3 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Clear.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Clear.java @@ -4,8 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; import net.dv8tion.jda.api.interactions.commands.OptionMapping; diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/EmbedSender.java b/src/main/java/de/presti/ree6/commands/impl/mod/EmbedSender.java index 9e85da08e..68fc9b49e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/EmbedSender.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/EmbedSender.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Import.java b/src/main/java/de/presti/ree6/commands/impl/mod/Import.java index 1f359b6b0..52415db62 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Import.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Import.java @@ -10,7 +10,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.level.ChatUserLevel; import de.presti.ree6.utils.apis.AmariAPI; diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Kick.java b/src/main/java/de/presti/ree6/commands/impl/mod/Kick.java index bd1e62650..e0bb277b0 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Kick.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Kick.java @@ -4,8 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Mute.java b/src/main/java/de/presti/ree6/commands/impl/mod/Mute.java index 9efef0411..8d74cecb2 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Mute.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Mute.java @@ -4,8 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Prefix.java b/src/main/java/de/presti/ree6/commands/impl/mod/Prefix.java index 7644ab067..cd4eb16cb 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Prefix.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Prefix.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.sql.SQLSession; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java b/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java index 62f24952e..044736c0e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Suggestions; diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Unban.java b/src/main/java/de/presti/ree6/commands/impl/mod/Unban.java index 6f3a54c22..85299b2ad 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Unban.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Unban.java @@ -4,8 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.UserSnowflake; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Unmute.java b/src/main/java/de/presti/ree6/commands/impl/mod/Unmute.java index 4870638e6..159d70869 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Unmute.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Unmute.java @@ -4,8 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions; diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Play.java b/src/main/java/de/presti/ree6/commands/impl/music/Play.java index a76d13625..8df145ba3 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Play.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Play.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Seek.java b/src/main/java/de/presti/ree6/commands/impl/music/Seek.java index 9410c764a..1942db9df 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Seek.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Seek.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Skip.java b/src/main/java/de/presti/ree6/commands/impl/music/Skip.java index 7d68ed51f..e204e7ebd 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Skip.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Skip.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Volume.java b/src/main/java/de/presti/ree6/commands/impl/music/Volume.java index 906b56a75..05d0c6473 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Volume.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Volume.java @@ -4,7 +4,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.bot.BotConfig; import lavalink.client.player.IPlayer; diff --git a/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java b/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java index 694fcb97d..97c0bb71b 100644 --- a/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java +++ b/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java @@ -7,7 +7,6 @@ import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.language.LanguageService; import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import de.presti.ree6.utils.others.RandomUtils; diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index ce822285e..854dc9b04 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -4,7 +4,6 @@ import club.minnced.discord.webhook.send.WebhookEmbedBuilder; import club.minnced.discord.webhook.send.WebhookMessageBuilder; import de.presti.ree6.audio.music.GuildMusicManager; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.bot.util.WebhookUtil; import de.presti.ree6.commands.impl.mod.Setup; @@ -15,7 +14,6 @@ import de.presti.ree6.sql.entities.*; import de.presti.ree6.sql.entities.roles.AutoRole; import de.presti.ree6.sql.entities.stats.ChannelStats; -import de.presti.ree6.sql.entities.webhook.base.Webhook; import de.presti.ree6.utils.apis.YouTubeAPIHandler; import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.data.TranscriptUtil; @@ -25,7 +23,6 @@ import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.channel.concrete.Category; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; diff --git a/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java b/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java index 986fadf2a..67a277606 100644 --- a/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java +++ b/src/main/java/de/presti/ree6/module/giveaway/GiveawayManager.java @@ -5,7 +5,6 @@ import de.presti.ree6.sql.entities.Giveaway; import de.presti.ree6.utils.others.RandomUtils; import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.utils.messages.MessageEditBuilder; diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java index 7f616b755..0f9d7f61e 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java @@ -17,7 +17,6 @@ import de.presti.ree6.module.notifications.SonicIdentifier; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.stats.ChannelStats; -import de.presti.ree6.utils.apis.YouTubeAPIHandler; import io.sentry.Sentry; import lombok.extern.slf4j.Slf4j; import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; diff --git a/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java b/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java index 0fc5e7e97..79ef12f01 100644 --- a/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java +++ b/src/main/java/de/presti/ree6/utils/data/EconomyUtil.java @@ -10,7 +10,6 @@ import java.sql.Timestamp; import java.time.Instant; import java.util.Map; -import java.util.concurrent.CompletableFuture; /** * Utility class for Economy related stuff. diff --git a/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Util.java b/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Util.java index 0ae4db667..f8bcd223e 100644 --- a/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Util.java +++ b/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Util.java @@ -33,7 +33,7 @@ public static CustomOAuth2Credential convert(long discordId, OAuth2Credential oA // OAuth2 OAuth2IdentityProvider oAuth2IdentityProvider = Main.getInstance().getNotifier().getCredentialManager().getIdentityProviderByName("twitch") .filter(idp -> idp.getProviderType().equalsIgnoreCase("oauth2") && idp instanceof OAuth2IdentityProvider) - .map(idp -> (OAuth2IdentityProvider) idp) + .map(OAuth2IdentityProvider.class::cast) .orElseThrow(() -> new RuntimeException("Can't find a unique identity provider for the specified credential!")); Optional enrichedCredential = oAuth2IdentityProvider.getAdditionalCredentialInformation(oAuth2Credential); diff --git a/src/main/java/de/presti/ree6/utils/others/ModerationUtil.java b/src/main/java/de/presti/ree6/utils/others/ModerationUtil.java index 7b7e908dc..e80fafa53 100644 --- a/src/main/java/de/presti/ree6/utils/others/ModerationUtil.java +++ b/src/main/java/de/presti/ree6/utils/others/ModerationUtil.java @@ -7,8 +7,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Future; /** * Class to handle the moderation user behaviour. From 981bece87829a8cc954f5ae5ed34227c960c7d1f Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 16:19:33 +0200 Subject: [PATCH 58/94] Code clean up. Signed-off-by: Presti --- .../ree6/audio/AudioPlayerReceiveHandler.java | 6 +-- .../impl/community/StreamActionCommand.java | 9 ++-- .../ree6/commands/impl/economy/Money.java | 43 ++++++++----------- .../ree6/commands/impl/economy/Work.java | 4 +- .../ree6/commands/impl/hidden/Addon.java | 20 ++++++++- .../ree6/commands/impl/mod/Blacklist.java | 34 +++++++-------- .../presti/ree6/commands/impl/mod/Import.java | 29 ++++++------- .../ree6/commands/interfaces/ICommand.java | 37 ---------------- 8 files changed, 76 insertions(+), 106 deletions(-) diff --git a/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java b/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java index c67144970..c3e7b9927 100644 --- a/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java +++ b/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java @@ -89,8 +89,8 @@ public AudioPlayerReceiveHandler(Member member, AudioChannelUnion audioChannelUn audioChannelUnion.asVoiceChannel().canTalk(); if (canTalk) { - LanguageService.getByGuild(member.getGuild(), "message.default.nameChangeFailed").subscribe(message -> - audioChannelUnion.asGuildMessageChannel().sendMessage(message).queue()); + LanguageService.getByGuild(member.getGuild(), "message.default.nameChangeFailed").subscribe(messageContent -> + audioChannelUnion.asGuildMessageChannel().sendMessage(messageContent).queue()); } return null; }).queue())); @@ -177,7 +177,7 @@ public void endReceiving() { if (canTalk) LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.default.nameChangeFailed") - .subscribe(message -> audioChannelUnion.asGuildMessageChannel().sendMessage(message).queue()); + .subscribe(messageContent -> audioChannelUnion.asGuildMessageChannel().sendMessage(messageContent).queue()); return null; }).queue()); } diff --git a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java index de5fb6650..c812328a0 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java @@ -2,14 +2,14 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; -import de.presti.ree6.module.actions.ActionInfo; -import de.presti.ree6.module.actions.streamtools.container.StreamActionContainer; import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; +import de.presti.ree6.module.actions.ActionInfo; +import de.presti.ree6.module.actions.streamtools.container.StreamActionContainer; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.StreamAction; import de.presti.ree6.sql.entities.TwitchIntegration; @@ -187,9 +187,8 @@ public void onPerform(CommandEvent commandEvent) { }); case "list" -> - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new StreamAction(), "FROM StreamAction WHERE guildAndName.guildId = :gid", Map.of("gid", commandEvent.getGuild().getIdLong())).subscribe(streamActions -> { - commandEvent.reply(commandEvent.getResource("message.stream-action.list", String.join("\n", streamActions.stream().map(StreamAction::getName).toArray(String[]::new)))); - }); + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new StreamAction(), "FROM StreamAction WHERE guildAndName.guildId = :gid", Map.of("gid", commandEvent.getGuild().getIdLong())).subscribe(streamActions -> + commandEvent.reply(commandEvent.getResource("message.stream-action.list", String.join("\n", streamActions.stream().map(StreamAction::getName).toArray(String[]::new))))); case "points" -> SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())).subscribe(twitchIntegrationOptional -> { diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Money.java b/src/main/java/de/presti/ree6/commands/impl/economy/Money.java index 3bb9b14be..6ca9f7327 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Money.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Money.java @@ -86,15 +86,14 @@ public void onPerform(CommandEvent commandEvent) { double sendAmount = RandomUtils.round(amount.getAsDouble(), 2); - EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> { - EconomyUtil.getMoneyHolder(member).subscribe(target -> { - if (EconomyUtil.pay(moneyHolder, target, sendAmount, true, true)) { - commandEvent.reply(commandEvent.getResource("message.money.send", EconomyUtil.formatMoney(sendAmount), member.getAsMention())); - } else { - commandEvent.reply(commandEvent.getResource("message.money.notEnoughMoney"), 5); - } - }); - }); + EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> + EconomyUtil.getMoneyHolder(member).subscribe(target -> { + if (EconomyUtil.pay(moneyHolder, target, sendAmount, true, true)) { + commandEvent.reply(commandEvent.getResource("message.money.send", EconomyUtil.formatMoney(sendAmount), member.getAsMention())); + } else { + commandEvent.reply(commandEvent.getResource("message.money.notEnoughMoney"), 5); + } + })); } default -> { if (user != null) { @@ -141,28 +140,22 @@ public void onPerform(CommandEvent commandEvent) { if (subcommandGroup.equals("admin")) { switch (subcommand) { - case "add" -> { - EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> { + case "add" -> EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> EconomyUtil.getMoneyHolder(member).subscribe(target -> { EconomyUtil.pay(moneyHolder, target, optionAmount, false, transferToBank, true); commandEvent.reply(commandEvent.getResource("message.money.add", EconomyUtil.formatMoney(optionAmount), member.getAsMention()), 5); - }); - }); - } - case "set" -> { - EconomyUtil.getMoneyHolder(member).subscribe(moneyHolder -> { - EconomyUtil.set(moneyHolder, optionAmount, transferToBank); - commandEvent.reply(commandEvent.getResource("message.money.set", member.getAsMention(), EconomyUtil.formatMoney(optionAmount)), 5); - }); - } - case "remove" -> { - EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> { + })); + case "set" -> EconomyUtil.getMoneyHolder(member).subscribe(moneyHolder -> { + EconomyUtil.set(moneyHolder, optionAmount, transferToBank); + commandEvent.reply(commandEvent.getResource("message.money.set", member.getAsMention(), EconomyUtil.formatMoney(optionAmount)), 5); + }); + case "remove" -> EconomyUtil.getMoneyHolder(commandEvent.getMember()).subscribe(moneyHolder -> EconomyUtil.getMoneyHolder(member).subscribe(target -> { EconomyUtil.pay(moneyHolder, target, -optionAmount, false, transferToBank, true); commandEvent.reply(commandEvent.getResource("message.money.remove", EconomyUtil.formatMoney(optionAmount), member.getAsMention()), 5); - }); - }); - } + })); + + default -> commandEvent.reply(commandEvent.getResource("message.default.invalidOption"), 5); } } else { commandEvent.reply(commandEvent.getResource("message.default.invalidOption"), 5); diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Work.java b/src/main/java/de/presti/ree6/commands/impl/economy/Work.java index 8f5389e7d..f6b06c672 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Work.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Work.java @@ -42,10 +42,10 @@ public void onPerform(CommandEvent commandEvent) { return; } - double min = Double.parseDouble((String) SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", + double min = Double.parseDouble(SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_min")).block().get().getStringValue()); - double max = Double.parseDouble((String) SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", + double max = Double.parseDouble(SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_max")).block().get().getStringValue()); double amount = RandomUtils.round(RandomUtils.nextDouble(min, max), 2); diff --git a/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java b/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java index 867cfe5a7..d80b18a87 100644 --- a/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java +++ b/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java @@ -2,6 +2,7 @@ import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; +import de.presti.ree6.commands.exceptions.CommandInitializerException; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; @@ -14,6 +15,7 @@ import org.pf4j.PluginWrapper; import java.nio.file.Path; +import java.util.List; /** * A command to either reload all Addons or list all of them. @@ -43,8 +45,24 @@ public void onPerform(CommandEvent commandEvent) { switch (subcommand) { case "reload" -> { commandEvent.reply(commandEvent.getResource("message.addon.reloadAll")); - //Main.getInstance().getPluginManager().reload(); + + List commands = Main.getInstance().getPluginManager().getExtensions(ICommand.class); + commands.forEach(command -> Main.getInstance().getCommandManager().removeCommand(command)); + Main.getInstance().getPluginManager().stopPlugins(); + Main.getInstance().getPluginManager().unloadPlugins(); + Main.getInstance().getPluginManager().loadPlugins(); + Main.getInstance().getPluginManager().startPlugins(); commandEvent.reply(commandEvent.getResource("message.addon.reloadedAll")); + + commands = Main.getInstance().getPluginManager().getExtensions(ICommand.class); + log.info("Found {} commands in all plugins.", commands.size()); + commands.forEach(command -> { + try { + Main.getInstance().getCommandManager().addCommand(command); + } catch (CommandInitializerException e) { + log.warn("Failed to initialize command: {}", command.getClass().getSimpleName(), e); + } + }); } case "list" -> { diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java b/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java index dcf1c38ba..d60d87e60 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Blacklist.java @@ -57,24 +57,22 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(commandEvent.getResource("message.blacklist.removed", word), 5); } - default -> { - ModerationUtil.shouldModerate(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { - if (aBoolean) { - ModerationUtil.getBlacklist(commandEvent.getGuild().getIdLong()).subscribe(blacklists -> { - StringBuilder end = new StringBuilder(); - - for (String s : blacklists) { - end.append("\n").append(s); - } - - commandEvent.reply("```" + end + "```"); - }); - } else { - commandEvent.reply(commandEvent.getResource("message.blacklist.setupNeeded")); - commandEvent.reply(commandEvent.getResource("message.default.usage", "blacklist add [WORD...]"), 5); - } - }); - } + default -> ModerationUtil.shouldModerate(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { + if (aBoolean) { + ModerationUtil.getBlacklist(commandEvent.getGuild().getIdLong()).subscribe(blacklists -> { + StringBuilder end = new StringBuilder(); + + for (String s : blacklists) { + end.append("\n").append(s); + } + + commandEvent.reply("```" + end + "```"); + }); + } else { + commandEvent.reply(commandEvent.getResource("message.blacklist.setupNeeded")); + commandEvent.reply(commandEvent.getResource("message.default.usage", "blacklist add [WORD...]"), 5); + } + }); } } else { diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Import.java b/src/main/java/de/presti/ree6/commands/impl/mod/Import.java index 52415db62..514a5f8f2 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Import.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Import.java @@ -120,21 +120,20 @@ public void importFromAmari(CommandEvent commandEvent) { try { Leaderboard leaderboard = AmariAPI.getAmari4J().getRawLeaderboard(commandEvent.getGuild().getId(), Integer.MAX_VALUE); - leaderboard.getMembers().forEach(member -> { - SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), Long.parseLong(member.getUserid())).subscribe(chatUserLevel -> { - if (chatUserLevel != null && chatUserLevel.getExperience() > member.getExperience()) { - return; - } - - if (chatUserLevel == null) { - chatUserLevel = new ChatUserLevel(commandEvent.getGuild().getIdLong(), Long.parseLong(member.getUserid()), member.getExperience()); - } else { - chatUserLevel.setExperience(member.getExperience()); - } - - SQLSession.getSqlConnector().getSqlWorker().updateEntity(chatUserLevel).block(); - }); - }); + leaderboard.getMembers().forEach(member -> + SQLSession.getSqlConnector().getSqlWorker().getChatLevelData(commandEvent.getGuild().getIdLong(), Long.parseLong(member.getUserid())).subscribe(chatUserLevel -> { + if (chatUserLevel != null && chatUserLevel.getExperience() > member.getExperience()) { + return; + } + + if (chatUserLevel == null) { + chatUserLevel = new ChatUserLevel(commandEvent.getGuild().getIdLong(), Long.parseLong(member.getUserid()), member.getExperience()); + } else { + chatUserLevel.setExperience(member.getExperience()); + } + + SQLSession.getSqlConnector().getSqlWorker().updateEntity(chatUserLevel).block(); + })); commandEvent.reply(commandEvent.getResource("message.import.success", leaderboard.getCount()), 5); } catch (InvalidAPIKeyException | InvalidServerResponseException | RateLimitException e) { // TODO:: make some extra stuff for the rate-limit. diff --git a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java index cd26b705b..f691b05e8 100644 --- a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java +++ b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java @@ -17,7 +17,6 @@ import reactor.core.publisher.Mono; import java.util.Optional; -import java.util.concurrent.CompletableFuture; /** * An Interface class, used to make it easier for the creation of Commands. @@ -62,42 +61,6 @@ default Mono onMonoPerform(CommandEvent commandEvent) { }); } - /** - * Will be fired when the Command is called. - * - * @param commandEvent the Event, with every necessary data. - * @deprecated Use {@link #onMonoPerform(CommandEvent)} instead. - */ - @Deprecated(forRemoval = true, since = "4.0.0") - default void onASyncPerform(CommandEvent commandEvent) { - CompletableFuture.runAsync(() -> onPerform(commandEvent)).exceptionally(throwable -> { - if (!throwable.getMessage().contains("Unknown Message")) { - commandEvent.reply(commandEvent.getResource("command.perform.internalError"), 5); - log.error("An error occurred while executing the command!", throwable); - Sentry.captureException(throwable); - } - return null; - }); - if (commandEvent.getGuild().isDetached()) return; - - // Update Stats. - SQLSession.getSqlConnector().getSqlWorker().addStats(commandEvent.getGuild().getIdLong(), commandEvent.getCommand()); - SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_news").subscribe(setting -> { - if (setting.isEmpty() || !setting.get().getBooleanValue()) return; - AnnouncementManager.getAnnouncementList().forEach(a -> { - if (!AnnouncementManager.hasReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id())) { - Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder().setTitle(a.title()) - .setAuthor(BotConfig.getBotName() + "-Info") - .setDescription(a.content().replace("\\n", "\n") + "\n\n" + LanguageService.getByGuild(commandEvent.getGuild(), "message.news.notice").block()) - .setFooter(BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) - .setColor(BotWorker.randomEmbedColor()), 15, commandEvent.getChannel()); - - AnnouncementManager.addReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id()); - } - }); - }); - } - default void onPerformWithLog(CommandEvent commandEvent) { onPerform(commandEvent); if (BotConfig.isDebug()) From a416ccc85718f8514e914b0a06ec7161083ccc7a Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 16:22:18 +0200 Subject: [PATCH 59/94] Code clean up. Signed-off-by: Presti --- src/main/java/de/presti/ree6/events/OtherEvents.java | 2 +- .../java/de/presti/ree6/module/game/core/base/GamePlayer.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/de/presti/ree6/events/OtherEvents.java b/src/main/java/de/presti/ree6/events/OtherEvents.java index 2ecf85d1c..86f36e887 100644 --- a/src/main/java/de/presti/ree6/events/OtherEvents.java +++ b/src/main/java/de/presti/ree6/events/OtherEvents.java @@ -466,7 +466,7 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) { log.info("Message was moderated: {}", moderated); return moderated; - }).flatMap((aBoolean) -> handleCommand(aBoolean, event)).doOnNext(handled -> { + }).flatMap(aBoolean -> handleCommand(aBoolean, event)).doOnNext(handled -> { if (!handled) { if (!event.getMessage().getMentions().getUsers().isEmpty() && event.getMessage().getMentions().getUsers().contains(event.getJDA().getSelfUser())) { if (event.getMessage().getMessageReference() != null) return; diff --git a/src/main/java/de/presti/ree6/module/game/core/base/GamePlayer.java b/src/main/java/de/presti/ree6/module/game/core/base/GamePlayer.java index 5bb1466b6..4b96c3c8b 100644 --- a/src/main/java/de/presti/ree6/module/game/core/base/GamePlayer.java +++ b/src/main/java/de/presti/ree6/module/game/core/base/GamePlayer.java @@ -50,7 +50,7 @@ public GamePlayer(long relatedUserId) { */ public User getRelatedUser() { if (relatedUser == null) - return relatedUser = BotWorker.getShardManager().getUserById(relatedUserId); + relatedUser = BotWorker.getShardManager().getUserById(relatedUserId); return relatedUser; } From 8a8839ce21bc302592db3374bf4e08d946e48dc5 Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 16:28:47 +0200 Subject: [PATCH 60/94] Code clean up. Signed-off-by: Presti --- .../presti/ree6/commands/impl/mod/Warn.java | 45 +- .../de/presti/ree6/events/MenuEvents.java | 587 ++++++++---------- .../module/logger/events/LogMessageVoice.java | 2 +- .../de/presti/ree6/utils/config/Config.java | 2 +- .../utils/oauth/CustomOAuth2Credential.java | 2 +- 5 files changed, 301 insertions(+), 337 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java b/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java index 384c00565..50a8f291d 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java @@ -121,31 +121,30 @@ public void onPerform(CommandEvent commandEvent) { }); } - case "list" -> { - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid", Map.of("gid", commandEvent.getGuild().getIdLong())).subscribe(punishmentsList -> { - StringBuilder stringBuilder = new StringBuilder(); - for (Punishments punishments : punishmentsList) { - int action = punishments.getAction(); - stringBuilder.append(punishments.getId()).append(" - ").append(punishments.getWarnings()).append(" -> "); + case "list" -> + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new Punishments(), "FROM Punishments WHERE guildAndId.guildId = :gid", Map.of("gid", commandEvent.getGuild().getIdLong())).subscribe(punishmentsList -> { + StringBuilder stringBuilder = new StringBuilder(); + for (Punishments punishments : punishmentsList) { + int action = punishments.getAction(); + stringBuilder.append(punishments.getId()).append(" - ").append(punishments.getWarnings()).append(" -> "); - switch (action) { - case 1 -> - stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.timeout", Duration.ofMillis(punishments.getTimeoutTime()).toSeconds())); - case 2 -> - stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.roleAdd", punishments.getRoleId())); - case 3 -> - stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.roleRemove", punishments.getRoleId())); - case 4 -> - stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.kick", punishments.getReason())); - case 5 -> - stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.ban", punishments.getReason())); - } + switch (action) { + case 1 -> + stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.timeout", Duration.ofMillis(punishments.getTimeoutTime()).toSeconds())); + case 2 -> + stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.roleAdd", punishments.getRoleId())); + case 3 -> + stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.roleRemove", punishments.getRoleId())); + case 4 -> + stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.kick", punishments.getReason())); + case 5 -> + stringBuilder.append(commandEvent.getResource("message.warn.punishment.listEntry.ban", punishments.getReason())); + } - stringBuilder.append("\n"); - } - commandEvent.reply(commandEvent.getResource("message.warn.punishment.list", stringBuilder.toString())); - }); - } + stringBuilder.append("\n"); + } + commandEvent.reply(commandEvent.getResource("message.warn.punishment.list", stringBuilder.toString())); + }); case "delete" -> { int id = idMapping.getAsInt(); diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index 854dc9b04..fa20d3144 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -4,6 +4,7 @@ import club.minnced.discord.webhook.send.WebhookEmbedBuilder; import club.minnced.discord.webhook.send.WebhookMessageBuilder; import de.presti.ree6.audio.music.GuildMusicManager; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.bot.util.WebhookUtil; import de.presti.ree6.commands.impl.mod.Setup; @@ -15,7 +16,6 @@ import de.presti.ree6.sql.entities.roles.AutoRole; import de.presti.ree6.sql.entities.stats.ChannelStats; import de.presti.ree6.utils.apis.YouTubeAPIHandler; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.data.TranscriptUtil; import de.presti.wrapper.entities.channel.ChannelResult; import io.github.redouane59.twitter.dto.user.UserV2; @@ -101,21 +101,18 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { } switch (event.getComponentId()) { - case "re_feedback" -> { - LanguageService.getByGuild(event.getGuild(), "label.feedback").subscribe(modalString -> { - Modal.Builder builder = Modal.create("re_feedback_modal", modalString); - builder.addActionRow(TextInput.create("re_feedback_text", modalString, TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(2042).setMinLength(16).build()); - event.replyModal(builder.build()).queue(); - }); - } + case "re_feedback" -> LanguageService.getByGuild(event.getGuild(), "label.feedback").subscribe(modalString -> { + Modal.Builder builder = Modal.create("re_feedback_modal", modalString); + builder.addActionRow(TextInput.create("re_feedback_text", modalString, TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(2042).setMinLength(16).build()); + event.replyModal(builder.build()).queue(); + }); - case "re_suggestion" -> { - LanguageService.getByGuild(event.getGuild(), "label.suggestion").subscribe(modalString -> { - Modal.Builder builder = Modal.create("re_suggestion_modal", modalString); - builder.addActionRow(TextInput.create("re_suggestion_text", modalString, TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(2042).setMinLength(16).build()); - event.replyModal(builder.build()).queue(); - }); - } + case "re_suggestion" -> + LanguageService.getByGuild(event.getGuild(), "label.suggestion").subscribe(modalString -> { + Modal.Builder builder = Modal.create("re_suggestion_modal", modalString); + builder.addActionRow(TextInput.create("re_suggestion_text", modalString, TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(2042).setMinLength(16).build()); + event.replyModal(builder.build()).queue(); + }); case "re_ticket_open" -> { event.deferReply(true).queue(); @@ -382,30 +379,29 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { }); } - case "re_suggestion_modal" -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Suggestions(), "FROM Suggestions WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(suggestions -> { - event.deferReply(true).queue(); + case "re_suggestion_modal" -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Suggestions(), "FROM Suggestions WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(suggestions -> { + event.deferReply(true).queue(); - if (suggestions.isPresent()) { - MessageChannel messageChannel = (MessageChannel) event.getGuild().getGuildChannelById(suggestions.get().getGuildChannelId().getChannelId()); + if (suggestions.isPresent()) { + MessageChannel messageChannel = (MessageChannel) event.getGuild().getGuildChannelById(suggestions.get().getGuildChannelId().getChannelId()); - if (messageChannel == null) return; + if (messageChannel == null) return; - EmbedBuilder embedBuilder = new EmbedBuilder() - .setTitle(LanguageService.getByGuild(event.getGuild(), "label.suggestion").block()) - .setColor(Color.ORANGE) - .setThumbnail(event.getMember().getEffectiveAvatarUrl()) - .setDescription("```" + event.getValue("re_suggestion_text").getAsString() + "```") - .setFooter(LanguageService.getByGuild(event.getGuild(), "message.suggestion.footer", event.getUser().getEffectiveName()).block(), event.getMember().getEffectiveAvatarUrl()) - .setTimestamp(Instant.now()); - - Main.getInstance().getCommandManager().sendMessage(embedBuilder, messageChannel); - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.suggestion.sent"), null, event.getInteraction().getHook()); - } else { - Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.suggestion.notSetup"), null, event.getInteraction().getHook()); - } - }); - } + EmbedBuilder embedBuilder = new EmbedBuilder() + .setTitle(LanguageService.getByGuild(event.getGuild(), "label.suggestion").block()) + .setColor(Color.ORANGE) + .setThumbnail(event.getMember().getEffectiveAvatarUrl()) + .setDescription("```" + event.getValue("re_suggestion_text").getAsString() + "```") + .setFooter(LanguageService.getByGuild(event.getGuild(), "message.suggestion.footer", event.getUser().getEffectiveName()).block(), event.getMember().getEffectiveAvatarUrl()) + .setTimestamp(Instant.now()); + + Main.getInstance().getCommandManager().sendMessage(embedBuilder, messageChannel); + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.suggestion.sent"), null, event.getInteraction().getHook()); + } else { + Main.getInstance().getCommandManager().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.suggestion.notSetup"), null, event.getInteraction().getHook()); + } + }); case "re_music_add_modal" -> { event.deferReply(true).queue(); @@ -920,62 +916,56 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even switch (event.getInteraction().getValues().get(0)) { - case "rewards" -> { - LanguageService.getByGuild(event.getGuild(), "label.rewards").subscribe(rewardLabel -> { - TextInput blackJackWin = TextInput.create("re_rewards_BlackJackWin", LanguageService.getByGuild(event.getGuild(), "label.blackJackWin").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - TextInput musicQuizWin = TextInput.create("re_rewards_MusicQuizWin", LanguageService.getByGuild(event.getGuild(), "label.musicQuizWin").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - TextInput musicQuizFeature = TextInput.create("re_rewards_MusicQuizFeature", LanguageService.getByGuild(event.getGuild(), "label.musicQuizFeatureGuess").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - TextInput musicQuizArtist = TextInput.create("re_rewards_MusicQuizArtist", LanguageService.getByGuild(event.getGuild(), "label.musicQuizArtistGuess").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - TextInput musicQuizTitle = TextInput.create("re_rewards_MusicQuizTitle", LanguageService.getByGuild(event.getGuild(), "label.musicQuizTitleGuess").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); - Modal modal = Modal.create("re_rewards_modal", rewardLabel).addActionRow(blackJackWin).addActionRow(musicQuizWin).addActionRow(musicQuizFeature).addActionRow(musicQuizArtist).addActionRow(musicQuizTitle).build(); - event.replyModal(modal).queue(); - }); - } + case "rewards" -> + LanguageService.getByGuild(event.getGuild(), "label.rewards").subscribe(rewardLabel -> { + TextInput blackJackWin = TextInput.create("re_rewards_BlackJackWin", LanguageService.getByGuild(event.getGuild(), "label.blackJackWin").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + TextInput musicQuizWin = TextInput.create("re_rewards_MusicQuizWin", LanguageService.getByGuild(event.getGuild(), "label.musicQuizWin").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + TextInput musicQuizFeature = TextInput.create("re_rewards_MusicQuizFeature", LanguageService.getByGuild(event.getGuild(), "label.musicQuizFeatureGuess").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + TextInput musicQuizArtist = TextInput.create("re_rewards_MusicQuizArtist", LanguageService.getByGuild(event.getGuild(), "label.musicQuizArtistGuess").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + TextInput musicQuizTitle = TextInput.create("re_rewards_MusicQuizTitle", LanguageService.getByGuild(event.getGuild(), "label.musicQuizTitleGuess").block(), TextInputStyle.SHORT).setRequired(true).setMinLength(1).build(); + Modal modal = Modal.create("re_rewards_modal", rewardLabel).addActionRow(blackJackWin).addActionRow(musicQuizWin).addActionRow(musicQuizFeature).addActionRow(musicQuizArtist).addActionRow(musicQuizTitle).build(); + event.replyModal(modal).queue(); + }); - case "lang" -> { - LanguageService.getByGuild(event.getGuild(), "message.setup.steps.lang").subscribe(description -> { - for (DiscordLocale locale : LanguageService.getSupported()) { - optionList.add(SelectOption.of(locale.getLanguageName(), locale.getLocale())); - } + case "lang" -> + LanguageService.getByGuild(event.getGuild(), "message.setup.steps.lang").subscribe(description -> { + for (DiscordLocale locale : LanguageService.getSupported()) { + optionList.add(SelectOption.of(locale.getLanguageName(), locale.getLocale())); + } - embedBuilder.setDescription(description); + embedBuilder.setDescription(description); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLangMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); - }); - } + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLangMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); + }); - case "log" -> { - LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { - optionList.add(SelectOption.of(label, "logSetup")); + case "log" -> LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { + optionList.add(SelectOption.of(label, "logSetup")); - if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).block()) - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "logDelete")); + if (SQLSession.getSqlConnector().getSqlWorker().isLogSetup(event.getGuild().getIdLong()).block()) + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "logDelete")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.auditLog").block()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.auditLog").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); - }); - } + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); + }); - case "welcome" -> { - LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { - optionList.add(SelectOption.of(label, "welcomeSetup")); + case "welcome" -> LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { + optionList.add(SelectOption.of(label, "welcomeSetup")); - SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).block().ifPresent(welcomeWebhook -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "welcomeDelete")); - }); + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).block().ifPresent(welcomeWebhook -> { + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "welcomeDelete")); + }); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setImage").block(), "welcomeImage")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setImage").block(), "welcomeImage")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.welcome").block()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.welcome").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); - }); - } + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); + }); case "autorole" -> Setup.createAutoRoleSetupSelectMenu(event.getGuild(), event.getHook()).subscribe(selectMenu -> @@ -985,63 +975,57 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even ActionRow.of(Button.link(BotConfig.getWebinterface(), "Webinterface"))) .queue()); - case "tempvoice" -> { - LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { - optionList.add(SelectOption.of(label, "tempVoiceSetup")); + case "tempvoice" -> LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { + optionList.add(SelectOption.of(label, "tempVoiceSetup")); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", - Map.of("gid", event.getGuild().getIdLong())).block().ifPresent(temporalVoicechannel -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "tempVoiceDelete")); - }); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", + Map.of("gid", event.getGuild().getIdLong())).block().ifPresent(temporalVoicechannel -> { + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "tempVoiceDelete")); + }); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.temporalVoice").block()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.setup.steps.temporalVoice").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoiceMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); - }); - } + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoiceMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); + }); - case "statistics" -> { - LanguageService.getByGuild(event.getGuild(), "message.statistics.setup").subscribe(description -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupMemberStatistics").block(), "statisticsSetupMember")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupTwitchStatistics").block(), "statisticsSetupTwitch")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupYoutubeStatistics").block(), "statisticsSetupYouTube")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupRedditStatistics").block(), "statisticsSetupReddit")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupTwitterStatistics").block(), "statisticsSetupTwitter")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupInstagramStatistics").block(), "statisticsSetupInstagram")); + case "statistics" -> + LanguageService.getByGuild(event.getGuild(), "message.statistics.setup").subscribe(description -> { + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupMemberStatistics").block(), "statisticsSetupMember")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupTwitchStatistics").block(), "statisticsSetupTwitch")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupYoutubeStatistics").block(), "statisticsSetupYouTube")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupRedditStatistics").block(), "statisticsSetupReddit")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupTwitterStatistics").block(), "statisticsSetupTwitter")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setupInstagramStatistics").block(), "statisticsSetupInstagram")); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); - embedBuilder.setDescription(description); + embedBuilder.setDescription(description); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupStatisticsMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); - }); - } + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupStatisticsMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); + }); - case "tickets" -> { - LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { - optionList.add(SelectOption.of(label, "ticketsSetup")); + case "tickets" -> LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { + optionList.add(SelectOption.of(label, "ticketsSetup")); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).block().ifPresent(tickets -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "ticketsDelete")); - }); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).block().ifPresent(tickets -> { + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "ticketsDelete")); + }); - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); + optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.setup").block()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.setup").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTicketsMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); - }); - } + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTicketsMenu", LanguageService.getByGuild(event.getGuild(), "message.default.actionRequired").block(), 1, 1, false, optionList)).queue(); + }); - default -> { - LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { - embedBuilder.setDescription(description); - event.editMessageEmbeds(embedBuilder.build()).queue(); - }); - } + default -> + LanguageService.getByGuild(event.getGuild(), "message.default.invalidOption").subscribe(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).queue(); + }); } } @@ -1057,128 +1041,119 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); - case "statisticsSetupMember" -> { - LanguageService.getByGuild(event.getGuild(), "message.statistics.memberSuccess").subscribe(description -> { - embedBuilder.setDescription(description); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - java.util.List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics").block(), true); - - Category category; + case "statisticsSetupMember" -> + LanguageService.getByGuild(event.getGuild(), "message.statistics.memberSuccess").subscribe(description -> { + embedBuilder.setDescription(description); + embedBuilder.setColor(Color.GREEN); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics").block(), true); - if (categories.isEmpty()) { - category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics").block()).complete(); - } else { - category = categories.get(0); - } + Category category; - event.getGuild().loadMembers().onSuccess(members -> event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.overallMembersName", event.getGuild().getMemberCount()).block(), category).queue(voiceChannel -> { - voiceChannel.getManager().setUserLimit(0).queue(); - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.realMembersName", members.stream().filter(member -> !member.getUser().isBot()).count()).block(), category).queue(voiceChannel1 -> { - voiceChannel1.getManager().setUserLimit(0).queue(); - event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.botMembersName", members.stream().filter(member -> member.getUser().isBot()).count()).block(), category).queue(voiceChannel2 -> { - voiceChannel2.getManager().setUserLimit(0).queue(); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { - if (channelStatsOptional.isPresent()) { - ChannelStats channelStats = channelStatsOptional.get(); - if (channelStats.getMemberStatsChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getMemberStatsChannelId()); - - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } - if (channelStats.getRealMemberStatsChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getRealMemberStatsChannelId()); + if (categories.isEmpty()) { + category = event.getGuild().createCategory(LanguageService.getByGuild(event.getGuild(), "label.statistics").block()).complete(); + } else { + category = categories.get(0); + } - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); + event.getGuild().loadMembers().onSuccess(members -> event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.overallMembersName", event.getGuild().getMemberCount()).block(), category).queue(voiceChannel -> { + voiceChannel.getManager().setUserLimit(0).queue(); + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.realMembersName", members.stream().filter(member -> !member.getUser().isBot()).count()).block(), category).queue(voiceChannel1 -> { + voiceChannel1.getManager().setUserLimit(0).queue(); + event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.botMembersName", members.stream().filter(member -> member.getUser().isBot()).count()).block(), category).queue(voiceChannel2 -> { + voiceChannel2.getManager().setUserLimit(0).queue(); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { + if (channelStatsOptional.isPresent()) { + ChannelStats channelStats = channelStatsOptional.get(); + if (channelStats.getMemberStatsChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getMemberStatsChannelId()); + + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } + if (channelStats.getRealMemberStatsChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getRealMemberStatsChannelId()); + + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } + if (channelStats.getBotMemberStatsChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getBotMemberStatsChannelId()); + + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); + } + channelStats.setMemberStatsChannelId(voiceChannel.getId()); + channelStats.setRealMemberStatsChannelId(voiceChannel1.getId()); + channelStats.setBotMemberStatsChannelId(voiceChannel2.getId()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + } else { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), + voiceChannel.getId(), + voiceChannel1.getId(), + voiceChannel2.getId(), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null)).block(); } - if (channelStats.getBotMemberStatsChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getBotMemberStatsChannelId()); + }); - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } - channelStats.setMemberStatsChannelId(voiceChannel.getId()); - channelStats.setRealMemberStatsChannelId(voiceChannel1.getId()); - channelStats.setBotMemberStatsChannelId(voiceChannel2.getId()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); - } else { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), - voiceChannel.getId(), - voiceChannel1.getId(), - voiceChannel2.getId(), - null, - null, - null, - null, - null, - null, - null, - null, - null, - null)).block(); - } }); - }); - }); - })); - }); - } - - case "statisticsSetupTwitch" -> { - LanguageService.getByGuild(event.getGuild(), "label.channelName").subscribe(label -> { - TextInput input = TextInput.create("twitchChannelName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Twitch Channel name here!").build(); - - Modal modal = Modal.create("statisticsSetupTwitchModal", LanguageService.getByGuild(event.getGuild(), "label.setupTwitchStatistics").block()).addActionRow(input).build(); - - event.replyModal(modal).queue(); - }); + })); + }); - } + case "statisticsSetupTwitch" -> + LanguageService.getByGuild(event.getGuild(), "label.channelName").subscribe(label -> { + TextInput input = TextInput.create("twitchChannelName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Twitch Channel name here!").build(); - case "statisticsSetupYouTube" -> { - LanguageService.getByGuild(event.getGuild(), "label.channelName").subscribe(label -> { - TextInput input = TextInput.create("youtubeChannelName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the YouTube Channel name here!").build(); + Modal modal = Modal.create("statisticsSetupTwitchModal", LanguageService.getByGuild(event.getGuild(), "label.setupTwitchStatistics").block()).addActionRow(input).build(); - Modal modal = Modal.create("statisticsSetupYouTubeModal", LanguageService.getByGuild(event.getGuild(), "label.setupYoutubeStatistics").block()).addActionRow(input).build(); + event.replyModal(modal).queue(); + }); - event.replyModal(modal).queue(); - }); - } + case "statisticsSetupYouTube" -> + LanguageService.getByGuild(event.getGuild(), "label.channelName").subscribe(label -> { + TextInput input = TextInput.create("youtubeChannelName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the YouTube Channel name here!").build(); - case "statisticsSetupReddit" -> { - LanguageService.getByGuild(event.getGuild(), "label.subreddit").subscribe(label -> { - TextInput input = TextInput.create("subredditName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Subreddit name here!").build(); + Modal modal = Modal.create("statisticsSetupYouTubeModal", LanguageService.getByGuild(event.getGuild(), "label.setupYoutubeStatistics").block()).addActionRow(input).build(); - Modal modal = Modal.create("statisticsSetupRedditModal", LanguageService.getByGuild(event.getGuild(), "label.setupRedditStatistics").block()).addActionRow(input).build(); + event.replyModal(modal).queue(); + }); - event.replyModal(modal).queue(); - }); - } + case "statisticsSetupReddit" -> + LanguageService.getByGuild(event.getGuild(), "label.subreddit").subscribe(label -> { + TextInput input = TextInput.create("subredditName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Subreddit name here!").build(); - case "statisticsSetupTwitter" -> { - LanguageService.getByGuild(event.getGuild(), "label.name").subscribe(label -> { - TextInput input = TextInput.create("twitterName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Twitter name here!").build(); + Modal modal = Modal.create("statisticsSetupRedditModal", LanguageService.getByGuild(event.getGuild(), "label.setupRedditStatistics").block()).addActionRow(input).build(); - Modal modal = Modal.create("statisticsSetupTwitterModal", LanguageService.getByGuild(event.getGuild(), "label.setupTwitterStatistics").block()).addActionRow(input).build(); + event.replyModal(modal).queue(); + }); - event.replyModal(modal).queue(); - }); + case "statisticsSetupTwitter" -> + LanguageService.getByGuild(event.getGuild(), "label.name").subscribe(label -> { + TextInput input = TextInput.create("twitterName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Twitter name here!").build(); - } + Modal modal = Modal.create("statisticsSetupTwitterModal", LanguageService.getByGuild(event.getGuild(), "label.setupTwitterStatistics").block()).addActionRow(input).build(); - case "statisticsSetupInstagram" -> { - LanguageService.getByGuild(event.getGuild(), "label.name").subscribe(label -> { - TextInput input = TextInput.create("instagramName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Instagram name here!").build(); + event.replyModal(modal).queue(); + }); - Modal modal = Modal.create("statisticsSetupInstagramModal", LanguageService.getByGuild(event.getGuild(), "label.setupInstagramStatistics").block()).addActionRow(input).build(); + case "statisticsSetupInstagram" -> + LanguageService.getByGuild(event.getGuild(), "label.name").subscribe(label -> { + TextInput input = TextInput.create("instagramName", label, TextInputStyle.SHORT).setMinLength(1).setMaxLength(50).setRequired(true).setPlaceholder("Enter the Instagram name here!").build(); - event.replyModal(modal).queue(); - }); + Modal modal = Modal.create("statisticsSetupInstagramModal", LanguageService.getByGuild(event.getGuild(), "label.setupInstagramStatistics").block()).addActionRow(input).build(); - } + event.replyModal(modal).queue(); + }); default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) @@ -1203,23 +1178,21 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); - case "ticketsSetup" -> { - LanguageService.getByGuild(event.getGuild(), "message.ticket.setupDescription").subscribe(description -> { - embedBuilder.setDescription(description); - event.editMessageEmbeds(embedBuilder.build()).setComponents().queue(); - }); - } + case "ticketsSetup" -> + LanguageService.getByGuild(event.getGuild(), "message.ticket.setupDescription").subscribe(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).setComponents().queue(); + }); - case "ticketsDelete" -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(tickets -> { - if (tickets.isPresent()) { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.deleted").block()); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(tickets.get()).block(); - } - }); - } + case "ticketsDelete" -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(tickets -> { + if (tickets.isPresent()) { + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.deleted").block()); + embedBuilder.setColor(Color.GREEN); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(tickets.get()).block(); + } + }); default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) @@ -1288,33 +1261,31 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); - case "tempVoiceSetup" -> { - LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(labelMore -> { - for (VoiceChannel channel : event.getGuild().getVoiceChannels()) { - if (optionList.size() == 24) { - optionList.add(SelectOption.of(labelMore, "more")); - break; - } + case "tempVoiceSetup" -> + LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(labelMore -> { + for (VoiceChannel channel : event.getGuild().getVoiceChannels()) { + if (optionList.size() == 24) { + optionList.add(SelectOption.of(labelMore, "more")); + break; + } - optionList.add(SelectOption.of(channel.getName(), channel.getId())); - } + optionList.add(SelectOption.of(channel.getName(), channel.getId())); + } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupDescription").block()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupDescription").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoicechannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); - }); - } + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupTempVoicechannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); + }); - case "tempVoiceDelete" -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(temporalVoicechannel -> { - if (temporalVoicechannel.isPresent()) { - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.deleted").block()); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel.get()).block(); - } - }); - } + case "tempVoiceDelete" -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(temporalVoicechannel -> { + if (temporalVoicechannel.isPresent()) { + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.deleted").block()); + embedBuilder.setColor(Color.GREEN); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel.get()).block(); + } + }); default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) @@ -1367,33 +1338,30 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); - case "logSetup" -> { - LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(labelMore -> { - for (TextChannel channel : event.getGuild().getTextChannels()) { - if (optionList.size() == 24) { - optionList.add(SelectOption.of(labelMore, "more")); - break; - } - - optionList.add(SelectOption.of(channel.getName(), channel.getId())); + case "logSetup" -> LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(labelMore -> { + for (TextChannel channel : event.getGuild().getTextChannels()) { + if (optionList.size() == 24) { + optionList.add(SelectOption.of(labelMore, "more")); + break; } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupDescription").block()); + optionList.add(SelectOption.of(channel.getName(), channel.getId())); + } - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); - }); - } + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupDescription").block()); - case "logDelete" -> { - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> - webhook.ifPresent(webhookLog -> event.getJDA().retrieveWebhookById(webhookLog.getChannelId()).queue(webhook1 -> { - webhook1.delete().queue(); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.deleted").block()); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookLog).block(); - }))); - } + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); + }); + + case "logDelete" -> + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> + webhook.ifPresent(webhookLog -> event.getJDA().retrieveWebhookById(webhookLog.getChannelId()).queue(webhook1 -> { + webhook1.delete().queue(); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.deleted").block()); + embedBuilder.setColor(Color.GREEN); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookLog).block(); + }))); default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) @@ -1470,40 +1438,37 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); - case "welcomeSetup" -> { - LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(moreLabel -> { - for (TextChannel channel : event.getGuild().getTextChannels()) { - if (optionList.size() == 24) { - optionList.add(SelectOption.of(moreLabel, "more")); - break; - } + case "welcomeSetup" -> + LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(moreLabel -> { + for (TextChannel channel : event.getGuild().getTextChannels()) { + if (optionList.size() == 24) { + optionList.add(SelectOption.of(moreLabel, "more")); + break; + } - optionList.add(SelectOption.of(channel.getName(), channel.getId())); - } + optionList.add(SelectOption.of(channel.getName(), channel.getId())); + } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupDescription").block()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupDescription").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); - }); - } + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupWelcomeChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); + }); - case "welcomeImage" -> { - LanguageService.getByGuild(event.getGuild(), "message.welcome.imageRequired").subscribe(description -> { - embedBuilder.setDescription(description); - event.editMessageEmbeds(embedBuilder.build()).setComponents().queue(); - }); - } + case "welcomeImage" -> + LanguageService.getByGuild(event.getGuild(), "message.welcome.imageRequired").subscribe(description -> { + embedBuilder.setDescription(description); + event.editMessageEmbeds(embedBuilder.build()).setComponents().queue(); + }); - case "welcomeDelete" -> { - SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).subscribe(webhook -> - webhook.ifPresent(webhookWelcome -> event.getJDA().retrieveWebhookById(webhookWelcome.getChannelId()).queue(webhook1 -> { - webhook1.delete().queue(); - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.deleted").block()); - embedBuilder.setColor(Color.GREEN); - event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookWelcome).block(); - }))); - } + case "welcomeDelete" -> + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).subscribe(webhook -> + webhook.ifPresent(webhookWelcome -> event.getJDA().retrieveWebhookById(webhookWelcome.getChannelId()).queue(webhook1 -> { + webhook1.delete().queue(); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.deleted").block()); + embedBuilder.setColor(Color.GREEN); + event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookWelcome).block(); + }))); default -> { if (event.getMessage().getEmbeds().isEmpty() || event.getMessage().getEmbeds().get(0) == null) diff --git a/src/main/java/de/presti/ree6/module/logger/events/LogMessageVoice.java b/src/main/java/de/presti/ree6/module/logger/events/LogMessageVoice.java index 82caf869f..fbace4fcb 100644 --- a/src/main/java/de/presti/ree6/module/logger/events/LogMessageVoice.java +++ b/src/main/java/de/presti/ree6/module/logger/events/LogMessageVoice.java @@ -17,7 +17,7 @@ public class LogMessageVoice extends LogMessage { /** * An instance of the Member Entity. */ - private Member member; + private final Member member; /** * The Audio Channels associated with the Events. diff --git a/src/main/java/de/presti/ree6/utils/config/Config.java b/src/main/java/de/presti/ree6/utils/config/Config.java index 0cbe82bfb..37e8fffe7 100644 --- a/src/main/java/de/presti/ree6/utils/config/Config.java +++ b/src/main/java/de/presti/ree6/utils/config/Config.java @@ -347,7 +347,7 @@ public void migrateOldConfig() { try { yamlFile.save(getFile()); } catch (Exception exception) { - exception.printStackTrace(); + log.error("Failed to save migrated config!", exception); } } } diff --git a/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Credential.java b/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Credential.java index 53b06d530..24eca8546 100644 --- a/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Credential.java +++ b/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Credential.java @@ -47,7 +47,7 @@ public class CustomOAuth2Credential extends Credential { /** * OAuth Scopes */ - private List scopes; + private final List scopes; /** * Access Token context that can be used to store additional information From 5e8baac7812b71155572cef843aeeb82f3abd54b Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 16:31:24 +0200 Subject: [PATCH 61/94] Code clean up. Signed-off-by: Presti --- .../presti/ree6/commands/impl/mod/Setup.java | 42 +-- .../presti/ree6/commands/impl/mod/Warn.java | 20 +- .../de/presti/ree6/events/MenuEvents.java | 333 +++++++++--------- .../notifications/impl/RedditSonic.java | 56 ++- .../notifications/impl/SpotifySonic.java | 16 +- .../notifications/impl/TwitchSonic.java | 137 ++++--- .../de/presti/ree6/utils/apis/Notifier.java | 46 +-- 7 files changed, 296 insertions(+), 354 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java index 6e7222df3..049387666 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java @@ -148,18 +148,14 @@ public void onPerform(CommandEvent commandEvent) { if (commandEvent.getSubcommand().equals("set")) { if (guildChannelUnion.getType() == ChannelType.TEXT) { - guildChannelUnion.asTextChannel().createWebhook(BotConfig.getBotName() + "-Logs").queue(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { - if (aBoolean) { - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> { - webhookEntity.ifPresent((entity) -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity)); - }); - } - - SQLSession.getSqlConnector().getSqlWorker().setLogWebhook(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong(), webhook.getIdLong(), webhook.getToken()); - commandEvent.reply(commandEvent.getResource("message.auditLog.setupSuccess")); - }); - }); + guildChannelUnion.asTextChannel().createWebhook(BotConfig.getBotName() + "-Logs").queue(webhook -> SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { + if (aBoolean) { + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> webhookEntity.ifPresent((entity) -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity))); + } + + SQLSession.getSqlConnector().getSqlWorker().setLogWebhook(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong(), webhook.getIdLong(), webhook.getToken()); + commandEvent.reply(commandEvent.getResource("message.auditLog.setupSuccess")); + })); } else { commandEvent.reply(commandEvent.getResource("message.default.invalidOptionChannel")); } @@ -184,17 +180,13 @@ public void onPerform(CommandEvent commandEvent) { if (commandEvent.getSubcommand().equals("set")) { if (guildChannelUnion.getType() == ChannelType.TEXT) { - guildChannelUnion.asTextChannel().createWebhook(BotConfig.getBotName() + "-Welcome").queue(webhook -> { - SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { - if (aBoolean) { - SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> { - webhookEntity.ifPresent((entity) -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity)); - }); - } - SQLSession.getSqlConnector().getSqlWorker().setWelcomeWebhook(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong(), webhook.getIdLong(), webhook.getToken()); - commandEvent.reply(commandEvent.getResource("message.welcome.setupSuccess")); - }); - }); + guildChannelUnion.asTextChannel().createWebhook(BotConfig.getBotName() + "-Welcome").queue(webhook -> SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { + if (aBoolean) { + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> webhookEntity.ifPresent((entity) -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity))); + } + SQLSession.getSqlConnector().getSqlWorker().setWelcomeWebhook(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong(), webhook.getIdLong(), webhook.getToken()); + commandEvent.reply(commandEvent.getResource("message.welcome.setupSuccess")); + })); } else { commandEvent.reply(commandEvent.getResource("message.default.invalidOptionChannel")); } @@ -212,9 +204,7 @@ public void onPerform(CommandEvent commandEvent) { case "tempvoice" -> { if (commandEvent.getSubcommand().equals("set")) { if (guildChannelUnion.getType() == ChannelType.VOICE) { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new TemporalVoicechannel(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong())).subscribe(save -> { - commandEvent.reply(commandEvent.getResource("message.temporalVoice.setupSuccess")); - }); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new TemporalVoicechannel(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong())).subscribe(save -> commandEvent.reply(commandEvent.getResource("message.temporalVoice.setupSuccess"))); } else { commandEvent.reply(commandEvent.getResource("message.default.invalidOptionChannel")); } diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java b/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java index 50a8f291d..665ec01d6 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Warn.java @@ -72,9 +72,7 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(2); punishments.setRoleId(roleMapping.getAsRole().getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> { - commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); - }); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> commandEvent.reply(commandEvent.getResource("message.warn.punishment.created"))); } case "roleremove" -> { @@ -83,9 +81,7 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(3); punishments.setRoleId(roleMapping.getAsRole().getIdLong()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> { - commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); - }); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> commandEvent.reply(commandEvent.getResource("message.warn.punishment.created"))); } case "timeout" -> { @@ -94,9 +90,7 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(1); punishments.setTimeoutTime(secondsMapping.getAsLong() * 1000); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> { - commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); - }); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> commandEvent.reply(commandEvent.getResource("message.warn.punishment.created"))); } case "kick" -> { @@ -105,9 +99,7 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(4); if (reasonMapping != null) punishments.setReason(reasonMapping.getAsString()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> { - commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); - }); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> commandEvent.reply(commandEvent.getResource("message.warn.punishment.created"))); } case "ban" -> { @@ -116,9 +108,7 @@ public void onPerform(CommandEvent commandEvent) { punishments.setWarnings(warningMapping.getAsInt()); punishments.setAction(5); if (reasonMapping != null) punishments.setReason(reasonMapping.getAsString()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> { - commandEvent.reply(commandEvent.getResource("message.warn.punishment.created")); - }); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(punishments).subscribe(save -> commandEvent.reply(commandEvent.getResource("message.warn.punishment.created"))); } case "list" -> diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index fa20d3144..79a1b7284 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -443,41 +443,39 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { } event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.twitchCountName", Main.getInstance().getNotifier().getTwitchClient().getHelix().getChannelFollowers(null, channelId, null, 1, null).execute().getTotal()).block(), category) - .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStats -> { - if (channelStats.isPresent()) { - ChannelStats channelStatsEntity = channelStats.get(); - if (channelStatsEntity.getTwitchFollowerChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStatsEntity.getTwitchFollowerChannelId()); - - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } - - channelStatsEntity.setTwitchFollowerChannelId(voiceChannel.getId()); - channelStatsEntity.setTwitchFollowerChannelUsername(twitchUsername); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStatsEntity).block(); - Main.getInstance().getNotifier().getTwitchSonic().add(twitchUsername); - } else { - ChannelStats channelStatsEntity = new ChannelStats(event.getGuild().getIdLong(), - null, - null, - null, - voiceChannel.getId(), - twitchUsername, - null, - null, - null, - null, - null, - null, - null, - null); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStatsEntity).block(); - Main.getInstance().getNotifier().getTwitterSonic().add(twitchUsername); + .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStats -> { + if (channelStats.isPresent()) { + ChannelStats channelStatsEntity = channelStats.get(); + if (channelStatsEntity.getTwitchFollowerChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStatsEntity.getTwitchFollowerChannelId()); + + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); } - }); - }); + + channelStatsEntity.setTwitchFollowerChannelId(voiceChannel.getId()); + channelStatsEntity.setTwitchFollowerChannelUsername(twitchUsername); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStatsEntity).block(); + Main.getInstance().getNotifier().getTwitchSonic().add(twitchUsername); + } else { + ChannelStats channelStatsEntity = new ChannelStats(event.getGuild().getIdLong(), + null, + null, + null, + voiceChannel.getId(), + twitchUsername, + null, + null, + null, + null, + null, + null, + null, + null); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStatsEntity).block(); + Main.getInstance().getNotifier().getTwitterSonic().add(twitchUsername); + } + })); EmbedBuilder embedBuilder = new EmbedBuilder() .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) @@ -543,40 +541,38 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { } event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.youtubeCountName", youTubeChannel.getSubscriberCountText()).block(), category) - .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { - if (channelStatsOptional.isPresent()) { - ChannelStats channelStats = channelStatsOptional.get(); - if (channelStats.getYoutubeSubscribersChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getYoutubeSubscribersChannelId()); - - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } - - channelStats.setYoutubeSubscribersChannelId(voiceChannel.getId()); - channelStats.setYoutubeSubscribersChannelUsername(youTubeChannel.getId()); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); - Main.getInstance().getNotifier().getYouTubeSonic().add(youTubeChannel.getId()); - } else { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), - null, - null, - null, - null, - null, - null, - null, - null, - null, - voiceChannel.getId(), - youTubeChannel.getId(), - null, - null)).block(); - Main.getInstance().getNotifier().getYouTubeSonic().add(youTubeChannel.getId()); + .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { + if (channelStatsOptional.isPresent()) { + ChannelStats channelStats = channelStatsOptional.get(); + if (channelStats.getYoutubeSubscribersChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getYoutubeSubscribersChannelId()); + + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); } - }); - }); + + channelStats.setYoutubeSubscribersChannelId(voiceChannel.getId()); + channelStats.setYoutubeSubscribersChannelUsername(youTubeChannel.getId()); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + Main.getInstance().getNotifier().getYouTubeSonic().add(youTubeChannel.getId()); + } else { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), + null, + null, + null, + null, + null, + null, + null, + null, + null, + voiceChannel.getId(), + youTubeChannel.getId(), + null, + null)).block(); + Main.getInstance().getNotifier().getYouTubeSonic().add(youTubeChannel.getId()); + } + })); embedBuilder = embedBuilder .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) @@ -627,40 +623,38 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { } event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.redditCountName", subreddit.getActiveUserCount()).block(), category) - .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { - if (channelStatsOptional.isPresent()) { - ChannelStats channelStats = channelStatsOptional.get(); - if (channelStats.getSubredditMemberChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getSubredditMemberChannelId()); - - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } - - channelStats.setSubredditMemberChannelId(voiceChannel.getId()); - channelStats.setSubredditMemberChannelSubredditName(subredditName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); - Main.getInstance().getNotifier().getRedditSonic().add(subredditName); - } else { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - voiceChannel.getId(), - subredditName)).block(); - Main.getInstance().getNotifier().getRedditSonic().add(subredditName); + .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { + if (channelStatsOptional.isPresent()) { + ChannelStats channelStats = channelStatsOptional.get(); + if (channelStats.getSubredditMemberChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getSubredditMemberChannelId()); + + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); } - }); - }); + + channelStats.setSubredditMemberChannelId(voiceChannel.getId()); + channelStats.setSubredditMemberChannelSubredditName(subredditName); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + Main.getInstance().getNotifier().getRedditSonic().add(subredditName); + } else { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + voiceChannel.getId(), + subredditName)).block(); + Main.getInstance().getNotifier().getRedditSonic().add(subredditName); + } + })); embedBuilder = embedBuilder .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) @@ -711,40 +705,38 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { } event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.twitterCountName", twitterUser.getFollowersCount()).block(), category) - .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { - if (channelStatsOptional.isPresent()) { - ChannelStats channelStats = channelStatsOptional.get(); - if (channelStats.getTwitterFollowerChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getTwitterFollowerChannelId()); - - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } - - channelStats.setTwitterFollowerChannelId(voiceChannel.getId()); - channelStats.setTwitterFollowerChannelUsername(twitterName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); - Main.getInstance().getNotifier().getTwitterSonic().add(twitterName); - } else { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), - null, - null, - null, - voiceChannel.getId(), - twitterName, - null, - null, - null, - null, - null, - null, - null, - null)).block(); - Main.getInstance().getNotifier().getTwitterSonic().add(twitterName); + .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { + if (channelStatsOptional.isPresent()) { + ChannelStats channelStats = channelStatsOptional.get(); + if (channelStats.getTwitterFollowerChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getTwitterFollowerChannelId()); + + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); } - }); - }); + + channelStats.setTwitterFollowerChannelId(voiceChannel.getId()); + channelStats.setTwitterFollowerChannelUsername(twitterName); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + Main.getInstance().getNotifier().getTwitterSonic().add(twitterName); + } else { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), + null, + null, + null, + voiceChannel.getId(), + twitterName, + null, + null, + null, + null, + null, + null, + null, + null)).block(); + Main.getInstance().getNotifier().getTwitterSonic().add(twitterName); + } + })); embedBuilder = embedBuilder .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) @@ -795,41 +787,38 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { } event.getGuild().createVoiceChannel(LanguageService.getByGuild(event.getGuild(), "label.instagramCountName", instagramUser.getFollower_count()).block(), category) - .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { - if (channelStatsOptional.isPresent()) { - ChannelStats channelStats = channelStatsOptional.get(); - if (channelStats.getInstagramFollowerChannelId() != null) { - VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getInstagramFollowerChannelId()); - - if (voiceChannel3 != null) - voiceChannel3.delete().queue(); - } - - channelStats.setInstagramFollowerChannelId(voiceChannel.getId()); - channelStats.setInstagramFollowerChannelUsername(instagramName); - SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); - Main.getInstance().getNotifier().getInstagramSonic().add(instagramName); - } else { - SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), - null, - null, - null, - null, - null, - voiceChannel.getId(), - instagramName, - null, - null, - null, - null, - null, - null)).block(); - Main.getInstance().getNotifier().getInstagramSonic().add(instagramName); + .addPermissionOverride(event.getGuild().getPublicRole(), 0, Permission.VOICE_CONNECT.getRawValue()).queue(voiceChannel -> SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(channelStatsOptional -> { + if (channelStatsOptional.isPresent()) { + ChannelStats channelStats = channelStatsOptional.get(); + if (channelStats.getInstagramFollowerChannelId() != null) { + VoiceChannel voiceChannel3 = event.getGuild().getVoiceChannelById(channelStats.getInstagramFollowerChannelId()); + + if (voiceChannel3 != null) + voiceChannel3.delete().queue(); } - }); - }); + channelStats.setInstagramFollowerChannelId(voiceChannel.getId()); + channelStats.setInstagramFollowerChannelUsername(instagramName); + SQLSession.getSqlConnector().getSqlWorker().updateEntity(channelStats).block(); + Main.getInstance().getNotifier().getInstagramSonic().add(instagramName); + } else { + SQLSession.getSqlConnector().getSqlWorker().updateEntity(new ChannelStats(event.getGuild().getIdLong(), + null, + null, + null, + null, + null, + voiceChannel.getId(), + instagramName, + null, + null, + null, + null, + null, + null)).block(); + Main.getInstance().getNotifier().getInstagramSonic().add(instagramName); + } + })); embedBuilder = embedBuilder .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) @@ -954,9 +943,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "welcome" -> LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { optionList.add(SelectOption.of(label, "welcomeSetup")); - SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).block().ifPresent(welcomeWebhook -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "welcomeDelete")); - }); + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).block().ifPresent(welcomeWebhook -> optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "welcomeDelete"))); optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.setImage").block(), "welcomeImage")); @@ -979,9 +966,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even optionList.add(SelectOption.of(label, "tempVoiceSetup")); SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", - Map.of("gid", event.getGuild().getIdLong())).block().ifPresent(temporalVoicechannel -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "tempVoiceDelete")); - }); + Map.of("gid", event.getGuild().getIdLong())).block().ifPresent(temporalVoicechannel -> optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "tempVoiceDelete"))); optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); @@ -1010,9 +995,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "tickets" -> LanguageService.getByGuild(event.getGuild(), "label.setup").subscribe(label -> { optionList.add(SelectOption.of(label, "ticketsSetup")); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).block().ifPresent(tickets -> { - optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "ticketsDelete")); - }); + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).block().ifPresent(tickets -> optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.delete").block(), "ticketsDelete"))); optionList.add(SelectOption.of(LanguageService.getByGuild(event.getGuild(), "label.backToMenu").block(), "backToSetupMenu")); diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java index cb0b2a8a3..0ea753dea 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java @@ -87,46 +87,44 @@ public void run() { } }); - getSubredditPosts(subreddit, Sorting.NEW, 50).stream().filter(redditPost -> redditPost.getCreated() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())).forEach(redditPost -> { - SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit).subscribe(webhooks -> { - if (webhooks.isEmpty()) return; + getSubredditPosts(subreddit, Sorting.NEW, 50).stream().filter(redditPost -> redditPost.getCreated() > (Duration.ofMillis(System.currentTimeMillis()).toSeconds() - Duration.ofMinutes(5).toSeconds())).forEach(redditPost -> SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(subreddit).subscribe(webhooks -> { + if (webhooks.isEmpty()) return; - // Create Webhook Message. - WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); + // Create Webhook Message. + WebhookMessageBuilder webhookMessageBuilder = new WebhookMessageBuilder(); - webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); - webhookMessageBuilder.setUsername(BotConfig.getBotName()); + webhookMessageBuilder.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl()); + webhookMessageBuilder.setUsername(BotConfig.getBotName()); - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(redditPost.getTitle(), redditPost.getUrl())); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Reddit Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(redditPost.getTitle(), redditPost.getUrl())); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Reddit Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl(), null)); - if (!redditPost.getThumbnail().equalsIgnoreCase("self")) - webhookEmbedBuilder.setImageUrl(redditPost.getThumbnail()); + if (!redditPost.getThumbnail().equalsIgnoreCase("self")) + webhookEmbedBuilder.setImageUrl(redditPost.getThumbnail()); - // Set rest of the Information. - webhookEmbedBuilder.setDescription(URLDecoder.decode(redditPost.getSelftext(), StandardCharsets.UTF_8)); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Author**", redditPost.getAuthor())); - webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Subreddit**", redditPost.getSubreddit())); - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); + // Set rest of the Information. + webhookEmbedBuilder.setDescription(URLDecoder.decode(redditPost.getSelftext(), StandardCharsets.UTF_8)); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Author**", redditPost.getAuthor())); + webhookEmbedBuilder.addField(new WebhookEmbed.EmbedField(true, "**Subreddit**", redditPost.getSubreddit())); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getAvatarUrl())); - webhookEmbedBuilder.setColor(Color.ORANGE.getRGB()); + webhookEmbedBuilder.setColor(Color.ORANGE.getRGB()); - webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); + webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - webhooks.forEach(webhook -> { - String message = webhook.getMessage() - .replace("%title%", redditPost.getTitle()) - .replace("%author%", redditPost.getAuthor()) - .replace("%name%", redditPost.getSubreddit()) - .replace("%url%", redditPost.getUrl()); - webhookMessageBuilder.setContent(message); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); - }); + webhooks.forEach(webhook -> { + String message = webhook.getMessage() + .replace("%title%", redditPost.getTitle()) + .replace("%author%", redditPost.getAuthor()) + .replace("%name%", redditPost.getSubreddit()) + .replace("%url%", redditPost.getUrl()); + webhookMessageBuilder.setContent(message); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); }); - }); + })); } } catch (Exception exception) { log.error("Could not get Reddit Posts!", exception); diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java index cd6fae9b1..f1f9c9d4a 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java @@ -42,15 +42,13 @@ public void load(List channelStats) { @Override public void load() { // Register all Spotify artists and podcasts. - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new WebhookSpotify(), "FROM WebhookSpotify", Map.of()).subscribe(spotifyNotify -> { - spotifyNotify.forEach(x -> { - if (x.getEntityTyp() == 0) { - add("art:" + x.getEntityId()); - } else { - add("pot:" + x.getEntityId()); - } - }); - }); + SQLSession.getSqlConnector().getSqlWorker().getEntityList(new WebhookSpotify(), "FROM WebhookSpotify", Map.of()).subscribe(spotifyNotify -> spotifyNotify.forEach(x -> { + if (x.getEntityTyp() == 0) { + add("art:" + x.getEntityId()); + } else { + add("pot:" + x.getEntityId()); + } + })); } @Override diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java index edca65045..53ec2a4c5 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java @@ -58,81 +58,76 @@ public List getList() { @Override public void run() { - Main.getInstance().getNotifier().getTwitchClient().getEventManager().onEvent(ChannelGoLiveEvent.class, channelGoLiveEvent -> { - - SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(channelGoLiveEvent.getChannel().getName()).subscribe(webhooks -> { - if (webhooks.isEmpty()) { - return; - } - - String twitchUrl = "https://twitch.tv/" + channelGoLiveEvent.getChannel().getName(); - - // Create a Webhook Message. - WebhookMessageBuilder wmb = new WebhookMessageBuilder(); - - wmb.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); - wmb.setUsername(BotConfig.getBotName()); - - WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); - - webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(channelGoLiveEvent.getStream().getUserName(), twitchUrl)); - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Twitch Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl(), null)); - - // Try getting the User. - Optional twitchUserRequest = Main.getInstance().getNotifier().getTwitchClient().getHelix().getUsers(null, null, Collections.singletonList(channelGoLiveEvent.getStream().getUserName())).execute().getUsers().stream().findFirst(); - if (twitchUserRequest.isPresent()) { - webhookEmbedBuilder.setThumbnailUrl(twitchUserRequest.orElseThrow().getProfileImageUrl()); - } - - // Set rest of the Information. - webhookEmbedBuilder.setDescription("**" + channelGoLiveEvent.getStream().getTitle() + "**"); - GameList gameList = Main.getInstance().getNotifier().getTwitchClient().getClientHelper().getTwitchHelix().getGames(null, List.of(channelGoLiveEvent.getStream().getGameId()), null, null).execute(); - if (!gameList.getGames().isEmpty()) { - webhookEmbedBuilder.setThumbnailUrl(gameList.getGames().get(0).getBoxArtUrl()); - } - - webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(channelGoLiveEvent.getStream().getUserName(), twitchUserRequest.map(User::getProfileImageUrl).orElse(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()), twitchUrl)); - webhookEmbedBuilder.setImageUrl(channelGoLiveEvent.getStream().getThumbnailUrlTemplate()); - webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(channelGoLiveEvent.getStream().getGameName(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); - webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); - - wmb.addComponents(ActionRow.of(new Button(Button.Style.LINK, twitchUrl).setLabel(twitchUserRequest.isPresent() ? twitchUserRequest.get().getDisplayName() : "Watch Stream"))); - wmb.addEmbeds(webhookEmbedBuilder.build()); - - // Go through every Webhook that is registered for the Twitch Channel - webhooks.forEach(webhook -> { - String message = webhook.getMessage() - .replace("%name%", channelGoLiveEvent.getStream().getUserName()) - .replace("%url%", twitchUrl); - wmb.setContent(message); - WebhookUtil.sendWebhook(wmb.build(), webhook); - }); + Main.getInstance().getNotifier().getTwitchClient().getEventManager().onEvent(ChannelGoLiveEvent.class, channelGoLiveEvent -> SQLSession.getSqlConnector().getSqlWorker().getTwitchWebhooksByName(channelGoLiveEvent.getChannel().getName()).subscribe(webhooks -> { + if (webhooks.isEmpty()) { + return; + } + + String twitchUrl = "https://twitch.tv/" + channelGoLiveEvent.getChannel().getName(); + + // Create a Webhook Message. + WebhookMessageBuilder wmb = new WebhookMessageBuilder(); + + wmb.setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()); + wmb.setUsername(BotConfig.getBotName()); + + WebhookEmbedBuilder webhookEmbedBuilder = new WebhookEmbedBuilder(); + + webhookEmbedBuilder.setTitle(new WebhookEmbed.EmbedTitle(channelGoLiveEvent.getStream().getUserName(), twitchUrl)); + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor("Twitch Notifier", BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl(), null)); + + // Try getting the User. + Optional twitchUserRequest = Main.getInstance().getNotifier().getTwitchClient().getHelix().getUsers(null, null, Collections.singletonList(channelGoLiveEvent.getStream().getUserName())).execute().getUsers().stream().findFirst(); + if (twitchUserRequest.isPresent()) { + webhookEmbedBuilder.setThumbnailUrl(twitchUserRequest.orElseThrow().getProfileImageUrl()); + } + + // Set rest of the Information. + webhookEmbedBuilder.setDescription("**" + channelGoLiveEvent.getStream().getTitle() + "**"); + GameList gameList = Main.getInstance().getNotifier().getTwitchClient().getClientHelper().getTwitchHelix().getGames(null, List.of(channelGoLiveEvent.getStream().getGameId()), null, null).execute(); + if (!gameList.getGames().isEmpty()) { + webhookEmbedBuilder.setThumbnailUrl(gameList.getGames().get(0).getBoxArtUrl()); + } + + webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(channelGoLiveEvent.getStream().getUserName(), twitchUserRequest.map(User::getProfileImageUrl).orElse(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()), twitchUrl)); + webhookEmbedBuilder.setImageUrl(channelGoLiveEvent.getStream().getThumbnailUrlTemplate()); + webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(channelGoLiveEvent.getStream().getGameName(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); + webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); + + wmb.addComponents(ActionRow.of(new Button(Button.Style.LINK, twitchUrl).setLabel(twitchUserRequest.isPresent() ? twitchUserRequest.get().getDisplayName() : "Watch Stream"))); + wmb.addEmbeds(webhookEmbedBuilder.build()); + + // Go through every Webhook that is registered for the Twitch Channel + webhooks.forEach(webhook -> { + String message = webhook.getMessage() + .replace("%name%", channelGoLiveEvent.getStream().getUserName()) + .replace("%url%", twitchUrl); + wmb.setContent(message); + WebhookUtil.sendWebhook(wmb.build(), webhook); }); - }); - - Main.getInstance().getNotifier().getTwitchClient().getEventManager().onEvent(ChannelFollowCountUpdateEvent.class, channelFollowCountUpdateEvent -> { - SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), - "FROM ChannelStats WHERE LOWER(twitchFollowerChannelUsername) = :name", - Map.of("name", channelFollowCountUpdateEvent.getChannel().getName().toLowerCase())).subscribe(channelStats -> { - if (!channelStats.isEmpty()) { - for (ChannelStats channelStat : channelStats) { - if (channelStat.getTwitchFollowerChannelId() != null) { - GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getTwitchFollowerChannelId()); - if (guildChannel != null) { - if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) - continue; - - LanguageService.getByGuild(guildChannel.getGuild(), "label.twitchCountName", channelFollowCountUpdateEvent.getFollowCount()).subscribe(newName -> { - if (!guildChannel.getName().equalsIgnoreCase(newName)) { - guildChannel.getManager().setName(newName).queue(); - } - }); - } + })); + + Main.getInstance().getNotifier().getTwitchClient().getEventManager().onEvent(ChannelFollowCountUpdateEvent.class, channelFollowCountUpdateEvent -> SQLSession.getSqlConnector().getSqlWorker().getEntityList(new ChannelStats(), + "FROM ChannelStats WHERE LOWER(twitchFollowerChannelUsername) = :name", + Map.of("name", channelFollowCountUpdateEvent.getChannel().getName().toLowerCase())).subscribe(channelStats -> { + if (!channelStats.isEmpty()) { + for (ChannelStats channelStat : channelStats) { + if (channelStat.getTwitchFollowerChannelId() != null) { + GuildChannel guildChannel = BotWorker.getShardManager().getGuildChannelById(channelStat.getTwitchFollowerChannelId()); + if (guildChannel != null) { + if (!guildChannel.getGuild().getSelfMember().hasAccess(guildChannel)) + continue; + + LanguageService.getByGuild(guildChannel.getGuild(), "label.twitchCountName", channelFollowCountUpdateEvent.getFollowCount()).subscribe(newName -> { + if (!guildChannel.getName().equalsIgnoreCase(newName)) { + guildChannel.getManager().setName(newName).queue(); + } + }); } } } - }); - }); + } + })); } @Override diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index 9556b8959..15bbc73e3 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -13,10 +13,10 @@ import com.github.twitch4j.eventsub.events.ChannelSubscribeEvent; import com.github.twitch4j.pubsub.PubSubSubscription; import com.github.twitch4j.pubsub.events.RewardRedeemedEvent; -import de.presti.ree6.module.actions.streamtools.container.StreamActionContainerCreator; import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.BotWorker; import de.presti.ree6.main.Main; +import de.presti.ree6.module.actions.streamtools.container.StreamActionContainerCreator; import de.presti.ree6.module.notifications.impl.*; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.TwitchIntegration; @@ -176,38 +176,26 @@ public Notifier() { } }); - twitchClient.getEventManager().onEvent(RewardRedeemedEvent.class, event -> { - StreamActionContainerCreator.getContainers(0).subscribe(list -> { - list.forEach(container -> { - if (!event.getRedemption().getChannelId().equalsIgnoreCase(container.getTwitchChannelId())) - return; - - if (container.getExtraArgument() == null || event.getRedemption().getReward().getId().equals(container.getExtraArgument())) { - container.runActions(event, event.getRedemption().getUserInput()); - } - }); - }); - }); + twitchClient.getEventManager().onEvent(RewardRedeemedEvent.class, event -> StreamActionContainerCreator.getContainers(0).subscribe(list -> list.forEach(container -> { + if (!event.getRedemption().getChannelId().equalsIgnoreCase(container.getTwitchChannelId())) + return; - twitchClient.getEventManager().onEvent(FollowEvent.class, event -> { - StreamActionContainerCreator.getContainers(1).subscribe(list -> { - list.forEach(container -> { - if (!event.getChannel().getId().equalsIgnoreCase(container.getTwitchChannelId())) return; + if (container.getExtraArgument() == null || event.getRedemption().getReward().getId().equals(container.getExtraArgument())) { + container.runActions(event, event.getRedemption().getUserInput()); + } + }))); - container.runActions(event, event.getUser().getName()); - }); - }); - }); + twitchClient.getEventManager().onEvent(FollowEvent.class, event -> StreamActionContainerCreator.getContainers(1).subscribe(list -> list.forEach(container -> { + if (!event.getChannel().getId().equalsIgnoreCase(container.getTwitchChannelId())) return; - twitchClient.getEventManager().onEvent(ChannelSubscribeEvent.class, event -> { - StreamActionContainerCreator.getContainers(2).subscribe(list -> { - list.forEach(container -> { - if (!event.getBroadcasterUserId().equalsIgnoreCase(container.getTwitchChannelId())) return; + container.runActions(event, event.getUser().getName()); + }))); - container.runActions(null, event.getUserName()); - }); - }); - }); + twitchClient.getEventManager().onEvent(ChannelSubscribeEvent.class, event -> StreamActionContainerCreator.getContainers(2).subscribe(list -> list.forEach(container -> { + if (!event.getBroadcasterUserId().equalsIgnoreCase(container.getTwitchChannelId())) return; + + container.runActions(null, event.getUserName()); + }))); } catch (Exception exception) { Sentry.captureException(exception); log.error("Failed to create Twitch Client.", exception); From 01d2aea76779da48d5ce175d30ee7e6d60060b83 Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 16:37:47 +0200 Subject: [PATCH 62/94] Code clean up. Signed-off-by: Presti --- src/main/java/de/presti/ree6/commands/impl/mod/Setup.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java index 049387666..2cc7ab2a6 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java @@ -150,7 +150,7 @@ public void onPerform(CommandEvent commandEvent) { if (guildChannelUnion.getType() == ChannelType.TEXT) { guildChannelUnion.asTextChannel().createWebhook(BotConfig.getBotName() + "-Logs").queue(webhook -> SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { if (aBoolean) { - SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> webhookEntity.ifPresent((entity) -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity))); + SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> webhookEntity.ifPresent(entity -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity))); } SQLSession.getSqlConnector().getSqlWorker().setLogWebhook(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong(), webhook.getIdLong(), webhook.getToken()); @@ -163,7 +163,7 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().isLogSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { if (aBoolean) { SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> { - webhookEntity.ifPresent((entity) -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity)); + webhookEntity.ifPresent(entity -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity)); commandEvent.reply(commandEvent.getResource("message.auditLog.deleted")); }); } else { @@ -182,7 +182,7 @@ public void onPerform(CommandEvent commandEvent) { if (guildChannelUnion.getType() == ChannelType.TEXT) { guildChannelUnion.asTextChannel().createWebhook(BotConfig.getBotName() + "-Welcome").queue(webhook -> SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { if (aBoolean) { - SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> webhookEntity.ifPresent((entity) -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity))); + SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> webhookEntity.ifPresent(entity -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity))); } SQLSession.getSqlConnector().getSqlWorker().setWelcomeWebhook(commandEvent.getGuild().getIdLong(), guildChannelUnion.getIdLong(), webhook.getIdLong(), webhook.getToken()); commandEvent.reply(commandEvent.getResource("message.welcome.setupSuccess")); @@ -194,7 +194,7 @@ public void onPerform(CommandEvent commandEvent) { SQLSession.getSqlConnector().getSqlWorker().isWelcomeSetup(commandEvent.getGuild().getIdLong()).subscribe(aBoolean -> { if (aBoolean) { SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(commandEvent.getGuild().getIdLong()).subscribe(webhookEntity -> - webhookEntity.ifPresent((entity) -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity))); + webhookEntity.ifPresent(entity -> WebhookUtil.deleteWebhook(commandEvent.getGuild().getIdLong(), entity))); commandEvent.reply(commandEvent.getResource("message.welcome.deleted")); } commandEvent.reply(commandEvent.getResource("message.default.invalidOption")); From e19e0b9ab87b11e292481df58bd313ab5f781f90 Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 16:40:57 +0200 Subject: [PATCH 63/94] Code clean up. Signed-off-by: Presti --- .../module/notifications/impl/RSSSonic.java | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java index 39f2b15d9..661f1b6e3 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java @@ -54,17 +54,18 @@ public void run() { Collection urls = getList().stream().map(SonicIdentifier::getIdentifier).toList(); /* - * TODO:: Either switch to RSSHub, YouTubes RSS or stay on API based. + * Either switch to RSSHub, YouTubes RSS or stay on API based. * Issue with RSSHub is that it takes 2 hours to update, because of caching. * Issue with YouTube is RSS that it takes over 30 minutes to update, because of idk random internal stuff. + * + * ////Collection urls = new ArrayList<>(registeredYouTubeChannels.stream().map(c -> "https://rsshub.app/youtube/channel/" + c).toList()); + * + * Wait till Nitter has fixed their RSS Feeds. Or Twitter finally gets the stick out of their ass and stop limiting simple scraping. 05.07: Twitter still has a stick up their ass and Nitter died because of it. WoW. + * ////urls.addAll(registeredTwitterUsers.stream().map(c -> "https://nitter.net/" + c + "/rss").toList()); + * + * ////urls.addAll(registeredRSSFeeds); */ - ////Collection urls = new ArrayList<>(registeredYouTubeChannels.stream().map(c -> "https://rsshub.app/youtube/channel/" + c).toList()); - - // TODO:: Wait till Nitter has fixed their RSS Feeds. Or Twitter finally gets the stick out of their ass and stop limiting simple scraping. 05.07: Twitter still has a stick up their ass and Nitter died because of it. WoW. - ////urls.addAll(registeredTwitterUsers.stream().map(c -> "https://nitter.net/" + c + "/rss").toList()); - - ////urls.addAll(registeredRSSFeeds); List checkedIds = new ArrayList<>(); @@ -117,10 +118,10 @@ public void run() { String id = ""; - switch (typ) { - case "tw" -> id = item.getChannel().getLink().replace("https://nitter.net/", ""); - - case "other" -> id = item.getChannel().getLink(); + if (typ.equals("tw")) { + id = item.getChannel().getLink().replace("https://nitter.net/", ""); + } else { + id = item.getChannel().getLink(); } if (checkedIds.contains(id)) { From fb895ebd492498d9046b24bd201f4b08f8253200 Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 16:43:33 +0200 Subject: [PATCH 64/94] Code clean up. Signed-off-by: Presti --- .../de/presti/ree6/module/game/core/GameManager.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/java/de/presti/ree6/module/game/core/GameManager.java b/src/main/java/de/presti/ree6/module/game/core/GameManager.java index 21da79f08..0a857e0ac 100644 --- a/src/main/java/de/presti/ree6/module/game/core/GameManager.java +++ b/src/main/java/de/presti/ree6/module/game/core/GameManager.java @@ -20,18 +20,25 @@ @Slf4j public class GameManager { + /** + * Constructor to prevent instance creation of the GameManager. + */ + private GameManager() { + throw new UnsupportedOperationException("Do not instance this."); + } + /** * A HashMap used to cache the Games. * The Key is the Name of the Game. */ @Getter - private final static HashMap> gameCache = new HashMap<>(); + private static final HashMap> gameCache = new HashMap<>(); /** * A HashMap used to cache the GameSessions. * The Key is the ID of the Channel. */ - private final static HashMap gameSessions = new HashMap<>(); + private static final HashMap gameSessions = new HashMap<>(); /** * Should be called to load all Games into the cache. From e3e7e32b4a00edc5a94e6291e1b82d6923c5a120 Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 16:48:00 +0200 Subject: [PATCH 65/94] Code clean up. Signed-off-by: Presti --- .../container/CustomEventContainerCreator.java | 2 +- .../container/StreamActionContainerCreator.java | 2 +- .../de/presti/ree6/module/news/AnnouncementManager.java | 7 +++++++ .../java/de/presti/ree6/utils/data/TranscriptUtil.java | 7 +++++++ .../java/de/presti/ree6/utils/oauth/CustomOAuth2Util.java | 7 +++++++ 5 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java b/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java index f6607659d..22b318fdf 100644 --- a/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java +++ b/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java @@ -28,7 +28,7 @@ public class CustomEventContainerCreator { /** * Constructor should not be called, since it is a utility class that doesn't need an instance. */ - public CustomEventContainerCreator() { + private CustomEventContainerCreator() { throw new IllegalStateException("Utility class"); } diff --git a/src/main/java/de/presti/ree6/module/actions/streamtools/container/StreamActionContainerCreator.java b/src/main/java/de/presti/ree6/module/actions/streamtools/container/StreamActionContainerCreator.java index 6b84ee6c6..a50e13160 100644 --- a/src/main/java/de/presti/ree6/module/actions/streamtools/container/StreamActionContainerCreator.java +++ b/src/main/java/de/presti/ree6/module/actions/streamtools/container/StreamActionContainerCreator.java @@ -28,7 +28,7 @@ public class StreamActionContainerCreator { /** * Constructor should not be called, since it is a utility class that doesn't need an instance. */ - public StreamActionContainerCreator() { + private StreamActionContainerCreator() { throw new IllegalStateException("Utility class"); } diff --git a/src/main/java/de/presti/ree6/module/news/AnnouncementManager.java b/src/main/java/de/presti/ree6/module/news/AnnouncementManager.java index 4387ec864..95134e561 100644 --- a/src/main/java/de/presti/ree6/module/news/AnnouncementManager.java +++ b/src/main/java/de/presti/ree6/module/news/AnnouncementManager.java @@ -12,6 +12,13 @@ */ public class AnnouncementManager { + /** + * Constructor should not be called, since it is a utility class that doesn't need an instance. + */ + private AnnouncementManager() { + throw new IllegalStateException("Utility class"); + } + /** * List of all announcements. */ diff --git a/src/main/java/de/presti/ree6/utils/data/TranscriptUtil.java b/src/main/java/de/presti/ree6/utils/data/TranscriptUtil.java index a443d41e8..94bcd63ca 100644 --- a/src/main/java/de/presti/ree6/utils/data/TranscriptUtil.java +++ b/src/main/java/de/presti/ree6/utils/data/TranscriptUtil.java @@ -7,6 +7,13 @@ public class TranscriptUtil { + /** + * Constructor should not be called, since it is a utility class that doesn't need an instance. + */ + private TranscriptUtil() { + throw new IllegalStateException("Utility class"); + } + /** * The HTML template that should be used for the transcripts. */ diff --git a/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Util.java b/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Util.java index f8bcd223e..8b27311d5 100644 --- a/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Util.java +++ b/src/main/java/de/presti/ree6/utils/oauth/CustomOAuth2Util.java @@ -12,6 +12,13 @@ */ public class CustomOAuth2Util { + /** + * Constructor should not be called, since it is a utility class that doesn't need an instance. + */ + private CustomOAuth2Util() { + throw new IllegalStateException("Utility class"); + } + /** * A bridge method to convert a CustomOAuth2Credential to an enriched CustomOAuth2Credential. * @param customOAuth2Credential The CustomOAuth2Credential to convert. From 776ddde29f21b1f8900b76ad411128e2a896dd08 Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 16:50:06 +0200 Subject: [PATCH 66/94] Code clean up. Signed-off-by: Presti --- .../de/presti/ree6/module/logger/events/LogMessageMember.java | 4 ++-- src/main/java/de/presti/ree6/utils/config/Config.java | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/de/presti/ree6/module/logger/events/LogMessageMember.java b/src/main/java/de/presti/ree6/module/logger/events/LogMessageMember.java index dad949d30..17d89c2e9 100644 --- a/src/main/java/de/presti/ree6/module/logger/events/LogMessageMember.java +++ b/src/main/java/de/presti/ree6/module/logger/events/LogMessageMember.java @@ -184,7 +184,7 @@ public void setCurrentName(String currentName) { */ public List getRemovedRoles() { if (removedRoles == null) - return removedRoles = new ArrayList<>(); + removedRoles = new ArrayList<>(); return removedRoles; } @@ -205,7 +205,7 @@ public void setRemovedRoles(List removedRoles) { */ public List getAddedRoles() { if (addedRoles == null) - return addedRoles = new ArrayList<>(); + addedRoles = new ArrayList<>(); return addedRoles; } diff --git a/src/main/java/de/presti/ree6/utils/config/Config.java b/src/main/java/de/presti/ree6/utils/config/Config.java index 37e8fffe7..f64a1f962 100644 --- a/src/main/java/de/presti/ree6/utils/config/Config.java +++ b/src/main/java/de/presti/ree6/utils/config/Config.java @@ -405,10 +405,12 @@ public File getFile() { */ public YamlFile createTemporal() { try { - return yamlTempFile = new YamlFile(getTemporalFile()); + yamlTempFile = new YamlFile(getTemporalFile()); } catch (Exception e) { return new YamlFile(); } + + return yamlTempFile; } /** From 813a9de955b67fb4defc65ced527b8c8d7c443da Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 16:56:23 +0200 Subject: [PATCH 67/94] Code clean up. Signed-off-by: Presti --- .../java/de/presti/ree6/module/notifications/ISonic.java | 4 +++- .../ree6/module/notifications/impl/InstagramSonic.java | 7 +------ .../presti/ree6/module/notifications/impl/RSSSonic.java | 8 +++++++- .../ree6/module/notifications/impl/RedditSonic.java | 7 +------ .../ree6/module/notifications/impl/SpotifySonic.java | 5 ----- .../ree6/module/notifications/impl/TikTokSonic.java | 8 +++++++- .../ree6/module/notifications/impl/TwitterSonic.java | 7 +------ .../ree6/module/notifications/impl/YouTubeSonic.java | 5 ----- 8 files changed, 20 insertions(+), 31 deletions(-) diff --git a/src/main/java/de/presti/ree6/module/notifications/ISonic.java b/src/main/java/de/presti/ree6/module/notifications/ISonic.java index 5e0159e62..fec82eb67 100644 --- a/src/main/java/de/presti/ree6/module/notifications/ISonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/ISonic.java @@ -15,7 +15,9 @@ default void load(List channelStats) { } void load(); void run(); - void unload(); + default void unload() { + clear(); + } default void add(long identifier) { add(new SonicIdentifier(String.valueOf(identifier))); diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java index 0f9d7f61e..bac36e99b 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java @@ -138,17 +138,12 @@ public void run() { } } - @Override - public void unload() { - - } - @Override public void remove(SonicIdentifier object) { if (Main.getInstance().getNotifier().getInstagramClient() == null) return; if (!contains(object)) return; - SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(object.getIdentifier()).subscribe(webhooks -> { + SQLSession.getSqlConnector().getSqlWorker().getInstagramWebhookByName(object.getIdentifier()).subscribe(webhooks -> { if (!webhooks.isEmpty()) return; SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE instagramFollowerChannelUsername=:name", diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java index 661f1b6e3..2d023b275 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java @@ -226,7 +226,13 @@ public void run() { } @Override - public void unload() { + public void remove(SonicIdentifier object) { + if (!contains(object)) return; + SQLSession.getSqlConnector().getSqlWorker().getRSSWebhooksByUrl(object.getIdentifier()).subscribe(webhooks -> { + if (!webhooks.isEmpty()) return; + + rssUrls.remove(object); + }); } } diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java index 0ea753dea..5d765fa7c 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java @@ -158,17 +158,12 @@ public List getSubredditPosts(String subreddit, Sorting sorting, int return Collections.emptyList(); } - @Override - public void unload() { - - } - @Override public void remove(SonicIdentifier object) { if (Main.getInstance().getNotifier().getRedditClient() == null) return; if (!contains(object)) return; - SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(object.getIdentifier()).subscribe(webhooks -> { + SQLSession.getSqlConnector().getSqlWorker().getRedditWebhookBySub(object.getIdentifier()).subscribe(webhooks -> { if (!webhooks.isEmpty()) return; SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE subredditMemberChannelSubredditName=:name", diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java index f1f9c9d4a..507df3a8d 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java @@ -131,11 +131,6 @@ public void sendWebhooks(WebhookEmbedBuilder webhookEmbed, String description, S }); } - @Override - public void unload() { - - } - @Override public void remove(SonicIdentifier object) { if (SpotifyAPIHandler.getInstance() == null) return; diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java index 34cc3bbd8..7d840f619 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java @@ -110,7 +110,13 @@ public void run() { } @Override - public void unload() { + public void remove(SonicIdentifier object) { + if (!contains(object)) return; + SQLSession.getSqlConnector().getSqlWorker().getTikTokWebhooksByName(object.getIdentifier()).subscribe(webhooks -> { + if (!webhooks.isEmpty()) return; + + tiktokChannels.remove(object); + }); } } diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/TwitterSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/TwitterSonic.java index 270ef0c9a..782ff3f2e 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/TwitterSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/TwitterSonic.java @@ -77,17 +77,12 @@ public void run() { } } - @Override - public void unload() { - - } - @Override public void remove(SonicIdentifier object) { if (Main.getInstance().getNotifier().getTwitterClient() == null) return; if (!contains(object)) return; - SQLSession.getSqlConnector().getSqlWorker().getYouTubeWebhooksByName(object.getIdentifier()).subscribe(webhooks -> { + SQLSession.getSqlConnector().getSqlWorker().getTwitterWebhooksByName(object.getIdentifier()).subscribe(webhooks -> { if (!webhooks.isEmpty()) return; SQLSession.getSqlConnector().getSqlWorker().getEntity(new ChannelStats(), "FROM ChannelStats WHERE twitterFollowerChannelUsername=:name", diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java index 701859d5e..c53ad0c21 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java @@ -145,11 +145,6 @@ public void run() { } } - @Override - public void unload() { - - } - @Override public void remove(SonicIdentifier object) { if (YouTubeAPIHandler.getInstance() == null) return; From 20f6863659ca189a30956ed5142b7d068bb1b21a Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 17:01:41 +0200 Subject: [PATCH 68/94] Code clean up. Signed-off-by: Presti --- .../de/presti/ree6/utils/config/Config.java | 89 +++++++++---------- 1 file changed, 41 insertions(+), 48 deletions(-) diff --git a/src/main/java/de/presti/ree6/utils/config/Config.java b/src/main/java/de/presti/ree6/utils/config/Config.java index f64a1f962..1cf42b73d 100644 --- a/src/main/java/de/presti/ree6/utils/config/Config.java +++ b/src/main/java/de/presti/ree6/utils/config/Config.java @@ -16,6 +16,7 @@ import java.util.Map; // TODO:: Rework the Config System to make the Config class be the actual config structure and use it to serialize and deserialize while making a new ConfigManager class that loads and saves the config. + /** * Config. */ @@ -278,77 +279,69 @@ public void migrateOldConfig() { log.warn("This means the config file is not backed up by us!"); } - if (getFile().delete()) { - init(); + try { + if (Files.deleteIfExists(getFile().toPath())) { + init(); - for (Map.Entry entry : resources.entrySet()) { - String key = entry.getKey(); + for (Map.Entry entry : resources.entrySet()) { + String key = entry.getKey(); - boolean modified = false; + boolean modified = false; - if (key.startsWith("config")) - continue; + if (key.startsWith("config") || entry.getValue() instanceof MemorySection) + continue; - if (entry.getValue() instanceof MemorySection) - continue; + // Migrate to 1.10.0 + if (compareVersion("1.10.0", configVersion)) { - // Migrate to 1.10.0 - if (compareVersion("1.10.0", configVersion)) { + if (key.startsWith("mysql")) + key = key.replace("mysql", "hikari.sql"); - if (key.startsWith("mysql")) - key = key.replace("mysql", "hikari.sql"); + if (key.endsWith(".rel")) + key = key.replace(".rel", ".release"); - if (key.endsWith(".rel")) - key = key.replace(".rel", ".release"); + yamlFile.set(key, entry.getValue()); + modified = true; + } - yamlFile.set(key, entry.getValue()); - modified = true; - } + // Migrate to 2.2.0 + if (compareVersion("2.2.0", configVersion) && !key.startsWith("youtube")) { + yamlFile.set(key, entry.getValue()); + modified = true; + } - // Migrate to 2.2.0 - if (compareVersion("2.2.0", configVersion)) { - if (key.startsWith("youtube")) + // Migrate to 2.4.11 + if (compareVersion("2.4.11", configVersion) && key.startsWith("twitter") && !key.endsWith("bearer")) continue; - yamlFile.set(key, entry.getValue()); - modified = true; - } - + // Migrate to 3.1.9 + if (compareVersion("3.1.9", configVersion)) { - // Migrate to 2.4.11 - if (compareVersion("2.4.11", configVersion)) { - if (key.startsWith("twitter") && !key.endsWith("bearer")) continue; - } + if (key.startsWith("bot.misc.leveling.modules.")) + key = key.replace("bot.misc.leveling.modules.", "bot.misc.modules."); - // Migrate to 3.1.9 - if (compareVersion("3.1.9", configVersion)) { + if (key.endsWith("bot.misc.leveling.rankCard.")) + key = key.replace("bot.misc.leveling.rankCard.", "bot.misc.rankCard."); - if (key.startsWith("bot.misc.leveling.modules.")) - key = key.replace("bot.misc.leveling.modules.", "bot.misc.modules."); + yamlFile.set(key, entry.getValue()); + modified = true; + } - if (key.endsWith("bot.misc.leveling.rankCard.")) - key = key.replace("bot.misc.leveling.rankCard.", "bot.misc.rankCard."); - yamlFile.set(key, entry.getValue()); - modified = true; + if (!modified) { + yamlFile.set(key, entry.getValue()); + } } - - if (!modified) { - yamlFile.set(key, entry.getValue()); + if (compareVersion("2.2.0", configVersion)) { + yamlFile.remove("youtube"); } - } - - if (compareVersion("2.2.0", configVersion)) { - yamlFile.remove("youtube"); - } - try { yamlFile.save(getFile()); - } catch (Exception exception) { - log.error("Failed to save migrated config!", exception); } + } catch (Exception exception) { + log.error("Could not migrate old config!", exception); } } From 9cc988a8b4a12e4adf8b4719c4d5d6a79e02bafa Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 17:03:16 +0200 Subject: [PATCH 69/94] Code clean up. Signed-off-by: Presti --- .../ree6/module/game/core/base/IGame.java | 1 + .../presti/ree6/module/news/Announcement.java | 28 ------------------- 2 files changed, 1 insertion(+), 28 deletions(-) diff --git a/src/main/java/de/presti/ree6/module/game/core/base/IGame.java b/src/main/java/de/presti/ree6/module/game/core/base/IGame.java index 392f14474..ed5758247 100644 --- a/src/main/java/de/presti/ree6/module/game/core/base/IGame.java +++ b/src/main/java/de/presti/ree6/module/game/core/base/IGame.java @@ -74,6 +74,7 @@ default void rewardPlayer(GameSession gameSession, GamePlayer player, Object par try { parameter = Double.parseDouble(parameterString.replace(",", ".")); } catch (Exception ignore) { + // Parsing failed. } } if (parameter instanceof Double money) { diff --git a/src/main/java/de/presti/ree6/module/news/Announcement.java b/src/main/java/de/presti/ree6/module/news/Announcement.java index 2b1d1dfd4..3fc8f2e50 100644 --- a/src/main/java/de/presti/ree6/module/news/Announcement.java +++ b/src/main/java/de/presti/ree6/module/news/Announcement.java @@ -8,32 +8,4 @@ * @param content The content of the announcement. */ public record Announcement(String id, String title, String content) { - - /** - * Get the ID of the announcement. - * @return The ID of the announcement. - */ - @Override - public String id() { - return id; - } - - /** - * Get the title of the announcement. - * - * @return The title of the announcement. - */ - @Override - public String title() { - return title; - } - - /** - * Get the content of the announcement. - * @return The content of the announcement. - */ - @Override - public String content() { - return content; - } } From c880360870e85f8d97bbd14328ffa8f4859b8ee2 Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 17:06:16 +0200 Subject: [PATCH 70/94] Code clean up. Signed-off-by: Presti --- .../presti/ree6/module/notifications/impl/TwitchSonic.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java index 53ec2a4c5..ae36eb093 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java @@ -132,7 +132,10 @@ public void run() { @Override public void unload() { - + twitchChannels.forEach(channel -> { + Main.getInstance().getNotifier().getTwitchClient().getClientHelper().disableStreamEventListener(channel.getIdentifier()); + Main.getInstance().getNotifier().getTwitchClient().getClientHelper().disableFollowEventListener(channel.getIdentifier()); + }); } @Override From 03ea599487ca18290b048f2dd9dc34d23ffef20c Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 17:09:27 +0200 Subject: [PATCH 71/94] Code clean up. Signed-off-by: Presti --- .../container/CustomEventContainerCreator.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java b/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java index 22b318fdf..467b87da1 100644 --- a/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java +++ b/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java @@ -36,6 +36,19 @@ private CustomEventContainerCreator() { * Load all actions. */ public static void loadAll() { + ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); + configurationBuilder.addClassLoaders(ClasspathHelper.staticClassLoader()); + Reflections reflections = new Reflections(configurationBuilder); + Set> classes = reflections.getSubTypesOf(IEventAction.class); + + for (Class aClass : classes) { + if (aClass.isAnnotationPresent(ActionInfo.class)) { + String actionName = aClass.getAnnotation(ActionInfo.class).name(); + if (!cachedActions.containsKey(actionName)) { + cachedActions.put(actionName, aClass); + } + } + } } /** From 07b31d022711966fd8a4807220e3882e72342e9b Mon Sep 17 00:00:00 2001 From: Presti Date: Thu, 10 Oct 2024 17:20:53 +0200 Subject: [PATCH 72/94] Bump Signed-off-by: Presti --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 326782eab..d04a73073 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ de.presti Ree6 - 4.0.0-alpha.1 + 4.0.0-alpha.2 jar From 119bdf89d4ba47514ad4e0df35fdb02654ed1e94 Mon Sep 17 00:00:00 2001 From: Presti Date: Mon, 14 Oct 2024 17:17:45 +0200 Subject: [PATCH 73/94] Fix a bug and bump SQL Signed-off-by: Presti --- pom.xml | 2 +- .../ree6/commands/impl/community/StreamActionCommand.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index d04a73073..3dde4086e 100644 --- a/pom.xml +++ b/pom.xml @@ -183,7 +183,7 @@ de.ree6 Ree6-SQL - bc06476620 + 63b8577457 diff --git a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java index c812328a0..aa17a3049 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/StreamActionCommand.java @@ -155,7 +155,7 @@ public void onPerform(CommandEvent commandEvent) { switch (subCommand) { case "create" -> - SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.actionName = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).subscribe(streamActionOptional -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.name = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).subscribe(streamActionOptional -> { if (streamActionOptional.isEmpty()) { SQLSession.getSqlConnector().getSqlWorker().getEntity(new TwitchIntegration(), "FROM TwitchIntegration WHERE userId = :uid", Map.of("uid", commandEvent.getUser().getIdLong())) .subscribe(twitchIntegrationOptional -> { @@ -177,7 +177,7 @@ public void onPerform(CommandEvent commandEvent) { }); case "delete" -> - SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.actionName = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).subscribe(streamAction -> { + SQLSession.getSqlConnector().getSqlWorker().getEntity(new StreamAction(), "FROM StreamAction WHERE guildAndName.name = :name AND guildAndName.guildId = :gid", Map.of("name", name.getAsString(), "gid", commandEvent.getGuild().getIdLong())).subscribe(streamAction -> { if (streamAction.isPresent()) { SQLSession.getSqlConnector().getSqlWorker().deleteEntity(streamAction.get()).block(); commandEvent.reply(commandEvent.getResource("message.stream-action.deleted", name.getAsString())); From 5691db5163c475eb81785d4fa4195d4178ad91c3 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 16 Oct 2024 11:55:28 +0200 Subject: [PATCH 74/94] Fix a bug and bump SQL Signed-off-by: Presti --- .../presti/ree6/utils/others/GuildUtil.java | 34 ++++++++++++++----- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/src/main/java/de/presti/ree6/utils/others/GuildUtil.java b/src/main/java/de/presti/ree6/utils/others/GuildUtil.java index 735ba2384..7f2fcc02e 100644 --- a/src/main/java/de/presti/ree6/utils/others/GuildUtil.java +++ b/src/main/java/de/presti/ree6/utils/others/GuildUtil.java @@ -48,7 +48,7 @@ public static void handleMemberJoin(Guild guild, Member member) { log.error("[AutoRole] Member: {} ({})", member.getUser().getName(), member.getId()); if (guild.getOwner() != null) - LanguageService.getByGuild(guild, "message.brs.autoRole.user", member.getAsMention()).subscribe(message -> + LanguageService.getByGuild(guild, "message.brs.autoRole.user", member.getUser().getName()).subscribe(message -> guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage(message) .queue())); @@ -108,7 +108,7 @@ public static void handleVoiceLevelReward(Guild guild, Member member) { if (guild.getOwner() != null) guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - LanguageService.getByGuild(guild, "message.brs.autoRole.user", member.getAsMention()).subscribe(message -> + LanguageService.getByGuild(guild, "message.brs.autoRole.user", member.getUser().getName()).subscribe(message -> privateChannel.sendMessage(message).queue())); return; @@ -170,7 +170,7 @@ public static void handleChatLevelReward(Guild guild, Member member) { if (guild.getOwner() != null) guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - LanguageService.getByGuild(guild, "message.brs.autoRole.user", member.getAsMention()) + LanguageService.getByGuild(guild, "message.brs.autoRole.user", member.getUser().getName()) .subscribe(message -> privateChannel.sendMessage(message).queue())); return; } @@ -222,14 +222,32 @@ private static void addRole(Guild guild, Member member, Role role) { log.error("[AutoRole] Failed to give a Role!"); log.error("[AutoRole] Server: {} ({})", guild.getName(), guild.getId()); if (guild.getOwner() != null) - guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> - LanguageService.getByGuild(guild, guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES) ? - "message.brs.autoRole.hierarchy" - : "message.brs.autoRole.missingPermission", role.getName()).subscribe(message -> - privateChannel.sendMessage(message).queue())); + guild.getOwner().getUser().openPrivateChannel().queue(privateChannel -> { + String[] languageResource = getFailedRoleReason(guild, member, role); + LanguageService.getByGuild(guild, languageResource[0], languageResource[1]).subscribe(message -> + privateChannel.sendMessage(message).queue()); + }); } } + /** + * Get a String Array with the Language Path and the correct Parameter. + * + * @param guild the {@link Guild} Entity. + * @param member the {@link Member} Entity. + * @param role the {@link Role} Entity. + * @return the String Array with two entries, 0 = language path and 1 = parameter. + */ + private static String[] getFailedRoleReason(Guild guild, Member member, Role role) { + String languageResource = "message.brs.autoRole.missingPermission"; + + if (!guild.getSelfMember().canInteract(member)) languageResource = "message.brs.autoRole.user"; + if (guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES)) + languageResource = "message.brs.autoRole.hierarchy"; + + return new String[]{languageResource, guild.getSelfMember().canInteract(member) ? role.getName() : member.getUser().getName()}; + } + /** * Get all roles that Ree6 can manage. * From 6c035bdd54e717d9b59316c4f1ef29f1747f1046 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 16 Oct 2024 13:19:54 +0200 Subject: [PATCH 75/94] Use the same main color instead of random selections such as green, cyan and magenta. Signed-off-by: Presti --- pom.xml | 2 +- .../ree6/audio/AudioPlayerReceiveHandler.java | 4 +- .../presti/ree6/audio/music/MusicWorker.java | 23 ++++---- .../ree6/audio/music/TrackScheduler.java | 19 ++++--- .../java/de/presti/ree6/bot/BotConfig.java | 13 ++++- .../ree6/commands/impl/community/Ticket.java | 5 +- .../presti/ree6/commands/impl/fun/Anime.java | 1 + .../ree6/commands/impl/fun/CatImage.java | 5 +- .../ree6/commands/impl/fun/DogImage.java | 5 +- .../presti/ree6/commands/impl/fun/Manga.java | 1 + .../ree6/commands/impl/fun/MemeImage.java | 5 +- .../presti/ree6/commands/impl/fun/Monkey.java | 5 +- .../ree6/commands/impl/fun/ShibaImage.java | 3 +- .../presti/ree6/commands/impl/fun/Waifu.java | 3 +- .../ree6/commands/impl/info/Avatar.java | 1 + .../presti/ree6/commands/impl/info/Help.java | 5 +- .../presti/ree6/commands/impl/info/Info.java | 3 +- .../ree6/commands/impl/info/Server.java | 5 +- .../presti/ree6/commands/impl/info/Stats.java | 2 +- .../presti/ree6/commands/impl/mod/Setup.java | 4 +- .../ree6/commands/impl/mod/Suggestion.java | 54 +++++++++--------- .../ree6/commands/impl/music/Clearqueue.java | 6 +- .../presti/ree6/commands/impl/music/Loop.java | 6 +- .../ree6/commands/impl/music/Lyrics.java | 5 +- .../ree6/commands/impl/music/MusicPanel.java | 6 +- .../ree6/commands/impl/music/Pause.java | 6 +- .../presti/ree6/commands/impl/music/Play.java | 8 +-- .../ree6/commands/impl/music/Resume.java | 6 +- .../presti/ree6/commands/impl/music/Seek.java | 6 +- .../ree6/commands/impl/music/Shuffle.java | 6 +- .../ree6/commands/impl/music/SongInfo.java | 15 +++-- .../ree6/commands/impl/music/SongList.java | 6 +- .../presti/ree6/commands/impl/music/Stop.java | 6 +- .../ree6/commands/impl/music/Volume.java | 12 ++-- .../presti/ree6/commands/impl/nsfw/NSFW.java | 1 + .../ree6/commands/impl/nsfw/Rule34.java | 3 +- .../ree6/commands/interfaces/ICommand.java | 3 +- .../de/presti/ree6/events/MenuEvents.java | 56 +++++++++---------- .../de/presti/ree6/events/OtherEvents.java | 4 +- .../module/game/impl/blackjack/Blackjack.java | 14 ++--- .../module/game/impl/musicquiz/MusicQuiz.java | 8 +-- .../module/notifications/impl/RSSSonic.java | 5 +- .../de/presti/ree6/utils/config/Config.java | 1 + 43 files changed, 178 insertions(+), 179 deletions(-) diff --git a/pom.xml b/pom.xml index 3dde4086e..203781b0e 100644 --- a/pom.xml +++ b/pom.xml @@ -183,7 +183,7 @@ de.ree6 Ree6-SQL - 63b8577457 + 3206c2e0ab diff --git a/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java b/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java index c3e7b9927..0841d8569 100644 --- a/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java +++ b/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java @@ -98,7 +98,7 @@ public AudioPlayerReceiveHandler(Member member, AudioChannelUnion audioChannelUn message = audioChannelUnion.asGuildMessageChannel().sendMessageEmbeds(new EmbedBuilder() .setDescription(LanguageService.getByGuild(member.getGuild(), "message.recording.started").block()) - .setColor(Color.YELLOW) + .setColor(Color.RED) .setFooter(LanguageService.getByGuild(member.getGuild(), "label.footerMessage", member.getEffectiveName(), BotConfig.getAdvertisement()).block(), member.getEffectiveAvatarUrl()) .setTitle(LanguageService.getByGuild(member.getGuild(), "label.recording.start").block()) .build()).complete(); @@ -198,7 +198,7 @@ public void endReceiving() { if (canTalk) { message.editMessageEmbeds(new EmbedBuilder() .setDescription(LanguageService.getByGuild(audioChannelUnion.getGuild(), "message.recording.stopped").block()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setFooter(BotConfig.getAdvertisement(), audioChannelUnion.getGuild().getIconUrl()) .setTitle(LanguageService.getByGuild(audioChannelUnion.getGuild(), "label.recording.finished").block()) .build()) diff --git a/src/main/java/de/presti/ree6/audio/music/MusicWorker.java b/src/main/java/de/presti/ree6/audio/music/MusicWorker.java index 482901451..7b296161a 100644 --- a/src/main/java/de/presti/ree6/audio/music/MusicWorker.java +++ b/src/main/java/de/presti/ree6/audio/music/MusicWorker.java @@ -12,12 +12,12 @@ import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import de.presti.ree6.api.events.MusicPlayerStateChangeEvent; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.utils.apis.SpotifyAPIHandler; import de.presti.ree6.utils.apis.YouTubeAPIHandler; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.FormatUtil; import dev.lavalink.youtube.YoutubeAudioSourceManager; import io.sentry.Sentry; @@ -212,7 +212,7 @@ public void trackLoaded(AudioTrack track) { .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").block()) .setImage((track.getInfo().artworkUrl != null && track.getInfo().artworkUrl.isBlank()) ? guild.getJDA().getSelfUser().getEffectiveAvatarUrl() : track.getInfo().artworkUrl) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(guild, "message.music.queueAdded.default", FormatUtil.filter(track.getInfo().title)).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()), 5, messageChannel, interactionHook); @@ -237,7 +237,7 @@ public void playlistLoaded(AudioPlaylist playlist) { .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(guild, "message.music.queueAdded.firstOfList", FormatUtil.filter(firstTrack.getInfo().title), FormatUtil.filter(playlist.getName())).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()), 5, messageChannel, interactionHook); @@ -262,7 +262,7 @@ public void noMatches() { .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(guild, "message.music.searchUrlFailed", FormatUtil.filter(trackUrl)).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()), 5, messageChannel, interactionHook); } @@ -279,7 +279,7 @@ public void loadFailed(FriendlyException exception) { .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setTitle(LanguageService.getByGuild(guild, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(guild, "message.music.failedLoading", exception.getMessage()).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()), 5, messageChannel, interactionHook); } @@ -372,7 +372,7 @@ public void playSong(String value, Guild guild, Member member, GuildMessageChann BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFound", value).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, 5, channel, interactionHook); @@ -409,7 +409,7 @@ public void playSong(String value, Guild guild, Member member, GuildMessageChann BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFoundMultiple", loadFailed.size()).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, 5, channel, interactionHook); @@ -438,7 +438,7 @@ public void playSong(String value, Guild guild, Member member, GuildMessageChann .setAuthor(guild.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) .setTitle(LanguageService.getByGuildOrInteraction(guild, interaction, "label.musicPlayer").block()) .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.YELLOW) + .setColor(Color.RED) .setDescription(LanguageService.getByGuildOrInteraction(guild, interaction, "message.music.notFound", FormatUtil.filter(value)).block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, 5, channel, interactionHook); @@ -472,7 +472,7 @@ public void skipTrack(GuildMessageChannelUnion channel, InteractionHook interact Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder().setAuthor(channel.getJDA().getSelfUser().getName(), BotConfig.getWebsite(), channel.getJDA().getSelfUser().getAvatarUrl()) .setTitle(LanguageService.getByGuild(channel.getGuild(), "label.musicPlayer").block()) .setThumbnail(channel.getJDA().getSelfUser().getAvatarUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(channel.getGuild(), "message.music.skip").block()) .setFooter(channel.getGuild().getName() + " - " + BotConfig.getAdvertisement(), channel.getGuild().getIconUrl()), 5, channel, interactionHook); } @@ -484,10 +484,11 @@ public void skipTrack(GuildMessageChannelUnion channel, InteractionHook interact * A method used to seek to a specific position in the current AudioTrack. * * @param channel the TextChannel, used to inform the user about the seek. + * @param interactionHook the Interactionhook incase it was used in a slash command. * @param seekAmountInSeconds the number of seconds that should be seeked. */ - public void seekInTrack(GuildMessageChannelUnion channel, int seekAmountInSeconds) { - getGuildAudioPlayer(channel.getGuild()).getScheduler().seekPosition(channel, seekAmountInSeconds); + public void seekInTrack(GuildMessageChannelUnion channel, InteractionHook interactionHook, long seekAmountInSeconds) { + getGuildAudioPlayer(channel.getGuild()).getScheduler().seekPosition(channel, interactionHook, seekAmountInSeconds); } /** diff --git a/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java b/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java index 9051f0c3d..61907060d 100644 --- a/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java +++ b/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java @@ -5,9 +5,9 @@ import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason; import de.presti.ree6.api.events.MusicPlayerStateChangeEvent; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.FormatUtil; import lavalink.client.player.IPlayer; import lavalink.client.player.event.AudioEventAdapterWrapped; @@ -179,7 +179,7 @@ public void nextTrack(GuildMessageChannelUnion textChannel, int position, boolea .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.songNext", FormatUtil.filter(track.getInfo().title)).block()) .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); @@ -203,9 +203,10 @@ public void nextTrack(GuildMessageChannelUnion textChannel, int position, boolea * Seek to a specific position in the current track. * * @param channel the Text-Channel where the command have been performed from. + * @param interactionHook the Interactionhook if it was used in a slashcommand * @param seekAmountInSeconds the amount of seconds to seek to. */ - public void seekPosition(GuildMessageChannelUnion channel, int seekAmountInSeconds) { + public void seekPosition(GuildMessageChannelUnion channel, InteractionHook interactionHook, long seekAmountInSeconds) { if (player.getPlayingTrack() == null) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) @@ -213,7 +214,7 @@ public void seekPosition(GuildMessageChannelUnion channel, int seekAmountInSecon .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.notPlaying").block()) - .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); + .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel(), interactionHook); return; } @@ -224,11 +225,11 @@ public void seekPosition(GuildMessageChannelUnion channel, int seekAmountInSecon .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setColor(Color.RED) .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.seek.failed").block()) - .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); + .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel(), interactionHook); return; } - long skipPosition = player.getPlayingTrack().getPosition() + ((long) seekAmountInSeconds * 1000); + long skipPosition = player.getPlayingTrack().getPosition() + (seekAmountInSeconds * 1000); if (skipPosition < 0) { player.getPlayingTrack().setPosition(0L); } else { @@ -239,9 +240,9 @@ public void seekPosition(GuildMessageChannelUnion channel, int seekAmountInSecon .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) .setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()) .setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.seek.success", FormatUtil.formatTime(player.getPlayingTrack().getPosition())).block()) - .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel()); + .setFooter(guildMusicManager.getGuild().getName() + " - " + BotConfig.getAdvertisement(), guildMusicManager.getGuild().getIconUrl()), 5, getChannel(), interactionHook); } @Override @@ -343,7 +344,7 @@ public void stopAll(InteractionHook interactionHook) { em.setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()); em.setTitle(LanguageService.getByGuild(guildMusicManager.getGuild(), "label.musicPlayer").block()); em.setThumbnail(guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(LanguageService.getByGuild(guildMusicManager.getGuild(), "message.music.stop").block()); } else { em.setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()); diff --git a/src/main/java/de/presti/ree6/bot/BotConfig.java b/src/main/java/de/presti/ree6/bot/BotConfig.java index 34e33cf64..84654bf82 100644 --- a/src/main/java/de/presti/ree6/bot/BotConfig.java +++ b/src/main/java/de/presti/ree6/bot/BotConfig.java @@ -21,7 +21,7 @@ private BotConfig() { /** * Color values to be preset to prevent parsing hex codes from the config over and over and over and over and over again. */ - private static Color rankTextColor, rankDetailColor, rankHighlightColor, rankProgressbarColor, rankProgressbarBackgroundColor; + private static Color rankTextColor, rankDetailColor, rankHighlightColor, rankProgressbarColor, rankProgressbarBackgroundColor, mainColor; /** * Get the configured Discord Bot status. @@ -290,5 +290,16 @@ public static Color getRankProgressbarBackgroundColor() { } //endregion + + /** + * Get the configured color for the background of the progressbar on the rank card. + * @return the color for the background of the progressbar on the rank card from the config. + */ + public static Color getMainColor() { + if (mainColor == null) { + mainColor = Color.decode(Main.getInstance().getConfig().getConfiguration().getString("bot.misc.mainColor", "#B9010B")); + } + return mainColor; + } } diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java b/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java index b7d6fe8ea..71672c5ff 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Ticket.java @@ -1,5 +1,6 @@ package de.presti.ree6.commands.impl.community; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; @@ -8,7 +9,6 @@ import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Tickets; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.channel.ChannelType; @@ -23,7 +23,6 @@ import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import net.dv8tion.jda.internal.interactions.CommandDataImpl; -import java.awt.*; import java.util.EnumSet; import java.util.Map; @@ -91,7 +90,7 @@ public void onPerform(CommandEvent commandEvent) { }); embedBuilder.setDescription(commandEvent.getResource("message.ticket.setupSuccess")); - embedBuilder.setColor(Color.GREEN); + embedBuilder.setColor(BotConfig.getMainColor()); commandEvent.reply(embedBuilder.build()); }); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java b/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java index 8bf6e06b6..34263eb69 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java @@ -131,6 +131,7 @@ public void sendAnime(CommandEvent commandEvent, Message message, String query) em.setTitle(name, url); em.setThumbnail(thumbnailUrl); em.setDescription(description); + em.setColor(BotConfig.getMainColor()); em.addField(":hourglass_flowing_sand: **" + commandEvent.getResource("label.status") + "**", status, true); em.addField(":dividers: **" + commandEvent.getResource("label.typ") + "**", type, true); em.addField(":arrow_right: **" + commandEvent.getResource("label.genres") + "**", genres, false); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/CatImage.java b/src/main/java/de/presti/ree6/commands/impl/fun/CatImage.java index 9081d1f24..247036ac7 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/CatImage.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/CatImage.java @@ -1,12 +1,11 @@ package de.presti.ree6.commands.impl.fun; import com.google.gson.JsonArray; -import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -28,7 +27,7 @@ public void onPerform(CommandEvent commandEvent) { EmbedBuilder em = new EmbedBuilder(); em.setTitle(commandEvent.getResource("label.randomCatImage")); - em.setColor(BotWorker.randomEmbedColor()); + em.setColor(BotConfig.getMainColor()); em.setImage(js.get(0).getAsJsonObject().get("url").getAsString()); em.setFooter(commandEvent.getResource("label.footerMessage", commandEvent.getMember().getEffectiveName(), BotConfig.getAdvertisement()), commandEvent.getMember().getEffectiveAvatarUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/DogImage.java b/src/main/java/de/presti/ree6/commands/impl/fun/DogImage.java index a33a1edd5..747c0070a 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/DogImage.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/DogImage.java @@ -1,12 +1,11 @@ package de.presti.ree6.commands.impl.fun; import com.google.gson.JsonObject; -import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -27,7 +26,7 @@ public void onPerform(CommandEvent commandEvent) { EmbedBuilder em = new EmbedBuilder(); em.setTitle(commandEvent.getResource("label.randomDogImage")); - em.setColor(BotWorker.randomEmbedColor()); + em.setColor(BotConfig.getMainColor()); em.setImage(js.get("message").getAsString()); em.setFooter(commandEvent.getResource("label.footerMessage", commandEvent.getMember().getEffectiveName(), BotConfig.getAdvertisement()), commandEvent.getMember().getEffectiveAvatarUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java b/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java index 884586c0f..0d8f3df19 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java @@ -130,6 +130,7 @@ public void sendManga(CommandEvent commandEvent, Message message, String query) em.setTitle(name, url); em.setThumbnail(thumbnailUrl); em.setDescription(description); + em.setColor(BotConfig.getMainColor()); em.addField(":hourglass_flowing_sand: **" + commandEvent.getResource("label.status") + "**", status, true); em.addField(":dividers: **" + commandEvent.getResource("label.typ") + "**", type, true); em.addField(":arrow_right: **" + commandEvent.getResource("label.genres") + "**", genres, false); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/MemeImage.java b/src/main/java/de/presti/ree6/commands/impl/fun/MemeImage.java index 5b16f4c36..8b40966f7 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/MemeImage.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/MemeImage.java @@ -1,12 +1,11 @@ package de.presti.ree6.commands.impl.fun; import com.google.gson.JsonObject; -import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -28,7 +27,7 @@ public void onPerform(CommandEvent commandEvent) { EmbedBuilder em = new EmbedBuilder(); em.setTitle(commandEvent.getResource("label.randomMemeImage")); - em.setColor(BotWorker.randomEmbedColor()); + em.setColor(BotConfig.getMainColor()); if (js.has("url")) { em.setImage(js.get("url").getAsString()); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Monkey.java b/src/main/java/de/presti/ree6/commands/impl/fun/Monkey.java index ac4d51c30..22786777e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Monkey.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Monkey.java @@ -1,11 +1,10 @@ package de.presti.ree6.commands.impl.fun; -import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -23,7 +22,7 @@ public void onPerform(CommandEvent commandEvent) { final EmbedBuilder em = new EmbedBuilder(); em.setTitle(commandEvent.getResource("label.monkey")); - em.setColor(BotWorker.randomEmbedColor()); + em.setColor(BotConfig.getMainColor()); em.setImage("https://c.tenor.com/Y89PE1f7exQAAAAd/reject-modernity-return-to-monke.gif"); em.setFooter(commandEvent.getResource("label.footerMessage", commandEvent.getMember().getEffectiveName(), BotConfig.getAdvertisement()), commandEvent.getMember().getEffectiveAvatarUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/ShibaImage.java b/src/main/java/de/presti/ree6/commands/impl/fun/ShibaImage.java index ac5f8ef29..d69b4dd13 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/ShibaImage.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/ShibaImage.java @@ -3,7 +3,6 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import de.presti.ree6.bot.BotConfig; -import de.presti.ree6.bot.BotWorker; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; @@ -35,7 +34,7 @@ public void onPerform(CommandEvent commandEvent) { EmbedBuilder em = new EmbedBuilder(); em.setTitle(commandEvent.getResource("label.randomShibaImage")); - em.setColor(BotWorker.randomEmbedColor()); + em.setColor(BotConfig.getMainColor()); em.setImage(js.get(0).getAsString()); em.setFooter(commandEvent.getResource("label.footerMessage", commandEvent.getMember().getEffectiveName(), BotConfig.getAdvertisement()), commandEvent.getMember().getEffectiveAvatarUrl()); commandEvent.reply(em.build()); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Waifu.java b/src/main/java/de/presti/ree6/commands/impl/fun/Waifu.java index cd97db826..ee467048b 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Waifu.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Waifu.java @@ -2,11 +2,11 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -90,6 +90,7 @@ public void onPerform(CommandEvent commandEvent) { from = commandEvent.getResource("message.default.retrievalError"); } + em.setColor(BotConfig.getMainColor()); em.addField("**" + commandEvent.getResource("label.from") + "**", from, true); em.setFooter(commandEvent.getMember().getEffectiveName() + " - " + BotConfig.getAdvertisement(), commandEvent.getMember().getEffectiveAvatarUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java b/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java index 32f4164b2..05be51ba6 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java @@ -73,6 +73,7 @@ public String[] getAlias() { public void sendAvatar(User member, CommandEvent commandEvent) { EmbedBuilder em = new EmbedBuilder(); + em.setColor(BotConfig.getMainColor()); em.setTitle(commandEvent.getResource("label.avatar")); em.setAuthor(member.getEffectiveName() + (GuildUtil.isSupporter(member) ? " " : ""), member.getEffectiveAvatarUrl(), member.getEffectiveAvatarUrl()); em.setImage(member.getEffectiveAvatar().getUrl(1024)); diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Help.java b/src/main/java/de/presti/ree6/commands/impl/info/Help.java index d1ca27d33..b5da63ece 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Help.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Help.java @@ -1,13 +1,12 @@ package de.presti.ree6.commands.impl.info; -import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.emoji.Emoji; import net.dv8tion.jda.api.interactions.commands.OptionMapping; @@ -60,7 +59,7 @@ public void sendHelpInformation(String categoryString, CommandEvent commandEvent EmbedBuilder em = new EmbedBuilder(); - em.setColor(BotWorker.randomEmbedColor()); + em.setColor(BotConfig.getMainColor()); em.setTitle("Help Center"); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Info.java b/src/main/java/de/presti/ree6/commands/impl/info/Info.java index 2873a0a71..b6a2f6bf0 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Info.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Info.java @@ -1,10 +1,10 @@ package de.presti.ree6.commands.impl.info; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.GuildUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Member; @@ -78,6 +78,7 @@ public void sendInfo(Member member, CommandEvent commandEvent) { em.setTitle(member.getEffectiveName() + (GuildUtil.isSupporter(member.getUser()) ? " " : "")); em.setThumbnail(member.getEffectiveAvatarUrl()); + em.setColor(BotConfig.getMainColor()); em.addField("**Username**", member.getUser().getName(), true); diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Server.java b/src/main/java/de/presti/ree6/commands/impl/info/Server.java index f8e3cf267..8517d79c3 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Server.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Server.java @@ -1,11 +1,10 @@ package de.presti.ree6.commands.impl.info; -import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.GuildUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; @@ -29,7 +28,7 @@ public void onPerform(CommandEvent commandEvent) { if (commandEvent.getMember().hasPermission(Permission.ADMINISTRATOR)) { EmbedBuilder em = new EmbedBuilder(); - em.setColor(BotWorker.randomEmbedColor()); + em.setColor(BotConfig.getMainColor()); Member owner = commandEvent.getGuild().getOwner(); diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java index ff766b4d5..9493ec0fa 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Stats.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Stats.java @@ -47,7 +47,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.statistics")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(BotWorker.randomEmbedColor()); + em.setColor(BotConfig.getMainColor()); long memberCount = firstBoot ? BotWorker.getShardManager().getUsers().size() : BotWorker.getShardManager().getUserCache().size(); firstBoot = true; diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java index 2cc7ab2a6..550899bda 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java @@ -91,7 +91,7 @@ public void onPerform(CommandEvent commandEvent) { EmbedBuilder embedBuilder = new EmbedBuilder() .setTitle(commandEvent.getResource("label.setup")) .setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) - .setColor(Color.cyan) + .setColor(BotConfig.getMainColor()) .setDescription(commandEvent.getResource("message.setup.setupMenu")); List optionList = new ArrayList<>(); @@ -274,7 +274,7 @@ public static EmbedBuilder createAutoRoleSetupMessage(Guild guild, InteractionHo return new EmbedBuilder() .setTitle(LanguageService.getByGuildOrInteractionHook(guild, interactionHook, "label.setup").block()) .setFooter(guild.getName() + " - " + BotConfig.getAdvertisement(), guild.getIconUrl()) - .setColor(hasRoles ? Color.cyan : Color.red) + .setColor(hasRoles ? BotConfig.getMainColor() : Color.RED) .setDescription(LanguageService.getByGuildOrInteractionHook(guild, interactionHook, hasRoles ? "message.autoRole.setupDescription" : "message.default.needPermission", (hasRoles ? null : Permission.MANAGE_ROLES.name())).block()); } diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java b/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java index 044736c0e..a66511cd9 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Suggestion.java @@ -1,5 +1,6 @@ package de.presti.ree6.commands.impl.mod; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; @@ -7,7 +8,6 @@ import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Suggestions; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.channel.ChannelType; @@ -68,8 +68,9 @@ public void onPerform(CommandEvent commandEvent) { /** * Create all the entries needed. - * @param commandEvent The CommandEvent. - * @param channel the Suggestion channel. + * + * @param commandEvent The CommandEvent. + * @param channel the Suggestion channel. * @param messageChannel the Channel for the Message. */ public void createSuggestions(CommandEvent commandEvent, MessageChannel channel, MessageChannel messageChannel) { @@ -77,29 +78,30 @@ public void createSuggestions(CommandEvent commandEvent, MessageChannel channel, SQLSession.getSqlConnector().getSqlWorker().getEntity(new Suggestions(), "FROM Suggestions WHERE guildChannelId.guildId = :id", Map.of("id", commandEvent.getGuild().getIdLong())) .publishOn(Schedulers.boundedElastic()) .mapNotNull(suggestionsOptional -> { - if (suggestionsOptional.isPresent()) { - Suggestions suggestions = suggestionsOptional.get(); - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(suggestions).block(); - - suggestions.getGuildChannelId().setChannelId(channel.getIdLong()); - return SQLSession.getSqlConnector().getSqlWorker().updateEntity(suggestions).block(); - } else { - return SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Suggestions(commandEvent.getGuild().getIdLong(), channel.getIdLong())).block(); - } - }).subscribe(suggestions -> SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_suggestion_menu").subscribe(setting -> { - MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.setTitle(commandEvent.getResource("label.suggestionMenu")); - embedBuilder.setColor(Color.ORANGE); - embedBuilder.setDescription(setting.get().getStringValue()); - embedBuilder.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); - messageCreateBuilder.setEmbeds(embedBuilder.build()); - messageCreateBuilder.setActionRow(Button.primary("re_suggestion", commandEvent.getResource("message.suggestion.suggestionMenuPlaceholder"))); - - Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), messageChannel); - - commandEvent.reply(commandEvent.getResource("message.suggestion.success"), 5); - })); + if (suggestionsOptional.isPresent()) { + Suggestions suggestions = suggestionsOptional.get(); + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(suggestions).block(); + + suggestions.getGuildChannelId().setChannelId(channel.getIdLong()); + return SQLSession.getSqlConnector().getSqlWorker().updateEntity(suggestions).block(); + } else { + return SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Suggestions(commandEvent.getGuild().getIdLong(), channel.getIdLong())).block(); + } + }).subscribe(suggestions -> SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "message_suggestion_menu").subscribe(setting -> { + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); + EmbedBuilder embedBuilder = new EmbedBuilder(); + embedBuilder.setColor(BotConfig.getMainColor()); + embedBuilder.setTitle(commandEvent.getResource("label.suggestionMenu")); + embedBuilder.setColor(Color.ORANGE); + embedBuilder.setDescription(setting.get().getStringValue()); + embedBuilder.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); + messageCreateBuilder.setEmbeds(embedBuilder.build()); + messageCreateBuilder.setActionRow(Button.primary("re_suggestion", commandEvent.getResource("message.suggestion.suggestionMenuPlaceholder"))); + + Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), messageChannel); + + commandEvent.reply(commandEvent.getResource("message.suggestion.success"), 5); + })); } diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Clearqueue.java b/src/main/java/de/presti/ree6/commands/impl/music/Clearqueue.java index 689fdc630..924c61036 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Clearqueue.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Clearqueue.java @@ -1,16 +1,14 @@ package de.presti.ree6.commands.impl.music; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; -import java.awt.*; - /** * Clears the Queue. */ @@ -33,7 +31,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.music.clearQueue")); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Loop.java b/src/main/java/de/presti/ree6/commands/impl/music/Loop.java index 0f9e2ea32..04ea4cd8e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Loop.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Loop.java @@ -1,16 +1,14 @@ package de.presti.ree6.commands.impl.music; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; -import java.awt.*; - /** * Set the Song onto Loop. */ @@ -37,7 +35,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(Main.getInstance().getMusicWorker().getGuildAudioPlayer(commandEvent.getGuild()).getScheduler().loop() ? commandEvent.getResource("message.music.loop.enabled") : commandEvent.getResource("message.music.loop.disabled")); diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Lyrics.java b/src/main/java/de/presti/ree6/commands/impl/music/Lyrics.java index cfd10f4b8..f97113ce4 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Lyrics.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Lyrics.java @@ -2,12 +2,12 @@ import com.jagrosh.jlyrics.LyricsClient; import de.presti.ree6.audio.music.GuildMusicManager; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.FormatUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -56,7 +56,8 @@ public void onPerform(CommandEvent commandEvent) { EmbedBuilder eb = new EmbedBuilder() .setAuthor(lyrics.getAuthor()) - .setTitle(lyrics.getTitle(), lyrics.getURL()); + .setTitle(lyrics.getTitle(), lyrics.getURL()) + .setColor(BotConfig.getMainColor()); if (lyrics.getContent().length() > 15000) { commandEvent.reply(commandEvent.getResource("message.music.lyrics.foundUnlikely", "`" + FormatUtil.filter(title) + "`", lyrics.getURL())); } else if (lyrics.getContent().length() > 2000) { diff --git a/src/main/java/de/presti/ree6/commands/impl/music/MusicPanel.java b/src/main/java/de/presti/ree6/commands/impl/music/MusicPanel.java index dbdfb7efc..f7a772cfc 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/MusicPanel.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/MusicPanel.java @@ -4,6 +4,7 @@ import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; import de.presti.ree6.api.events.MusicPlayerStateChangeEvent; import de.presti.ree6.audio.music.GuildMusicManager; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; @@ -11,7 +12,6 @@ import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; import de.presti.ree6.utils.data.ArrayUtil; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.FormatUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; @@ -22,8 +22,6 @@ import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import net.dv8tion.jda.api.utils.messages.MessageEditBuilder; -import java.awt.*; - /** * Creates a small typeof UI to control music in a channel. */ @@ -95,7 +93,7 @@ public void onPerform(CommandEvent commandEvent) { guildMusicManager.getPlayer().getPlayingTrack().getInfo() : null; EmbedBuilder embedBuilder = new EmbedBuilder() - .setColor(Color.MAGENTA) + .setColor(BotConfig.getMainColor()) .setImage(audioTrackInfo != null && (audioTrackInfo.artworkUrl != null && !audioTrackInfo.artworkUrl.isBlank()) ? audioTrackInfo.artworkUrl : "https://images.unsplash.com/photo-1546977463-943d58b78c19") .setTitle("**" + (audioTrackInfo != null ? commandEvent.getResource("message.music.songInfoSlim", audioTrackInfo.title, audioTrackInfo.author) : commandEvent.getResource("message.music.notPlaying")) + "**") diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Pause.java b/src/main/java/de/presti/ree6/commands/impl/music/Pause.java index b29f2d54b..db44e9ab5 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Pause.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Pause.java @@ -1,16 +1,14 @@ package de.presti.ree6.commands.impl.music; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; -import java.awt.*; - /** * Pauses the current Song. */ @@ -40,7 +38,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.music.pause")); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); commandEvent.reply(em.build(), 5); diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Play.java b/src/main/java/de/presti/ree6/commands/impl/music/Play.java index 8df145ba3..f0cf42491 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Play.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Play.java @@ -1,11 +1,11 @@ package de.presti.ree6.commands.impl.music; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; @@ -13,8 +13,6 @@ import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.internal.interactions.CommandDataImpl; -import java.awt.*; - /** * Play a Song. */ @@ -43,7 +41,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.default.usage","play (Url)")); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); commandEvent.reply(em.build(), 5); @@ -56,7 +54,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.default.usage","play (Url)")); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); commandEvent.reply(em.build(), 5); diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Resume.java b/src/main/java/de/presti/ree6/commands/impl/music/Resume.java index 9296e5756..9cbae8bcf 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Resume.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Resume.java @@ -1,16 +1,14 @@ package de.presti.ree6.commands.impl.music; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; -import java.awt.*; - /** * Resume a Song. */ @@ -39,7 +37,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.music.resume")); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Seek.java b/src/main/java/de/presti/ree6/commands/impl/music/Seek.java index 1942db9df..990263d97 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Seek.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Seek.java @@ -22,12 +22,12 @@ public class Seek implements ICommand { */ @Override public void onPerform(CommandEvent commandEvent) { - int seekAmountInSeconds = 1; + long seekAmountInSeconds = 1; if (commandEvent.isSlashCommand()) { OptionMapping optionMapping = commandEvent.getOption("seconds"); if (optionMapping != null) { - seekAmountInSeconds = optionMapping.getAsInt(); + seekAmountInSeconds = optionMapping.getAsLong(); } } else if (commandEvent.getArguments().length >= 1) { try { @@ -45,7 +45,7 @@ public void onPerform(CommandEvent commandEvent) { return; } - Main.getInstance().getMusicWorker().seekInTrack(commandEvent.getChannel(), seekAmountInSeconds); + Main.getInstance().getMusicWorker().seekInTrack(commandEvent.getChannel(), commandEvent.getInteractionHook(), seekAmountInSeconds); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Shuffle.java b/src/main/java/de/presti/ree6/commands/impl/music/Shuffle.java index 312b1365a..4bc0f2d94 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Shuffle.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Shuffle.java @@ -1,16 +1,14 @@ package de.presti.ree6.commands.impl.music; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; -import java.awt.*; - /** * Shuffle the current Playlist. */ @@ -40,7 +38,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.music.shuffle")); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/music/SongInfo.java b/src/main/java/de/presti/ree6/commands/impl/music/SongInfo.java index 4c2989400..c01be9235 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/SongInfo.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/SongInfo.java @@ -2,17 +2,18 @@ import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import de.presti.ree6.audio.music.GuildMusicManager; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.FormatUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; - -import java.awt.*; +import net.dv8tion.jda.api.interactions.components.buttons.Button; +import net.dv8tion.jda.api.interactions.components.buttons.ButtonStyle; +import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; /** * Get information about the current Song. @@ -30,6 +31,7 @@ public void onPerform(CommandEvent commandEvent) { return; } + MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); EmbedBuilder em = new EmbedBuilder(); GuildMusicManager guildMusicManager = Main.getInstance().getMusicWorker().getGuildAudioPlayer(commandEvent.getGuild()); @@ -39,14 +41,17 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + if (audioTrack != null && audioTrack.getInfo().artworkUrl != null) em.setImage(audioTrack.getInfo().artworkUrl); + em.setColor(BotConfig.getMainColor()); em.setDescription(audioTrack == null ? commandEvent.getResource("message.music.notPlaying") : commandEvent.getResource("message.music.songInfo", audioTrack.getInfo().title, audioTrack.getInfo().author, FormatUtil.getStatusEmoji(guildMusicManager.getPlayer()) + FormatUtil.progressBar((double)audioTrack.getPosition() / audioTrack.getDuration()), FormatUtil.formatTime(audioTrack.getPosition()), FormatUtil.formatTime(audioTrack.getDuration()), FormatUtil.volumeIcon(guildMusicManager.getPlayer().getVolume()))); em.setFooter(commandEvent.getGuild().getName() + " - " + BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()); + messageCreateBuilder.setEmbeds(em.build()); + if (audioTrack != null) messageCreateBuilder.addActionRow(Button.of(ButtonStyle.LINK, audioTrack.getInfo().uri, "Watch")); - commandEvent.reply(em.build(), 5); + commandEvent.reply(messageCreateBuilder.build(), 5); } /** diff --git a/src/main/java/de/presti/ree6/commands/impl/music/SongList.java b/src/main/java/de/presti/ree6/commands/impl/music/SongList.java index 26794e4a4..4dbf768b6 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/SongList.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/SongList.java @@ -1,18 +1,16 @@ package de.presti.ree6.commands.impl.music; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.FormatUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; -import java.awt.*; - /** * Get the current list of songs. */ @@ -37,7 +35,7 @@ public void onPerform(CommandEvent commandEvent) { em.setAuthor(commandEvent.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(Main.getInstance().getMusicWorker().getGuildAudioPlayer(commandEvent.getGuild()).getScheduler().getQueue().isEmpty() ? commandEvent.getResource("message.music.songQueueEmpty") : (end.length() > 4096 ? commandEvent.getResource("command.perform.errorWithException","Error (M-SL-01)") : diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Stop.java b/src/main/java/de/presti/ree6/commands/impl/music/Stop.java index 4a31608ca..0d8b3058c 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Stop.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Stop.java @@ -1,16 +1,14 @@ package de.presti.ree6.commands.impl.music; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.build.CommandData; -import java.awt.*; - /** * Stop the Ree6 from playing Music. */ @@ -28,7 +26,7 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.reply(new EmbedBuilder().setAuthor(commandEvent.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()).setTitle(commandEvent.getResource("label.musicPlayer")) .setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.RED) + .setColor(BotConfig.getMainColor()) .setDescription(commandEvent.getResource("message.music.notPlaying")).build(), 5); } } diff --git a/src/main/java/de/presti/ree6/commands/impl/music/Volume.java b/src/main/java/de/presti/ree6/commands/impl/music/Volume.java index 05d0c6473..35d61fd11 100644 --- a/src/main/java/de/presti/ree6/commands/impl/music/Volume.java +++ b/src/main/java/de/presti/ree6/commands/impl/music/Volume.java @@ -1,11 +1,11 @@ package de.presti.ree6.commands.impl.music; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.main.Main; -import de.presti.ree6.bot.BotConfig; import lavalink.client.player.IPlayer; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.interactions.commands.OptionMapping; @@ -14,8 +14,6 @@ import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.internal.interactions.CommandDataImpl; -import java.awt.*; - /** * Set the Volume of the AudioPlayer of Ree6. */ @@ -54,14 +52,14 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.music.volume.success", volume)); } else { em.setAuthor(commandEvent.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.RED); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.music.volume.default")); } @@ -82,14 +80,14 @@ public void onPerform(CommandEvent commandEvent) { commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.music.volume.success", vol)); } else { em.setAuthor(commandEvent.getGuild().getJDA().getSelfUser().getName(), BotConfig.getWebsite(), commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(commandEvent.getResource("label.musicPlayer")); em.setThumbnail(commandEvent.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(commandEvent.getResource("message.music.volume.default", player.getVolume())); } } diff --git a/src/main/java/de/presti/ree6/commands/impl/nsfw/NSFW.java b/src/main/java/de/presti/ree6/commands/impl/nsfw/NSFW.java index 0d0733b1b..f413dbf6f 100644 --- a/src/main/java/de/presti/ree6/commands/impl/nsfw/NSFW.java +++ b/src/main/java/de/presti/ree6/commands/impl/nsfw/NSFW.java @@ -73,6 +73,7 @@ public void sendImage(CommandEvent commandEvent) { String randomUrl = images.get(RandomUtils.secureRandom.nextInt(images.size() - 1)); EmbedBuilder em = new EmbedBuilder(); + em.setColor(BotConfig.getMainColor()); em.setImage(randomUrl); em.setFooter(commandEvent.getMember().getEffectiveName() + " - " + BotConfig.getAdvertisement(), commandEvent.getMember().getEffectiveAvatarUrl()); diff --git a/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java b/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java index 97c0bb71b..d86d7204d 100644 --- a/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java +++ b/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java @@ -3,11 +3,11 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.commands.Category; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.external.RequestUtility; import de.presti.ree6.utils.others.RandomUtils; import net.dv8tion.jda.api.EmbedBuilder; @@ -107,6 +107,7 @@ public void sendImage(CommandEvent commandEvent, Message message, String tags) { if (object.has("sample_url")) { EmbedBuilder em = new EmbedBuilder(); + em.setColor(BotConfig.getMainColor()); em.setImage(object.get("sample_url").getAsString()); em.setFooter(commandEvent.getMember().getEffectiveName() + " - " + BotConfig.getAdvertisement(), commandEvent.getMember().getEffectiveAvatarUrl()); diff --git a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java index f691b05e8..354394b57 100644 --- a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java +++ b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java @@ -1,7 +1,6 @@ package de.presti.ree6.commands.interfaces; import de.presti.ree6.bot.BotConfig; -import de.presti.ree6.bot.BotWorker; import de.presti.ree6.commands.CommandEvent; import de.presti.ree6.language.LanguageService; import de.presti.ree6.main.Main; @@ -53,7 +52,7 @@ default Mono onMonoPerform(CommandEvent commandEvent) { .setAuthor(BotConfig.getBotName() + "-Info") .setDescription(a.content().replace("\\n", "\n") + "\n\n" + LanguageService.getByGuild(commandEvent.getGuild(), "message.news.notice").block()) .setFooter(BotConfig.getAdvertisement(), commandEvent.getGuild().getIconUrl()) - .setColor(BotWorker.randomEmbedColor()), 15, commandEvent.getChannel()); + .setColor(BotConfig.getMainColor()), 15, commandEvent.getChannel()); AnnouncementManager.addReceivedAnnouncement(commandEvent.getGuild().getIdLong(), a.id()); } diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index 79a1b7284..deedc29ca 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -79,7 +79,7 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { if (recording.isPresent()) { messageEditBuilder.setEmbeds(new EmbedBuilder() .setDescription(LanguageService.getByGuild(event.getGuild(), "message.recording.inChat").block()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) .setTitle(LanguageService.getByGuild(event.getGuild(), "label.recording.finished").block()) .build()); @@ -136,7 +136,7 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); messageCreateBuilder.setEmbeds(new EmbedBuilder().setTitle(LanguageService.getByGuild(event.getGuild(), "label.ticket").block()) .setDescription(ticketMessage.get().getStringValue()) - .setThumbnail(event.getMember().getEffectiveAvatarUrl()).setColor(Color.GREEN).setTimestamp(Instant.now()).build()); + .setThumbnail(event.getMember().getEffectiveAvatarUrl()).setColor(BotConfig.getMainColor()).setTimestamp(Instant.now()).build()); messageCreateBuilder.addActionRow(Button.primary("re_ticket_close", LanguageService.getByGuild(event.getGuild(), "label.closeTicket").block())); Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), channel); event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.created", channel.getAsMention()).block()).queue(); @@ -166,7 +166,7 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { webhookEmbedBuilder.setDescription("Here is the transcript of the ticket " + ticketEntity.getTicketCount() + "!"); webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - webhookEmbedBuilder.setColor(BotWorker.randomEmbedColor().getRGB()); + webhookEmbedBuilder.setColor(BotConfig.getMainColor().getRGB()); webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); webhookMessageBuilder.addFile(event.getGuild().getId() + "_" + ticketEntity.getTicketCount() + "_transcript.html", @@ -194,7 +194,7 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").block()) .setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.resume").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); @@ -204,7 +204,7 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").block()) .setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.pause").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); @@ -226,7 +226,7 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) .setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").block()) .setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.pause").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); Main.getInstance().getCommandManager().sendMessage(em, event.getChannel(), event.getHook()); @@ -259,7 +259,7 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").block()); em.setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(Main.getInstance().getMusicWorker().getGuildAudioPlayer(event.getGuild()).getScheduler().loop() ? LanguageService.getByGuild(event.getGuild(), "message.music.loop.enabled").block() : LanguageService.getByGuild(event.getGuild(), "message.music.loop.disabled").block()); @@ -285,7 +285,7 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); em.setTitle(LanguageService.getByGuild(event.getGuild(), "label.musicPlayer").block()); em.setThumbnail(event.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()); - em.setColor(Color.GREEN); + em.setColor(BotConfig.getMainColor()); em.setDescription(LanguageService.getByGuild(event.getGuild(), "message.music.shuffle").block()); em.setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()); @@ -355,7 +355,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setTitle(title) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(event.getGuild(), "message.rewards.success").block()) .setFooter(BotConfig.getAdvertisement(), event.getGuild().getIconUrl()), null, event.getInteraction().getHook()); }); @@ -368,7 +368,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { LanguageService.getByGuild(event.getGuild(), "label.feedback").subscribe(title -> { EmbedBuilder embedBuilder = new EmbedBuilder() .setTitle(title) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setThumbnail(event.getUser().getEffectiveAvatarUrl()) .setDescription("```" + event.getValue("re_feedback_text").getAsString() + "```") .setFooter("By " + event.getUser().getEffectiveName() + " (" + event.getUser().getId() + ")", event.getUser().getEffectiveAvatarUrl()) @@ -480,7 +480,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { EmbedBuilder embedBuilder = new EmbedBuilder() .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitchSuccess").block()); event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); @@ -504,7 +504,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { EmbedBuilder embedBuilder = new EmbedBuilder() .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeSuccess").block()); if (categories.isEmpty()) { @@ -577,7 +577,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { embedBuilder = embedBuilder .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.youtubeSuccess").block()); event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); @@ -600,7 +600,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { EmbedBuilder embedBuilder = new EmbedBuilder() .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.redditSuccess").block()); if (categories.isEmpty()) { @@ -659,7 +659,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { embedBuilder = embedBuilder .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.redditSuccess").block()); event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); @@ -682,7 +682,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { EmbedBuilder embedBuilder = new EmbedBuilder() .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitterSuccess").block()); if (categories.isEmpty()) { @@ -741,7 +741,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { embedBuilder = embedBuilder .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.twitterSuccess").block()); event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); @@ -764,7 +764,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { EmbedBuilder embedBuilder = new EmbedBuilder() .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.instagramSuccess").block()); if (categories.isEmpty()) { @@ -823,7 +823,7 @@ public void onModalInteraction(@NotNull ModalInteractionEvent event) { embedBuilder = embedBuilder .setTitle(LanguageService.getByGuild(event.getGuild(), "label.setupMenu").block()) .setFooter(event.getGuild().getName() + " - " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl()) - .setColor(Color.GREEN) + .setColor(BotConfig.getMainColor()) .setDescription(LanguageService.getByGuild(event.getGuild(), "message.statistics.instagramSuccess").block()); event.deferEdit().setEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); @@ -1027,7 +1027,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "statisticsSetupMember" -> LanguageService.getByGuild(event.getGuild(), "message.statistics.memberSuccess").subscribe(description -> { embedBuilder.setDescription(description); - embedBuilder.setColor(Color.GREEN); + embedBuilder.setColor(BotConfig.getMainColor()); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); List categories = event.getGuild().getCategoriesByName(LanguageService.getByGuild(event.getGuild(), "label.statistics").block(), true); @@ -1171,7 +1171,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(tickets -> { if (tickets.isPresent()) { embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.ticket.deleted").block()); - embedBuilder.setColor(Color.GREEN); + embedBuilder.setColor(BotConfig.getMainColor()); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); SQLSession.getSqlConnector().getSqlWorker().deleteEntity(tickets.get()).block(); } @@ -1219,7 +1219,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.setupSuccess").subscribe(description -> { SQLSession.getSqlConnector().getSqlWorker().updateEntity(new TemporalVoicechannel(event.getGuild().getIdLong(), voiceChannel.getIdLong())).block(); embedBuilder.setDescription(description); - embedBuilder.setColor(Color.GREEN); + embedBuilder.setColor(BotConfig.getMainColor()); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } else { @@ -1264,7 +1264,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even SQLSession.getSqlConnector().getSqlWorker().getEntity(new TemporalVoicechannel(), "FROM TemporalVoicechannel WHERE guildChannelId.guildId=:gid", Map.of("gid", event.getGuild().getIdLong())).subscribe(temporalVoicechannel -> { if (temporalVoicechannel.isPresent()) { embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.temporalVoice.deleted").block()); - embedBuilder.setColor(Color.GREEN); + embedBuilder.setColor(BotConfig.getMainColor()); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); SQLSession.getSqlConnector().getSqlWorker().deleteEntity(temporalVoicechannel.get()).block(); } @@ -1296,7 +1296,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even LanguageService.getByGuild(event.getGuild(), "message.lang.setupSuccess", language.getName() + " by " + language.getAuthor()).subscribe(description -> { SQLSession.getSqlConnector().getSqlWorker().setSetting(event.getGuild().getIdLong(), "configuration_language", "Language", selectedLocale.getLocale()); embedBuilder.setDescription(description); - embedBuilder.setColor(Color.GREEN); + embedBuilder.setColor(BotConfig.getMainColor()); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } else { @@ -1341,7 +1341,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even webhook.ifPresent(webhookLog -> event.getJDA().retrieveWebhookById(webhookLog.getChannelId()).queue(webhook1 -> { webhook1.delete().queue(); embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.deleted").block()); - embedBuilder.setColor(Color.GREEN); + embedBuilder.setColor(BotConfig.getMainColor()); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookLog).block(); }))); @@ -1397,7 +1397,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even WebhookUtil.deleteWebhook(event.getGuild().getIdLong(), webhookEntity)); SQLSession.getSqlConnector().getSqlWorker().setLogWebhook(event.getGuild().getIdLong(), textChannel.getIdLong(), webhook.getIdLong(), webhook.getToken()); embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupSuccess").block()); - embedBuilder.setColor(Color.GREEN); + embedBuilder.setColor(BotConfig.getMainColor()); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } else { @@ -1448,7 +1448,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even webhook.ifPresent(webhookWelcome -> event.getJDA().retrieveWebhookById(webhookWelcome.getChannelId()).queue(webhook1 -> { webhook1.delete().queue(); embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.deleted").block()); - embedBuilder.setColor(Color.GREEN); + embedBuilder.setColor(BotConfig.getMainColor()); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookWelcome).block(); }))); @@ -1505,7 +1505,7 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even SQLSession.getSqlConnector().getSqlWorker().setWelcomeWebhook(event.getGuild().getIdLong(), textChannel.getIdLong(), webhook.getIdLong(), webhook.getToken()); embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.welcome.setupSuccess").block()); - embedBuilder.setColor(Color.GREEN); + embedBuilder.setColor(BotConfig.getMainColor()); event.editMessageEmbeds(embedBuilder.build()).setComponents(new ArrayList<>()).queue(); }); } else { diff --git a/src/main/java/de/presti/ree6/events/OtherEvents.java b/src/main/java/de/presti/ree6/events/OtherEvents.java index 86f36e887..9d163fc78 100644 --- a/src/main/java/de/presti/ree6/events/OtherEvents.java +++ b/src/main/java/de/presti/ree6/events/OtherEvents.java @@ -89,7 +89,7 @@ public void onReady(@Nonnull ReadyEvent event) { */ @Override public void onGuildJoin(@NotNull GuildJoinEvent event) { - SQLSession.getSqlConnector().getSqlWorker().createSettings(event.getGuild().getIdLong()); + SQLSession.getSqlConnector().getSqlWorker().createCommandSettings(event.getGuild().getIdLong()); } /** @@ -229,7 +229,7 @@ public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) { webhookEmbedBuilder.setDescription("Here is the transcript of the ticket " + ticketsEntity.getTicketCount() + "!"); webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(event.getGuild().getName() + " " + BotConfig.getAdvertisement(), event.getGuild().getIconUrl())); - webhookEmbedBuilder.setColor(BotWorker.randomEmbedColor().getRGB()); + webhookEmbedBuilder.setColor(BotConfig.getMainColor().getRGB()); webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); webhookMessageBuilder.addFile(event.getGuild().getId() + "_" + ticketsEntity.getTicketCount() + "_transcript.html", diff --git a/src/main/java/de/presti/ree6/module/game/impl/blackjack/Blackjack.java b/src/main/java/de/presti/ree6/module/game/impl/blackjack/Blackjack.java index bb4324dd3..be30e1d52 100644 --- a/src/main/java/de/presti/ree6/module/game/impl/blackjack/Blackjack.java +++ b/src/main/java/de/presti/ree6/module/game/impl/blackjack/Blackjack.java @@ -1,6 +1,8 @@ package de.presti.ree6.module.game.impl.blackjack; -import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.language.LanguageService; +import de.presti.ree6.main.Main; import de.presti.ree6.module.game.core.GameManager; import de.presti.ree6.module.game.core.GameSession; import de.presti.ree6.module.game.core.base.GameInfo; @@ -10,8 +12,6 @@ import de.presti.ree6.module.game.impl.blackjack.entities.BlackJackCard; import de.presti.ree6.module.game.impl.blackjack.entities.BlackJackPlayer; import de.presti.ree6.module.game.impl.blackjack.util.BlackJackCardUtility; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Setting; import net.dv8tion.jda.api.EmbedBuilder; @@ -85,7 +85,7 @@ public void createGame() { EmbedBuilder embedBuilder = new EmbedBuilder(); embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").block()); - embedBuilder.setColor(BotWorker.randomEmbedColor()); + embedBuilder.setColor(BotConfig.getMainColor()); embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.welcome", session.getGameIdentifier()).block()); messageCreateBuilder.setEmbeds(embedBuilder.build()); @@ -293,7 +293,7 @@ public void stopGame(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlayer) MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder(); embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").block()); - embedBuilder.setColor(BotWorker.randomEmbedColor()); + embedBuilder.setColor(BotConfig.getMainColor()); BlackJackPlayer winner = findWinner(); if (winner == null) { @@ -340,7 +340,7 @@ public void updateViews(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlaye EmbedBuilder currentPlayerEmbed = new EmbedBuilder(); currentPlayerEmbed.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").block()); - currentPlayerEmbed.setColor(Color.GREEN); + currentPlayerEmbed.setColor(BotConfig.getMainColor()); currentPlayerEmbed.setAuthor(currentPlayer.getRelatedUser().getEffectiveName(), null, currentPlayer.getRelatedUser().getEffectiveAvatarUrl()); currentPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCardsSelf").block(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", currentPlayer.getHandAsString(true), currentPlayer.getHandValue(true)).block(), true); @@ -361,7 +361,7 @@ public void updateViews(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlaye EmbedBuilder nextPlayerEmbed = new EmbedBuilder(); nextPlayerEmbed.setTitle(LanguageService.getByGuild(session.getGuild(), "label.blackJack").block()); - nextPlayerEmbed.setColor(Color.red); + nextPlayerEmbed.setColor(Color.RED); nextPlayerEmbed.setAuthor(nextPlayer.getRelatedUser().getEffectiveName(), null, nextPlayer.getRelatedUser().getEffectiveAvatarUrl()); nextPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCardsSelf").block(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", nextPlayer.getHandAsString(true), nextPlayer.getHandValue(true)).block(), true); nextPlayerEmbed.addField(LanguageService.getByGuild(session.getGuild(), "label.userCards", currentPlayer.getRelatedUser().getEffectiveName()).block(), LanguageService.getByGuild(session.getGuild(), "message.blackJackGame.playerHand", currentPlayer.getHandAsString(false), currentPlayer.getHandValue(false)).block(), true); diff --git a/src/main/java/de/presti/ree6/module/game/impl/musicquiz/MusicQuiz.java b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/MusicQuiz.java index 7193238d8..45462d39e 100644 --- a/src/main/java/de/presti/ree6/module/game/impl/musicquiz/MusicQuiz.java +++ b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/MusicQuiz.java @@ -1,6 +1,8 @@ package de.presti.ree6.module.game.impl.musicquiz; -import de.presti.ree6.bot.BotWorker; +import de.presti.ree6.bot.BotConfig; +import de.presti.ree6.language.LanguageService; +import de.presti.ree6.main.Main; import de.presti.ree6.module.game.core.GameSession; import de.presti.ree6.module.game.core.base.GameInfo; import de.presti.ree6.module.game.core.base.GamePlayer; @@ -9,8 +11,6 @@ import de.presti.ree6.module.game.impl.musicquiz.entities.MusicQuizEntry; import de.presti.ree6.module.game.impl.musicquiz.entities.MusicQuizPlayer; import de.presti.ree6.module.game.impl.musicquiz.util.MusicQuizUtil; -import de.presti.ree6.language.LanguageService; -import de.presti.ree6.main.Main; import de.presti.ree6.sql.SQLSession; import de.presti.ree6.sql.entities.Setting; import de.presti.ree6.utils.others.ThreadUtil; @@ -113,7 +113,7 @@ public void createGame() { EmbedBuilder embedBuilder = new EmbedBuilder(); embedBuilder.setTitle(LanguageService.getByGuild(session.getGuild(), "label.musicQuiz").block()); - embedBuilder.setColor(BotWorker.randomEmbedColor()); + embedBuilder.setColor(BotConfig.getMainColor()); embedBuilder.setDescription(LanguageService.getByGuild(session.getGuild(), "message.musicQuiz.welcome", session.getGameIdentifier()).block()); messageCreateBuilder.setEmbeds(embedBuilder.build()); diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java index 2d023b275..4f766b70f 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java @@ -17,7 +17,6 @@ import io.sentry.Sentry; import lombok.extern.slf4j.Slf4j; -import java.awt.*; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.time.Instant; @@ -161,7 +160,7 @@ public void run() { webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); webhookEmbedBuilder.setTimestamp(Instant.now()); - webhookEmbedBuilder.setColor(Color.CYAN.getRGB()); + webhookEmbedBuilder.setColor(BotConfig.getMainColor().getRGB()); webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); @@ -209,7 +208,7 @@ public void run() { webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(BotConfig.getAdvertisement(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); webhookEmbedBuilder.setTimestamp(Instant.now()); - webhookEmbedBuilder.setColor(Color.CYAN.getRGB()); + webhookEmbedBuilder.setColor(BotConfig.getMainColor().getRGB()); webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); diff --git a/src/main/java/de/presti/ree6/utils/config/Config.java b/src/main/java/de/presti/ree6/utils/config/Config.java index 1cf42b73d..050c25699 100644 --- a/src/main/java/de/presti/ree6/utils/config/Config.java +++ b/src/main/java/de/presti/ree6/utils/config/Config.java @@ -122,6 +122,7 @@ public void createConfigFile() { .parent().path("dev").addDefault("DevTokenhere").commentSide("Token used when set to dev build.") .parent().parent().path("misc").comment("Configuration for the Bot itself.").blankLine() .path("status").addDefault("ree6.de | %guilds% Servers. (%shard%)").commentSide("The Status of the Bot.") + .parent().path("mainColor").addDefault("#B9010B").commentSide("Color that should be used in various places.") .parent().path("feedbackChannelId").addDefault(0L).commentSide("The Channel used for Feedback.") .parent().path("ownerId").addDefault(321580743488831490L).commentSide("The ID of the Bot Owner. Change this to yours!") .parent().path("predefineInformation").addDefault(""" From cb0a7a1b5f9a189b7022de1b1578b88d3838abd5 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 16 Oct 2024 13:27:33 +0200 Subject: [PATCH 76/94] Change default color. Signed-off-by: Presti --- src/main/java/de/presti/ree6/utils/config/Config.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/de/presti/ree6/utils/config/Config.java b/src/main/java/de/presti/ree6/utils/config/Config.java index 050c25699..56e20d44b 100644 --- a/src/main/java/de/presti/ree6/utils/config/Config.java +++ b/src/main/java/de/presti/ree6/utils/config/Config.java @@ -122,7 +122,7 @@ public void createConfigFile() { .parent().path("dev").addDefault("DevTokenhere").commentSide("Token used when set to dev build.") .parent().parent().path("misc").comment("Configuration for the Bot itself.").blankLine() .path("status").addDefault("ree6.de | %guilds% Servers. (%shard%)").commentSide("The Status of the Bot.") - .parent().path("mainColor").addDefault("#B9010B").commentSide("Color that should be used in various places.") + .parent().path("mainColor").addDefault("#c80292").commentSide("Color that should be used in various places.") .parent().path("feedbackChannelId").addDefault(0L).commentSide("The Channel used for Feedback.") .parent().path("ownerId").addDefault(321580743488831490L).commentSide("The ID of the Bot Owner. Change this to yours!") .parent().path("predefineInformation").addDefault(""" From f01282197fe50e4f9a0be760e73ceb1cc806afac Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 16 Oct 2024 13:30:52 +0200 Subject: [PATCH 77/94] Clean up. Signed-off-by: Presti --- .../ree6/audio/AudioPlayerReceiveHandler.java | 2 +- .../de/presti/ree6/events/MenuEvents.java | 35 ++++++++++--------- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java b/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java index 0841d8569..15907278c 100644 --- a/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java +++ b/src/main/java/de/presti/ree6/audio/AudioPlayerReceiveHandler.java @@ -98,7 +98,7 @@ public AudioPlayerReceiveHandler(Member member, AudioChannelUnion audioChannelUn message = audioChannelUnion.asGuildMessageChannel().sendMessageEmbeds(new EmbedBuilder() .setDescription(LanguageService.getByGuild(member.getGuild(), "message.recording.started").block()) - .setColor(Color.RED) + .setColor(BotConfig.getMainColor()) .setFooter(LanguageService.getByGuild(member.getGuild(), "label.footerMessage", member.getEffectiveName(), BotConfig.getAdvertisement()).block(), member.getEffectiveAvatarUrl()) .setTitle(LanguageService.getByGuild(member.getGuild(), "label.recording.start").block()) .build()).complete(); diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index deedc29ca..1eb90c888 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -101,11 +101,12 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { } switch (event.getComponentId()) { - case "re_feedback" -> LanguageService.getByGuild(event.getGuild(), "label.feedback").subscribe(modalString -> { - Modal.Builder builder = Modal.create("re_feedback_modal", modalString); - builder.addActionRow(TextInput.create("re_feedback_text", modalString, TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(2042).setMinLength(16).build()); - event.replyModal(builder.build()).queue(); - }); + case "re_feedback" -> + LanguageService.getByGuild(event.getGuild(), "label.feedback").subscribe(modalString -> { + Modal.Builder builder = Modal.create("re_feedback_modal", modalString); + builder.addActionRow(TextInput.create("re_feedback_text", modalString, TextInputStyle.PARAGRAPH).setRequired(true).setMaxLength(2042).setMinLength(16).build()); + event.replyModal(builder.build()).queue(); + }); case "re_suggestion" -> LanguageService.getByGuild(event.getGuild(), "label.suggestion").subscribe(modalString -> { @@ -136,6 +137,7 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { MessageCreateBuilder messageCreateBuilder = new MessageCreateBuilder(); messageCreateBuilder.setEmbeds(new EmbedBuilder().setTitle(LanguageService.getByGuild(event.getGuild(), "label.ticket").block()) .setDescription(ticketMessage.get().getStringValue()) + .setColor(BotConfig.getMainColor()) .setThumbnail(event.getMember().getEffectiveAvatarUrl()).setColor(BotConfig.getMainColor()).setTimestamp(Instant.now()).build()); messageCreateBuilder.addActionRow(Button.primary("re_ticket_close", LanguageService.getByGuild(event.getGuild(), "label.closeTicket").block())); Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), channel); @@ -1321,20 +1323,21 @@ public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent even case "backToSetupMenu" -> sendDefaultChoice(event); - case "logSetup" -> LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(labelMore -> { - for (TextChannel channel : event.getGuild().getTextChannels()) { - if (optionList.size() == 24) { - optionList.add(SelectOption.of(labelMore, "more")); - break; - } + case "logSetup" -> + LanguageService.getByGuild(event.getGuild(), "label.more").subscribe(labelMore -> { + for (TextChannel channel : event.getGuild().getTextChannels()) { + if (optionList.size() == 24) { + optionList.add(SelectOption.of(labelMore, "more")); + break; + } - optionList.add(SelectOption.of(channel.getName(), channel.getId())); - } + optionList.add(SelectOption.of(channel.getName(), channel.getId())); + } - embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupDescription").block()); + embedBuilder.setDescription(LanguageService.getByGuild(event.getGuild(), "message.auditLog.setupDescription").block()); - event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); - }); + event.editMessageEmbeds(embedBuilder.build()).setActionRow(new StringSelectMenuImpl("setupLogChannel", LanguageService.getByGuild(event.getGuild(), "label.selectChannel").block(), 1, 1, false, optionList)).queue(); + }); case "logDelete" -> SQLSession.getSqlConnector().getSqlWorker().getLogWebhook(event.getGuild().getIdLong()).subscribe(webhook -> From 4a2056d4e5a8738e9ea71e2d6972dae862691ffa Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 16 Oct 2024 13:44:16 +0200 Subject: [PATCH 78/94] Birthday changes. Signed-off-by: Presti --- languages/en-GB.yml | 1 + .../ree6/commands/impl/community/Birthday.java | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/languages/en-GB.yml b/languages/en-GB.yml index dcbb56d4c..7b0152337 100644 --- a/languages/en-GB.yml +++ b/languages/en-GB.yml @@ -238,6 +238,7 @@ message: other: "The Birthday of %s has been removed!" noPerms: "You don't have the permission to remove a Birthday!" wish: "Happy birthday to <@%s>!" + list: "Here are all Birthday wishes:\n```%s```" instagramNotifier: added: "A Instagram Notifier has been created for the User %s!" list: "Here are all Instagram Notifier that have been setup:\n```%s```" diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java b/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java index 33490e779..4d34b1c32 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java @@ -5,8 +5,10 @@ import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.BirthdayWish; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -42,6 +44,21 @@ public void onPerform(CommandEvent commandEvent) { OptionMapping birthYearMapping = commandEvent.getOption("year"); switch (command) { + case "list" -> { + if (commandEvent.getMember().hasPermission(Permission.ADMINISTRATOR)) { + SQLSession.getSqlConnector().getSqlWorker().getBirthdays(commandEvent.getGuild().getIdLong()).subscribe(birthdayWishes -> { + StringBuilder sb = new StringBuilder(); + for (BirthdayWish wish : birthdayWishes) { + Member member = commandEvent.getGuild().getMemberById(wish.getUserId()); + GuildChannel guildChannel = commandEvent.getGuild().getGuildChannelById(wish.getChannelId()); + sb.append("@" + member.getUser().getName()).append(" ").append("-").append(" ").append("#").append(guildChannel.getName()).append("\n"); + } + commandEvent.reply(commandEvent.getResource("message.birthday.list", sb)); + }); + } else { + commandEvent.reply(commandEvent.getResource("message.default.insufficientPermission", Permission.ADMINISTRATOR.getName()), 5); + } + } case "remove" -> { if (userMapping == null) { SQLSession.getSqlConnector().getSqlWorker().removeBirthday(commandEvent.getGuild().getIdLong(), commandEvent.getMember().getIdLong()); From 50f84a988badf90ca245eb8cc470fd122ada16a1 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 16 Oct 2024 13:44:40 +0200 Subject: [PATCH 79/94] Bump Signed-off-by: Presti --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 203781b0e..79734df0c 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ de.presti Ree6 - 4.0.0-alpha.2 + 4.0.0-alpha.3 jar From 84627daaea4f9500a7e2419b601a2c797a54a256 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 16 Oct 2024 13:46:43 +0200 Subject: [PATCH 80/94] Missing subcommand. Signed-off-by: Presti --- .../java/de/presti/ree6/commands/impl/community/Birthday.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java b/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java index 4d34b1c32..806863f65 100644 --- a/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java +++ b/src/main/java/de/presti/ree6/commands/impl/community/Birthday.java @@ -119,6 +119,7 @@ public CommandData getCommandData() { "command.description.birthday") .addSubcommands(new SubcommandData("remove", "Remove a Birthday entry!") .addOptions(new OptionData(OptionType.USER, "user", "The User which should get their birthday entry removed.", false)), + new SubcommandData("list", "See all of the Birthday entries!"), new SubcommandData("add", "Add a Birthday entry!") .addOptions(new OptionData(OptionType.INTEGER, "day", "The day of the month.", true).setMinValue(1).setMaxValue(31), new OptionData(OptionType.INTEGER, "month", "Your birth month.", true).setMinValue(1).setMaxValue(12), From 130f37bccbc1013072ea05e3874de439e0e33331 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 16 Oct 2024 13:51:24 +0200 Subject: [PATCH 81/94] Code cleanup. Signed-off-by: Presti --- .../container/CustomEventContainerCreator.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java b/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java index 467b87da1..e49c4f707 100644 --- a/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java +++ b/src/main/java/de/presti/ree6/module/actions/customevents/container/CustomEventContainerCreator.java @@ -44,9 +44,7 @@ public static void loadAll() { for (Class aClass : classes) { if (aClass.isAnnotationPresent(ActionInfo.class)) { String actionName = aClass.getAnnotation(ActionInfo.class).name(); - if (!cachedActions.containsKey(actionName)) { - cachedActions.put(actionName, aClass); - } + cachedActions.computeIfAbsent(actionName, s -> aClass); } } } @@ -69,9 +67,7 @@ public static Class getAction(String action) { for (Class aClass : classes) { if (aClass.isAnnotationPresent(ActionInfo.class) && aClass.getAnnotation(ActionInfo.class).name().trim().equalsIgnoreCase(action)) { - if (!cachedActions.containsKey(action)) { - cachedActions.put(action, aClass); - } + cachedActions.computeIfAbsent(action, s -> aClass); return aClass; } From 84da3d26cb91ab886ba41db3a5d84346b9040758 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 16 Oct 2024 15:57:28 +0200 Subject: [PATCH 82/94] Fixed codestyle. Signed-off-by: Presti --- src/main/java/de/presti/ree6/addons/ReePluginManager.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/de/presti/ree6/addons/ReePluginManager.java b/src/main/java/de/presti/ree6/addons/ReePluginManager.java index 06bd13166..e307a113f 100644 --- a/src/main/java/de/presti/ree6/addons/ReePluginManager.java +++ b/src/main/java/de/presti/ree6/addons/ReePluginManager.java @@ -8,7 +8,6 @@ @Slf4j public class ReePluginManager extends DefaultPluginManager { - public ReePluginManager() { super(); addPluginStateListener(x -> { From b10dce4130ad521138abc47c03d9ef54358a093d Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 16 Oct 2024 16:04:18 +0200 Subject: [PATCH 83/94] Use .getUser instead of .getMember Signed-off-by: Presti --- src/main/java/de/presti/ree6/commands/impl/fun/Game.java | 6 +++--- src/main/java/de/presti/ree6/commands/impl/info/Avatar.java | 4 ++-- .../java/de/presti/ree6/commands/interfaces/ICommand.java | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Game.java b/src/main/java/de/presti/ree6/commands/impl/fun/Game.java index da3d2ef41..2fa79837a 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Game.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Game.java @@ -60,7 +60,7 @@ public void onPerform(CommandEvent commandEvent) { ArrayList participants = new ArrayList<>(); participants.add(commandEvent.getUser()); - GamePlayer gamePlayer = new GamePlayer(commandEvent.getMember().getUser()); + GamePlayer gamePlayer = new GamePlayer(commandEvent.getUser()); gamePlayer.setInteractionHook(commandEvent.getInteractionHook()); GameManager.createGameSession(GameManager.generateInvite(), nameMapping.getAsString(), commandEvent.getMember(), @@ -84,8 +84,8 @@ public void onPerform(CommandEvent commandEvent) { return; } - gameSession.getParticipants().add(commandEvent.getMember().getUser()); - GamePlayer gamePlayer = new GamePlayer(commandEvent.getMember().getUser()); + gameSession.getParticipants().add(commandEvent.getUser()); + GamePlayer gamePlayer = new GamePlayer(commandEvent.getUser()); gamePlayer.setInteractionHook(commandEvent.getInteractionHook()); gameSession.getGame().joinGame(gamePlayer); } diff --git a/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java b/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java index 05be51ba6..7db17816a 100644 --- a/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java +++ b/src/main/java/de/presti/ree6/commands/impl/info/Avatar.java @@ -31,7 +31,7 @@ public void onPerform(CommandEvent commandEvent) { if (targetOption != null && targetOption.getAsMember() != null) { sendAvatar(targetOption.getAsUser(), commandEvent); } else { - sendAvatar(commandEvent.getMember().getUser(), commandEvent); + sendAvatar(commandEvent.getUser(), commandEvent); } } else { @@ -43,7 +43,7 @@ public void onPerform(CommandEvent commandEvent) { sendAvatar(commandEvent.getMessage().getMentions().getUsers().get(0), commandEvent); } } else { - sendAvatar(commandEvent.getMember().getUser(), commandEvent); + sendAvatar(commandEvent.getUser(), commandEvent); } } } diff --git a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java index 354394b57..978232bee 100644 --- a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java +++ b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java @@ -63,7 +63,7 @@ default Mono onMonoPerform(CommandEvent commandEvent) { default void onPerformWithLog(CommandEvent commandEvent) { onPerform(commandEvent); if (BotConfig.isDebug()) - log.info("Command {} has ended, called by {} in {} ({}).", commandEvent.getCommand(), commandEvent.getMember().getUser().getName(), commandEvent.getGuild().getName(), commandEvent.getGuild().getId()); + log.info("Command {} has ended, called by {} in {} ({}).", commandEvent.getCommand(), commandEvent.getUser().getName(), commandEvent.getGuild().getName(), commandEvent.getGuild().getId()); } /** From 908ee9276fb1c15bd129d3c82af4eb3a9e0cb6d6 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 16 Oct 2024 16:14:42 +0200 Subject: [PATCH 84/94] Worked off a few todos. Signed-off-by: Presti --- src/main/java/de/presti/ree6/audio/music/TrackScheduler.java | 1 - .../java/de/presti/ree6/commands/impl/economy/Steal.java | 1 - src/main/java/de/presti/ree6/commands/impl/economy/Work.java | 1 - src/main/java/de/presti/ree6/commands/impl/mod/Setup.java | 1 - .../ree6/module/notifications/impl/InstagramSonic.java | 5 ++--- .../presti/ree6/module/notifications/impl/SpotifySonic.java | 1 - .../presti/ree6/module/notifications/impl/YouTubeSonic.java | 1 - .../java/de/presti/ree6/utils/apis/YouTubeAPIHandler.java | 2 -- src/main/java/de/presti/ree6/utils/config/Config.java | 2 -- .../java/de/presti/ree6/utils/data/ImageCreationUtility.java | 2 -- 10 files changed, 2 insertions(+), 15 deletions(-) diff --git a/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java b/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java index 61907060d..fd6e0ae6e 100644 --- a/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java +++ b/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java @@ -173,7 +173,6 @@ public void nextTrack(GuildMessageChannelUnion textChannel, int position, boolea } if (track != null) { - // TODO:: Really stupid workaround for https://github.com/Ree6-Applications/Ree6/issues/299! This should be rechecked later if it even worked. if (!silent) Main.getInstance().getCommandManager().sendMessage(new EmbedBuilder() .setAuthor(guildMusicManager.getGuild().getSelfMember().getEffectiveName(), BotConfig.getWebsite(), guildMusicManager.getGuild().getSelfMember().getEffectiveAvatarUrl()) diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java b/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java index a40a62e99..53c6e4fc6 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java @@ -91,7 +91,6 @@ public void onPerform(CommandEvent commandEvent) { } if (EconomyUtil.pay(targetHolder, holder, stealAmount, false, false)) { - // TODO:: more variation in the messages. commandEvent.reply(commandEvent.getResource("message.steal.success", EconomyUtil.formatMoney(stealAmount), member.getAsMention()), 5); } else { commandEvent.reply(commandEvent.getResource("message.steal.failed", EconomyUtil.formatMoney(stealAmount), member.getAsMention()), 5); diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Work.java b/src/main/java/de/presti/ree6/commands/impl/economy/Work.java index f6b06c672..fba471a22 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Work.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Work.java @@ -54,7 +54,6 @@ public void onPerform(CommandEvent commandEvent) { if (moneyHolder == null) return; if (EconomyUtil.pay(null, moneyHolder, amount, false, false, true)) { - // TODO:: add more variation messages. commandEvent.reply(commandEvent.getResource("message.work.success", EconomyUtil.formatMoney(amount))); } else { commandEvent.reply(commandEvent.getResource("message.work.fail")); diff --git a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java index 550899bda..8dbd66690 100644 --- a/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java +++ b/src/main/java/de/presti/ree6/commands/impl/mod/Setup.java @@ -252,7 +252,6 @@ public void onPerform(CommandEvent commandEvent) { for (Setting setting : SettingsManager.getSettings()) { if (!setting.getName().startsWith("configuration_rewards_")) continue; - // TODO:: thing of how to handle this. SQLSession.getSqlConnector().getSqlWorker().updateEntity(new Setting(commandEvent.getGuild().getIdLong(), setting.getName(), setting.getDisplayName(), setting.getValue())).block(); } diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java index bac36e99b..af672119d 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java @@ -123,9 +123,8 @@ public void run() { webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - // TODO:: add this with message. - - webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook)); + webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.setContent(webhook.getMessage() + .replace("%username%", user.getUsername())).build(), webhook)); }); } } diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java index 507df3a8d..e74070d3f 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java @@ -102,7 +102,6 @@ public void run() { } } catch (Exception exception) { Sentry.captureException(exception); - // TODO:: handle this shit } } }); diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java index c53ad0c21..43adeaffd 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java @@ -115,7 +115,6 @@ public void run() { if (!channelStats.isEmpty()) { ChannelResult youTubeChannel; try { - // TODO:: change YT Tracker to use the ID instead of username. youTubeChannel = YouTubeAPIHandler.getInstance().getYouTubeChannelById(channel); } catch (Exception e) { Sentry.captureException(e); diff --git a/src/main/java/de/presti/ree6/utils/apis/YouTubeAPIHandler.java b/src/main/java/de/presti/ree6/utils/apis/YouTubeAPIHandler.java index 453e05fb5..52740a4af 100644 --- a/src/main/java/de/presti/ree6/utils/apis/YouTubeAPIHandler.java +++ b/src/main/java/de/presti/ree6/utils/apis/YouTubeAPIHandler.java @@ -18,8 +18,6 @@ import java.util.List; import java.util.regex.Pattern; -// TODO:: check if there is a way to make this more efficient, maybe use a cache system or merge multiple requests into one and split the result for further use again? - /** * YouTubeAPIHandler. */ diff --git a/src/main/java/de/presti/ree6/utils/config/Config.java b/src/main/java/de/presti/ree6/utils/config/Config.java index 56e20d44b..da454caf4 100644 --- a/src/main/java/de/presti/ree6/utils/config/Config.java +++ b/src/main/java/de/presti/ree6/utils/config/Config.java @@ -15,8 +15,6 @@ import java.util.List; import java.util.Map; -// TODO:: Rework the Config System to make the Config class be the actual config structure and use it to serialize and deserialize while making a new ConfigManager class that loads and saves the config. - /** * Config. */ diff --git a/src/main/java/de/presti/ree6/utils/data/ImageCreationUtility.java b/src/main/java/de/presti/ree6/utils/data/ImageCreationUtility.java index c95015bcf..e8b2160fd 100644 --- a/src/main/java/de/presti/ree6/utils/data/ImageCreationUtility.java +++ b/src/main/java/de/presti/ree6/utils/data/ImageCreationUtility.java @@ -22,8 +22,6 @@ import java.util.HashMap; import java.util.Optional; -// TODO:: translate. - /** * A utility to create Images. */ From a2e397a02efea5a0f8bf34a1522d0d5b299d15fa Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 16 Oct 2024 17:03:07 +0200 Subject: [PATCH 85/94] Worked off a few todos. Signed-off-by: Presti --- .../presti/ree6/audio/music/MusicWorker.java | 1 - .../ree6/audio/music/TrackScheduler.java | 1 - .../ree6/commands/impl/hidden/Addon.java | 2 -- .../module/invite/InviteContainerManager.java | 24 ++++++++++--------- .../de/presti/ree6/utils/apis/Notifier.java | 3 --- 5 files changed, 13 insertions(+), 18 deletions(-) diff --git a/src/main/java/de/presti/ree6/audio/music/MusicWorker.java b/src/main/java/de/presti/ree6/audio/music/MusicWorker.java index 7b296161a..1dedc4f06 100644 --- a/src/main/java/de/presti/ree6/audio/music/MusicWorker.java +++ b/src/main/java/de/presti/ree6/audio/music/MusicWorker.java @@ -47,7 +47,6 @@ /** * Wrapper class that handles most Music-related stuff. */ -// TODO:: async all these messages. @Slf4j public class MusicWorker { diff --git a/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java b/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java index fd6e0ae6e..da82f7345 100644 --- a/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java +++ b/src/main/java/de/presti/ree6/audio/music/TrackScheduler.java @@ -28,7 +28,6 @@ * This class schedules tracks for the audio player. It contains the queue of * tracks. */ -// TODO:: async all these messages. @Slf4j @SuppressWarnings("ALL") public class TrackScheduler extends AudioEventAdapterWrapped { diff --git a/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java b/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java index d80b18a87..b6bf20e6e 100644 --- a/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java +++ b/src/main/java/de/presti/ree6/commands/impl/hidden/Addon.java @@ -23,8 +23,6 @@ @Command(name = "addon", description = "command.description.addon", category = Category.HIDDEN) public class Addon implements ICommand { - // TODO:: add messages to language file. - /** * @inheritDoc */ diff --git a/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java b/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java index 42fa63b75..9a12a6c62 100644 --- a/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java +++ b/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java @@ -172,35 +172,37 @@ public InviteContainer getRightInvite(Guild guild) { } // Go through every Invite of the Guild from our Database. - for (InviteContainer inv2 : getInvites(guild.getIdLong())) { + for (InviteContainer databaseInvite : getInvites(guild.getIdLong())) { // Check if its correct invite. - if (inv.getCode().equalsIgnoreCase(inv2.getCode())) { + if (inv.getCode().equalsIgnoreCase(databaseInvite.getCode())) { foundOne = true; // Check if the Creator of the Invite isn't the same as in our Database. - if (inv.getInviter().getIdLong() != inv2.getCreatorId()) { + if (inv.getInviter().getIdLong() != databaseInvite.getCreatorId()) { // Check if its Vanity Invite. if (vanityInvite != null && inv.getCode().equalsIgnoreCase(vanityInvite.getCode())) { // Correct the information. - inv2.setVanity(true); - inv2.setGuildId(guild.getIdLong()); - if (inv2.getCreatorId() == 0) { - inv2.setCreatorId(guild.getOwnerIdLong()); + databaseInvite.setVanity(true); + databaseInvite.setGuildId(guild.getIdLong()); + if (databaseInvite.getCreatorId() == 0) { + databaseInvite.setCreatorId(guild.getOwnerIdLong()); } } else { // This should never be reached so, log it. - log.warn("Detected a very weird Invite? Owner does not match database entry! Guild: " + guild.getName() + " (" + guild.getId() + ") Invite: " + inv.getInviter().getIdLong() + " Database: " + inv2.getCreatorId()); + log.warn("Detected a very weird Invite? Owner does not match database entry! Guild: " + guild.getName() + " (" + guild.getId() + ") Invite: " + inv.getInviter().getIdLong() + " Database: " + databaseInvite.getCreatorId()); break; } } // Check if the Invite from Discord exactly one more usage than in our Database. // If so, we most likely got the correct one. - if (inv.getUses() - 1 == inv2.getUses()) { - inv2.setVanity(vanityInvite != null && inv2.getCode().equalsIgnoreCase(vanityInvite.getCode())); - return inv2; + // Big Issue, if many users join at the same time the value updates quicker than Ree6 can react. + // So -1 would not work at all. + if (inv.getUses() - 1 == databaseInvite.getUses()) { + databaseInvite.setVanity(vanityInvite != null && databaseInvite.getCode().equalsIgnoreCase(vanityInvite.getCode())); + return databaseInvite; } } } diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index 15bbc73e3..9c229a12b 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -36,9 +36,6 @@ import java.util.Scanner; import java.util.concurrent.Callable; -// TODO:: translate -// TODO:: fix the Twitter Stream handler, wait for responses via https://github.com/redouane59/twittered/issues/447 - /** * Utility class used for Event Notifiers. Such as Twitch Livestream, YouTube Upload or Twitter Tweet. */ From 8551359c470a4d8c58395002ef37bb24f48faee4 Mon Sep 17 00:00:00 2001 From: Presti Date: Wed, 16 Oct 2024 17:04:19 +0200 Subject: [PATCH 86/94] Worked off a few todos. Signed-off-by: Presti --- .../module/actions/customevents/CustomEventActionEvent.java | 2 -- .../de/presti/ree6/module/invite/InviteContainerManager.java | 1 - 2 files changed, 3 deletions(-) diff --git a/src/main/java/de/presti/ree6/module/actions/customevents/CustomEventActionEvent.java b/src/main/java/de/presti/ree6/module/actions/customevents/CustomEventActionEvent.java index 20f05452f..d8322de5c 100644 --- a/src/main/java/de/presti/ree6/module/actions/customevents/CustomEventActionEvent.java +++ b/src/main/java/de/presti/ree6/module/actions/customevents/CustomEventActionEvent.java @@ -8,8 +8,6 @@ import net.dv8tion.jda.api.entities.Guild; import org.jetbrains.annotations.Nullable; -// TODO:: gotta think about a better naming schema. - /** * A Container class containing the needed Information to run a CustomEventAction. */ diff --git a/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java b/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java index 9a12a6c62..58c5b5402 100644 --- a/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java +++ b/src/main/java/de/presti/ree6/module/invite/InviteContainerManager.java @@ -18,7 +18,6 @@ /** * Utility class to contain every Invite and manage the Invites in our Database. */ -// TODO:: continue with the rework of this entire system @Slf4j public class InviteContainerManager implements IManager { From 9f5f878753fec702d0185a51c2fc927ac03040ca Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 18 Oct 2024 16:45:07 +0200 Subject: [PATCH 87/94] Use twitch color instead. Signed-off-by: Presti --- .../de/presti/ree6/module/notifications/impl/TwitchSonic.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java index ae36eb093..85ef137a5 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java @@ -92,7 +92,7 @@ public void run() { webhookEmbedBuilder.setAuthor(new WebhookEmbed.EmbedAuthor(channelGoLiveEvent.getStream().getUserName(), twitchUserRequest.map(User::getProfileImageUrl).orElse(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()), twitchUrl)); webhookEmbedBuilder.setImageUrl(channelGoLiveEvent.getStream().getThumbnailUrlTemplate()); webhookEmbedBuilder.setFooter(new WebhookEmbed.EmbedFooter(channelGoLiveEvent.getStream().getGameName(), BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl())); - webhookEmbedBuilder.setColor(Color.MAGENTA.getRGB()); + webhookEmbedBuilder.setColor(Color.MAGENTA.darker().getRGB()); wmb.addComponents(ActionRow.of(new Button(Button.Style.LINK, twitchUrl).setLabel(twitchUserRequest.isPresent() ? twitchUserRequest.get().getDisplayName() : "Watch Stream"))); wmb.addEmbeds(webhookEmbedBuilder.build()); From 0e7653f35197607b7075d4d85fc26d89a44c1d7e Mon Sep 17 00:00:00 2001 From: Presti Date: Fri, 18 Oct 2024 16:55:46 +0200 Subject: [PATCH 88/94] Fix Setting stuff. Signed-off-by: Presti --- .../ree6/commands/impl/economy/Steal.java | 6 ++---- .../presti/ree6/commands/impl/economy/Work.java | 13 +++++-------- .../module/game/impl/blackjack/Blackjack.java | 6 ++---- .../module/game/impl/musicquiz/MusicQuiz.java | 17 +++++++---------- 4 files changed, 16 insertions(+), 26 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java b/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java index 53c6e4fc6..a162171f2 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Steal.java @@ -5,7 +5,6 @@ import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.sql.entities.Setting; import de.presti.ree6.utils.data.EconomyUtil; import de.presti.ree6.utils.others.RandomUtils; import de.presti.ree6.utils.others.ThreadUtil; @@ -17,7 +16,6 @@ import java.time.Duration; import java.util.ArrayList; -import java.util.Map; /** * Steal money from other users. @@ -42,8 +40,8 @@ public void onPerform(CommandEvent commandEvent) { String entryString = commandEvent.getGuild().getIdLong() + "-" + commandEvent.getMember().getIdLong(); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_steal_delay")).subscribe(value -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), + "configuration_steal_delay").subscribe(value -> { long delay = Long.parseLong(value.get().getStringValue()); if (stealTimeout.contains(entryString)) { diff --git a/src/main/java/de/presti/ree6/commands/impl/economy/Work.java b/src/main/java/de/presti/ree6/commands/impl/economy/Work.java index fba471a22..79d2bd66f 100644 --- a/src/main/java/de/presti/ree6/commands/impl/economy/Work.java +++ b/src/main/java/de/presti/ree6/commands/impl/economy/Work.java @@ -5,7 +5,6 @@ import de.presti.ree6.commands.interfaces.Command; import de.presti.ree6.commands.interfaces.ICommand; import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.sql.entities.Setting; import de.presti.ree6.utils.data.EconomyUtil; import de.presti.ree6.utils.others.RandomUtils; import de.presti.ree6.utils.others.ThreadUtil; @@ -13,7 +12,6 @@ import java.time.Duration; import java.util.ArrayList; -import java.util.Map; /** * Work for money. @@ -33,8 +31,7 @@ public class Work implements ICommand { public void onPerform(CommandEvent commandEvent) { String entryString = commandEvent.getGuild().getIdLong() + "-" + commandEvent.getMember().getIdLong(); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_delay")).subscribe(value -> { + SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), "configuration_work_delay").subscribe(value -> { long delay = Long.parseLong(value.get().getStringValue()); if (workTimeout.contains(entryString)) { @@ -42,11 +39,11 @@ public void onPerform(CommandEvent commandEvent) { return; } - double min = Double.parseDouble(SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_min")).block().get().getStringValue()); + double min = Double.parseDouble(SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), + "configuration_work_min").block().get().getStringValue()); - double max = Double.parseDouble(SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", commandEvent.getGuild().getId(), "name", "configuration_work_max")).block().get().getStringValue()); + double max = Double.parseDouble(SQLSession.getSqlConnector().getSqlWorker().getSetting(commandEvent.getGuild().getIdLong(), + "configuration_work_max").block().get().getStringValue()); double amount = RandomUtils.round(RandomUtils.nextDouble(min, max), 2); diff --git a/src/main/java/de/presti/ree6/module/game/impl/blackjack/Blackjack.java b/src/main/java/de/presti/ree6/module/game/impl/blackjack/Blackjack.java index be30e1d52..346b45b71 100644 --- a/src/main/java/de/presti/ree6/module/game/impl/blackjack/Blackjack.java +++ b/src/main/java/de/presti/ree6/module/game/impl/blackjack/Blackjack.java @@ -13,7 +13,6 @@ import de.presti.ree6.module.game.impl.blackjack.entities.BlackJackPlayer; import de.presti.ree6.module.game.impl.blackjack.util.BlackJackCardUtility; import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.sql.entities.Setting; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; @@ -23,7 +22,6 @@ import java.awt.*; import java.util.ArrayList; -import java.util.Map; /** * Class used to represent the game of blackjack. @@ -311,8 +309,8 @@ public void stopGame(BlackJackPlayer currentPlayer, BlackJackPlayer nextPlayer) nextPlayer.getInteractionHook().editOriginalComponents(new ArrayList<>()).queue(); Main.getInstance().getCommandManager().sendMessage(messageCreateBuilder.build(), session.getChannel()); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_blackjack_win")) + SQLSession.getSqlConnector().getSqlWorker().getSetting(session.getGuild().getIdLong(), + "configuration_rewards_blackjack_win") .subscribe(setting -> rewardPlayer(session, winner, setting.get().getValue())); stopGame(); diff --git a/src/main/java/de/presti/ree6/module/game/impl/musicquiz/MusicQuiz.java b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/MusicQuiz.java index 45462d39e..cf3cc6ec3 100644 --- a/src/main/java/de/presti/ree6/module/game/impl/musicquiz/MusicQuiz.java +++ b/src/main/java/de/presti/ree6/module/game/impl/musicquiz/MusicQuiz.java @@ -12,7 +12,6 @@ import de.presti.ree6.module.game.impl.musicquiz.entities.MusicQuizPlayer; import de.presti.ree6.module.game.impl.musicquiz.util.MusicQuizUtil; import de.presti.ree6.sql.SQLSession; -import de.presti.ree6.sql.entities.Setting; import de.presti.ree6.utils.others.ThreadUtil; import lavalink.client.player.event.IPlayerEventListener; import lavalink.client.player.event.TrackEndEvent; @@ -29,7 +28,6 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.List; -import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; @@ -214,8 +212,7 @@ public void onMessageReceive(MessageReceivedEvent messageReceivedEvent) { if (currentEntry.checkTitle(messageContent)) { musicQuizPlayer.addPoints(1); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_title")) + SQLSession.getSqlConnector().getSqlWorker().getSetting(session.getGuild().getIdLong(), "configuration_rewards_musicquiz_title") .subscribe(setting -> rewardPlayer(session, musicQuizPlayer, setting.get().getValue())); messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundTitle", currentEntry.getTitle()).block()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); @@ -225,8 +222,8 @@ public void onMessageReceive(MessageReceivedEvent messageReceivedEvent) { if (currentEntry.checkArtist(messageContent)) { musicQuizPlayer.addPoints(2); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_artist")) + SQLSession.getSqlConnector().getSqlWorker().getSetting(session.getGuild().getIdLong(), + "configuration_rewards_musicquiz_artist") .subscribe(setting -> rewardPlayer(session, musicQuizPlayer, setting.get().getValue())); messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundArtists", currentEntry.getArtist()).block()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); @@ -236,8 +233,8 @@ public void onMessageReceive(MessageReceivedEvent messageReceivedEvent) { if (currentEntry.checkFeatures(messageContent)) { musicQuizPlayer.addPoints(3); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_feature")) + SQLSession.getSqlConnector().getSqlWorker().getSetting(session.getGuild().getIdLong(), + "configuration_rewards_musicquiz_feature") .subscribe(setting -> rewardPlayer(session, musicQuizPlayer, setting.get().getValue())); messageReceivedEvent.getMessage().reply(LanguageService.getByGuild(messageReceivedEvent.getGuild(), "message.musicQuiz.foundFeature", String.join(",", currentEntry.getFeatures())).block()).delay(5, TimeUnit.SECONDS).flatMap(Message::delete).queue(); @@ -286,8 +283,8 @@ public void stopGame() { menuMessage.delete().queue(); session.getChannel().sendMessage(messageCreateBuilder.build()).queue(); - SQLSession.getSqlConnector().getSqlWorker().getEntity(new Setting(), "FROM Setting WHERE settingId.guildId=:gid AND settingId.name=:name", - Map.of("gid", session.getGuild().getIdLong(), "name", "configuration_rewards_musicquiz_win")) + SQLSession.getSqlConnector().getSqlWorker().getSetting(session.getGuild().getIdLong(), + "configuration_rewards_musicquiz_win") .subscribe(setting -> rewardPlayer(session, sortedList.get(0), setting.get().getValue())); Main.getInstance().getMusicWorker().disconnect(session.getGuild()); From 24bd2c0644e6a97d6af9f7029dcb47af71c63335 Mon Sep 17 00:00:00 2001 From: Presti Date: Mon, 21 Oct 2024 16:56:30 +0200 Subject: [PATCH 89/94] WE GOT HELLA SPEED GANG Signed-off-by: Presti --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d8540ba15..af477336a 100644 --- a/pom.xml +++ b/pom.xml @@ -183,7 +183,7 @@ de.ree6 Ree6-SQL - 3206c2e0ab + 7916908de2 From 321ccf372976b5c8dfc37cdc6c60d06008e26aa2 Mon Sep 17 00:00:00 2001 From: Presti Date: Mon, 21 Oct 2024 17:02:20 +0200 Subject: [PATCH 90/94] Fix Spotify Signed-off-by: Presti --- .../notifications/impl/SpotifySonic.java | 2 +- .../de/presti/ree6/utils/apis/Notifier.java | 199 ++++++++++-------- 2 files changed, 118 insertions(+), 83 deletions(-) diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java index e74070d3f..b5a958d1f 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java @@ -31,7 +31,7 @@ public class SpotifySonic implements ISonic { ArrayList spotifyEntries = new ArrayList<>(); - SimpleDateFormat spotifyTimestamp = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ssZ"); + SimpleDateFormat spotifyTimestamp = new SimpleDateFormat("yyyy-MM-dd"); @Override public void load(List channelStats) { diff --git a/src/main/java/de/presti/ree6/utils/apis/Notifier.java b/src/main/java/de/presti/ree6/utils/apis/Notifier.java index 9c229a12b..ebb05227c 100644 --- a/src/main/java/de/presti/ree6/utils/apis/Notifier.java +++ b/src/main/java/de/presti/ree6/utils/apis/Notifier.java @@ -198,18 +198,18 @@ public Notifier() { log.error("Failed to create Twitch Client.", exception); } - log.info("Initializing Twitter Client..."); - twitterSonic = new TwitterSonic(); try { + log.info("Initializing Twitter Client..."); + twitterSonic = new TwitterSonic(); twitterClient = new TwitterClient(TwitterCredentials.builder() .bearerToken(Main.getInstance().getConfig().getConfiguration().getString("twitter.bearer")).build()); } catch (Exception exception) { log.error("Failed to create Twitter Client.", exception); } - log.info("Initializing Reddit Client..."); - redditSonic = new RedditSonic(); try { + log.info("Initializing Reddit Client..."); + redditSonic = new RedditSonic(); redditClient = Reddit4J .rateLimited() .setClientId(Main.getInstance().getConfig().getConfiguration().getString("reddit.client.id")) @@ -225,87 +225,122 @@ public Notifier() { Sentry.captureException(exception); } } + try { + log.info("Initializing Instagram Client..."); + instagramSonic = new InstagramSonic(); + // Callable that returns inputted code from System.in + Callable inputCode = () -> { + Scanner scanner = new Scanner(System.in); + log.error("Please input code: "); + String code = scanner.nextLine(); + scanner.close(); + return code; + }; + + // handler for challenge login + IGClient.Builder.LoginHandler challengeHandler = (client, response) -> IGChallengeUtils.resolveChallenge(client, response, inputCode); + + instagramClient = IGClient.builder() + .username(Main.getInstance().getConfig().getConfiguration().getString("instagram.username")) + .password(Main.getInstance().getConfig().getConfiguration().getString("instagram.password")) + .onChallenge(challengeHandler).build(); + + instagramClient.sendLoginRequest().exceptionally(throwable -> { + if (BotConfig.isDebug()) { + log.error("Failed to login to Instagram API, you can ignore this if you don't use Instagram.", throwable); + } else { + log.error("Failed to login to Instagram API, you can ignore this if you don't use Instagram."); + log.error("Error Message: {}", throwable.getMessage() + .replace("com.github.instagram4j.instagram4j.exceptions.IGResponseException: ", "") + .replace("'", "'")); + } + return null; + }); + } catch (Exception exception) { + log.error("Failed to create Instagram Client.", exception); + } - log.info("Initializing Instagram Client..."); - instagramSonic = new InstagramSonic(); - // Callable that returns inputted code from System.in - Callable inputCode = () -> { - Scanner scanner = new Scanner(System.in); - log.error("Please input code: "); - String code = scanner.nextLine(); - scanner.close(); - return code; - }; - - // handler for challenge login - IGClient.Builder.LoginHandler challengeHandler = (client, response) -> IGChallengeUtils.resolveChallenge(client, response, inputCode); - - instagramClient = IGClient.builder() - .username(Main.getInstance().getConfig().getConfiguration().getString("instagram.username")) - .password(Main.getInstance().getConfig().getConfiguration().getString("instagram.password")) - .onChallenge(challengeHandler).build(); - - instagramClient.sendLoginRequest().exceptionally(throwable -> { - if (BotConfig.isDebug()) { - log.error("Failed to login to Instagram API, you can ignore this if you don't use Instagram.", throwable); - } else { - log.error("Failed to login to Instagram API, you can ignore this if you don't use Instagram."); - log.error("Error Message: {}", throwable.getMessage() - .replace("com.github.instagram4j.instagram4j.exceptions.IGResponseException: ", "") - .replace("'", "'")); - } - return null; - }); - - log.info("Initializing Spotify Client..."); - spotifySonic = new SpotifySonic(); + try { + log.info("Initializing Spotify Client..."); + spotifySonic = new SpotifySonic(); + } catch (Exception exception) { + log.error("Failed to create Spotify Client.", exception); + } log.info("Initializing Streams..."); - log.info("Creating YouTube Streams..."); - youTubeSonic = new YouTubeSonic(); - ThreadUtil.createThread(x -> youTubeSonic.run(), x -> { - log.error("Failed to run YouTube Stream!", x); - Sentry.captureException(x); - }, Duration.ofMinutes(5), true, true); - - log.info("Creating Twitter Streams..."); - ThreadUtil.createThread(x -> twitterSonic.run(), x -> { - log.error("Failed to run Twitter Follower count checker!", x); - Sentry.captureException(x); - }, Duration.ofMinutes(5), true, true); - - log.info("Creating RSS Streams..."); - rssSonic = new RSSSonic(); - ThreadUtil.createThread(x -> rssSonic.run(), x -> { - log.error("Failed to run RSS Feed Stream!", x); - Sentry.captureException(x); - }, Duration.ofMinutes(3), true, true); - - log.info("Creating TikTok Streams..."); - tikTokSonic = new TikTokSonic(); - ThreadUtil.createThread(x -> tikTokSonic.run(), x -> { - log.error("Failed to run TikTok Stream!", x); - Sentry.captureException(x); - }, Duration.ofMinutes(5), true, true); - - log.info("Creating Instagram Streams..."); - ThreadUtil.createThread(x -> instagramSonic.run(), x -> { - log.error("Failed to run Instagram Stream!", x); - Sentry.captureException(x); - }, Duration.ofMinutes(5), true, true); - - log.info("Creating Reddit Streams..."); - ThreadUtil.createThread(x -> redditSonic.run(), x -> { - log.error("Failed to run Reddit Stream!", x); - Sentry.captureException(x); - }, Duration.ofMinutes(5), true, true); - - // Use 1 day instead of minutes, because Spotify release date is at max precise to the day - log.info("Creating Spotify Streams..."); - ThreadUtil.createThread(x -> spotifySonic.run(), x -> { - log.error("Failed to run Spotify Stream!", x); - Sentry.captureException(x); - }, Duration.ofDays(1), true, true); + try { + log.info("Creating YouTube Streams..."); + youTubeSonic = new YouTubeSonic(); + ThreadUtil.createThread(x -> youTubeSonic.run(), x -> { + log.error("Failed to run YouTube Stream!", x); + Sentry.captureException(x); + }, Duration.ofMinutes(5), true, true); + } catch (Exception exception) { + log.error("Failed to create YouTube Streams.", exception); + } + + try { + log.info("Creating Twitter Streams..."); + ThreadUtil.createThread(x -> twitterSonic.run(), x -> { + log.error("Failed to run Twitter Follower count checker!", x); + Sentry.captureException(x); + }, Duration.ofMinutes(5), true, true); + } catch (Exception exception) { + log.error("Failed to create Twitter Streams.", exception); + } + + try { + log.info("Creating RSS Streams..."); + rssSonic = new RSSSonic(); + ThreadUtil.createThread(x -> rssSonic.run(), x -> { + log.error("Failed to run RSS Feed Stream!", x); + Sentry.captureException(x); + }, Duration.ofMinutes(3), true, true); + } catch (Exception exception) { + log.error("Failed to create RSS Streams.", exception); + } + + try { + log.info("Creating TikTok Streams..."); + tikTokSonic = new TikTokSonic(); + ThreadUtil.createThread(x -> tikTokSonic.run(), x -> { + log.error("Failed to run TikTok Stream!", x); + Sentry.captureException(x); + }, Duration.ofMinutes(5), true, true); + } catch (Exception exception) { + log.error("Failed to create TikTok Streams.", exception); + } + + try { + log.info("Creating Instagram Streams..."); + ThreadUtil.createThread(x -> instagramSonic.run(), x -> { + log.error("Failed to run Instagram Stream!", x); + Sentry.captureException(x); + }, Duration.ofMinutes(5), true, true); + } catch (Exception exception) { + log.error("Failed to create Instagram Streams.", exception); + } + + try { + log.info("Creating Reddit Streams..."); + ThreadUtil.createThread(x -> redditSonic.run(), x -> { + log.error("Failed to run Reddit Stream!", x); + Sentry.captureException(x); + }, Duration.ofMinutes(5), true, true); + } catch (Exception exception) { + log.error("Failed to create Reddit Streams.", exception); + } + + try { + // Use 1 day instead of minutes, because Spotify release date is at max precise to the day + log.info("Creating Spotify Streams..."); + ThreadUtil.createThread(x -> spotifySonic.run(), x -> { + log.error("Failed to run Spotify Stream!", x); + Sentry.captureException(x); + }, Duration.ofDays(1), true, true); + } catch (Exception exception) { + log.error("Failed to create Spotify Streams.", exception); + } } } From a5f928ed8b0f8c006a56e76e9d38bf5d12691ba4 Mon Sep 17 00:00:00 2001 From: Presti Date: Mon, 21 Oct 2024 17:28:10 +0200 Subject: [PATCH 91/94] Code cleanup Signed-off-by: Presti --- .../de/presti/ree6/bot/util/WebhookUtil.java | 193 ++++++++++-------- .../de/presti/ree6/events/MenuEvents.java | 2 +- .../de/presti/ree6/events/OtherEvents.java | 4 +- src/main/java/de/presti/ree6/main/Main.java | 6 +- .../ree6/module/logger/LoggerQueue.java | 4 +- .../notifications/impl/InstagramSonic.java | 2 +- .../module/notifications/impl/RSSSonic.java | 4 +- .../notifications/impl/RedditSonic.java | 2 +- .../notifications/impl/SpotifySonic.java | 2 +- .../notifications/impl/TikTokSonic.java | 2 +- .../notifications/impl/TwitchSonic.java | 2 +- .../notifications/impl/YouTubeSonic.java | 2 +- 12 files changed, 121 insertions(+), 104 deletions(-) diff --git a/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java b/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java index f54d849ee..e278e3581 100644 --- a/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java +++ b/src/main/java/de/presti/ree6/bot/util/WebhookUtil.java @@ -3,9 +3,11 @@ import club.minnced.discord.webhook.WebhookClient; import club.minnced.discord.webhook.send.WebhookMessage; import de.presti.ree6.bot.BotWorker; -import de.presti.ree6.module.logger.LogMessage; import de.presti.ree6.main.Main; +import de.presti.ree6.module.logger.LogMessage; import de.presti.ree6.sql.SQLSession; +import de.presti.ree6.sql.entities.ScheduledMessage; +import de.presti.ree6.sql.entities.Tickets; import de.presti.ree6.sql.entities.webhook.*; import de.presti.ree6.sql.entities.webhook.base.Webhook; import de.presti.ree6.sql.entities.webhook.base.WebhookSocial; @@ -34,9 +36,10 @@ private WebhookUtil() { * * @param message the MessageContent. * @param webhook the Webhook. + * @param typ the typ of the Webhook */ - public static void sendWebhook(WebhookMessage message, Webhook webhook) { - sendWebhook(null, message, webhook.getWebhookId(), webhook.getToken(), false); + public static void sendWebhook(WebhookMessage message, Webhook webhook, WebhookTyp typ) { + sendWebhook(null, message, webhook.getWebhookId(), webhook.getToken(), typ); } /** @@ -45,10 +48,10 @@ public static void sendWebhook(WebhookMessage message, Webhook webhook) { * @param loggerMessage the MessageContent, if it has been merged. * @param message the MessageContent. * @param webhook the Webhook. - * @param isLog is the Webhook Message a Log-Message? + * @param typ the typ of the Webhook */ - public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, Webhook webhook, boolean isLog) { - sendWebhook(loggerMessage, message, webhook.getWebhookId(), webhook.getToken(), isLog); + public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, Webhook webhook, WebhookTyp typ) { + sendWebhook(loggerMessage, message, webhook.getWebhookId(), webhook.getToken(), typ); } /** @@ -56,9 +59,10 @@ public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, * * @param message the MessageContent. * @param webhook the Webhook. + * @param typ the typ of the Webhook */ - public static void sendWebhook(WebhookMessage message, WebhookSocial webhook) { - sendWebhook(null, message, webhook.getWebhookId(), webhook.getToken(), false); + public static void sendWebhook(WebhookMessage message, WebhookSocial webhook, WebhookTyp typ) { + sendWebhook(null, message, webhook.getWebhookId(), webhook.getToken(), typ); } /** @@ -67,10 +71,10 @@ public static void sendWebhook(WebhookMessage message, WebhookSocial webhook) { * @param loggerMessage the MessageContent, if it has been merged. * @param message the MessageContent. * @param webhook the Webhook. - * @param isLog is the Webhook Message a Log-Message? + * @param typ the typ of the Webhook */ - public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, WebhookSocial webhook, boolean isLog) { - sendWebhook(loggerMessage, message, webhook.getWebhookId(), webhook.getToken(), isLog); + public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, WebhookSocial webhook, WebhookTyp typ) { + sendWebhook(loggerMessage, message, webhook.getWebhookId(), webhook.getToken(), typ); } @@ -81,15 +85,15 @@ public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, * @param message the MessageContent. * @param webhookId the ID of the Webhook. * @param webhookToken the Auth-Token of the Webhook. - * @param isLog is the Webhook Message a Log-Message? + * @param typ the typ of the Webhook */ - public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, long webhookId, String webhookToken, boolean isLog) { - Main.getInstance().logAnalytic("Received a Webhook to send. (Log-Typ: {})", isLog ? loggerMessage != null ? loggerMessage.getType().name() : "NONE-LOG" : "NONE-LOG"); + public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, long webhookId, String webhookToken, WebhookTyp typ) { + Main.getInstance().logAnalytic("Received a Webhook to send. (Log-Typ: {})", typ == WebhookTyp.LOG ? loggerMessage != null ? loggerMessage.getType().name() : "NONE-LOG" : "NONE-LOG"); // Check if the given data is valid. if (webhookToken.contains("Not setup!") || webhookId == 0) return; // Check if the given data is in the Database. - if (isLog) { + if (typ == WebhookTyp.LOG) { SQLSession.getSqlConnector().getSqlWorker().existsLogData(webhookId, webhookToken).subscribe(x -> { if (!x) { // If not, inform about invalid send. @@ -102,95 +106,104 @@ public static void sendWebhook(LogMessage loggerMessage, WebhookMessage message, return; } - sendWebhookMessage(loggerMessage, message, webhookId, webhookToken, true); + sendWebhookMessage(loggerMessage, message, webhookId, webhookToken, typ); } }); } else { - sendWebhookMessage(loggerMessage, message, webhookId, webhookToken, false); + sendWebhookMessage(loggerMessage, message, webhookId, webhookToken, typ); } } - private static void sendWebhookMessage(LogMessage loggerMessage, WebhookMessage message, long webhookId, String webhookToken, boolean isLog) { + private static void sendWebhookMessage(LogMessage loggerMessage, WebhookMessage message, long webhookId, String webhookToken, WebhookTyp typ) { // Try sending a Webhook to the given data. try (WebhookClient wcl = WebhookClient.withId(webhookId, webhookToken)) { // Send the message and handle exceptions. wcl.send(message).exceptionally(throwable -> { // If error 404 comes, that means that the webhook is invalid. if (throwable.getMessage().contains("failure 404")) { - // Inform and delete invalid webhook. - if (isLog) { - SQLSession.getSqlConnector().getSqlWorker().deleteLogWebhook(webhookId, webhookToken); - log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - } else { - // TODO:: this has become worst so please for the love of god find a better solution brain. - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookWelcome(), "FROM WebhookWelcome WHERE webhookId = :cid AND token = :token", - Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(welcome -> { - if (welcome.isPresent()) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(welcome.get()).block(); - log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - } else { + switch (typ) { + case LOG -> + SQLSession.getSqlConnector().getSqlWorker().deleteLogWebhook(webhookId, webhookToken); + + case WELCOME -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookWelcome(), "FROM WebhookWelcome WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case YOUTUBE -> SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookYouTube(), "FROM WebhookYouTube WHERE webhookId = :cid AND token = :token", - Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookYouTube -> { - if (webhookYouTube.isPresent()) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookYouTube.get()).block(); - log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - } else { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTwitter(), "FROM WebhookTwitter WHERE webhookId = :cid AND token = :token", - Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookTwitter -> { - if (webhookTwitter.isPresent()) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTwitter.get()).block(); - log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - } else { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTwitch(), "FROM WebhookTwitch WHERE webhookId = :cid AND token = :token", - Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookTwitch -> { - - if (webhookTwitch.isPresent()) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTwitch.get()).block(); - log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - } else { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookReddit(), "FROM WebhookReddit WHERE webhookId = :cid AND token = :token", - Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookReddit -> { - - if (webhookReddit.isPresent()) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookReddit.get()).block(); - log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - } else { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookInstagram(), "FROM WebhookInstagram WHERE webhookId = :cid AND token = :token", - Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookInstagram -> { - - if (webhookInstagram.isPresent()) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookInstagram.get()).block(); - log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - } else { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTikTok(), "FROM WebhookTikTok WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(webhookTikTok -> { - if (webhookTikTok.isPresent()) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(webhookTikTok.get()).block(); - log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - } else { - SQLSession.getSqlConnector().getSqlWorker().getEntity(new RSSFeed(), "FROM WebhookTikTok WHERE webhookId = :cid AND token = :token", Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(rssFeed -> { - if (rssFeed.isPresent()) { - SQLSession.getSqlConnector().getSqlWorker().deleteEntity(rssFeed.get()).block(); - log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); - } else { - log.error("[Webhook] Invalid Webhook: {} - {}, has not been deleted since it is not a Log-Webhook.", webhookId, webhookToken); - } - }); - } - }); - } - }); - } - }); - } - }); - } - }); - } + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case TWITTER -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTwitter(), "FROM WebhookTwitter WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case TWITCH -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTwitch(), "FROM WebhookTwitch WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case REDDIT -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookReddit(), "FROM WebhookReddit WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case SPOTIFY -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookSpotify(), "FROM WebhookSpotify WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case TIKTOK -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookTikTok(), "FROM WebhookTikTok WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case INSTAGRAM -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new WebhookInstagram(), "FROM WebhookInstagram WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case RSS -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new RSSFeed(), "FROM RSSFeed WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case SCHEDULE -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new ScheduledMessage(), "FROM ScheduledMessage WHERE webhookId = :cid AND token = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); + }); + + case TICKET -> + SQLSession.getSqlConnector().getSqlWorker().getEntity(new Tickets(), "FROM Tickets WHERE logChannelWebhookId = :cid AND logChannelWebhookToken = :token", + Map.of("cid", String.valueOf(webhookId), "token", webhookToken)).subscribe(x -> { + if (x.isPresent()) + SQLSession.getSqlConnector().getSqlWorker().deleteEntity(x.get()); }); - } - }); } + log.error("[Webhook] Deleted invalid Webhook: {} - {}", webhookId, webhookToken); } else if (throwable.getMessage().contains("failure 400")) { // If 404 inform that the Message had an invalid Body. log.error("[Webhook] Invalid Body with LogTyp: {}", loggerMessage.getType().name()); @@ -223,4 +236,8 @@ public static void deleteWebhook(long guildId, Webhook webhookEntity) { .forEach(webhook -> webhook.delete().queue())); } } + + public enum WebhookTyp { + LOG, WELCOME, TIKTOK, SPOTIFY, YOUTUBE, REDDIT, TWITCH, TWITTER, INSTAGRAM, RSS, SCHEDULE, TICKET + } } \ No newline at end of file diff --git a/src/main/java/de/presti/ree6/events/MenuEvents.java b/src/main/java/de/presti/ree6/events/MenuEvents.java index 1eb90c888..c42dc2f2a 100644 --- a/src/main/java/de/presti/ree6/events/MenuEvents.java +++ b/src/main/java/de/presti/ree6/events/MenuEvents.java @@ -176,7 +176,7 @@ public void onButtonInteraction(@NotNull ButtonInteractionEvent event) { event.getChannel().getTimeCreated().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)).replace("T", " "), ZonedDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)).replace("T", " ")).getBytes(StandardCharsets.UTF_8)); - WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), ticketEntity.getLogChannelWebhookId(), ticketEntity.getLogChannelWebhookToken(), false); + WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), ticketEntity.getLogChannelWebhookId(), ticketEntity.getLogChannelWebhookToken(), WebhookUtil.WebhookTyp.TICKET); event.getHook().sendMessage(LanguageService.getByGuild(event.getGuild(), "message.ticket.close").block()).queue(); event.getChannel().delete().delay(2, TimeUnit.SECONDS).queue(); diff --git a/src/main/java/de/presti/ree6/events/OtherEvents.java b/src/main/java/de/presti/ree6/events/OtherEvents.java index 9d163fc78..bced6b12d 100644 --- a/src/main/java/de/presti/ree6/events/OtherEvents.java +++ b/src/main/java/de/presti/ree6/events/OtherEvents.java @@ -166,7 +166,7 @@ public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { SQLSession.getSqlConnector().getSqlWorker().getWelcomeWebhook(event.getGuild().getIdLong()).subscribe(webhook -> { if (webhook.isEmpty()) return; - WebhookUtil.sendWebhook(wmb.build(), webhook.get()); + WebhookUtil.sendWebhook(wmb.build(), webhook.get(), WebhookUtil.WebhookTyp.WELCOME); }); }); } @@ -237,7 +237,7 @@ public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) { channel.getTimeCreated().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)).replace("T", " "), ZonedDateTime.now().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)).replace("T", " ")).getBytes(StandardCharsets.UTF_8)); - WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), ticketsEntity.getLogChannelId(), ticketsEntity.getLogChannelWebhookToken(), false); + WebhookUtil.sendWebhook(null, webhookMessageBuilder.build(), ticketsEntity.getLogChannelId(), ticketsEntity.getLogChannelWebhookToken(), WebhookUtil.WebhookTyp.TICKET); channel.delete().queue(); } } diff --git a/src/main/java/de/presti/ree6/main/Main.java b/src/main/java/de/presti/ree6/main/Main.java index 7f8043c94..bb65bb420 100644 --- a/src/main/java/de/presti/ree6/main/Main.java +++ b/src/main/java/de/presti/ree6/main/Main.java @@ -612,7 +612,7 @@ public void createCheckerThread() { WebhookUtil.sendWebhook(new WebhookMessageBuilder() .setUsername(BotConfig.getBotName() + "-Scheduler") .setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()) - .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); + .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook(), WebhookUtil.WebhookTyp.SCHEDULE); SQLSession.getSqlConnector().getSqlWorker().deleteEntity(scheduledMessage).block(); } @@ -626,7 +626,7 @@ public void createCheckerThread() { WebhookUtil.sendWebhook(new WebhookMessageBuilder() .setUsername(BotConfig.getBotName() + "-Scheduler") .setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()) - .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); + .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook(), WebhookUtil.WebhookTyp.SCHEDULE); scheduledMessage.setLastExecute(Timestamp.from(Instant.now())); SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage).block(); @@ -637,7 +637,7 @@ public void createCheckerThread() { WebhookUtil.sendWebhook(new WebhookMessageBuilder() .setUsername(BotConfig.getBotName() + "-Scheduler") .setAvatarUrl(BotWorker.getShardManager().getShards().get(0).getSelfUser().getEffectiveAvatarUrl()) - .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook()); + .append(scheduledMessage.getMessage()).build(), scheduledMessage.getScheduledMessageWebhook(), WebhookUtil.WebhookTyp.SCHEDULE); scheduledMessage.setLastExecute(Timestamp.from(Instant.now())); SQLSession.getSqlConnector().getSqlWorker().updateEntity(scheduledMessage).block(); diff --git a/src/main/java/de/presti/ree6/module/logger/LoggerQueue.java b/src/main/java/de/presti/ree6/module/logger/LoggerQueue.java index a0e2b71e5..bc3e6ec84 100644 --- a/src/main/java/de/presti/ree6/module/logger/LoggerQueue.java +++ b/src/main/java/de/presti/ree6/module/logger/LoggerQueue.java @@ -3,13 +3,13 @@ import club.minnced.discord.webhook.send.WebhookEmbed; import club.minnced.discord.webhook.send.WebhookEmbedBuilder; import club.minnced.discord.webhook.send.WebhookMessageBuilder; +import de.presti.ree6.bot.BotConfig; import de.presti.ree6.bot.util.WebhookUtil; import de.presti.ree6.language.LanguageService; import de.presti.ree6.module.logger.events.LogMessageMember; import de.presti.ree6.module.logger.events.LogMessageRole; import de.presti.ree6.module.logger.events.LogMessageUser; import de.presti.ree6.module.logger.events.LogMessageVoice; -import de.presti.ree6.bot.BotConfig; import de.presti.ree6.utils.others.ThreadUtil; import net.dv8tion.jda.api.Permission; @@ -470,7 +470,7 @@ else if (loggerMessage.getType() == LogTyp.SERVER_LEAVE && loggerMessage instanc ThreadUtil.createThread(x -> { // If not canceled, send it. if (!loggerMessage.isCanceled()) { - WebhookUtil.sendWebhook(loggerMessage, loggerMessage.getWebhookMessage(), loggerMessage.getId(), loggerMessage.getAuthCode(), true); + WebhookUtil.sendWebhook(loggerMessage, loggerMessage.getWebhookMessage(), loggerMessage.getId(), loggerMessage.getAuthCode(), WebhookUtil.WebhookTyp.LOG); } // Remove it from the list. diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java index af672119d..f15fa6e5f 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/InstagramSonic.java @@ -124,7 +124,7 @@ public void run() { webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.setContent(webhook.getMessage() - .replace("%username%", user.getUsername())).build(), webhook)); + .replace("%username%", user.getUsername())).build(), webhook, WebhookUtil.WebhookTyp.INSTAGRAM)); }); } } diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java index 4f766b70f..cb6ec5f66 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/RSSSonic.java @@ -174,7 +174,7 @@ public void run() { .replace("#m", ""); } webhookMessageBuilder.setContent(message); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook, WebhookUtil.WebhookTyp.RSS); }); }); } else { @@ -212,7 +212,7 @@ public void run() { webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook)); + webhooks.forEach(webhook -> WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook, WebhookUtil.WebhookTyp.RSS)); }); } catch (Exception exception) { Sentry.captureException(exception); diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java index 5d765fa7c..b0e7e2821 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/RedditSonic.java @@ -122,7 +122,7 @@ public void run() { .replace("%name%", redditPost.getSubreddit()) .replace("%url%", redditPost.getUrl()); webhookMessageBuilder.setContent(message); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook, WebhookUtil.WebhookTyp.REDDIT); }); })); } diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java index b5a958d1f..a2e633940 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/SpotifySonic.java @@ -126,7 +126,7 @@ public void sendWebhooks(WebhookEmbedBuilder webhookEmbed, String description, S .replace("%name%", authorName) .replace("%url%", redirect); webhookMessageBuilder.setContent(message); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook, WebhookUtil.WebhookTyp.SPOTIFY); }); } diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java index 7d840f619..049101781 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java @@ -92,7 +92,7 @@ public void run() { .replace("%name%", user.getDisplayName()) .replace("%url%", "https://tiktok.com/share/video/" + post.getId()); webhookMessageBuilder.setContent(message); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook, WebhookUtil.WebhookTyp.TIKTOK); }); } limit.incrementAndGet(); diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java index 85ef137a5..275e00a9c 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/TwitchSonic.java @@ -103,7 +103,7 @@ public void run() { .replace("%name%", channelGoLiveEvent.getStream().getUserName()) .replace("%url%", twitchUrl); wmb.setContent(message); - WebhookUtil.sendWebhook(wmb.build(), webhook); + WebhookUtil.sendWebhook(wmb.build(), webhook, WebhookUtil.WebhookTyp.TWITCH); }); })); diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java index 43adeaffd..bbbeb6cde 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/YouTubeSonic.java @@ -96,7 +96,7 @@ public void run() { webhookMessageBuilder.setContent(message); webhookMessageBuilder.addEmbeds(webhookEmbedBuilder.build()); - WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook); + WebhookUtil.sendWebhook(webhookMessageBuilder.build(), webhook, WebhookUtil.WebhookTyp.YOUTUBE); }); break; From aabb368adaaa2d99143f114a3c83eddde0606717 Mon Sep 17 00:00:00 2001 From: Presti Date: Tue, 22 Oct 2024 11:54:10 +0200 Subject: [PATCH 92/94] Worked on more todos. Signed-off-by: Presti --- pom.xml | 2 +- .../presti/ree6/commands/CommandManager.java | 70 +++++++++++++------ .../presti/ree6/language/LanguageService.java | 28 +++++++- 3 files changed, 77 insertions(+), 23 deletions(-) diff --git a/pom.xml b/pom.xml index af477336a..b3f640bb7 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ de.presti Ree6 - 4.0.0-alpha.3 + 4.0.0-alpha.4 jar diff --git a/src/main/java/de/presti/ree6/commands/CommandManager.java b/src/main/java/de/presti/ree6/commands/CommandManager.java index 8656a4198..20fa15ff0 100644 --- a/src/main/java/de/presti/ree6/commands/CommandManager.java +++ b/src/main/java/de/presti/ree6/commands/CommandManager.java @@ -276,39 +276,67 @@ public void addSlashCommand(JDA jda) { listUpdateAction.queue(); } - public void translateSubgroups(SubcommandGroupData subcommandGroupData, DiscordLocale locale) { - // TODO:: add the same language check to option names/description and add a translation to it. - // Also for the love of god Imma need to optimize this. + private void translateSubgroups(SubcommandGroupData subcommandGroupData, DiscordLocale locale) { String groupDescription = subcommandGroupData.getDescription(); if (groupDescription.matches(RegExUtil.ALLOWED_LANGUAGE_PATHS)) { - groupDescription = LanguageService.getByLocale(locale, groupDescription).block(); - - if (groupDescription != null) { - if (groupDescription.equals("Missing language resource!")) { - groupDescription = LanguageService.getDefault(subcommandGroupData.getDescription()).block(); - } - - if (groupDescription != null && !groupDescription.equals("Missing language resource!")) { - subcommandGroupData.setDescriptionLocalization(locale, groupDescription); - } + if (LanguageService.hasTranslation(locale, groupDescription).block()) { + groupDescription = LanguageService.getByLocale(locale, groupDescription).block(); + } else if (LanguageService.hasDefaultTranslation(groupDescription).block()) { + groupDescription = LanguageService.getDefault(groupDescription).block(); } + + subcommandGroupData.setDescriptionLocalization(locale, groupDescription); } + // Translate Subcommands for (SubcommandData subcommandData : subcommandGroupData.getSubcommands()) { - String commandDescription = subcommandData.getDescription(); + translateSubcomand(subcommandData, locale); + } + } + + private void translateSubcomand(SubcommandData subcommandData, DiscordLocale locale) { + String commandDescription = subcommandData.getDescription(); - if (groupDescription != null && groupDescription.matches(RegExUtil.ALLOWED_LANGUAGE_PATHS)) { + if (commandDescription != null && commandDescription.matches(RegExUtil.ALLOWED_LANGUAGE_PATHS)) { + if (LanguageService.hasTranslation(locale, commandDescription).block()) { commandDescription = LanguageService.getByLocale(locale, commandDescription).block(); + } else if (LanguageService.hasDefaultTranslation(commandDescription).block()) { + commandDescription = LanguageService.getDefault(commandDescription).block(); + } - if (commandDescription != null && commandDescription.equals("Missing language resource!")) { - commandDescription = LanguageService.getDefault(subcommandData.getDescription()).block(); - } + subcommandData.setDescriptionLocalization(locale, commandDescription); + } - if (commandDescription != null && !commandDescription.equals("Missing language resource!")) { - subcommandData.setDescriptionLocalization(locale, commandDescription); - } + // Translate Options + for (OptionData optionData : subcommandData.getOptions()) { + translateOption(optionData, locale); + } + } + + private void translateOption(OptionData optionData, DiscordLocale locale) { + // Name translation + String optionName = optionData.getName(); + if (optionName != null && optionName.matches(RegExUtil.ALLOWED_LANGUAGE_PATHS)) { + if (LanguageService.hasTranslation(locale, optionName).block()) { + optionName = LanguageService.getByLocale(locale, optionName).block(); + } else if (LanguageService.hasDefaultTranslation(optionName).block()) { + optionName = LanguageService.getDefault(optionName).block(); } + + optionData.setNameLocalization(locale, optionName); + } + + // Description translation + String optionDescription = optionData.getDescription(); + if (optionDescription != null && optionDescription.matches(RegExUtil.ALLOWED_LANGUAGE_PATHS)) { + if (LanguageService.hasTranslation(locale, optionDescription).block()) { + optionDescription = LanguageService.getByLocale(locale, optionDescription).block(); + } else if (LanguageService.hasDefaultTranslation(optionDescription).block()) { + optionDescription = LanguageService.getDefault(optionDescription).block(); + } + + optionData.setDescriptionLocalization(locale, optionDescription); } } diff --git a/src/main/java/de/presti/ree6/language/LanguageService.java b/src/main/java/de/presti/ree6/language/LanguageService.java index 6730412a5..3d792e3a2 100644 --- a/src/main/java/de/presti/ree6/language/LanguageService.java +++ b/src/main/java/de/presti/ree6/language/LanguageService.java @@ -196,7 +196,7 @@ public static void downloadLanguages() { * @return The String. */ public static @NotNull Mono getByGuildOrInteractionHook(Guild guild, InteractionHook interaction, @NotNull String key, @Nullable Object... parameter) { - return getByGuildOrInteraction(guild, interaction != null ? interaction.getInteraction() : null, key, parameter); + return getByGuildOrInteraction(guild, interaction != null ? interaction.getInteraction() : null, key, parameter); } @@ -315,6 +315,32 @@ public static void downloadLanguages() { })); } + /** + * Check if given Locale has a translation for the key + * + * @param discordLocale The locale of the Language file. + * @param key The key of the String. + * @return true, if the key is translated. + */ + public static @NotNull Mono hasTranslation(@NotNull DiscordLocale discordLocale, @NotNull String key) { + return Mono.fromFuture(CompletableFuture.supplyAsync(() -> { + if (discordLocale == DiscordLocale.UNKNOWN) return false; + + return languageResources.containsKey(discordLocale) && languageResources.get(discordLocale).resources.containsKey(key); + })); + } + + /** + * Check if the default Locale has a translation for the key + * + * @param key The key of the String. + * @return true, if the key is translated. + */ + public static @NotNull Mono hasDefaultTranslation(@NotNull String key) { + DiscordLocale discordLocale = DiscordLocale.from(BotConfig.getDefaultLanguage()); + return hasTranslation(discordLocale, key); + } + /** * Called to retrieve all supported Locals. * From ce72e8b8b7ada8ff7285a267623082cb68229c06 Mon Sep 17 00:00:00 2001 From: Presti Date: Tue, 22 Oct 2024 12:21:01 +0200 Subject: [PATCH 93/94] Cleanup Signed-off-by: Presti --- .../de/presti/ree6/module/notifications/impl/TikTokSonic.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java b/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java index 049101781..5afac9e98 100644 --- a/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java +++ b/src/main/java/de/presti/ree6/module/notifications/impl/TikTokSonic.java @@ -99,9 +99,9 @@ public void run() { }); }); } catch (IOException e) { - if (e instanceof HttpStatusException httpStatusException) { - if (httpStatusException.getStatusCode() == 404) return; + if (e instanceof HttpStatusException httpStatusException && httpStatusException.getStatusCode() == 404) { // TODO:: check, maybe delete on 404? + return; } Sentry.captureException(e); From 5ee4083186bf146cc09c27098795565c9cc11b67 Mon Sep 17 00:00:00 2001 From: Presti Date: Tue, 22 Oct 2024 12:42:06 +0200 Subject: [PATCH 94/94] Fix up a stupid way of handling ephermal support. Signed-off-by: Presti --- src/main/java/de/presti/ree6/commands/CommandEvent.java | 5 +++-- src/main/java/de/presti/ree6/commands/CommandManager.java | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/de/presti/ree6/commands/CommandEvent.java b/src/main/java/de/presti/ree6/commands/CommandEvent.java index 905e5d39d..bd9141a20 100644 --- a/src/main/java/de/presti/ree6/commands/CommandEvent.java +++ b/src/main/java/de/presti/ree6/commands/CommandEvent.java @@ -77,7 +77,7 @@ public class CommandEvent { * @param arguments the given Arguments. * @param slashCommandInteractionEvent the {@link SlashCommandInteractionEvent} Entity. */ - public CommandEvent(String command, @Nonnull Member member, @Nonnull Guild guild, @Nullable Message message, @Nonnull GuildMessageChannelUnion textChannel, @Nullable String[] arguments, @Nullable SlashCommandInteractionEvent slashCommandInteractionEvent) { + public CommandEvent(String command, @Nonnull Member member, @Nonnull Guild guild, @Nullable Message message, @Nonnull GuildMessageChannelUnion textChannel, @Nullable String[] arguments, @Nullable SlashCommandInteractionEvent slashCommandInteractionEvent, boolean isEphermal) { this.command = command; this.member = member; this.guild = guild; @@ -85,6 +85,7 @@ public CommandEvent(String command, @Nonnull Member member, @Nonnull Guild guild this.channel = textChannel; this.arguments = arguments; this.slashCommandInteractionEvent = slashCommandInteractionEvent; + setEphemeral(isEphermal); } /** @@ -357,7 +358,7 @@ public boolean isSlashCommand() { * @return the {@link InteractionHook} Entity. */ public InteractionHook getInteractionHook() { - if (isSlashCommand()) return getSlashCommandInteractionEvent().getHook().setEphemeral(true); + if (isSlashCommand()) return getSlashCommandInteractionEvent().getHook(); return null; } diff --git a/src/main/java/de/presti/ree6/commands/CommandManager.java b/src/main/java/de/presti/ree6/commands/CommandManager.java index 20fa15ff0..6e25160b6 100644 --- a/src/main/java/de/presti/ree6/commands/CommandManager.java +++ b/src/main/java/de/presti/ree6/commands/CommandManager.java @@ -588,7 +588,7 @@ private Mono performMessageCommand(Member member, Guild guild, String m String[] argumentsParsed = Arrays.copyOfRange(arguments, 1, arguments.length); // Perform the Command. - return command.onMonoPerform(new CommandEvent(commandAnnotation.name(), member, guild, message, textChannel, argumentsParsed, null)).block(); + return command.onMonoPerform(new CommandEvent(commandAnnotation.name(), member, guild, message, textChannel, argumentsParsed, null, true)).block(); }); } @@ -615,7 +615,7 @@ private Mono performSlashCommand(GuildMessageChannelUnion messageChanne if (!annotation.allowAppInstall() && guild.isDetached()) return Mono.just(false); - CommandEvent commandEvent = new CommandEvent(annotation.name(), slashCommandInteractionEvent.getMember(), guild, null, messageChannel, null, slashCommandInteractionEvent); + CommandEvent commandEvent = new CommandEvent(annotation.name(), slashCommandInteractionEvent.getMember(), guild, null, messageChannel, null, slashCommandInteractionEvent, true); if (guild.isDetached()) { return command.onMonoPerform(commandEvent);