From 40eb8170b746b00a762022ad2b9d31a8937cb728 Mon Sep 17 00:00:00 2001 From: Nxllpointer <54677650+Nxllpointer@users.noreply.github.com> Date: Mon, 17 Oct 2022 14:29:42 +0200 Subject: [PATCH 01/26] Fix JOOQ version mismatch (#640) After the bump to JOOQ gradle plugin 7.1.1 the JOOQ version in application/build/tmp/generateJooq/config.xml changed to 3.16.0. This created a version mismatch with database-settings.gradle that were followed by a few warnings. Intellij would recognize these warnings as errors which was very annoying. Co-authored-by: Nxllpointer --- buildSrc/src/main/groovy/database-settings.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/buildSrc/src/main/groovy/database-settings.gradle b/buildSrc/src/main/groovy/database-settings.gradle index 37927aea20..7c32bbfc6e 100644 --- a/buildSrc/src/main/groovy/database-settings.gradle +++ b/buildSrc/src/main/groovy/database-settings.gradle @@ -28,7 +28,7 @@ tasks.flywayMigrate { } jooq { - version = "3.15.2" + version = "3.16.0" configurations { main { From 4317f576eb0eef0c4bc45e9e601b9c8ff7c3f84f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 19 Oct 2022 08:46:39 +0200 Subject: [PATCH 02/26] Bump io.spring.dependency-management from 1.0.13.RELEASE to 1.1.0 (#642) Bumps [io.spring.dependency-management](https://github.com/spring-gradle-plugins/dependency-management-plugin) from 1.0.13.RELEASE to 1.1.0. - [Release notes](https://github.com/spring-gradle-plugins/dependency-management-plugin/releases) - [Commits](https://github.com/spring-gradle-plugins/dependency-management-plugin/compare/v1.0.13.RELEASE...v1.1.0) --- updated-dependencies: - dependency-name: io.spring.dependency-management dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- website/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/build.gradle b/website/build.gradle index c666d52164..b42146db15 100644 --- a/website/build.gradle +++ b/website/build.gradle @@ -1,6 +1,6 @@ plugins { id 'org.springframework.boot' version '2.7.3' - id 'io.spring.dependency-management' version '1.0.13.RELEASE' + id 'io.spring.dependency-management' version '1.1.0' id "com.google.cloud.tools.jib" version "3.3.0" id 'java' } From 131a06d56501e5cb11707331a111cd3bc45edd63 Mon Sep 17 00:00:00 2001 From: Tais993 <49957334+Tais993@users.noreply.github.com> Date: Wed, 19 Oct 2022 09:55:12 +0200 Subject: [PATCH 03/26] Implemented modal support (#626) Implemented modal support This change includes a rename of the onSelectionMenu method. It's now called onSelectMenuSelection to match onButtonClick. Modals will use the onModalSubmit method. --- .../tjbot/commands/BotCommand.java | 2 +- .../tjbot/commands/BotCommandAdapter.java | 13 ++- .../tjbot/commands/MessageContextCommand.java | 2 +- .../tjbot/commands/SlashCommand.java | 2 +- .../tjbot/commands/SlashCommandAdapter.java | 4 +- .../tjbot/commands/UserContextCommand.java | 2 +- .../tjbot/commands/UserInteractor.java | 24 ++++- .../commands/basic/RoleSelectCommand.java | 2 +- .../commands/moderation/scam/ScamBlocker.java | 8 +- .../tjbot/commands/system/BotCore.java | 90 ++++++++++++++----- 10 files changed, 115 insertions(+), 34 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/BotCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/BotCommand.java index 0bd53a32b7..769659d0ad 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/BotCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/BotCommand.java @@ -19,7 +19,7 @@ *

* After registration, the system will notify a command whenever one of its corresponding command * method, buttons ({@link #onButtonClick(ButtonInteractionEvent, List)}) or menus - * ({@link #onSelectionMenu(SelectMenuInteractionEvent, List)}) have been triggered. + * ({@link #onSelectMenuSelection(SelectMenuInteractionEvent, List)}) have been triggered. *

* Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}. */ diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/BotCommandAdapter.java b/application/src/main/java/org/togetherjava/tjbot/commands/BotCommandAdapter.java index c9c4a52dbb..f7e4d5a4d6 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/BotCommandAdapter.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/BotCommandAdapter.java @@ -1,5 +1,6 @@ package org.togetherjava.tjbot.commands; +import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent; @@ -20,8 +21,8 @@ * {@link Features}. *

* Further, {@link #onButtonClick(ButtonInteractionEvent, List)} and - * {@link #onSelectionMenu(SelectMenuInteractionEvent, List)} can be overridden if desired. The - * default implementation is empty, the adapter will not react to such events. + * {@link #onSelectMenuSelection(SelectMenuInteractionEvent, List)} can be overridden if desired. + * The default implementation is empty, the adapter will not react to such events. *

* The adapter manages some getters for you, you've to create the {@link CommandData} yourself. See * {@link #BotCommandAdapter(CommandData, CommandVisibility)}} for more info on that. Minimal @@ -100,7 +101,13 @@ public void onButtonClick(ButtonInteractionEvent event, List args) { @SuppressWarnings("NoopMethodInAbstractClass") @Override - public void onSelectionMenu(SelectMenuInteractionEvent event, List args) { + public void onSelectMenuSelection(SelectMenuInteractionEvent event, List args) { + // Adapter does not react by default, subclasses may change this behavior + } + + @SuppressWarnings("NoopMethodInAbstractClass") + @Override + public void onModalSubmitted(ModalInteractionEvent event, List args) { // Adapter does not react by default, subclasses may change this behavior } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/MessageContextCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/MessageContextCommand.java index 3983535f1d..0d0e767340 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/MessageContextCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/MessageContextCommand.java @@ -29,7 +29,7 @@ * After registration, the system will notify a command whenever one of its corresponding message * context-commands ({@link #onMessageContext(MessageContextInteractionEvent)}), buttons * ({@link #onButtonClick(ButtonInteractionEvent, List)}) or menus - * ({@link #onSelectionMenu(SelectMenuInteractionEvent, List)}) have been triggered. + * ({@link #onSelectMenuSelection(SelectMenuInteractionEvent, List)}) have been triggered. *

* Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}. */ diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommand.java index af7c17fa28..0e89ee50c1 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommand.java @@ -35,7 +35,7 @@ * After registration, the system will notify a command whenever one of its corresponding slash * commands ({@link #onSlashCommand(SlashCommandInteractionEvent)}), buttons * ({@link #onButtonClick(ButtonInteractionEvent, List)}) or menus - * ({@link #onSelectionMenu(SelectMenuInteractionEvent, List)}) have been triggered. + * ({@link #onSelectMenuSelection(SelectMenuInteractionEvent, List)}) have been triggered. *

* Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}. */ diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java index 9923a15ea4..48a4caf4c6 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java @@ -23,8 +23,8 @@ * adding it to {@link Features}. *

* Further, {@link #onButtonClick(ButtonInteractionEvent, List)} and - * {@link #onSelectionMenu(SelectMenuInteractionEvent, List)} can be overridden if desired. The - * default implementation is empty, the adapter will not react to such events. + * {@link #onSelectMenuSelection(SelectMenuInteractionEvent, List)} can be overridden if desired. + * The default implementation is empty, the adapter will not react to such events. *

* The adapter manages all command related data itself, which can be provided during construction * (see {@link #SlashCommandAdapter(String, String, CommandVisibility)}). In order to add options, diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/UserContextCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/UserContextCommand.java index 4d25446f15..36a7aeb5cc 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/UserContextCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/UserContextCommand.java @@ -30,7 +30,7 @@ * After registration, the system will notify a command whenever one of its corresponding user * context-commands ({@link #onUserContext(UserContextInteractionEvent)}), buttons * ({@link #onButtonClick(ButtonInteractionEvent, List)}) or menus - * ({@link #onSelectionMenu(SelectMenuInteractionEvent, List)}) have been triggered. + * ({@link #onSelectMenuSelection(SelectMenuInteractionEvent, List)}) have been triggered. *

* Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}. */ diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/UserInteractor.java b/application/src/main/java/org/togetherjava/tjbot/commands/UserInteractor.java index 714a944afd..7bae9e1036 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/UserInteractor.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/UserInteractor.java @@ -1,5 +1,6 @@ package org.togetherjava.tjbot.commands; +import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent; @@ -75,7 +76,26 @@ public interface UserInteractor extends Feature { * {@link SlashCommand#onSlashCommand(SlashCommandInteractionEvent)} for details on how * these are created */ - void onSelectionMenu(SelectMenuInteractionEvent event, List args); + void onSelectMenuSelection(SelectMenuInteractionEvent event, List args); + + + /** + * Triggered by the core system when a modal corresponding to this implementation (based on + * {@link #getName()}) has been clicked. + *

+ * This method may be called multithreaded. In particular, there are no guarantees that it will + * be executed on the same thread repeatedly or on the same thread that other event methods have + * been called on. + *

+ * Details are available in the given event and the event also enables implementations to + * respond to it. + * + * @param event the event that triggered this + * @param args the arguments transported with the modal, see + * {@link SlashCommand#onSlashCommand(SlashCommandInteractionEvent)} for details on how + * these are created + */ + void onModalSubmitted(ModalInteractionEvent event, List args); /** * Triggered by the core system during its setup phase. It will provide the command a component @@ -90,7 +110,7 @@ public interface UserInteractor extends Feature { * given to this method during system setup. The required {@link ComponentId} instance accepts * optional extra arguments, which, if provided, can be picked up during the corresponding event * (see {@link #onButtonClick(ButtonInteractionEvent, List)}, - * {@link #onSelectionMenu(SelectMenuInteractionEvent, List)}). + * {@link #onSelectMenuSelection(SelectMenuInteractionEvent, List)}). *

* Alternatively, if {@link BotCommandAdapter} has been extended, it also offers a handy * {@link BotCommandAdapter#generateComponentId(String...)} method to ease the flow. diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/basic/RoleSelectCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/basic/RoleSelectCommand.java index d8e6970132..a96ddef619 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/basic/RoleSelectCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/basic/RoleSelectCommand.java @@ -204,7 +204,7 @@ private static SelectOption mapToSelectOption(Role role) { } @Override - public void onSelectionMenu(SelectMenuInteractionEvent event, List args) { + public void onSelectMenuSelection(SelectMenuInteractionEvent event, List args) { Guild guild = event.getGuild(); List selectedRoles = event.getSelectedOptions() .stream() diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java index de54d7e19a..6cb668ab08 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java @@ -4,6 +4,7 @@ import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; +import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; @@ -97,7 +98,12 @@ public UserInteractionType getInteractionType() { } @Override - public void onSelectionMenu(SelectMenuInteractionEvent event, List args) { + public void onSelectMenuSelection(SelectMenuInteractionEvent event, List args) { + throw new UnsupportedOperationException("Not used"); + } + + @Override + public void onModalSubmitted(ModalInteractionEvent event, List args) { throw new UnsupportedOperationException("Not used"); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/system/BotCore.java b/application/src/main/java/org/togetherjava/tjbot/commands/system/BotCore.java index 14ece90c2f..d0e4ec3ad6 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/system/BotCore.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/system/BotCore.java @@ -2,6 +2,7 @@ import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.channel.Channel; +import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.MessageContextInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; @@ -11,6 +12,7 @@ import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageUpdateEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; +import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback; import net.dv8tion.jda.api.interactions.components.ComponentInteraction; import org.jetbrains.annotations.Unmodifiable; import org.slf4j.Logger; @@ -256,7 +258,29 @@ public void onSelectMenuInteraction(SelectMenuInteractionEvent event) { logger.debug("Received selection menu event '{}' (#{}) on guild '{}'", event.getComponentId(), event.getId(), event.getGuild()); COMMAND_SERVICE - .execute(() -> forwardComponentCommand(event, UserInteractor::onSelectionMenu)); + .execute(() -> forwardComponentCommand(event, UserInteractor::onSelectMenuSelection)); + } + + @Override + public void onModalInteraction(final ModalInteractionEvent event) { + logger.debug("Received modal event '{}' (#{}) on guild '{}'", event.getModalId(), + event.getId(), event.getGuild()); + COMMAND_SERVICE.execute(() -> { + Optional componentIdOptional = + handleParseComponentId(event, event.getModalId()); + + if (componentIdOptional.isEmpty()) { + return; + } + + ComponentId componentId = componentIdOptional.orElseThrow(); + + UserInteractor interactor = + requireUserInteractor(componentId.userInteractorName(), UserInteractor.class); + logger.trace("Routing a modal event with id '{}' back to user interactor '{}'", + event.getModalId(), interactor.getName()); + interactor.onModalSubmitted(event, componentId.elements()); + }); } @Override @@ -281,6 +305,42 @@ public void onUserContextInteraction(final UserContextInteractionEvent event) { UserContextCommand.class).onUserContext(event)); } + /** + * Returns the {@link ComponentId} instace of the given componentId. If the component has + * expired, the user gets a message stating that. + * + * @param event the {@link IReplyCallback event} to reply to + * @param componentId the component's ID + * @return the relating {@link ComponentId} + */ + public Optional handleParseComponentId(IReplyCallback event, String componentId) { + Optional componentIdOpt; + try { + componentIdOpt = componentIdParser.parse(componentId); + } catch (InvalidComponentIdFormatException | IllegalArgumentException e) { + logger.error( + """ + Unable to route event (#{}) back to its corresponding {}}. + The component ID was in an unexpected format. All button and menu events have to use a component ID created in a specific format + (refer to the documentation of {}}). Component ID was: {} + {} + """, + event.getId(), UserInteractor.class.getSimpleName(), + UserInteractor.class.getSimpleName(), componentId, e); + // Unable to forward, simply fade out the event + return Optional.empty(); + } + + if (componentIdOpt.isEmpty()) { + logger.warn("The event (#{}) has an expired component ID, which was: {}.", + event.getId(), componentId); + event.reply("Sorry, but this event has expired. You can not use it anymore.") + .setEphemeral(true) + .queue(); + } + + return componentIdOpt; + } /** * Forwards the given component event to the associated user interactor. @@ -300,27 +360,15 @@ public void onUserContextInteraction(final UserContextInteractionEvent event) { */ private void forwardComponentCommand(T event, TriConsumer> interactorArgumentConsumer) { - Optional componentIdOpt; - try { - componentIdOpt = componentIdParser.parse(event.getComponentId()); - } catch (InvalidComponentIdFormatException e) { - logger - .error("Unable to route event (#{}) back to its corresponding user interactor. The component ID was in an unexpected format." - + " All button and menu events have to use a component ID created in a specific format" - + " (refer to the documentation of UserInteractor). Component ID was: {}", - event.getId(), event.getComponentId(), e); - // Unable to forward, simply fade out the event - return; - } - if (componentIdOpt.isEmpty()) { - logger.warn("The event (#{}) has an expired component ID, which was: {}.", - event.getId(), event.getComponentId()); - event.reply("Sorry, but this event has expired. You can not use it anymore.") - .setEphemeral(true) - .queue(); + + Optional componentIdOptional = + handleParseComponentId(event, event.getComponentId()); + + if (componentIdOptional.isEmpty()) { return; } - ComponentId componentId = componentIdOpt.orElseThrow(); + + ComponentId componentId = componentIdOptional.orElseThrow(); UserInteractor interactor = requireUserInteractor(componentId.userInteractorName(), UserInteractor.class); @@ -334,8 +382,8 @@ private void forwardComponentCommand(T event, * * @param prefixedName the prefixed name of the interactor * @param typeToken a token of the type to expect - * @return the user interactor with the given name * @param the type to expect the user interactor to be of + * @return the user interactor with the given name */ private T requireUserInteractor(String prefixedName, Class typeToken) { From 4a3947152737309cfac6d90524d558bc5a966c4a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 20 Oct 2022 09:24:57 +0200 Subject: [PATCH 04/26] Bump gradle-plugin-publishing from 9.4.0 to 9.5.0 (#644) Bumps gradle-plugin-publishing from 9.4.0 to 9.5.0. --- updated-dependencies: - dependency-name: gradle.plugin.org.flywaydb:gradle-plugin-publishing dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- buildSrc/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle index dbfc204b7a..12351c1ccc 100644 --- a/buildSrc/build.gradle +++ b/buildSrc/build.gradle @@ -7,6 +7,6 @@ repositories { } dependencies { - implementation "gradle.plugin.org.flywaydb:gradle-plugin-publishing:9.4.0" + implementation "gradle.plugin.org.flywaydb:gradle-plugin-publishing:9.5.0" implementation 'nu.studer:gradle-jooq-plugin:7.1.1' } From 0ed33170c0b7c3b5f8bff33dae2e6026ed602e3b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 20 Oct 2022 09:25:16 +0200 Subject: [PATCH 05/26] Bump flyway-core from 9.4.0 to 9.5.0 (#643) Bumps [flyway-core](https://github.com/flyway/flyway) from 9.4.0 to 9.5.0. - [Release notes](https://github.com/flyway/flyway/releases) - [Commits](https://github.com/flyway/flyway/compare/flyway-9.4.0...flyway-9.5.0) --- updated-dependencies: - dependency-name: org.flywaydb:flyway-core dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- database/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/database/build.gradle b/database/build.gradle index a1c6261320..353569b5ee 100644 --- a/database/build.gradle +++ b/database/build.gradle @@ -7,7 +7,7 @@ var sqliteVersion = "3.39.2.0" dependencies { implementation 'com.google.code.findbugs:jsr305:3.0.2' implementation "org.xerial:sqlite-jdbc:${sqliteVersion}" - implementation 'org.flywaydb:flyway-core:9.4.0' + implementation 'org.flywaydb:flyway-core:9.5.0' implementation 'org.jooq:jooq:3.17.2' implementation project(':utils') From 16fd8426c58c99a157212168f05f79a6fa5c3205 Mon Sep 17 00:00:00 2001 From: IslamSakrak <58050604+DevSerendipity@users.noreply.github.com> Date: Thu, 20 Oct 2022 10:50:17 +0200 Subject: [PATCH 06/26] Adding the /modmail command (#493) * Adding the /modmail command Commands which redirects command called from Guild or Dm to a dedicated channel in Config#getModAuditLogChannelPattern() * Removing comments , plus signs and commented out code * Adding modmail channel to config and reflecting those changes in command * Removing comments, unnecessary lines and making methods * Improving the naming, removing require not null and additional ... Improvements requested from the reviews * Adding the time remaining since command called and bunch ... of helper methods * Removing print statement also adding an else if the value is not present * Changing from Math.toExactInt to a int cast instead for sonar * Different math operant sonar , attempt #2 * Removing the guild id and adding guildNamePredicate instead * Making the class final * Removing @NotNull * Removing BlackListedListener * Adding a modmail command message to all channels which handles DM's * Adding the changes mentioned in the PR * Adding the choice for the user guild * Adding param into the comment * Adding the improvements from the code review * Removing unnecessary imports * Resolving all conflicts and making improvements * Making more changes * Removing unused imports * Adding a package.info * Improving the message package info * Adding to the config template, adding the little UX improvements * Merging two queues into one * Removing description * Improving the things mentioned * Making an ModerationUtil for Dm advices after ModerationAction * Removing unnecessary imports * Improving the logger warning * Removing unnecessary import, ran spotless * Manually fixing spotless errors * Quick before zabu changes his mind * Push quick * Fixing the Global Command Problem * please * UNUSED METHOD * little by little I am over * Closer and closer * Improved the Return type * Finish it * Fixed a few bugs here and there * Shortened name in javadoc Co-authored-by: Tais993 <49957334+Tais993@users.noreply.github.com> * Added missing command mentions Co-authored-by: Zabuzard Co-authored-by: Tais993 <49957334+Tais993@users.noreply.github.com> --- application/config.json.template | 1 + .../togetherjava/tjbot/commands/Features.java | 2 + .../tjbot/commands/help/HelpSystemHelper.java | 4 +- .../commands/help/ImplicitAskListener.java | 6 +- .../commands/moderation/ModerationUtils.java | 78 ++++++++ .../commands/moderation/MuteCommand.java | 14 +- .../moderation/QuarantineCommand.java | 13 +- .../commands/moderation/UnmuteCommand.java | 9 +- .../moderation/UnquarantineCommand.java | 10 +- .../commands/moderation/WarnCommand.java | 9 +- .../BlacklistedAttachmentListener.java | 34 ++-- .../moderation/attachment/package-info.java | 4 +- .../moderation/modmail/ModMailCommand.java | 183 ++++++++++++++++++ .../moderation/modmail/package-info.java | 11 ++ .../commands/moderation/scam/ScamBlocker.java | 23 ++- .../tjbot/commands/utils/MessageUtils.java | 52 ++++- .../org/togetherjava/tjbot/config/Config.java | 14 ++ 17 files changed, 392 insertions(+), 75 deletions(-) create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java diff --git a/application/config.json.template b/application/config.json.template index d7a3563a38..6a661bdb02 100644 --- a/application/config.json.template +++ b/application/config.json.template @@ -5,6 +5,7 @@ "projectWebsite": "https://github.com/Together-Java/TJ-Bot", "discordGuildInvite": "https://discord.com/invite/XXFUXzK", "modAuditLogChannelPattern": "mod_audit_log", + "modMailChannelPattern": "modmail", "mutedRolePattern": "Muted", "heavyModerationRolePattern": "Moderator", "softModerationRolePattern": "Moderator|Staff Assistant", diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java index 581296a77d..28c4f1284f 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java @@ -13,6 +13,7 @@ import org.togetherjava.tjbot.commands.mediaonly.MediaOnlyChannelListener; import org.togetherjava.tjbot.commands.moderation.*; import org.togetherjava.tjbot.commands.moderation.attachment.BlacklistedAttachmentListener; +import org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand; import org.togetherjava.tjbot.commands.moderation.scam.ScamBlocker; import org.togetherjava.tjbot.commands.moderation.scam.ScamHistoryPurgeRoutine; import org.togetherjava.tjbot.commands.moderation.scam.ScamHistoryStore; @@ -126,6 +127,7 @@ public static Collection createFeatures(JDA jda, Database database, Con features.add(new WhoIsCommand()); features.add(new WolframAlphaCommand(config)); features.add(new AskCommand(config, helpSystemHelper)); + features.add(new ModMailCommand(jda, config)); features.add(new HelpThreadCommand(config, helpSystemHelper)); // Mixtures diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java b/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java index 4dce9512e0..9f622837b1 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java @@ -96,7 +96,7 @@ public HelpSystemHelper(JDA jda, Config config, Database database) { RestAction sendExplanationMessage(GuildMessageChannel threadChannel) { return MessageUtils - .mentionSlashCommand(threadChannel.getGuild(), HelpThreadCommand.COMMAND_NAME, + .mentionGuildSlashCommand(threadChannel.getGuild(), HelpThreadCommand.COMMAND_NAME, HelpThreadCommand.Subcommand.CLOSE.getCommandName()) .flatMap(closeCommandMention -> sendExplanationMessage(threadChannel, closeCommandMention)); @@ -313,7 +313,7 @@ private void executeUncategorizedAdviceCheck(long threadChannelId, long authorId // Still no category, send advice return MessageUtils - .mentionSlashCommand(threadChannel.getGuild(), HelpThreadCommand.COMMAND_NAME, + .mentionGuildSlashCommand(threadChannel.getGuild(), HelpThreadCommand.COMMAND_NAME, HelpThreadCommand.CHANGE_SUBCOMMAND_GROUP, HelpThreadCommand.Subcommand.CHANGE_CATEGORY.getCommandName()) .flatMap(command -> { diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/help/ImplicitAskListener.java b/application/src/main/java/org/togetherjava/tjbot/commands/help/ImplicitAskListener.java index 3b550cb0b0..22ad2eca3f 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/help/ImplicitAskListener.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/help/ImplicitAskListener.java @@ -118,7 +118,7 @@ private boolean handleIsNotOnCooldown(Message message) { String threadDescription = lastHelpThread == null ? "your previously created help thread" : lastHelpThread.getAsMention(); - MessageUtils.mentionSlashCommand(message.getGuild(), AskCommand.COMMAND_NAME) + MessageUtils.mentionGuildSlashCommand(message.getGuild(), AskCommand.COMMAND_NAME) .flatMap(command -> message.getChannel() .sendMessage(""" %s Please use %s to follow up on your question, \ @@ -185,7 +185,7 @@ private static RestAction sendInitialMessage(ThreadChannel threadChanne .build(); return MessageUtils - .mentionSlashCommand(originalMessage.getGuild(), HelpThreadCommand.COMMAND_NAME, + .mentionGuildSlashCommand(originalMessage.getGuild(), HelpThreadCommand.COMMAND_NAME, HelpThreadCommand.CHANGE_SUBCOMMAND_GROUP, HelpThreadCommand.Subcommand.CHANGE_CATEGORY.getCommandName()) .flatMap(command -> { @@ -204,7 +204,7 @@ private static RestAction sendInitialMessage(ThreadChannel threadChanne } private static RestAction notifyUser(IMentionable threadChannel, Message message) { - return MessageUtils.mentionSlashCommand(message.getGuild(), AskCommand.COMMAND_NAME) + return MessageUtils.mentionGuildSlashCommand(message.getGuild(), AskCommand.COMMAND_NAME) .flatMap(command -> message.getChannel() .sendMessage( """ diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java index 58a2e232ce..b4877fc0e5 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java @@ -3,11 +3,15 @@ import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.*; +import net.dv8tion.jda.api.entities.channel.concrete.PrivateChannel; import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback; +import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.requests.restaction.AuditableRestAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand; +import org.togetherjava.tjbot.commands.utils.MessageUtils; import org.togetherjava.tjbot.config.Config; import javax.annotation.Nullable; @@ -16,8 +20,11 @@ import java.time.Instant; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalUnit; +import java.util.EnumSet; import java.util.Optional; +import java.util.Set; import java.util.function.Predicate; +import java.util.function.UnaryOperator; import java.util.regex.Pattern; /** @@ -45,6 +52,25 @@ private ModerationUtils() { */ static final Color AMBIENT_COLOR = Color.decode("#895FE8"); + /** + * Actions with timely constraint, like being muted for 1 hour. + */ + private static final Set TEMPORARY_ACTIONS = + EnumSet.of(ModerationAction.MUTE); + /** + * Actions with revoking previously made actions on the user, like unmuting the user after it + * has been muted. + */ + private static final Set REVOKE_ACTIONS = + EnumSet.of(ModerationAction.UNMUTE, ModerationAction.UNQUARANTINE); + /** + * Soft violations were the user still remains member of the guild, such as a warning + */ + private static final Set SOFT_ACTIONS = + EnumSet.of(ModerationAction.WARN, ModerationAction.QUARANTINE); + + + /** * Checks whether the given reason is valid. If not, it will handle the situation and respond to * the user. @@ -372,4 +398,56 @@ static Optional computeTemporaryData(String durationText) { */ record TemporaryData(Instant expiresAt, String duration) { } + + /** + * Gives out advice depending on the {@link ModerationAction} and the parameters passed into it. + * + * @param action the action that is being performed, such as banning a user. + * @param temporaryData if the action is a temporary action, such as a 1 hour mute. + * @param additionalDescription any extra description that should be part of the message, if + * desired + * @param guild for which the action was triggered. + * @param reason for the action. + * @param textChannel for which messages are being sent to. + * + * @return the appropriate advice. + */ + public static RestAction sendDmAdvice(ModerationAction action, + @Nullable TemporaryData temporaryData, @Nullable String additionalDescription, + Guild guild, String reason, PrivateChannel textChannel) { + String additionalDescriptionInfix = + additionalDescription == null ? "" : "\n" + additionalDescription; + + if (REVOKE_ACTIONS.contains(action)) { + return textChannel.sendMessage(""" + Hey there, you have been %s in the server %s.%s + The reason for being %s is: %s + """.formatted(action.getVerb(), guild.getName(), additionalDescriptionInfix, + action.getVerb(), reason)); + } + String durationMessage; + if (SOFT_ACTIONS.contains(action)) { + durationMessage = ""; + } else if (TEMPORARY_ACTIONS.contains(action)) { + durationMessage = + temporaryData == null ? " permanently" : " for " + temporaryData.duration(); + } else { + throw new IllegalArgumentException( + "Action '%s' is not supported by this method".formatted(action)); + } + + UnaryOperator createDmMessage = + commandMention -> """ + Hey there, sorry to tell you but unfortunately you have been %s%s in the server %s.%s + To get in touch with a moderator, you can simply use the %s command here in this chat. \ + Your message will then be forwarded and a moderator will get back to you soon 😊 + The reason for being %s is: %s + """ + .formatted(action.getVerb(), durationMessage, guild.getName(), + additionalDescriptionInfix, commandMention, action.getVerb(), reason); + + return MessageUtils.mentionGlobalSlashCommand(guild.getJDA(), ModMailCommand.COMMAND_NAME) + .map(createDmMessage) + .flatMap(textChannel::sendMessage); + } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java index c925496ad1..94a4efed9a 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java @@ -73,19 +73,11 @@ private static void handleAlreadyMutedTarget(IReplyCallback event) { private static RestAction sendDm(ISnowflake target, @Nullable ModerationUtils.TemporaryData temporaryData, String reason, Guild guild, GenericEvent event) { - String durationMessage = - temporaryData == null ? "permanently" : "for " + temporaryData.duration(); - String dmMessage = - """ - Hey there, sorry to tell you but unfortunately you have been muted %s in the server %s. - This means you can no longer send any messages in the server until you have been unmuted again. - If you think this was a mistake, please contact a moderator or admin of the server. - The reason for the mute is: %s - """ - .formatted(durationMessage, guild.getName(), reason); return event.getJDA() .openPrivateChannelById(target.getId()) - .flatMap(channel -> channel.sendMessage(dmMessage)) + .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.MUTE, temporaryData, + "This means you can no longer send any messages in the server until you have been unmuted again.", + guild, reason, channel)) .mapToResult() .map(Result::isSuccess); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java index 7dd2efdb5d..dffb29292e 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java @@ -63,18 +63,11 @@ private static void handleAlreadyQuarantinedTarget(IReplyCallback event) { private static RestAction sendDm(ISnowflake target, String reason, Guild guild, GenericEvent event) { - String dmMessage = - """ - Hey there, sorry to tell you but unfortunately you have been put under quarantine in the server %s. - This means you can no longer interact with anyone in the server until you have been unquarantined again. - If you think this was a mistake, or the reason no longer applies, please contact a moderator or admin of the server. - The reason for the quarantine is: %s - """ - .formatted(guild.getName(), reason); - return event.getJDA() .openPrivateChannelById(target.getIdLong()) - .flatMap(channel -> channel.sendMessage(dmMessage)) + .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.QUARANTINE, null, + "This means you can no longer interact with anyone in the server until you have been unquarantined again.", + guild, reason, channel)) .mapToResult() .map(Result::isSuccess); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java index 0e388a2911..ce050fcd07 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java @@ -60,14 +60,11 @@ private static void handleNotMutedTarget(IReplyCallback event) { private static RestAction sendDm(ISnowflake target, String reason, Guild guild, GenericEvent event) { - String dmMessage = """ - Hey there, you have been unmuted in the server %s. - This means you can now send messages in the server again. - The reason for the unmute is: %s - """.formatted(guild.getName(), reason); return event.getJDA() .openPrivateChannelById(target.getId()) - .flatMap(channel -> channel.sendMessage(dmMessage)) + .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.UNMUTE, null, + "This means you can now send messages in the server again 👌", guild, reason, + channel)) .mapToResult() .map(Result::isSuccess); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java index 2839d77b2f..771d9e787f 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java @@ -64,15 +64,11 @@ private static void handleNotQuarantinedTarget(IReplyCallback event) { private static RestAction sendDm(ISnowflake target, String reason, Guild guild, GenericEvent event) { - String dmMessage = """ - Hey there, you have been put out of quarantine in the server %s. - This means you can now interact with others in the server again. - The reason for the unquarantine is: %s - """.formatted(guild.getName(), reason); - return event.getJDA() .openPrivateChannelById(target.getIdLong()) - .flatMap(channel -> channel.sendMessage(dmMessage)) + .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.UNQUARANTINE, null, + "This means you can now interact with others in the server again 👌", guild, + reason, channel)) .mapToResult() .map(Result::isSuccess); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 0e52fea049..26b767b652 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -60,13 +60,8 @@ private static RestAction dmUser(ISnowflake target, String reason, Guil SlashCommandInteractionEvent event) { return event.getJDA() .openPrivateChannelById(target.getId()) - .flatMap(channel -> channel.sendMessage( - """ - Hey there, sorry to tell you but unfortunately you have been warned in the server %s. - If you think this was a mistake, please contact a moderator or admin of the server. - The reason for the warning is: %s - """ - .formatted(guild.getName(), reason))) + .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.WARN, null, null, + guild, reason, channel)) .mapToResult() .map(Result::isSuccess); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java index cd42cc2d82..69a8e6024c 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java @@ -3,18 +3,22 @@ import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageEmbed; +import net.dv8tion.jda.api.entities.channel.concrete.PrivateChannel; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import net.dv8tion.jda.api.utils.messages.MessageCreateData; import org.togetherjava.tjbot.commands.MessageReceiverAdapter; +import org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand; +import org.togetherjava.tjbot.commands.utils.MessageUtils; import org.togetherjava.tjbot.config.Config; import org.togetherjava.tjbot.moderation.ModAuditLogWriter; import java.awt.Color; import java.util.List; import java.util.Locale; +import java.util.function.UnaryOperator; import java.util.regex.Pattern; /** @@ -53,28 +57,36 @@ private void handleBadMessage(Message message) { private RestAction dmUser(Message message) { return message.getAuthor() .openPrivateChannel() - .flatMap(privateChannel -> privateChannel.sendMessage(createDmMessage(message))); + .flatMap(privateChannel -> sendDmMessage(message, privateChannel)); } - private MessageCreateData createDmMessage(Message originalMessage) { + private RestAction sendDmMessage(Message originalMessage, PrivateChannel channel) { String contentRaw = originalMessage.getContentRaw(); String blacklistedAttachments = String.join(", ", getBlacklistedAttachmentsFromMessage(originalMessage)); - String dmMessageContent = - """ + UnaryOperator createDmText = + commandMention -> """ Hey there, you posted a message containing a blacklisted file attachment: %s. We had to delete your message for security reasons. + To get in touch with a moderator, you can simply use the %s command here in this chat. \ + Your message will then be forwarded and a moderator will get back to you soon 👍 Feel free to repost your message without, or with a different file instead. Sorry for any inconvenience caused by this 🙇️ """ - .formatted(blacklistedAttachments); - - // No embed needed if there was no message from the user - if (contentRaw.isEmpty()) { - return new MessageCreateBuilder().setContent(dmMessageContent).build(); - } - return createBaseResponse(contentRaw, dmMessageContent); + .formatted(blacklistedAttachments, commandMention); + + return MessageUtils + .mentionGlobalSlashCommand(originalMessage.getJDA(), ModMailCommand.COMMAND_NAME) + .map(createDmText) + .map(dmMessageContent -> { + // No embed needed if there was no message from the user + if (contentRaw.isEmpty()) { + return new MessageCreateBuilder().setContent(dmMessageContent).build(); + } + return createBaseResponse(contentRaw, dmMessageContent); + }) + .flatMap(channel::sendMessage); } private MessageCreateData createBaseResponse(String originalMessageContent, diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java index cb62b969b0..9fb7d29f53 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java @@ -1,5 +1,7 @@ /** - * This packages offers all the functionality for checking attachment safety. + * This packages offers all the functionality for checking attachment safety see + * {@link org.togetherjava.tjbot.commands.moderation.attachment.BlacklistedAttachmentListener + * BlacklistedAttachmentListener} as main entry point. */ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java new file mode 100644 index 0000000000..c50f8af208 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -0,0 +1,183 @@ +package org.togetherjava.tjbot.commands.moderation.modmail; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.entities.MessageEmbed; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.interactions.InteractionHook; +import net.dv8tion.jda.api.interactions.commands.Command; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.OptionData; +import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.togetherjava.tjbot.commands.CommandVisibility; +import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.utils.DiscordClientAction; +import org.togetherjava.tjbot.config.Config; + +import java.awt.*; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.function.Predicate; +import java.util.regex.Pattern; + + +/** + * Implements the /modmail command, which allows users to contact a moderator within the server + * which forwards messages to moderators in a dedicated channel given by + * {@link Config#getModAuditLogChannelPattern()}. + */ + +public final class ModMailCommand extends SlashCommandAdapter { + + private static final Logger logger = LoggerFactory.getLogger(ModMailCommand.class); + public static final String COMMAND_NAME = "modmail"; + private static final String OPTION_MESSAGE = "message"; + private static final String OPTION_STAY_ANONYMOUS = "stay-anonymous"; + private static final String OPTION_GUILD = "server"; + private static final int COOLDOWN_DURATION_VALUE = 30; + private static final ChronoUnit COOLDOWN_DURATION_UNIT = ChronoUnit.MINUTES; + private static final Color AMBIENT_COLOR = Color.BLACK; + private final Cache authorToLastModMailInvocation = createCooldownCache(); + private final Predicate modMailChannelNamePredicate; + private final String configModMailChannelPattern; + + + /** + * Creates a new instance. + * + * @param jda the JDA instance to retrieve guildCache + * @param config to get the channel to forward modmails to + */ + public ModMailCommand(JDA jda, Config config) { + super(COMMAND_NAME, "Contact the moderators of the selected guild", + CommandVisibility.GLOBAL); + + OptionData messageOption = new OptionData(OptionType.STRING, OPTION_MESSAGE, + "What do you want to tell them?", true); + OptionData guildOption = new OptionData(OptionType.STRING, OPTION_GUILD, + "The server to contact mods from", true); + OptionData anonymousOption = new OptionData(OptionType.BOOLEAN, OPTION_STAY_ANONYMOUS, + "If set, your name is hidden - note that mods then can not get back to you", true); + + List choices = jda.getGuildCache() + .stream() + .map(guild -> new Command.Choice(guild.getName(), guild.getIdLong())) + .toList(); + + guildOption.addChoices(choices); + + getData().addOptions(messageOption, guildOption, anonymousOption); + + modMailChannelNamePredicate = + Pattern.compile(config.getModMailChannelPattern()).asMatchPredicate(); + + configModMailChannelPattern = config.getModMailChannelPattern(); + } + + private Cache createCooldownCache() { + return Caffeine.newBuilder() + .maximumSize(1_000) + .expireAfterAccess(COOLDOWN_DURATION_VALUE, TimeUnit.of(COOLDOWN_DURATION_UNIT)) + .build(); + } + + @Override + public void onSlashCommand(SlashCommandInteractionEvent event) { + long userId = event.getUser().getIdLong(); + + if (handleIsOnCooldown(userId, event)) { + return; + } + authorToLastModMailInvocation.put(userId, Instant.now()); + event.deferReply().setEphemeral(true).queue(); + + long userGuildId = event.getOption(OPTION_GUILD).getAsLong(); + Optional modMailAuditLog = getModMailChannel(event.getJDA(), userGuildId); + if (modMailAuditLog.isEmpty()) { + logger.warn( + "Cannot find the designated modmail channel in server by id {} with the pattern {}", + userGuildId, configModMailChannelPattern); + return; + } + + MessageCreateAction message = + createModMessage(event, userId, modMailAuditLog.orElseThrow()); + + sendMessage(event, message); + + } + + private boolean handleIsOnCooldown(long userId, SlashCommandInteractionEvent event) { + if (!isChannelOnCooldown(userId)) { + return false; + } + event.reply("Can only be used once per %s minutes.".formatted(COOLDOWN_DURATION_VALUE)) + .setEphemeral(true) + .queue(); + return true; + } + + private Optional getModMailChannel(JDA jda, long guildId) { + return jda.getGuildById(guildId) + .getTextChannelCache() + .stream() + .filter(channel -> modMailChannelNamePredicate.test(channel.getName())) + .findAny(); + } + + private MessageCreateAction createModMessage(SlashCommandInteractionEvent event, long userId, + TextChannel modMailAuditLog) { + String userMessage = event.getOption(OPTION_MESSAGE).getAsString(); + boolean wantsToStayAnonymous = event.getOption(OPTION_STAY_ANONYMOUS).getAsBoolean(); + + User user = wantsToStayAnonymous ? null : event.getUser(); + MessageCreateAction message = + modMailAuditLog.sendMessageEmbeds(createModMailMessage(user, userMessage)); + if (!wantsToStayAnonymous) { + message.addActionRow(DiscordClientAction.General.USER.asLinkButton("Author Profile", + String.valueOf(userId))); + } + return message; + } + + private void sendMessage(SlashCommandInteractionEvent event, MessageCreateAction message) { + InteractionHook hook = event.getHook(); + message.mapToResult().map(result -> { + if (result.isSuccess()) { + return "Your message has been forwarded, thanks."; + } + logger.warn("There was an issue with forwarding users message."); + return "There was an issue forwarding your message, sorry. We are investigating."; + }).flatMap(hook::editOriginal).queue(); + } + + private MessageEmbed createModMailMessage(@Nullable User author, String userMessage) { + String authorTag = author == null ? "Anonymous" : author.getAsTag(); + String authorAvatar = author == null ? null : author.getAvatarUrl(); + return new EmbedBuilder().setTitle("Modmail") + .setAuthor(authorTag, null, authorAvatar) + .setDescription(userMessage) + .setColor(AMBIENT_COLOR) + .build(); + } + + private boolean isChannelOnCooldown(long userId) { + return Optional.ofNullable(authorToLastModMailInvocation.getIfPresent(userId)) + .map(sinceCommandInvoked -> sinceCommandInvoked.plus(COOLDOWN_DURATION_VALUE, + COOLDOWN_DURATION_UNIT)) + .filter(Instant.now()::isBefore) + .isPresent(); + } + +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java new file mode 100644 index 0000000000..d0a2de9825 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java @@ -0,0 +1,11 @@ +/** + * This packages offers all the functionality for messaging moderators trough mod mail see + * {@link org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand} as main entry point. + */ +@MethodsReturnNonnullByDefault +@ParametersAreNonnullByDefault +package org.togetherjava.tjbot.commands.moderation.modmail; + +import org.togetherjava.tjbot.annotations.MethodsReturnNonnullByDefault; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java index 6cb668ab08..d38584ddf0 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java @@ -3,6 +3,7 @@ import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.*; +import net.dv8tion.jda.api.entities.channel.concrete.PrivateChannel; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; @@ -12,6 +13,7 @@ import net.dv8tion.jda.api.interactions.components.buttons.Button; import net.dv8tion.jda.api.interactions.components.buttons.ButtonStyle; import net.dv8tion.jda.api.requests.ErrorResponse; +import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import net.dv8tion.jda.api.utils.messages.MessageCreateData; import org.slf4j.Logger; @@ -25,6 +27,7 @@ import org.togetherjava.tjbot.commands.moderation.ModerationAction; import org.togetherjava.tjbot.commands.moderation.ModerationActionsStore; import org.togetherjava.tjbot.commands.moderation.ModerationUtils; +import org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand; import org.togetherjava.tjbot.commands.utils.MessageUtils; import org.togetherjava.tjbot.config.Config; import org.togetherjava.tjbot.config.ScamBlockerConfig; @@ -34,6 +37,7 @@ import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; +import java.util.function.UnaryOperator; import java.util.regex.Pattern; /** @@ -249,19 +253,24 @@ private void dmUser(MessageReceivedEvent event) { } private void dmUser(Guild guild, long userId, JDA jda) { - String dmMessage = - """ + jda.openPrivateChannelById(userId).flatMap(channel -> dmUser(guild, channel)).queue(); + } + + private RestAction dmUser(Guild guild, PrivateChannel channel) { + UnaryOperator createDmMessage = + commandMention -> """ Hey there, we detected that you did send scam in the server %s and therefore put you under quarantine. This means you can no longer interact with anyone in the server until you have been unquarantined again. If you think this was a mistake (for example, your account was hacked, but you got back control over it), - please contact a moderator or admin of the server. + you can get in touch with a moderator by using the %s command. \ + Your message will then be forwarded and a moderator will get back to you soon 👍 """ - .formatted(guild.getName()); + .formatted(guild.getName(), commandMention); - jda.openPrivateChannelById(userId) - .flatMap(channel -> channel.sendMessage(dmMessage)) - .queue(); + return MessageUtils.mentionGlobalSlashCommand(guild.getJDA(), ModMailCommand.COMMAND_NAME) + .map(createDmMessage) + .flatMap(channel::sendMessage); } private Optional getReportChannel(Guild guild) { diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java b/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java index 4768006d75..d92e7d4e00 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java @@ -1,5 +1,6 @@ package org.togetherjava.tjbot.commands.utils; +import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.interactions.commands.Command; @@ -9,6 +10,7 @@ import net.dv8tion.jda.api.utils.MarkdownSanitizer; import java.util.List; +import java.util.function.Supplier; /** * Utility methods for {@link Message}. @@ -62,8 +64,8 @@ public static String escapeMarkdown(String text) { } /** - * Converts a slash command text to a mentioned slash command, which you can directly click on - * in Discord. + * Converts a guild slash command text to a mentioned slash command, which you can directly + * click on in Discord. * * @param guild the {@link Guild} that contains the command * @param commandName the command's name @@ -71,20 +73,50 @@ public static String escapeMarkdown(String text) { * @return Formatted string for the mentioned slash command * @throws IllegalArgumentException when the command isn't found in the guild */ - public static RestAction mentionSlashCommand(Guild guild, String commandName, + public static RestAction mentionGuildSlashCommand(Guild guild, String commandName, String... subCommands) { - return guild.retrieveCommands().map(guildCommands -> { - Command guildCommand = guildCommands.stream() - .filter(c -> c.getName().equalsIgnoreCase(commandName)) + RestAction> availableCommands = guild.retrieveCommands(); + Supplier notFoundMessage = () -> "Command '%s' does not exist in guild %s" + .formatted(commandName, guild.getId()); + + return mentionSlashCommand(availableCommands, notFoundMessage, commandName, subCommands); + } + + /** + * Converts a global slash command text to a mentioned slash command, which you can directly + * click on in Discord. + * + * @param jda to retrieve global commands from + * @param commandName the command's name + * @param subCommands optional subcommand group & subcommand, depending on the base command used + * @return Formatted string for the mentioned slash command + * @throws IllegalArgumentException when the global command was not found + */ + public static RestAction mentionGlobalSlashCommand(JDA jda, String commandName, + String... subCommands) { + RestAction> availableCommands = jda.retrieveCommands(); + Supplier notFoundMessage = + () -> "The global command '%s' does not exist".formatted(commandName); + + return mentionSlashCommand(availableCommands, notFoundMessage, commandName, subCommands); + } + + private static RestAction mentionSlashCommand( + RestAction> availableCommands, Supplier notFoundMessage, + String commandName, String... subCommands) { + return availableCommands.map(commands -> { + Command command = commands.stream() + .filter(commandCandidate -> commandCandidate.getName() + .equalsIgnoreCase(commandName)) .findAny() - .orElseThrow( - () -> new IllegalArgumentException("Command '%s' does not exist in guild %s" - .formatted(commandName, guild.getId()))); + .orElseThrow(() -> new IllegalArgumentException(notFoundMessage.get())); + String commandPath = commandName; if (subCommands.length > 0) { commandPath += " " + String.join(" ", subCommands); } - return String.format("", String.join(" ", commandPath), guildCommand.getId()); + + return String.format("", String.join(" ", commandPath), command.getId()); }); } diff --git a/application/src/main/java/org/togetherjava/tjbot/config/Config.java b/application/src/main/java/org/togetherjava/tjbot/config/Config.java index d9b9d8a88f..7c078a97f7 100644 --- a/application/src/main/java/org/togetherjava/tjbot/config/Config.java +++ b/application/src/main/java/org/togetherjava/tjbot/config/Config.java @@ -21,6 +21,7 @@ public final class Config { private final String projectWebsite; private final String discordGuildInvite; private final String modAuditLogChannelPattern; + private final String modMailChannelPattern; private final String mutedRolePattern; private final String heavyModerationRolePattern; private final String softModerationRolePattern; @@ -44,6 +45,8 @@ private Config(@JsonProperty(value = "token", required = true) String token, @JsonProperty(value = "discordGuildInvite", required = true) String discordGuildInvite, @JsonProperty(value = "modAuditLogChannelPattern", required = true) String modAuditLogChannelPattern, + @JsonProperty(value = "modMailChannelPattern", + required = true) String modMailChannelPattern, @JsonProperty(value = "mutedRolePattern", required = true) String mutedRolePattern, @JsonProperty(value = "heavyModerationRolePattern", required = true) String heavyModerationRolePattern, @@ -71,6 +74,7 @@ private Config(@JsonProperty(value = "token", required = true) String token, this.projectWebsite = Objects.requireNonNull(projectWebsite); this.discordGuildInvite = Objects.requireNonNull(discordGuildInvite); this.modAuditLogChannelPattern = Objects.requireNonNull(modAuditLogChannelPattern); + this.modMailChannelPattern = Objects.requireNonNull(modMailChannelPattern); this.mutedRolePattern = Objects.requireNonNull(mutedRolePattern); this.heavyModerationRolePattern = Objects.requireNonNull(heavyModerationRolePattern); this.softModerationRolePattern = Objects.requireNonNull(softModerationRolePattern); @@ -117,6 +121,16 @@ public String getModAuditLogChannelPattern() { return modAuditLogChannelPattern; } + /** + * Gets the REGEX pattern used to identify the channel that is supposed to contain all messages + * from users who want to contact a moderator. + * + * @return the channel name pattern + */ + public String getModMailChannelPattern() { + return modMailChannelPattern; + } + /** * Gets the token of the Discord bot to connect this application to. * From 5aaba3d9526cba1a6d526d80fdfd3c3499c3b312 Mon Sep 17 00:00:00 2001 From: Nxllpointer <54677650+Nxllpointer@users.noreply.github.com> Date: Fri, 21 Oct 2022 18:07:10 +0200 Subject: [PATCH 07/26] Fix Top-Helper message length exploit (#649) * Fix Top-Helper message length exploit One was able to farm Top-Helper message length points by adding invisible characters to help messages * Made RegEx more readable and added info --- .../tophelper/TopHelpersMessageListener.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/tophelper/TopHelpersMessageListener.java b/application/src/main/java/org/togetherjava/tjbot/commands/tophelper/TopHelpersMessageListener.java index 58603474cd..52815bbdb6 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/tophelper/TopHelpersMessageListener.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/tophelper/TopHelpersMessageListener.java @@ -18,6 +18,14 @@ * {@link TopHelpersCommand} to pick them up. */ public final class TopHelpersMessageListener extends MessageReceiverAdapter { + /** + * Matches invisible control characters and unused code points + * + * @see Unicode + * Categories + */ + private static final String UNCOUNTED_CHARS = "\\P{C}"; + private final Database database; private final Predicate isStagingChannelName; @@ -65,13 +73,16 @@ private boolean isHelpThread(MessageReceivedEvent event) { } private void addMessageRecord(MessageReceivedEvent event) { + String messageContent = event.getMessage().getContentRaw(); + long messageLength = messageContent.replaceAll(UNCOUNTED_CHARS, "").length(); + database.write(context -> context.newRecord(HELP_CHANNEL_MESSAGES) .setMessageId(event.getMessage().getIdLong()) .setGuildId(event.getGuild().getIdLong()) .setChannelId(event.getChannel().getIdLong()) .setAuthorId(event.getAuthor().getIdLong()) .setSentAt(event.getMessage().getTimeCreated().toInstant()) - .setMessageLength((long) event.getMessage().getContentRaw().length()) + .setMessageLength(messageLength) .insert()); } } From 2fb7483e79a139a9e206333a15b3c302d63ce88c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 24 Oct 2022 09:49:00 +0200 Subject: [PATCH 08/26] Bump gradle-jooq-plugin from 7.1.1 to 8.0 (#652) Bumps gradle-jooq-plugin from 7.1.1 to 8.0. --- updated-dependencies: - dependency-name: nu.studer:gradle-jooq-plugin dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- buildSrc/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle index 12351c1ccc..ec32272b29 100644 --- a/buildSrc/build.gradle +++ b/buildSrc/build.gradle @@ -8,5 +8,5 @@ repositories { dependencies { implementation "gradle.plugin.org.flywaydb:gradle-plugin-publishing:9.5.0" - implementation 'nu.studer:gradle-jooq-plugin:7.1.1' + implementation 'nu.studer:gradle-jooq-plugin:8.0' } From b51020f0147625876af9d8029a18c7189edf116a Mon Sep 17 00:00:00 2001 From: Daniel Tischner Date: Mon, 24 Oct 2022 11:01:47 +0200 Subject: [PATCH 09/26] Fixed issue with jooq version (#657) * increased jooq to currently used version * Moved jooq version to a single point --- application/build.gradle | 2 +- build.gradle | 4 ++++ buildSrc/src/main/groovy/database-settings.gradle | 4 ++-- database/build.gradle | 2 +- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/application/build.gradle b/application/build.gradle index 75ede0d319..555c2b5c9d 100644 --- a/application/build.gradle +++ b/application/build.gradle @@ -52,7 +52,7 @@ dependencies { implementation 'club.minnced:discord-webhooks:0.8.2' - implementation 'org.jooq:jooq:3.17.2' + implementation "org.jooq:jooq:$jooqVersion" implementation 'io.mikael:urlbuilder:2.0.9' diff --git a/build.gradle b/build.gradle index e04ada7d0d..7e5fda31b6 100644 --- a/build.gradle +++ b/build.gradle @@ -8,6 +8,10 @@ plugins { group 'org.togetherjava' version '1.0-SNAPSHOT' +ext { + jooqVersion = '3.17.2' +} + // Skips sonarlint during the build, useful for testing purposes. Boolean skipSonarlint = false diff --git a/buildSrc/src/main/groovy/database-settings.gradle b/buildSrc/src/main/groovy/database-settings.gradle index 7c32bbfc6e..8d931179d6 100644 --- a/buildSrc/src/main/groovy/database-settings.gradle +++ b/buildSrc/src/main/groovy/database-settings.gradle @@ -28,7 +28,7 @@ tasks.flywayMigrate { } jooq { - version = "3.16.0" + version = jooqVersion configurations { main { @@ -73,7 +73,7 @@ var sqliteVersion = "3.36.0.3" dependencies { implementation "org.xerial:sqlite-jdbc:${sqliteVersion}" implementation 'org.flywaydb:flyway-core:8.0.0' - implementation 'org.jooq:jooq:3.15.3' + implementation "org.jooq:jooq:$jooqVersion" jooqGenerator "org.xerial:sqlite-jdbc:${sqliteVersion}" } diff --git a/database/build.gradle b/database/build.gradle index 353569b5ee..cef351032f 100644 --- a/database/build.gradle +++ b/database/build.gradle @@ -8,7 +8,7 @@ dependencies { implementation 'com.google.code.findbugs:jsr305:3.0.2' implementation "org.xerial:sqlite-jdbc:${sqliteVersion}" implementation 'org.flywaydb:flyway-core:9.5.0' - implementation 'org.jooq:jooq:3.17.2' + implementation "org.jooq:jooq:$jooqVersion" implementation project(':utils') } From bb788aaa453ee607679ecc9b7ae953c8453394ee Mon Sep 17 00:00:00 2001 From: Nxllpointer <54677650+Nxllpointer@users.noreply.github.com> Date: Tue, 25 Oct 2022 14:30:09 +0200 Subject: [PATCH 10/26] Fix and speed up top helper anticheat (#659) * Fixed anti-cheat not counting visible characters instead of invisible ones * Sped up uncounted char matching Sped up uncounted char matching by compiling the pattern once and using the pattern to replace chars instead of passing the RegEx string to String#replaceAll which would compile the pattern every time Co-authored-by: Nxllpointer --- .../tjbot/commands/tophelper/TopHelpersMessageListener.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/tophelper/TopHelpersMessageListener.java b/application/src/main/java/org/togetherjava/tjbot/commands/tophelper/TopHelpersMessageListener.java index 52815bbdb6..f7b7611fc4 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/tophelper/TopHelpersMessageListener.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/tophelper/TopHelpersMessageListener.java @@ -24,7 +24,7 @@ public final class TopHelpersMessageListener extends MessageReceiverAdapter { * @see Unicode * Categories */ - private static final String UNCOUNTED_CHARS = "\\P{C}"; + private static final Pattern UNCOUNTED_CHARS = Pattern.compile("\\p{C}"); private final Database database; @@ -74,7 +74,7 @@ private boolean isHelpThread(MessageReceivedEvent event) { private void addMessageRecord(MessageReceivedEvent event) { String messageContent = event.getMessage().getContentRaw(); - long messageLength = messageContent.replaceAll(UNCOUNTED_CHARS, "").length(); + long messageLength = UNCOUNTED_CHARS.matcher(messageContent).replaceAll("").length(); database.write(context -> context.newRecord(HELP_CHANNEL_MESSAGES) .setMessageId(event.getMessage().getIdLong()) From 522d5c37160c5498c9f904a9d0132341b274bceb Mon Sep 17 00:00:00 2001 From: Daniel Tischner Date: Wed, 26 Oct 2022 09:54:16 +0200 Subject: [PATCH 11/26] Added suspicious keywords to scam blocker (#658) --- application/config.json.template | 1 + .../moderation/scam/ScamDetector.java | 26 ++++++++++++++----- .../tjbot/config/ScamBlockerConfig.java | 13 ++++++++++ .../moderation/scam/ScamDetectorTest.java | 7 ++++- 4 files changed, 40 insertions(+), 7 deletions(-) diff --git a/application/config.json.template b/application/config.json.template index 6a661bdb02..0c776ed38c 100644 --- a/application/config.json.template +++ b/application/config.json.template @@ -19,6 +19,7 @@ "scamBlocker": { "mode": "AUTO_DELETE_BUT_APPROVE_QUARANTINE", "reportChannelPattern": "commands", + "suspiciousKeywords": ["nitro", "boob", "sexy", "sexi", "esex"], "hostWhitelist": ["discord.com", "discord.gg", "discord.media", "discordapp.com", "discordapp.net", "discordstatus.com"], "hostBlacklist": ["bit.ly"], "suspiciousHostKeywords": ["discord", "nitro", "premium"], diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamDetector.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamDetector.java index d4a2281834..f0203588b6 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamDetector.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamDetector.java @@ -5,6 +5,7 @@ import org.togetherjava.tjbot.config.ScamBlockerConfig; import java.net.URI; +import java.util.Locale; import java.util.regex.Pattern; /** @@ -39,19 +40,23 @@ public boolean isScam(CharSequence message) { } private boolean isScam(AnalyseResults results) { - if (results.pingsEveryone && results.containsNitroKeyword && results.hasUrl) { + if (results.pingsEveryone && results.containsSuspiciousKeyword && results.hasUrl) { return true; } - return results.containsNitroKeyword && results.hasSuspiciousUrl; + return results.containsSuspiciousKeyword && results.hasSuspiciousUrl; } private void analyzeToken(String token, AnalyseResults results) { - if ("@everyone".equalsIgnoreCase(token)) { + if (token.isBlank()) { + return; + } + + if (!results.pingsEveryone && "@everyone".equalsIgnoreCase(token)) { results.pingsEveryone = true; } - if ("nitro".equalsIgnoreCase(token)) { - results.containsNitroKeyword = true; + if (!results.containsSuspiciousKeyword && containsSuspiciousKeyword(token)) { + results.containsSuspiciousKeyword = true; } if (token.startsWith("http")) { @@ -91,6 +96,15 @@ private void analyzeUrl(String url, AnalyseResults results) { } } + private boolean containsSuspiciousKeyword(String token) { + String preparedToken = token.toLowerCase(Locale.US); + + return config.getSuspiciousKeywords() + .stream() + .map(keyword -> keyword.toLowerCase(Locale.US)) + .anyMatch(preparedToken::contains); + } + private boolean isHostSimilarToKeyword(String host, String keyword) { // NOTE This algorithm is far from optimal. // It is good enough for our purpose though and not that complex. @@ -116,7 +130,7 @@ private boolean isHostSimilarToKeyword(String host, String keyword) { private static class AnalyseResults { private boolean pingsEveryone; - private boolean containsNitroKeyword; + private boolean containsSuspiciousKeyword; private boolean hasUrl; private boolean hasSuspiciousUrl; } diff --git a/application/src/main/java/org/togetherjava/tjbot/config/ScamBlockerConfig.java b/application/src/main/java/org/togetherjava/tjbot/config/ScamBlockerConfig.java index 3881600250..275d8032ff 100644 --- a/application/src/main/java/org/togetherjava/tjbot/config/ScamBlockerConfig.java +++ b/application/src/main/java/org/togetherjava/tjbot/config/ScamBlockerConfig.java @@ -17,6 +17,7 @@ public final class ScamBlockerConfig { private final Mode mode; private final String reportChannelPattern; + private final Set suspiciousKeywords; private final Set hostWhitelist; private final Set hostBlacklist; private final Set suspiciousHostKeywords; @@ -26,6 +27,8 @@ public final class ScamBlockerConfig { private ScamBlockerConfig(@JsonProperty(value = "mode", required = true) Mode mode, @JsonProperty(value = "reportChannelPattern", required = true) String reportChannelPattern, + @JsonProperty(value = "suspiciousKeywords", + required = true) Set suspiciousKeywords, @JsonProperty(value = "hostWhitelist", required = true) Set hostWhitelist, @JsonProperty(value = "hostBlacklist", required = true) Set hostBlacklist, @JsonProperty(value = "suspiciousHostKeywords", @@ -34,6 +37,7 @@ private ScamBlockerConfig(@JsonProperty(value = "mode", required = true) Mode mo required = true) int isHostSimilarToKeywordDistanceThreshold) { this.mode = Objects.requireNonNull(mode); this.reportChannelPattern = Objects.requireNonNull(reportChannelPattern); + this.suspiciousKeywords = new HashSet<>(Objects.requireNonNull(suspiciousKeywords)); this.hostWhitelist = new HashSet<>(Objects.requireNonNull(hostWhitelist)); this.hostBlacklist = new HashSet<>(Objects.requireNonNull(hostBlacklist)); this.suspiciousHostKeywords = new HashSet<>(Objects.requireNonNull(suspiciousHostKeywords)); @@ -59,6 +63,15 @@ public String getReportChannelPattern() { return reportChannelPattern; } + /** + * Gets the set of keywords that are considered suspicious if they appear in a message. + * + * @return the set of suspicious keywords + */ + public Set getSuspiciousKeywords() { + return Collections.unmodifiableSet(suspiciousKeywords); + } + /** * Gets the set of trusted hosts. Urls using those hosts are not considered scam. * diff --git a/application/src/test/java/org/togetherjava/tjbot/commands/moderation/scam/ScamDetectorTest.java b/application/src/test/java/org/togetherjava/tjbot/commands/moderation/scam/ScamDetectorTest.java index 8aaf8e08e8..3208ff8079 100644 --- a/application/src/test/java/org/togetherjava/tjbot/commands/moderation/scam/ScamDetectorTest.java +++ b/application/src/test/java/org/togetherjava/tjbot/commands/moderation/scam/ScamDetectorTest.java @@ -26,6 +26,8 @@ void setUp() { ScamBlockerConfig scamConfig = mock(ScamBlockerConfig.class); when(config.getScamBlocker()).thenReturn(scamConfig); + when(scamConfig.getSuspiciousKeywords()) + .thenReturn(Set.of("nitro", "boob", "sexi", "esex")); when(scamConfig.getHostWhitelist()).thenReturn(Set.of("discord.com", "discord.gg", "discord.media", "discordapp.com", "discordapp.net", "discordstatus.com")); when(scamConfig.getHostBlacklist()).thenReturn(Set.of("bit.ly")); @@ -139,6 +141,9 @@ private static List provideRealScamMessages() { Steam is giving away free discord nitro, have time to pick up at my link https://bit.ly/3nlzmUa before the action is over.""", """ @everyone, take nitro faster, it's already running out - https://discordu.gift/u1CHEX2sjpDuR3T5"""); + https://discordu.gift/u1CHEX2sjpDuR3T5""", + "@everyone join now https://discord.gg/boobise", + "@everyone join now https://discord.gg/esexiest", + "@everyone Join Now | Free All 12-18 y.o. https://discord.gg/eesexe"); } } From 593b07390927d0707bf8440248a5a04e5c9ea533 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 27 Oct 2022 08:37:17 +0200 Subject: [PATCH 12/26] Bump flyway-core from 9.5.0 to 9.6.0 (#664) Bumps [flyway-core](https://github.com/flyway/flyway) from 9.5.0 to 9.6.0. - [Release notes](https://github.com/flyway/flyway/releases) - [Commits](https://github.com/flyway/flyway/compare/flyway-9.5.0...flyway-9.6.0) --- updated-dependencies: - dependency-name: org.flywaydb:flyway-core dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- database/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/database/build.gradle b/database/build.gradle index cef351032f..1eef89fc15 100644 --- a/database/build.gradle +++ b/database/build.gradle @@ -7,7 +7,7 @@ var sqliteVersion = "3.39.2.0" dependencies { implementation 'com.google.code.findbugs:jsr305:3.0.2' implementation "org.xerial:sqlite-jdbc:${sqliteVersion}" - implementation 'org.flywaydb:flyway-core:9.5.0' + implementation 'org.flywaydb:flyway-core:9.6.0' implementation "org.jooq:jooq:$jooqVersion" implementation project(':utils') From 5ee24b6c551d749465144454b2454be8d0a6b0e8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 27 Oct 2022 08:37:42 +0200 Subject: [PATCH 13/26] Bump gradle-plugin-publishing from 9.5.0 to 9.6.0 (#663) Bumps gradle-plugin-publishing from 9.5.0 to 9.6.0. --- updated-dependencies: - dependency-name: gradle.plugin.org.flywaydb:gradle-plugin-publishing dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- buildSrc/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle index ec32272b29..ae55f92844 100644 --- a/buildSrc/build.gradle +++ b/buildSrc/build.gradle @@ -7,6 +7,6 @@ repositories { } dependencies { - implementation "gradle.plugin.org.flywaydb:gradle-plugin-publishing:9.5.0" + implementation "gradle.plugin.org.flywaydb:gradle-plugin-publishing:9.6.0" implementation 'nu.studer:gradle-jooq-plugin:8.0' } From fcbd298c8a895d67d9fd35e6caeace4b814444b6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 28 Oct 2022 09:41:41 +0200 Subject: [PATCH 14/26] Bump org.sonarqube from 3.4.0.2513 to 3.5.0.2730 (#665) Bumps org.sonarqube from 3.4.0.2513 to 3.5.0.2730. --- updated-dependencies: - dependency-name: org.sonarqube dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 7e5fda31b6..a452e25d5d 100644 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,7 @@ plugins { id 'java' id "com.diffplug.spotless" version "6.11.0" - id "org.sonarqube" version "3.4.0.2513" + id "org.sonarqube" version "3.5.0.2730" id "name.remal.sonarlint" version "1.5.0" } From 9767ae709201c7375d3df620aec8729a3280745d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 3 Nov 2022 08:50:17 +0100 Subject: [PATCH 15/26] Bump flyway-core from 9.6.0 to 9.7.0 (#671) Bumps [flyway-core](https://github.com/flyway/flyway) from 9.6.0 to 9.7.0. - [Release notes](https://github.com/flyway/flyway/releases) - [Commits](https://github.com/flyway/flyway/compare/flyway-9.6.0...flyway-9.7.0) --- updated-dependencies: - dependency-name: org.flywaydb:flyway-core dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- database/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/database/build.gradle b/database/build.gradle index 1eef89fc15..4b7902eced 100644 --- a/database/build.gradle +++ b/database/build.gradle @@ -7,7 +7,7 @@ var sqliteVersion = "3.39.2.0" dependencies { implementation 'com.google.code.findbugs:jsr305:3.0.2' implementation "org.xerial:sqlite-jdbc:${sqliteVersion}" - implementation 'org.flywaydb:flyway-core:9.6.0' + implementation 'org.flywaydb:flyway-core:9.7.0' implementation "org.jooq:jooq:$jooqVersion" implementation project(':utils') From 89dd46115576077a8fe70ae49dc08523a020bea3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 3 Nov 2022 08:50:40 +0100 Subject: [PATCH 16/26] Bump gradle-plugin-publishing from 9.6.0 to 9.7.0 (#670) Bumps gradle-plugin-publishing from 9.6.0 to 9.7.0. --- updated-dependencies: - dependency-name: gradle.plugin.org.flywaydb:gradle-plugin-publishing dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- buildSrc/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle index ae55f92844..30898ce55d 100644 --- a/buildSrc/build.gradle +++ b/buildSrc/build.gradle @@ -7,6 +7,6 @@ repositories { } dependencies { - implementation "gradle.plugin.org.flywaydb:gradle-plugin-publishing:9.6.0" + implementation "gradle.plugin.org.flywaydb:gradle-plugin-publishing:9.7.0" implementation 'nu.studer:gradle-jooq-plugin:8.0' } From a7b7044826d8ae2093761bc9209f7106d459dc60 Mon Sep 17 00:00:00 2001 From: Tanish Azad <73871477+Taz03@users.noreply.github.com> Date: Fri, 4 Nov 2022 21:14:51 +0530 Subject: [PATCH 17/26] Added list for reminders (#650) --- .../togetherjava/tjbot/commands/Features.java | 4 +- .../commands/moderation/AuditCommand.java | 7 +- .../commands/reminder/RemindCommand.java | 154 ---------- .../commands/reminder/RemindRoutine.java | 4 +- .../commands/reminder/ReminderCommand.java | 289 ++++++++++++++++++ .../tjbot/commands/reminder/package-info.java | 2 +- .../tjbot/commands/utils/MessageUtils.java | 12 + .../tjbot/commands/utils/Pagination.java | 23 ++ ...mandTest.java => ReminderCommandTest.java} | 17 +- 9 files changed, 340 insertions(+), 172 deletions(-) delete mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindCommand.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/reminder/ReminderCommand.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/utils/Pagination.java rename application/src/test/java/org/togetherjava/tjbot/commands/reminder/{RemindCommandTest.java => ReminderCommandTest.java} (90%) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java index 28c4f1284f..1b9c2ec6d0 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java @@ -18,8 +18,8 @@ import org.togetherjava.tjbot.commands.moderation.scam.ScamHistoryPurgeRoutine; import org.togetherjava.tjbot.commands.moderation.scam.ScamHistoryStore; import org.togetherjava.tjbot.commands.moderation.temp.TemporaryModerationRoutine; -import org.togetherjava.tjbot.commands.reminder.RemindCommand; import org.togetherjava.tjbot.commands.reminder.RemindRoutine; +import org.togetherjava.tjbot.commands.reminder.ReminderCommand; import org.togetherjava.tjbot.commands.system.BotCore; import org.togetherjava.tjbot.commands.system.LogLevelCommand; import org.togetherjava.tjbot.commands.tags.TagCommand; @@ -121,7 +121,7 @@ public static Collection createFeatures(JDA jda, Database database, Con features.add(new TopHelpersCommand(database)); features.add(new RoleSelectCommand()); features.add(new NoteCommand(actionsStore)); - features.add(new RemindCommand(database)); + features.add(new ReminderCommand(database)); features.add(new QuarantineCommand(actionsStore, config)); features.add(new UnquarantineCommand(actionsStore, config)); features.add(new WhoIsCommand()); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java index 0a173c63ed..d490713b2d 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java @@ -21,6 +21,7 @@ import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.utils.Pagination; import javax.annotation.Nullable; @@ -106,7 +107,7 @@ private > RestAction auditUser( if (pageNumber == -1) { pageNumberInLimits = totalPages; } else { - pageNumberInLimits = clamp(1, pageNumber, totalPages); + pageNumberInLimits = Pagination.clamp(1, pageNumber, totalPages); } return jda.retrieveUserById(targetId) @@ -130,10 +131,6 @@ private List> groupActionsByPages(List actions) return groupedActions; } - private static int clamp(int minInclusive, int value, int maxInclusive) { - return Math.min(Math.max(minInclusive, value), maxInclusive); - } - private static EmbedBuilder createSummaryEmbed(User user, Collection actions) { return new EmbedBuilder().setTitle("Audit log of **%s**".formatted(user.getAsTag())) .setAuthor(user.getName(), null, user.getAvatarUrl()) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindCommand.java deleted file mode 100644 index 97ab7d02cd..0000000000 --- a/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindCommand.java +++ /dev/null @@ -1,154 +0,0 @@ -package org.togetherjava.tjbot.commands.reminder; - -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.ISnowflake; -import net.dv8tion.jda.api.entities.User; -import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; -import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback; -import net.dv8tion.jda.api.interactions.commands.OptionType; -import net.dv8tion.jda.api.interactions.commands.build.OptionData; - -import org.togetherjava.tjbot.commands.CommandVisibility; -import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.db.Database; - -import java.time.*; -import java.time.temporal.TemporalAmount; -import java.util.List; - -import static org.togetherjava.tjbot.db.generated.Tables.PENDING_REMINDERS; - -/** - * Implements the '/remind' command which can be used to automatically send reminders to oneself at - * a future date. - *

- * Example usage: - * - *

- * {@code
- * /remind time-amount: 5 time-unit: weeks content: Hello World!
- * }
- * 
- *

- * Pending reminders are processed and send by {@link RemindRoutine}. - */ -public final class RemindCommand extends SlashCommandAdapter { - private static final String COMMAND_NAME = "remind"; - static final String TIME_AMOUNT_OPTION = "time-amount"; - static final String TIME_UNIT_OPTION = "time-unit"; - static final String CONTENT_OPTION = "content"; - - private static final int MIN_TIME_AMOUNT = 1; - private static final int MAX_TIME_AMOUNT = 1_000; - private static final List TIME_UNITS = - List.of("minutes", "hours", "days", "weeks", "months", "years"); - private static final Period MAX_TIME_PERIOD = Period.ofYears(3); - static final int MAX_PENDING_REMINDERS_PER_USER = 100; - - private final Database database; - - /** - * Creates an instance of the command. - * - * @param database to store and fetch the reminders from - */ - public RemindCommand(Database database) { - super(COMMAND_NAME, "Reminds you after a given time period has passed (e.g. in 5 weeks)", - CommandVisibility.GUILD); - - // TODO As soon as JDA offers date/time selector input, this should also offer - // "/remind at" next to "/remind in" and use subcommands then - OptionData timeAmount = new OptionData(OptionType.INTEGER, TIME_AMOUNT_OPTION, - "period to remind you in, the amount of time (e.g. [5] weeks)", true) - .setRequiredRange(MIN_TIME_AMOUNT, MAX_TIME_AMOUNT); - OptionData timeUnit = new OptionData(OptionType.STRING, TIME_UNIT_OPTION, - "period to remind you in, the unit of time (e.g. 5 [weeks])", true); - TIME_UNITS.forEach(unit -> timeUnit.addChoice(unit, unit)); - - getData().addOptions(timeUnit, timeAmount) - .addOption(OptionType.STRING, CONTENT_OPTION, "what to remind you about", true); - - this.database = database; - } - - @Override - public void onSlashCommand(SlashCommandInteractionEvent event) { - int timeAmount = Math.toIntExact(event.getOption(TIME_AMOUNT_OPTION).getAsLong()); - String timeUnit = event.getOption(TIME_UNIT_OPTION).getAsString(); - String content = event.getOption(CONTENT_OPTION).getAsString(); - - Instant remindAt = parseWhen(timeAmount, timeUnit); - User author = event.getUser(); - Guild guild = event.getGuild(); - - if (!handleIsRemindAtWithinLimits(remindAt, event)) { - return; - } - if (!handleIsUserBelowMaxPendingReminders(author, guild, event)) { - return; - } - - event.reply("Will remind you about '%s' in %d %s.".formatted(content, timeAmount, timeUnit)) - .setEphemeral(true) - .queue(); - - database.write(context -> context.newRecord(PENDING_REMINDERS) - .setCreatedAt(Instant.now()) - .setGuildId(guild.getIdLong()) - .setChannelId(event.getChannel().getIdLong()) - .setAuthorId(author.getIdLong()) - .setRemindAt(remindAt) - .setContent(content) - .insert()); - } - - private static Instant parseWhen(int whenAmount, String whenUnit) { - TemporalAmount period = switch (whenUnit) { - case "second", "seconds" -> Duration.ofSeconds(whenAmount); - case "minute", "minutes" -> Duration.ofMinutes(whenAmount); - case "hour", "hours" -> Duration.ofHours(whenAmount); - case "day", "days" -> Period.ofDays(whenAmount); - case "week", "weeks" -> Period.ofWeeks(whenAmount); - case "month", "months" -> Period.ofMonths(whenAmount); - case "year", "years" -> Period.ofYears(whenAmount); - default -> throw new IllegalArgumentException("Unsupported unit, was: " + whenUnit); - }; - - return ZonedDateTime.now(ZoneOffset.UTC).plus(period).toInstant(); - } - - private static boolean handleIsRemindAtWithinLimits(Instant remindAt, IReplyCallback event) { - ZonedDateTime maxWhen = ZonedDateTime.now(ZoneOffset.UTC).plus(MAX_TIME_PERIOD); - - if (remindAt.atZone(ZoneOffset.UTC).isBefore(maxWhen)) { - return true; - } - - event - .reply("The reminder is set too far in the future. The maximal allowed period is '%s'." - .formatted(MAX_TIME_PERIOD)) - .setEphemeral(true) - .queue(); - - return false; - } - - private boolean handleIsUserBelowMaxPendingReminders(ISnowflake author, ISnowflake guild, - IReplyCallback event) { - int pendingReminders = database.read(context -> context.fetchCount(PENDING_REMINDERS, - PENDING_REMINDERS.AUTHOR_ID.equal(author.getIdLong()) - .and(PENDING_REMINDERS.GUILD_ID.equal(guild.getIdLong())))); - - if (pendingReminders < MAX_PENDING_REMINDERS_PER_USER) { - return true; - } - - event.reply( - "You have reached the maximum amount of pending reminders per user (%s). Please wait until some of them have been sent." - .formatted(MAX_PENDING_REMINDERS_PER_USER)) - .setEphemeral(true) - .queue(); - - return false; - } -} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindRoutine.java b/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindRoutine.java index db09fe8ea4..b5bedd5906 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindRoutine.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindRoutine.java @@ -28,11 +28,11 @@ /** * Routine that processes and sends pending reminders. *

- * Reminders can be set by using {@link RemindCommand}. + * Reminders can be set by using {@link ReminderCommand}. */ public final class RemindRoutine implements Routine { static final Logger logger = LoggerFactory.getLogger(RemindRoutine.class); - private static final Color AMBIENT_COLOR = Color.decode("#F7F492"); + static final Color AMBIENT_COLOR = Color.decode("#F7F492"); private static final int SCHEDULE_INTERVAL_SECONDS = 30; private final Database database; diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/reminder/ReminderCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/reminder/ReminderCommand.java new file mode 100644 index 0000000000..a0bb1ee9a3 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/reminder/ReminderCommand.java @@ -0,0 +1,289 @@ +package org.togetherjava.tjbot.commands.reminder; + +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.ISnowflake; +import net.dv8tion.jda.api.entities.MessageEmbed; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.entities.emoji.Emoji; +import net.dv8tion.jda.api.entities.emoji.EmojiUnion; +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; +import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.OptionData; +import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; +import net.dv8tion.jda.api.interactions.components.buttons.Button; +import net.dv8tion.jda.api.utils.TimeFormat; +import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; +import net.dv8tion.jda.api.utils.messages.MessageCreateData; +import net.dv8tion.jda.api.utils.messages.MessageEditData; +import org.jooq.Result; + +import org.togetherjava.tjbot.commands.CommandVisibility; +import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.utils.MessageUtils; +import org.togetherjava.tjbot.commands.utils.Pagination; +import org.togetherjava.tjbot.db.Database; +import org.togetherjava.tjbot.db.generated.tables.records.PendingRemindersRecord; + +import java.time.*; +import java.time.temporal.TemporalAmount; +import java.util.List; + +import static org.togetherjava.tjbot.db.generated.Tables.PENDING_REMINDERS; + +/** + * Implements the '/reminder' command which can be used to automatically send reminders to oneself + * at a future date. + *

+ * Example usage: + * + *

+ * {@code
+ * /reminder create time-amount: 5 time-unit: weeks content: Hello World!
+ * }
+ *
+ * {@code
+ * /reminder list
+ * }
+ * 
+ *

+ * Pending reminders are processed and send by {@link RemindRoutine}. + */ +public final class ReminderCommand extends SlashCommandAdapter { + private static final String COMMAND_NAME = "reminder"; + private static final String LIST_SUBCOMMAND = "list"; + static final String CREATE_SUBCOMMAND = "create"; + static final String TIME_AMOUNT_OPTION = "time-amount"; + static final String TIME_UNIT_OPTION = "time-unit"; + static final String CONTENT_OPTION = "content"; + + private static final int MIN_TIME_AMOUNT = 1; + private static final int MAX_TIME_AMOUNT = 1_000; + private static final List TIME_UNITS = + List.of("minutes", "hours", "days", "weeks", "months", "years"); + private static final Period MAX_TIME_PERIOD = Period.ofYears(3); + private static final int REMINDERS_PER_PAGE = 10; + private static final Emoji PREVIOUS_BUTTON_EMOJI = Emoji.fromUnicode("⬅"); + private static final Emoji NEXT_BUTTON_EMOJI = Emoji.fromUnicode("➡"); + static final int MAX_PENDING_REMINDERS_PER_USER = 100; + + private final Database database; + + /** + * Creates an instance of the command. + * + * @param database to store and fetch the reminders from + */ + public ReminderCommand(Database database) { + super(COMMAND_NAME, "Reminds you after a given time period has passed (e.g. in 5 weeks)", + CommandVisibility.GUILD); + + // TODO As soon as JDA offers date/time selector input, this should also offer + // "/remind at" next to "/remind in" and use subcommands then + OptionData timeAmount = new OptionData(OptionType.INTEGER, TIME_AMOUNT_OPTION, + "period to remind you in, the amount of time (e.g. [5] weeks)", true) + .setRequiredRange(MIN_TIME_AMOUNT, MAX_TIME_AMOUNT); + OptionData timeUnit = new OptionData(OptionType.STRING, TIME_UNIT_OPTION, + "period to remind you in, the unit of time (e.g. 5 [weeks])", true); + TIME_UNITS.forEach(unit -> timeUnit.addChoice(unit, unit)); + OptionData content = + new OptionData(OptionType.STRING, CONTENT_OPTION, "what to remind you about", true); + + getData().addSubcommands( + new SubcommandData(CREATE_SUBCOMMAND, "creates a reminder").addOptions(timeAmount, + timeUnit, content), + new SubcommandData(LIST_SUBCOMMAND, "shows all your currently pending reminders")); + + this.database = database; + } + + @Override + public void onSlashCommand(SlashCommandInteractionEvent event) { + switch (event.getSubcommandName()) { + case CREATE_SUBCOMMAND -> handleCreateCommand(event); + case LIST_SUBCOMMAND -> handleListCommand(event); + default -> throw new AssertionError( + "Unexpected Subcommand: " + event.getSubcommandName()); + } + } + + @Override + public void onButtonClick(ButtonInteractionEvent event, List args) { + int pageToShow = Integer.parseInt(args.get(0)); + + EmojiUnion emoji = event.getButton().getEmoji(); + if (PREVIOUS_BUTTON_EMOJI.equals(emoji)) { + pageToShow--; + } else if (NEXT_BUTTON_EMOJI.equals(emoji)) { + pageToShow++; + } + + Result pendingReminders = + getPendingReminders(event.getGuild(), event.getUser()); + + MessageCreateData message = createPendingRemindersPage(pendingReminders, pageToShow); + event.editMessage(MessageEditData.fromCreateData(message)).queue(); + } + + private void handleCreateCommand(SlashCommandInteractionEvent event) { + int timeAmount = Math.toIntExact(event.getOption(TIME_AMOUNT_OPTION).getAsLong()); + String timeUnit = event.getOption(TIME_UNIT_OPTION).getAsString(); + String content = event.getOption(CONTENT_OPTION).getAsString(); + + Instant remindAt = parseWhen(timeAmount, timeUnit); + User author = event.getUser(); + Guild guild = event.getGuild(); + + if (!handleIsRemindAtWithinLimits(remindAt, event)) { + return; + } + if (!handleIsUserBelowMaxPendingReminders(author, guild, event)) { + return; + } + + event.reply("Will remind you about '%s' in %d %s.".formatted(content, timeAmount, timeUnit)) + .setEphemeral(true) + .queue(); + + database.write(context -> context.newRecord(PENDING_REMINDERS) + .setCreatedAt(Instant.now()) + .setGuildId(guild.getIdLong()) + .setChannelId(event.getChannel().getIdLong()) + .setAuthorId(author.getIdLong()) + .setRemindAt(remindAt) + .setContent(content) + .insert()); + } + + private void handleListCommand(SlashCommandInteractionEvent event) { + Result pendingReminders = + getPendingReminders(event.getGuild(), event.getUser()); + + event.reply(createPendingRemindersPage(pendingReminders, 1)).setEphemeral(true).queue(); + } + + private Result getPendingReminders(Guild guild, User user) { + return database.read(context -> context.selectFrom(PENDING_REMINDERS) + .where(PENDING_REMINDERS.GUILD_ID.eq(guild.getIdLong()) + .and(PENDING_REMINDERS.AUTHOR_ID.eq(user.getIdLong()))) + .orderBy(PENDING_REMINDERS.REMIND_AT.asc()) + .fetch()); + } + + private MessageCreateData createPendingRemindersPage( + List pendingReminders, int pageToShow) { + // 12 reminders, 10 per page, ceil(12 / 10) = 2 + int totalPages = Math.ceilDiv(pendingReminders.size(), REMINDERS_PER_PAGE); + + pageToShow = Pagination.clamp(1, pageToShow, totalPages); + + EmbedBuilder remindersEmbed = new EmbedBuilder().setTitle("Pending reminders") + .setColor(RemindRoutine.AMBIENT_COLOR); + MessageCreateBuilder pendingRemindersPage = new MessageCreateBuilder(); + + if (pendingReminders.isEmpty()) { + remindersEmbed.setDescription("No pending reminders"); + } else { + if (totalPages > 1) { + pendingReminders = getPageEntries(pendingReminders, pageToShow); + remindersEmbed.setFooter("Page: %d/%d".formatted(pageToShow, totalPages)); + pendingRemindersPage.addActionRow(createPageTurnButtons(pageToShow, totalPages)); + } + pendingReminders.forEach(reminder -> addReminderAsField(reminder, remindersEmbed)); + } + + return pendingRemindersPage.addEmbeds(remindersEmbed.build()).build(); + } + + private List