From cab2b5995fe380bd6bdf3241e93dffecd7c4b3bc Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Wed, 15 Dec 2021 14:29:48 +0100 Subject: [PATCH 01/14] Added routine to revoke temporary actions --- .../togetherjava/tjbot/commands/Commands.java | 1 + .../moderation/ModerationActionsStore.java | 47 ++++- .../TemporaryModerationRoutine.java | 171 ++++++++++++++++++ 3 files changed, 209 insertions(+), 10 deletions(-) create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/moderation/TemporaryModerationRoutine.java diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java index dd5694792e..1aecb6c762 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -46,6 +46,7 @@ public enum Commands { // TODO This should be moved into some proper command system instead (see GH issue #235 // which adds support for routines) new ModAuditLogRoutine(jda, database).start(); + new TemporaryModerationRoutine(jda, actionsStore).start(); // TODO This should be moved into some proper command system instead (see GH issue #236 // which adds support for listeners) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java index 27555e3097..f2c160e1bd 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java @@ -15,16 +15,16 @@ /** * Store for moderation actions, e.g. as banning users. Can be used to retrieve information about * past events, such as when a user has been banned the last time. - * + *

* Actions have to be added to the store using * {@link #addAction(long, long, long, ModerationUtils.Action, Instant, String)} at the time they * are executed and can then be retrieved by methods such as * {@link #getActionsByTypeAscending(long, ModerationUtils.Action)} or * {@link #findActionByCaseId(int)}. - * + *

* Be aware that timestamps associated with actions, such as {@link ActionRecord#issuedAt()} are * slightly off the timestamps used by Discord. - * + *

* The store persists the actions and is thread safe. */ @SuppressWarnings("ClassCanBeRecord") @@ -33,17 +33,25 @@ public final class ModerationActionsStore { /** * Creates a new instance which writes and retrieves actions from a given database. - * + * * @param database the database to write and retrieve actions from */ public ModerationActionsStore(@NotNull Database database) { this.database = Objects.requireNonNull(database); } + // FIXME javadoc + public @NotNull List getExpiredActionsAscending() { + return getActionsAscendingWhere( + ModerationActions.MODERATION_ACTIONS.ACTION_EXPIRES_AT.isNotNull() + .and(ModerationActions.MODERATION_ACTIONS.ACTION_EXPIRES_AT + .lessOrEqual(Instant.now()))); + } + /** * Gets all actions of a given type that have been written to the store, chronologically * ascending with the earliest action first. - * + * * @param guildId the id of the guild, only actions that happened in the context of that guild * will be retrieved * @param actionType the type of action to filter for @@ -60,7 +68,7 @@ public ModerationActionsStore(@NotNull Database database) { /** * Gets all actions executed against a given target that have been written to the store, * chronologically ascending with the earliest action first. - * + * * @param guildId the id of the guild, only actions that happened in the context of that guild * will be retrieved * @param targetId the id of the target user to filter for @@ -74,7 +82,7 @@ public ModerationActionsStore(@NotNull Database database) { /** * Gets all actions executed by a given author that have been written to the store, * chronologically ascending with the earliest action first. - * + * * @param guildId the id of the guild, only actions that happened in the context of that guild * will be retrieved * @param authorId the id of the author user to filter for @@ -85,9 +93,21 @@ public ModerationActionsStore(@NotNull Database database) { ModerationActions.MODERATION_ACTIONS.AUTHOR_ID.eq(authorId)); } + // FIXME javadoc + public @NotNull Optional findLastActionAgainstTargetByType(long guildId, + long targetId, @NotNull ModerationUtils.Action actionType) { + return Optional.of(database.read(context -> context + .selectFrom(ModerationActions.MODERATION_ACTIONS) + .where(ModerationActions.MODERATION_ACTIONS.GUILD_ID.eq(guildId) + .and(ModerationActions.MODERATION_ACTIONS.TARGET_ID.eq(targetId) + .and(ModerationActions.MODERATION_ACTIONS.ACTION_TYPE.eq(actionType.name())))) + .orderBy(ModerationActions.MODERATION_ACTIONS.ISSUED_AT.desc()) + .fetchOne())).map(ActionRecord::of); + } + /** * Gets the action with the given case id from the store, if present. - * + * * @param caseId the actions' case id to search for * @return the action with the given case id, if present */ @@ -102,7 +122,7 @@ public ModerationActionsStore(@NotNull Database database) { /** * Adds the given action to the store. A unique case id will be associated to the action and * returned. - * + *

* It is assumed that the action is issued at the point in time this method is called. It is not * possible to assign a different timestamp, especially not an earlier point in time. * Consequently, this causes the timestamps to be slightly off from the timestamps recorded by @@ -143,8 +163,15 @@ public int addAction(long guildId, long authorId, long targetId, @NotNull Condition condition) { Objects.requireNonNull(condition); + return getActionsAscendingWhere( + ModerationActions.MODERATION_ACTIONS.GUILD_ID.eq(guildId).and(condition)); + } + + private @NotNull List getActionsAscendingWhere(@NotNull Condition condition) { + Objects.requireNonNull(condition); + return database.read(context -> context.selectFrom(ModerationActions.MODERATION_ACTIONS) - .where(ModerationActions.MODERATION_ACTIONS.GUILD_ID.eq(guildId).and(condition)) + .where(condition) .orderBy(ModerationActions.MODERATION_ACTIONS.ISSUED_AT.asc()) .stream() .map(ActionRecord::of) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/TemporaryModerationRoutine.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/TemporaryModerationRoutine.java new file mode 100644 index 0000000000..1189199df6 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/TemporaryModerationRoutine.java @@ -0,0 +1,171 @@ +package org.togetherjava.tjbot.commands.moderation; + +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.exceptions.ErrorResponseException; +import net.dv8tion.jda.api.requests.ErrorResponse; +import net.dv8tion.jda.api.requests.restaction.AuditableRestAction; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.time.Instant; +import java.util.*; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +// FIXME javadoc +public final class TemporaryModerationRoutine { + private static final Logger logger = LoggerFactory.getLogger(TemporaryModerationRoutine.class); + private static final Set REVOCABLE_ACTIONS = + EnumSet.of(ModerationUtils.Action.BAN, ModerationUtils.Action.MUTE); + + private final ModerationActionsStore actionsStore; + private final JDA jda; + private final ScheduledExecutorService checkExpiredActionsService = + Executors.newSingleThreadScheduledExecutor(); + + /** + * Creates a new instance. + * + * @param jda the JDA instance to use to send messages and retrieve information + * @param actionsStore the store used to retrieve temporary moderation actions + */ + public TemporaryModerationRoutine(@NotNull JDA jda, + @NotNull ModerationActionsStore actionsStore) { + this.actionsStore = actionsStore; + this.jda = jda; + } + + private static void handleFailure(@NotNull Throwable failure, + @NotNull RevocationGroupIdentifier groupIdentifier) { + if (failure instanceof ErrorResponseException errorResponseException) { + if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_USER) { + logger.info( + "Attempted to revoke a temporary moderation action but user '{}' does not exist anymore.", + groupIdentifier.targetId); + return; + } + + if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_BAN) { + logger.info( + "Attempted to revoke a temporary moderation action but the action is not relevant for user '{}' anymore.", + groupIdentifier.targetId); + return; + } + } + + logger.warn( + "Attempted to revoke a temporary moderation action for user '{}' but something unexpected went wrong.", + groupIdentifier.targetId, failure); + } + + private void checkExpiredActions() { + logger.debug("Checking expired temporary moderation actions to revoke..."); + + actionsStore.getExpiredActionsAscending() + .stream() + .filter(action -> REVOCABLE_ACTIONS.contains(action.actionType())) + .collect(Collectors.groupingBy(RevocationGroupIdentifier::of)) + .forEach(this::processGroupedActions); + + logger.debug("Finished checking expired temporary moderation actions to revoke."); + } + + private void processGroupedActions(@NotNull RevocationGroupIdentifier groupIdentifier, + @NotNull Collection expiredActions) { + // Last issued temporary action takes priority + ActionRecord actionToRevoke = expiredActions.stream() + .max(Comparator.comparing(ActionRecord::issuedAt)) + .orElseThrow(); + + // Do not revoke an action which was overwritten by a permanent action that was issued + // afterwards + // For example if a user was perm-banned after being temp-banned + ActionRecord lastAction = actionsStore + .findLastActionAgainstTargetByType(groupIdentifier.guildId, groupIdentifier.targetId, + groupIdentifier.type) + .orElseThrow(); + if (lastAction.actionExpiresAt() == null) { + return; + } + + // Do not revoke an action which was already revoked by another action issued afterwards + // For example if a user was unbanned manually after being temp-banned, + // but also if the system automatically revoked a temp-ban already itself + ModerationUtils.Action revokeActionType = switch (groupIdentifier.type) { + case BAN -> ModerationUtils.Action.UNBAN; + case MUTE -> ModerationUtils.Action.UNMUTE; + default -> throw new AssertionError("Unsupported action type: " + groupIdentifier.type); + }; + ActionRecord lastRevokeAction = actionsStore + .findLastActionAgainstTargetByType(groupIdentifier.guildId, groupIdentifier.targetId, + revokeActionType) + .orElseThrow(); + if (lastRevokeAction.issuedAt().isAfter(actionToRevoke.issuedAt()) + && (lastRevokeAction.actionExpiresAt() == null + || lastRevokeAction.actionExpiresAt().isAfter(Instant.now()))) { + return; + } + + revokeAction(groupIdentifier); + } + + private void revokeAction(@NotNull RevocationGroupIdentifier groupIdentifier) { + if (!REVOCABLE_ACTIONS.contains(groupIdentifier.type)) { + throw new AssertionError("Unsupported action type: " + groupIdentifier.type); + } + + Guild guild = jda.getGuildById(groupIdentifier.guildId); + if (guild == null) { + logger.info( + "Attempted to revoke a temporary moderation action but the bot is not connected to the guild '{}' anymore, skipping revoking.", + groupIdentifier.guildId); + return; + } + + jda.retrieveUserById(groupIdentifier.targetId) + .flatMap(target -> executeRevocation(guild, target, groupIdentifier.type)) + .queue(result -> { + }, failure -> handleFailure(failure, groupIdentifier)); + } + + private @NotNull AuditableRestAction executeRevocation(@NotNull Guild guild, + @NotNull User target, @NotNull ModerationUtils.Action actionType) { + logger.info("Revoked temporary action {} against user '{}' ({}).", actionType, + target.getAsTag(), target.getId()); + + String reason = "Automatic revocation of temporary action."; + actionsStore.addAction(guild.getIdLong(), jda.getSelfUser().getIdLong(), target.getIdLong(), + actionType, null, reason); + + return (switch (actionType) { + case BAN -> guild.unban(target); + case MUTE -> guild.removeRoleFromMember(target.getIdLong(), + ModerationUtils.getMutedRole(guild).orElseThrow()); + default -> throw new AssertionError("Unsupported action type: " + actionType); + }).reason(reason); + } + + /** + * Starts the routine, automatically checking expired temporary moderation actions on a + * schedule. + */ + public void start() { + // TODO This should be registered at some sort of routine system instead (see GH issue #235 + // which adds support for routines) + checkExpiredActionsService.scheduleWithFixedDelay(this::checkExpiredActions, 0, 5, + TimeUnit.MINUTES); + } + + private record RevocationGroupIdentifier(long guildId, long targetId, + @NotNull ModerationUtils.Action type) { + public static RevocationGroupIdentifier of(@NotNull ActionRecord actionRecord) { + return new RevocationGroupIdentifier(actionRecord.guildId(), actionRecord.targetId(), + actionRecord.actionType()); + } + } +} From dffd4da5d833b116a77c642b5847ff89d740e6e7 Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Wed, 15 Dec 2021 14:41:38 +0100 Subject: [PATCH 02/14] Added temp ban --- .../tjbot/commands/moderation/BanCommand.java | 133 +++++++++++++----- 1 file changed, 95 insertions(+), 38 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java index 5e48064647..a55f78bd75 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java @@ -22,6 +22,9 @@ import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; @@ -38,10 +41,14 @@ public final class BanCommand extends SlashCommandAdapter { private static final Logger logger = LoggerFactory.getLogger(BanCommand.class); private static final String TARGET_OPTION = "user"; + private static final String DURATION_OPTION = "duration"; private static final String DELETE_HISTORY_OPTION = "delete-history"; private static final String REASON_OPTION = "reason"; private static final String COMMAND_NAME = "ban"; private static final String ACTION_VERB = "ban"; + private static final String PERMANENT_DURATION = "permanent"; + private static final List DURATIONS = List.of(PERMANENT_DURATION, "1 hour", "3 hours", + "1 day", "2 days", "3 days", "7 days", "1 month"); private final Predicate hasRequiredRole; private final ModerationActionsStore actionsStore; @@ -53,7 +60,12 @@ public final class BanCommand extends SlashCommandAdapter { public BanCommand(@NotNull ModerationActionsStore actionsStore) { super(COMMAND_NAME, "Bans the given user from the server", SlashCommandVisibility.GUILD); + OptionData durationData = new OptionData(OptionType.STRING, DURATION_OPTION, + "the duration of the ban, permanent or temporary", true); + DURATIONS.forEach(duration -> durationData.addChoice(duration, duration)); + getData().addOption(OptionType.USER, TARGET_OPTION, "The user who you want to ban", true) + .addOptions(durationData) .addOption(OptionType.STRING, REASON_OPTION, "Why the user should be banned", true) .addOptions(new OptionData(OptionType.INTEGER, DELETE_HISTORY_OPTION, "the amount of days of the message history to delete, none means no messages are deleted.", @@ -75,53 +87,39 @@ private static RestAction handleAlreadyBanned(@NotNull Guild.Ba return event.reply(message).setEphemeral(true); } - @SuppressWarnings("MethodWithTooManyParameters") - private RestAction banUserFlow(@NotNull User target, @NotNull Member author, - @NotNull String reason, int deleteHistoryDays, @NotNull Guild guild, - @NotNull SlashCommandEvent event) { - return sendDm(target, reason, guild, event) - .flatMap(hasSentDm -> banUser(target, author, reason, deleteHistoryDays, guild) - .map(banResult -> hasSentDm)) - .map(hasSentDm -> sendFeedback(hasSentDm, target, author, reason)) - .flatMap(event::replyEmbeds); - } - - private static RestAction sendDm(@NotNull ISnowflake target, @NotNull String reason, + private static RestAction sendDm(@NotNull ISnowflake target, + @Nullable TemporaryBanData temporaryBanData, @NotNull String reason, @NotNull Guild guild, @NotNull GenericEvent event) { + String durationMessage = + temporaryBanData == null ? "permanently" : "for " + temporaryBanData.duration; + String dmMessage = + """ + Hey there, sorry to tell you but unfortunately you have been banned %s from the server %s. + If you think this was a mistake, please contact a moderator or admin of the server. + The reason for the ban is: %s + """ + .formatted(durationMessage, guild.getName(), reason); + return event.getJDA() .openPrivateChannelById(target.getId()) - .flatMap(channel -> channel.sendMessage( - """ - Hey there, sorry to tell you but unfortunately you have been banned from the server %s. - If you think this was a mistake, please contact a moderator or admin of the server. - The reason for the ban is: %s - """ - .formatted(guild.getName(), reason))) + .flatMap(channel -> channel.sendMessage(dmMessage)) .mapToResult() .map(Result::isSuccess); } - private AuditableRestAction banUser(@NotNull User target, @NotNull Member author, - @NotNull String reason, int deleteHistoryDays, @NotNull Guild guild) { - logger.info( - "'{}' ({}) banned the user '{}' ({}) from guild '{}' and deleted their message history of the last {} days, for reason '{}'.", - author.getUser().getAsTag(), author.getId(), target.getAsTag(), target.getId(), - guild.getName(), deleteHistoryDays, reason); - - actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationUtils.Action.BAN, null, reason); - - return guild.ban(target, deleteHistoryDays, reason); - } - private static @NotNull MessageEmbed sendFeedback(boolean hasSentDm, @NotNull User target, - @NotNull Member author, @NotNull String reason) { + @NotNull Member author, @Nullable TemporaryBanData temporaryBanData, + @NotNull String reason) { + @SuppressWarnings("java:S1192") // this is not the name of the option but the user-friendly + // display text + String durationText = "The ban duration is: " + + (temporaryBanData == null ? "permanent" : temporaryBanData.duration); String dmNoticeText = ""; if (!hasSentDm) { - dmNoticeText = "(Unable to send them a DM.)"; + dmNoticeText = "\n(Unable to send them a DM.)"; } return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.BAN, - target, dmNoticeText, reason); + target, durationText + dmNoticeText, reason); } private static Optional> handleNotAlreadyBannedResponse( @@ -147,6 +145,56 @@ private static Optional> handleNotAlreadyBannedRespo .setEphemeral(true)); } + private static @NotNull Optional computeTemporaryBanData( + @NotNull String durationText) { + if (PERMANENT_DURATION.equals(durationText)) { + return Optional.empty(); + } + + // 1 day, 1 days, 1 month, ... + String[] data = durationText.split(" ", 2); + int duration = Integer.parseInt(data[0]); + ChronoUnit unit = switch (data[1]) { + case "minute", "minutes" -> ChronoUnit.MINUTES; + case "hour", "hours" -> ChronoUnit.HOURS; + case "day", "days" -> ChronoUnit.DAYS; + case "week", "weeks" -> ChronoUnit.WEEKS; + case "month", "months" -> ChronoUnit.MONTHS; + default -> throw new IllegalArgumentException( + "Unsupported ban duration: " + durationText); + }; + + return Optional.of(new TemporaryBanData(Instant.now().plus(duration, unit), durationText)); + } + + @SuppressWarnings("MethodWithTooManyParameters") + private RestAction banUserFlow(@NotNull User target, @NotNull Member author, + @Nullable TemporaryBanData temporaryBanData, @NotNull String reason, + int deleteHistoryDays, @NotNull Guild guild, @NotNull SlashCommandEvent event) { + return sendDm(target, temporaryBanData, reason, guild, event) + .flatMap(hasSentDm -> banUser(target, author, temporaryBanData, reason, + deleteHistoryDays, guild).map(banResult -> hasSentDm)) + .map(hasSentDm -> sendFeedback(hasSentDm, target, author, temporaryBanData, reason)) + .flatMap(event::replyEmbeds); + } + + private AuditableRestAction banUser(@NotNull User target, @NotNull Member author, + @Nullable TemporaryBanData temporaryBanData, @NotNull String reason, + int deleteHistoryDays, @NotNull Guild guild) { + String durationMessage = + temporaryBanData == null ? "permanently" : "for " + temporaryBanData.duration; + logger.info( + "'{}' ({}) banned the user '{}' ({}) {} from guild '{}' and deleted their message history of the last {} days, for reason '{}'.", + author.getUser().getAsTag(), author.getId(), target.getAsTag(), target.getId(), + durationMessage, guild.getName(), deleteHistoryDays, reason); + + Instant expiresAt = temporaryBanData == null ? null : temporaryBanData.unbanTime; + actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), + ModerationUtils.Action.BAN, expiresAt, reason); + + return guild.ban(target, deleteHistoryDays, reason); + } + @SuppressWarnings({"BooleanMethodNameMustStartWithQuestion", "MethodWithTooManyParameters"}) private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @Nullable Member target, @NotNull CharSequence reason, @NotNull Guild guild, @@ -178,9 +226,13 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { Member author = Objects.requireNonNull(event.getMember(), "The author is null"); String reason = Objects.requireNonNull(event.getOption(REASON_OPTION), "The reason is null") .getAsString(); + String duration = + Objects.requireNonNull(event.getOption(DURATION_OPTION), "The duration is null") + .getAsString(); Guild guild = Objects.requireNonNull(event.getGuild()); Member bot = guild.getSelfMember(); + Optional temporaryBanData = computeTemporaryBanData(duration); if (!handleChecks(bot, author, targetOption.getAsMember(), reason, guild, event)) { return; @@ -195,9 +247,14 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { return handleAlreadyBanned(alreadyBanned.get(), event); } - return handleNotAlreadyBannedResponse(Objects - .requireNonNull(alreadyBanned.getFailure()), event, guild, target).orElseGet( - () -> banUserFlow(target, author, reason, deleteHistoryDays, guild, event)); + return handleNotAlreadyBannedResponse( + Objects.requireNonNull(alreadyBanned.getFailure()), event, guild, target) + .orElseGet(() -> banUserFlow(target, author, temporaryBanData.orElse(null), + reason, deleteHistoryDays, guild, event)); }).queue(); } + + + private record TemporaryBanData(@NotNull Instant unbanTime, @NotNull String duration) { + } } From d0efd09e65268eede08b987e9c019026aa85115f Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Wed, 15 Dec 2021 15:32:29 +0100 Subject: [PATCH 03/14] Added temp mute --- .../commands/moderation/MuteCommand.java | 87 +++++++++++++++---- 1 file changed, 72 insertions(+), 15 deletions(-) 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 cb363190fc..7d40974121 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 @@ -5,6 +5,7 @@ import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.interactions.Interaction; import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.requests.restaction.AuditableRestAction; import net.dv8tion.jda.api.utils.Result; @@ -16,7 +17,11 @@ import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; import java.util.Objects; +import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Pattern; @@ -30,9 +35,13 @@ public final class MuteCommand extends SlashCommandAdapter { private static final Logger logger = LoggerFactory.getLogger(MuteCommand.class); private static final String TARGET_OPTION = "user"; + private static final String DURATION_OPTION = "duration"; private static final String REASON_OPTION = "reason"; private static final String COMMAND_NAME = "mute"; private static final String ACTION_VERB = "mute"; + private static final String PERMANENT_DURATION = "permanent"; + private static final List DURATIONS = List.of(PERMANENT_DURATION, "1 hour", "3 hours", + "1 day", "2 days", "3 days", "7 days", "1 month"); private final Predicate hasRequiredRole; private final ModerationActionsStore actionsStore; @@ -45,7 +54,12 @@ public MuteCommand(@NotNull ModerationActionsStore actionsStore) { super(COMMAND_NAME, "Mutes the given user so that they can not send messages anymore", SlashCommandVisibility.GUILD); + OptionData durationData = new OptionData(OptionType.STRING, DURATION_OPTION, + "the duration of the mute, permanent or temporary", true); + DURATIONS.forEach(duration -> durationData.addChoice(duration, duration)); + getData().addOption(OptionType.USER, TARGET_OPTION, "The user who you want to mute", true) + .addOptions(durationData) .addOption(OptionType.STRING, REASON_OPTION, "Why the user should be muted", true); hasRequiredRole = Pattern.compile(Config.getInstance().getSoftModerationRolePattern()) @@ -57,16 +71,19 @@ private static void handleAlreadyMutedTarget(@NotNull Interaction event) { event.reply("The user is already muted.").setEphemeral(true).queue(); } - private static RestAction sendDm(@NotNull ISnowflake target, @NotNull String reason, + private static RestAction sendDm(@NotNull ISnowflake target, + @Nullable TemporaryMuteData temporaryMuteData, @NotNull String reason, @NotNull Guild guild, @NotNull GenericEvent event) { + String durationMessage = + temporaryMuteData == null ? "permanently" : "for " + temporaryMuteData.duration; String dmMessage = """ - Hey there, sorry to tell you but unfortunately you have been muted in the server %s. + 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(guild.getName(), reason); + .formatted(durationMessage, guild.getName(), reason); return event.getJDA() .openPrivateChannelById(target.getId()) .flatMap(channel -> channel.sendMessage(dmMessage)) @@ -75,34 +92,66 @@ private static RestAction sendDm(@NotNull ISnowflake target, @NotNull S } private static @NotNull MessageEmbed sendFeedback(boolean hasSentDm, @NotNull Member target, - @NotNull Member author, @NotNull String reason) { + @NotNull Member author, @Nullable TemporaryMuteData temporaryMuteData, + @NotNull String reason) { + @SuppressWarnings("java:S1192") // this is not the name of the option but the user-friendly + // display text + String durationText = "The mute duration is: " + + (temporaryMuteData == null ? "permanent" : temporaryMuteData.duration); String dmNoticeText = ""; if (!hasSentDm) { - dmNoticeText = "(Unable to send them a DM.)"; + dmNoticeText = "\n(Unable to send them a DM.)"; } return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.MUTE, - target.getUser(), dmNoticeText, reason); + target.getUser(), durationText + dmNoticeText, reason); + } + + private static @NotNull Optional computeTemporaryMuteData( + @NotNull String durationText) { + if (PERMANENT_DURATION.equals(durationText)) { + return Optional.empty(); + } + + // 1 day, 1 days, 1 month, ... + String[] data = durationText.split(" ", 2); + int duration = Integer.parseInt(data[0]); + ChronoUnit unit = switch (data[1]) { + case "minute", "minutes" -> ChronoUnit.MINUTES; + case "hour", "hours" -> ChronoUnit.HOURS; + case "day", "days" -> ChronoUnit.DAYS; + case "week", "weeks" -> ChronoUnit.WEEKS; + case "month", "months" -> ChronoUnit.MONTHS; + default -> throw new IllegalArgumentException( + "Unsupported mute duration: " + durationText); + }; + + return Optional.of(new TemporaryMuteData(Instant.now().plus(duration, unit), durationText)); } private AuditableRestAction muteUser(@NotNull Member target, @NotNull Member author, - @NotNull String reason, @NotNull Guild guild) { - logger.info("'{}' ({}) muted the user '{}' ({}) in guild '{}' for reason '{}'.", + @Nullable TemporaryMuteData temporaryMuteData, @NotNull String reason, + @NotNull Guild guild) { + String durationMessage = + temporaryMuteData == null ? "permanently" : "for " + temporaryMuteData.duration; + logger.info("'{}' ({}) muted the user '{}' ({}) {} in guild '{}' for reason '{}'.", author.getUser().getAsTag(), author.getId(), target.getUser().getAsTag(), - target.getId(), guild.getName(), reason); + target.getId(), durationMessage, guild.getName(), reason); + Instant expiresAt = temporaryMuteData == null ? null : temporaryMuteData.unmuteTime; actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationUtils.Action.MUTE, null, reason); + ModerationUtils.Action.MUTE, expiresAt, reason); return guild.addRoleToMember(target, ModerationUtils.getMutedRole(guild).orElseThrow()) .reason(reason); } private void muteUserFlow(@NotNull Member target, @NotNull Member author, - @NotNull String reason, @NotNull Guild guild, @NotNull SlashCommandEvent event) { - sendDm(target, reason, guild, event) - .flatMap(hasSentDm -> muteUser(target, author, reason, guild) + @Nullable TemporaryMuteData temporaryMuteData, @NotNull String reason, + @NotNull Guild guild, @NotNull SlashCommandEvent event) { + sendDm(target, temporaryMuteData, reason, guild, event) + .flatMap(hasSentDm -> muteUser(target, author, temporaryMuteData, reason, guild) .map(banResult -> hasSentDm)) - .map(hasSentDm -> sendFeedback(hasSentDm, target, author, reason)) + .map(hasSentDm -> sendFeedback(hasSentDm, target, author, temporaryMuteData, reason)) .flatMap(event::replyEmbeds) .queue(); } @@ -134,14 +183,22 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { Member author = Objects.requireNonNull(event.getMember(), "The author is null"); String reason = Objects.requireNonNull(event.getOption(REASON_OPTION), "The reason is null") .getAsString(); + String duration = + Objects.requireNonNull(event.getOption(DURATION_OPTION), "The duration is null") + .getAsString(); Guild guild = Objects.requireNonNull(event.getGuild()); Member bot = guild.getSelfMember(); + Optional temporaryMuteData = computeTemporaryMuteData(duration); if (!handleChecks(bot, author, target, reason, guild, event)) { return; } - muteUserFlow(Objects.requireNonNull(target), author, reason, guild, event); + muteUserFlow(Objects.requireNonNull(target), author, temporaryMuteData.orElse(null), reason, + guild, event); + } + + private record TemporaryMuteData(@NotNull Instant unmuteTime, @NotNull String duration) { } } From 3dcdd07768c1b4ca3d6de52cbb47c9139753b0a2 Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Wed, 15 Dec 2021 15:46:15 +0100 Subject: [PATCH 04/14] Moved ModerationUtils.Action into its own class * It was used quite a lot in the package but also outside, it made no sense anymore to keep it locked down in the utils class. --- .../commands/moderation/ActionRecord.java | 6 +- .../commands/moderation/AuditCommand.java | 4 +- .../tjbot/commands/moderation/BanCommand.java | 6 +- .../commands/moderation/KickCommand.java | 4 +- .../commands/moderation/ModerationAction.java | 52 +++++++++++++++++ .../moderation/ModerationActionsStore.java | 13 ++--- .../commands/moderation/ModerationUtils.java | 58 +------------------ .../commands/moderation/MuteCommand.java | 4 +- .../moderation/RejoinMuteListener.java | 4 +- .../TemporaryModerationRoutine.java | 14 ++--- .../commands/moderation/UnbanCommand.java | 4 +- .../commands/moderation/UnmuteCommand.java | 4 +- 12 files changed, 86 insertions(+), 87 deletions(-) create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationAction.java diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java index dbfb81fa24..b568a2e0d2 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java @@ -21,8 +21,8 @@ * @param reason the reason why this action was executed */ public record ActionRecord(int caseId, @NotNull Instant issuedAt, long guildId, long authorId, - long targetId, @NotNull ModerationUtils.Action actionType, - @Nullable Instant actionExpiresAt, @NotNull String reason) { + long targetId, @NotNull ModerationAction actionType, @Nullable Instant actionExpiresAt, + @NotNull String reason) { /** * Creates the action record that corresponds to the given action entry from the database table. @@ -34,7 +34,7 @@ public record ActionRecord(int caseId, @NotNull Instant issuedAt, long guildId, static @NotNull ActionRecord of(@NotNull ModerationActionsRecord action) { return new ActionRecord(action.getCaseId(), action.getIssuedAt(), action.getGuildId(), action.getAuthorId(), action.getTargetId(), - ModerationUtils.Action.valueOf(action.getActionType()), action.getActionExpiresAt(), + ModerationAction.valueOf(action.getActionType()), action.getActionExpiresAt(), action.getReason()); } } 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 e33f3feded..a9391a5871 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 @@ -71,12 +71,12 @@ public AuditCommand(@NotNull ModerationActionsStore actionsStore) { String shortSummary = "There are **%d actions** against the user.".formatted(actionAmount); // Summary of all actions with their count, like "- Warn: 5", descending - Map actionTypeToCount = actions.stream() + Map actionTypeToCount = actions.stream() .collect(Collectors.groupingBy(ActionRecord::actionType, Collectors.counting())); String typeCountSummary = actionTypeToCount.entrySet() .stream() .filter(typeAndCount -> typeAndCount.getValue() > 0) - .sorted(Map.Entry.comparingByValue().reversed()) + .sorted(Map.Entry.comparingByValue().reversed()) .map(typeAndCount -> "- **%s**: %d".formatted(typeAndCount.getKey(), typeAndCount.getValue())) .collect(Collectors.joining("\n")); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java index a55f78bd75..83cea60c1c 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java @@ -118,8 +118,8 @@ private static RestAction sendDm(@NotNull ISnowflake target, if (!hasSentDm) { dmNoticeText = "\n(Unable to send them a DM.)"; } - return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.BAN, - target, durationText + dmNoticeText, reason); + return ModerationUtils.createActionResponse(author.getUser(), ModerationAction.BAN, target, + durationText + dmNoticeText, reason); } private static Optional> handleNotAlreadyBannedResponse( @@ -190,7 +190,7 @@ private AuditableRestAction banUser(@NotNull User target, @NotNull Member Instant expiresAt = temporaryBanData == null ? null : temporaryBanData.unbanTime; actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationUtils.Action.BAN, expiresAt, reason); + ModerationAction.BAN, expiresAt, reason); return guild.ban(target, deleteHistoryDays, reason); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java index 731e3ef83d..8c9fcf5dfe 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java @@ -92,7 +92,7 @@ private AuditableRestAction kickUser(@NotNull Member target, @NotNull Memb target.getId(), guild.getName(), reason); actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationUtils.Action.KICK, null, reason); + ModerationAction.KICK, null, reason); return guild.kick(target, reason).reason(reason); } @@ -103,7 +103,7 @@ private AuditableRestAction kickUser(@NotNull Member target, @NotNull Memb if (!hasSentDm) { dmNoticeText = "(Unable to send them a DM.)"; } - return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.KICK, + return ModerationUtils.createActionResponse(author.getUser(), ModerationAction.KICK, target.getUser(), dmNoticeText, reason); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationAction.java new file mode 100644 index 0000000000..fe9e9c774d --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationAction.java @@ -0,0 +1,52 @@ +package org.togetherjava.tjbot.commands.moderation; + +import org.jetbrains.annotations.NotNull; + +/** + * All available moderation actions. + */ +public enum ModerationAction { + /** + * When a user bans another user. + */ + BAN("banned"), + /** + * When a user unbans another user. + */ + UNBAN("unbanned"), + /** + * When a user kicks another user. + */ + KICK("kicked"), + /** + * When a user mutes another user. + */ + MUTE("muted"), + /** + * When a user unmutes another user. + */ + UNMUTE("unmuted"); + + private final String verb; + + /** + * Creates an instance with the given verb + * + * @param verb the verb of the action, as it would be used in a sentence, such as "banned" or + * "kicked" + */ + ModerationAction(@NotNull String verb) { + this.verb = verb; + } + + /** + * Gets the verb of the action, as it would be used in a sentence. + *

+ * Such as "banned" or "kicked" + * + * @return the verb of this action + */ + public @NotNull String getVerb() { + return verb; + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java index f2c160e1bd..3f2b5f56cc 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java @@ -17,10 +17,9 @@ * past events, such as when a user has been banned the last time. *

* Actions have to be added to the store using - * {@link #addAction(long, long, long, ModerationUtils.Action, Instant, String)} at the time they - * are executed and can then be retrieved by methods such as - * {@link #getActionsByTypeAscending(long, ModerationUtils.Action)} or - * {@link #findActionByCaseId(int)}. + * {@link #addAction(long, long, long, ModerationAction, Instant, String)} at the time they are + * executed and can then be retrieved by methods such as + * {@link #getActionsByTypeAscending(long, ModerationAction)} or {@link #findActionByCaseId(int)}. *

* Be aware that timestamps associated with actions, such as {@link ActionRecord#issuedAt()} are * slightly off the timestamps used by Discord. @@ -58,7 +57,7 @@ public ModerationActionsStore(@NotNull Database database) { * @return a list of all actions with the given type, chronologically ascending */ public @NotNull List getActionsByTypeAscending(long guildId, - @NotNull ModerationUtils.Action actionType) { + @NotNull ModerationAction actionType) { Objects.requireNonNull(actionType); return getActionsFromGuildAscending(guildId, @@ -95,7 +94,7 @@ public ModerationActionsStore(@NotNull Database database) { // FIXME javadoc public @NotNull Optional findLastActionAgainstTargetByType(long guildId, - long targetId, @NotNull ModerationUtils.Action actionType) { + long targetId, @NotNull ModerationAction actionType) { return Optional.of(database.read(context -> context .selectFrom(ModerationActions.MODERATION_ACTIONS) .where(ModerationActions.MODERATION_ACTIONS.GUILD_ID.eq(guildId) @@ -139,7 +138,7 @@ public ModerationActionsStore(@NotNull Database database) { */ @SuppressWarnings("MethodWithTooManyParameters") public int addAction(long guildId, long authorId, long targetId, - @NotNull ModerationUtils.Action actionType, @Nullable Instant actionExpiresAt, + @NotNull ModerationAction actionType, @Nullable Instant actionExpiresAt, @NotNull String reason) { Objects.requireNonNull(actionType); Objects.requireNonNull(reason); 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 524d72ee1e..c1fab54b70 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 @@ -298,8 +298,9 @@ static boolean handleHasAuthorRole(@NotNull String actionVerb, * @param reason an optional reason for why the action is executed, {@code null} if not desired * @return the created response */ - static @NotNull MessageEmbed createActionResponse(@NotNull User author, @NotNull Action action, - @NotNull User target, @Nullable String extraMessage, @Nullable String reason) { + static @NotNull MessageEmbed createActionResponse(@NotNull User author, + @NotNull ModerationAction action, @NotNull User target, @Nullable String extraMessage, + @Nullable String reason) { String description = "%s **%s** (id: %s).".formatted(action.getVerb(), target.getAsTag(), target.getId()); if (extraMessage != null && !extraMessage.isBlank()) { @@ -325,57 +326,4 @@ static boolean handleHasAuthorRole(@NotNull String actionVerb, return guild.getRoles().stream().filter(role -> isMuteRole.test(role.getName())).findAny(); } - /** - * All available moderation actions. - */ - enum Action { - /** - * When a user bans another user. - */ - BAN("banned"), - /** - * When a user unbans another user. - */ - UNBAN("unbanned"), - /** - * When a user kicks another user. - */ - KICK("kicked"), - /** - * When a user warns another user. - */ - WARN("warned"), - /** - * When a user mutes another user. - */ - MUTE("muted"), - /** - * When a user unmutes another user. - */ - UNMUTE("unmuted"); - - private final String verb; - - /** - * Creates an instance with the given verb - * - * @param verb the verb of the action, as it would be used in a sentence, such as "banned" - * or "kicked" - */ - Action(@NotNull String verb) { - this.verb = verb; - } - - /** - * Gets the verb of the action, as it would be used in a sentence. - *

- * Such as "banned" or "kicked" - * - * @return the verb of this action - */ - @NotNull - String getVerb() { - return verb; - } - } } 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 7d40974121..d2545bdbbc 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 @@ -102,7 +102,7 @@ private static RestAction sendDm(@NotNull ISnowflake target, if (!hasSentDm) { dmNoticeText = "\n(Unable to send them a DM.)"; } - return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.MUTE, + return ModerationUtils.createActionResponse(author.getUser(), ModerationAction.MUTE, target.getUser(), durationText + dmNoticeText, reason); } @@ -139,7 +139,7 @@ private AuditableRestAction muteUser(@NotNull Member target, @NotNull Memb Instant expiresAt = temporaryMuteData == null ? null : temporaryMuteData.unmuteTime; actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationUtils.Action.MUTE, expiresAt, reason); + ModerationAction.MUTE, expiresAt, reason); return guild.addRoleToMember(target, ModerationUtils.getMutedRole(guild).orElseThrow()) .reason(reason); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/RejoinMuteListener.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/RejoinMuteListener.java index 0278ce1c7c..793126513e 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/RejoinMuteListener.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/RejoinMuteListener.java @@ -60,7 +60,7 @@ private boolean shouldMemberBeMuted(@NotNull IPermissionHolder member) { Collections.reverse(actions); Optional lastMute = actions.stream() - .filter(action -> action.actionType() == ModerationUtils.Action.MUTE) + .filter(action -> action.actionType() == ModerationAction.MUTE) .findFirst(); if (lastMute.isEmpty()) { // User was never muted @@ -68,7 +68,7 @@ private boolean shouldMemberBeMuted(@NotNull IPermissionHolder member) { } Optional lastUnmute = actions.stream() - .filter(action -> action.actionType() == ModerationUtils.Action.UNMUTE) + .filter(action -> action.actionType() == ModerationAction.UNMUTE) .findFirst(); if (lastUnmute.isEmpty()) { // User was never unmuted diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/TemporaryModerationRoutine.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/TemporaryModerationRoutine.java index 1189199df6..b3e7a2e213 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/TemporaryModerationRoutine.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/TemporaryModerationRoutine.java @@ -20,8 +20,8 @@ // FIXME javadoc public final class TemporaryModerationRoutine { private static final Logger logger = LoggerFactory.getLogger(TemporaryModerationRoutine.class); - private static final Set REVOCABLE_ACTIONS = - EnumSet.of(ModerationUtils.Action.BAN, ModerationUtils.Action.MUTE); + private static final Set REVOCABLE_ACTIONS = + EnumSet.of(ModerationAction.BAN, ModerationAction.MUTE); private final ModerationActionsStore actionsStore; private final JDA jda; @@ -96,9 +96,9 @@ private void processGroupedActions(@NotNull RevocationGroupIdentifier groupIdent // Do not revoke an action which was already revoked by another action issued afterwards // For example if a user was unbanned manually after being temp-banned, // but also if the system automatically revoked a temp-ban already itself - ModerationUtils.Action revokeActionType = switch (groupIdentifier.type) { - case BAN -> ModerationUtils.Action.UNBAN; - case MUTE -> ModerationUtils.Action.UNMUTE; + ModerationAction revokeActionType = switch (groupIdentifier.type) { + case BAN -> ModerationAction.UNBAN; + case MUTE -> ModerationAction.UNMUTE; default -> throw new AssertionError("Unsupported action type: " + groupIdentifier.type); }; ActionRecord lastRevokeAction = actionsStore @@ -134,7 +134,7 @@ private void revokeAction(@NotNull RevocationGroupIdentifier groupIdentifier) { } private @NotNull AuditableRestAction executeRevocation(@NotNull Guild guild, - @NotNull User target, @NotNull ModerationUtils.Action actionType) { + @NotNull User target, @NotNull ModerationAction actionType) { logger.info("Revoked temporary action {} against user '{}' ({}).", actionType, target.getAsTag(), target.getId()); @@ -162,7 +162,7 @@ public void start() { } private record RevocationGroupIdentifier(long guildId, long targetId, - @NotNull ModerationUtils.Action type) { + @NotNull ModerationAction type) { public static RevocationGroupIdentifier of(@NotNull ActionRecord actionRecord) { return new RevocationGroupIdentifier(actionRecord.guildId(), actionRecord.targetId(), actionRecord.actionType()); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnbanCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnbanCommand.java index b44daa3730..516ee88183 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnbanCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnbanCommand.java @@ -53,7 +53,7 @@ private void unban(@NotNull User target, @NotNull Member author, @NotNull String @NotNull Guild guild, @NotNull Interaction event) { guild.unban(target).reason(reason).queue(result -> { MessageEmbed message = ModerationUtils.createActionResponse(author.getUser(), - ModerationUtils.Action.UNBAN, target, null, reason); + ModerationAction.UNBAN, target, null, reason); event.replyEmbeds(message).queue(); logger.info("'{}' ({}) unbanned the user '{}' ({}) from guild '{}' for reason '{}'.", @@ -61,7 +61,7 @@ private void unban(@NotNull User target, @NotNull Member author, @NotNull String guild.getName(), reason); actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationUtils.Action.UNBAN, null, reason); + ModerationAction.UNBAN, null, reason); }, unbanFailure -> handleFailure(unbanFailure, target, event)); } 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 6828981c68..fcd0f66a31 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 @@ -78,7 +78,7 @@ private static RestAction sendDm(@NotNull ISnowflake target, @NotNull S if (!hasSentDm) { dmNoticeText = "(Unable to send them a DM.)"; } - return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.UNMUTE, + return ModerationUtils.createActionResponse(author.getUser(), ModerationAction.UNMUTE, target.getUser(), dmNoticeText, reason); } @@ -89,7 +89,7 @@ private AuditableRestAction unmuteUser(@NotNull Member target, @NotNull Me target.getId(), guild.getName(), reason); actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationUtils.Action.UNMUTE, null, reason); + ModerationAction.UNMUTE, null, reason); return guild.removeRoleFromMember(target, ModerationUtils.getMutedRole(guild).orElseThrow()) .reason(reason); From 3fc945525f16da852b58f4c709f975fda38f420e Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Wed, 15 Dec 2021 15:48:44 +0100 Subject: [PATCH 05/14] Moved TempMod routine into subpackage it will get more classes soon --- .../main/java/org/togetherjava/tjbot/commands/Commands.java | 1 + .../moderation/{ => temp}/TemporaryModerationRoutine.java | 6 +++++- .../tjbot/commands/moderation/temp/package-info.java | 4 ++++ 3 files changed, 10 insertions(+), 1 deletion(-) rename application/src/main/java/org/togetherjava/tjbot/commands/moderation/{ => temp}/TemporaryModerationRoutine.java (95%) create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/package-info.java diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java index 1aecb6c762..556ea519d2 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -7,6 +7,7 @@ import org.togetherjava.tjbot.commands.free.FreeCommand; import org.togetherjava.tjbot.commands.mathcommands.TeXCommand; import org.togetherjava.tjbot.commands.moderation.*; +import org.togetherjava.tjbot.commands.moderation.temp.TemporaryModerationRoutine; import org.togetherjava.tjbot.commands.tags.TagCommand; import org.togetherjava.tjbot.commands.tags.TagManageCommand; import org.togetherjava.tjbot.commands.tags.TagSystem; diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/TemporaryModerationRoutine.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java similarity index 95% rename from application/src/main/java/org/togetherjava/tjbot/commands/moderation/TemporaryModerationRoutine.java rename to application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java index b3e7a2e213..2e634bed5f 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/TemporaryModerationRoutine.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java @@ -1,4 +1,4 @@ -package org.togetherjava.tjbot.commands.moderation; +package org.togetherjava.tjbot.commands.moderation.temp; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.Guild; @@ -9,6 +9,10 @@ import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.moderation.ActionRecord; +import org.togetherjava.tjbot.commands.moderation.ModerationAction; +import org.togetherjava.tjbot.commands.moderation.ModerationActionsStore; +import org.togetherjava.tjbot.commands.moderation.ModerationUtils; import java.time.Instant; import java.util.*; diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/package-info.java new file mode 100644 index 0000000000..ba0fe1bbe9 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/package-info.java @@ -0,0 +1,4 @@ +/** + * This package offers classes dealing with temporary moderation actions, such as temporary bans. + */ +package org.togetherjava.tjbot.commands.moderation.temp; From 5428f60f35f629da4c843f8d92e0b258cb19a8c7 Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Wed, 15 Dec 2021 16:15:15 +0100 Subject: [PATCH 06/14] Simplified vertical scalability of temp actions, removed duplication * temporary moderation actions can now be added easily via interface instead of being all mushed into the main logic class --- .../temp/RevocableModerationAction.java | 28 +++++++ .../moderation/temp/TemporaryBanAction.java | 53 ++++++++++++ .../temp/TemporaryModerationRoutine.java | 82 ++++++++----------- .../moderation/temp/TemporaryMuteAction.java | 50 +++++++++++ 4 files changed, 166 insertions(+), 47 deletions(-) create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/RevocableModerationAction.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryBanAction.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryMuteAction.java diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/RevocableModerationAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/RevocableModerationAction.java new file mode 100644 index 0000000000..70f6b2bf93 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/RevocableModerationAction.java @@ -0,0 +1,28 @@ +package org.togetherjava.tjbot.commands.moderation.temp; + +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.requests.RestAction; +import org.jetbrains.annotations.NotNull; +import org.togetherjava.tjbot.commands.moderation.ModerationAction; + +// FIXME Javadoc +interface RevocableModerationAction { + enum FailureIdentification { + KNOWN, + UNKNOWN + } + + @NotNull + ModerationAction getApplyType(); + + @NotNull + ModerationAction getRevokeType(); + + @NotNull + RestAction revokeAction(@NotNull Guild guild, @NotNull User target, + @NotNull String reason); + + @NotNull + FailureIdentification handleRevokeFailure(@NotNull Throwable failure, long targetId); +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryBanAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryBanAction.java new file mode 100644 index 0000000000..ddee6a5064 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryBanAction.java @@ -0,0 +1,53 @@ +package org.togetherjava.tjbot.commands.moderation.temp; + +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.exceptions.ErrorResponseException; +import net.dv8tion.jda.api.requests.ErrorResponse; +import net.dv8tion.jda.api.requests.RestAction; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.moderation.ModerationAction; + +// FIXME Javadoc +final class TemporaryBanAction implements RevocableModerationAction { + private static final Logger logger = LoggerFactory.getLogger(TemporaryBanAction.class); + + @Override + public @NotNull ModerationAction getApplyType() { + return ModerationAction.BAN; + } + + @Override + public @NotNull ModerationAction getRevokeType() { + return ModerationAction.UNBAN; + } + + @Override + public @NotNull RestAction revokeAction(@NotNull Guild guild, @NotNull User target, + @NotNull String reason) { + return guild.unban(target).reason(reason); + } + + @Override + public @NotNull FailureIdentification handleRevokeFailure(@NotNull Throwable failure, + long targetId) { + if (failure instanceof ErrorResponseException errorResponseException) { + if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_USER) { + logger.info( + "Attempted to revoke a temporary ban but user '{}' does not exist anymore.", + targetId); + return FailureIdentification.KNOWN; + } + + if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_BAN) { + logger.info( + "Attempted to revoke a temporary ban but the user '{}' is not banned anymore.", + targetId); + return FailureIdentification.KNOWN; + } + } + return FailureIdentification.UNKNOWN; + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java index 2e634bed5f..7c53780116 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java @@ -3,34 +3,35 @@ import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.User; -import net.dv8tion.jda.api.exceptions.ErrorResponseException; -import net.dv8tion.jda.api.requests.ErrorResponse; -import net.dv8tion.jda.api.requests.restaction.AuditableRestAction; +import net.dv8tion.jda.api.requests.RestAction; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.togetherjava.tjbot.commands.moderation.ActionRecord; import org.togetherjava.tjbot.commands.moderation.ModerationAction; import org.togetherjava.tjbot.commands.moderation.ModerationActionsStore; -import org.togetherjava.tjbot.commands.moderation.ModerationUtils; import java.time.Instant; -import java.util.*; +import java.util.Collection; +import java.util.Comparator; +import java.util.Map; +import java.util.Objects; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import java.util.function.Function; import java.util.stream.Collectors; +import java.util.stream.Stream; // FIXME javadoc public final class TemporaryModerationRoutine { private static final Logger logger = LoggerFactory.getLogger(TemporaryModerationRoutine.class); - private static final Set REVOCABLE_ACTIONS = - EnumSet.of(ModerationAction.BAN, ModerationAction.MUTE); private final ModerationActionsStore actionsStore; private final JDA jda; private final ScheduledExecutorService checkExpiredActionsService = Executors.newSingleThreadScheduledExecutor(); + private final Map typeToRevocableAction; /** * Creates a new instance. @@ -42,29 +43,10 @@ public TemporaryModerationRoutine(@NotNull JDA jda, @NotNull ModerationActionsStore actionsStore) { this.actionsStore = actionsStore; this.jda = jda; - } - - private static void handleFailure(@NotNull Throwable failure, - @NotNull RevocationGroupIdentifier groupIdentifier) { - if (failure instanceof ErrorResponseException errorResponseException) { - if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_USER) { - logger.info( - "Attempted to revoke a temporary moderation action but user '{}' does not exist anymore.", - groupIdentifier.targetId); - return; - } - - if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_BAN) { - logger.info( - "Attempted to revoke a temporary moderation action but the action is not relevant for user '{}' anymore.", - groupIdentifier.targetId); - return; - } - } - logger.warn( - "Attempted to revoke a temporary moderation action for user '{}' but something unexpected went wrong.", - groupIdentifier.targetId, failure); + typeToRevocableAction = Stream.of(new TemporaryBanAction(), new TemporaryMuteAction()) + .collect( + Collectors.toMap(RevocableModerationAction::getApplyType, Function.identity())); } private void checkExpiredActions() { @@ -72,7 +54,7 @@ private void checkExpiredActions() { actionsStore.getExpiredActionsAscending() .stream() - .filter(action -> REVOCABLE_ACTIONS.contains(action.actionType())) + .filter(action -> typeToRevocableAction.containsKey(action.actionType())) .collect(Collectors.groupingBy(RevocationGroupIdentifier::of)) .forEach(this::processGroupedActions); @@ -100,11 +82,8 @@ private void processGroupedActions(@NotNull RevocationGroupIdentifier groupIdent // Do not revoke an action which was already revoked by another action issued afterwards // For example if a user was unbanned manually after being temp-banned, // but also if the system automatically revoked a temp-ban already itself - ModerationAction revokeActionType = switch (groupIdentifier.type) { - case BAN -> ModerationAction.UNBAN; - case MUTE -> ModerationAction.UNMUTE; - default -> throw new AssertionError("Unsupported action type: " + groupIdentifier.type); - }; + ModerationAction revokeActionType = + getRevocableActionByType(groupIdentifier.type).getRevokeType(); ActionRecord lastRevokeAction = actionsStore .findLastActionAgainstTargetByType(groupIdentifier.guildId, groupIdentifier.targetId, revokeActionType) @@ -119,10 +98,6 @@ private void processGroupedActions(@NotNull RevocationGroupIdentifier groupIdent } private void revokeAction(@NotNull RevocationGroupIdentifier groupIdentifier) { - if (!REVOCABLE_ACTIONS.contains(groupIdentifier.type)) { - throw new AssertionError("Unsupported action type: " + groupIdentifier.type); - } - Guild guild = jda.getGuildById(groupIdentifier.guildId); if (guild == null) { logger.info( @@ -137,8 +112,8 @@ private void revokeAction(@NotNull RevocationGroupIdentifier groupIdentifier) { }, failure -> handleFailure(failure, groupIdentifier)); } - private @NotNull AuditableRestAction executeRevocation(@NotNull Guild guild, - @NotNull User target, @NotNull ModerationAction actionType) { + private @NotNull RestAction executeRevocation(@NotNull Guild guild, @NotNull User target, + @NotNull ModerationAction actionType) { logger.info("Revoked temporary action {} against user '{}' ({}).", actionType, target.getAsTag(), target.getId()); @@ -146,12 +121,25 @@ private void revokeAction(@NotNull RevocationGroupIdentifier groupIdentifier) { actionsStore.addAction(guild.getIdLong(), jda.getSelfUser().getIdLong(), target.getIdLong(), actionType, null, reason); - return (switch (actionType) { - case BAN -> guild.unban(target); - case MUTE -> guild.removeRoleFromMember(target.getIdLong(), - ModerationUtils.getMutedRole(guild).orElseThrow()); - default -> throw new AssertionError("Unsupported action type: " + actionType); - }).reason(reason); + return getRevocableActionByType(actionType).revokeAction(guild, target, reason); + } + + private void handleFailure(@NotNull Throwable failure, + @NotNull RevocationGroupIdentifier groupIdentifier) { + if (getRevocableActionByType(groupIdentifier.type).handleRevokeFailure(failure, + groupIdentifier.targetId) == RevocableModerationAction.FailureIdentification.KNOWN) { + return; + } + + logger.warn( + "Attempted to revoke a temporary moderation action for user '{}' but something unexpected went wrong.", + groupIdentifier.targetId, failure); + } + + private @NotNull RevocableModerationAction getRevocableActionByType( + @NotNull ModerationAction type) { + return Objects.requireNonNull(typeToRevocableAction.get(type), + "Action type is not revocable: " + type); } /** diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryMuteAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryMuteAction.java new file mode 100644 index 0000000000..006423987b --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryMuteAction.java @@ -0,0 +1,50 @@ +package org.togetherjava.tjbot.commands.moderation.temp; + +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.exceptions.ErrorResponseException; +import net.dv8tion.jda.api.requests.ErrorResponse; +import net.dv8tion.jda.api.requests.RestAction; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.moderation.ModerationAction; +import org.togetherjava.tjbot.commands.moderation.ModerationUtils; + +// FIXME Javadoc +final class TemporaryMuteAction implements RevocableModerationAction { + private static final Logger logger = LoggerFactory.getLogger(TemporaryMuteAction.class); + + @Override + public @NotNull ModerationAction getApplyType() { + return ModerationAction.MUTE; + } + + @Override + public @NotNull ModerationAction getRevokeType() { + return ModerationAction.UNMUTE; + } + + @Override + public @NotNull RestAction revokeAction(@NotNull Guild guild, @NotNull User target, + @NotNull String reason) { + return guild + .removeRoleFromMember(target.getIdLong(), + ModerationUtils.getMutedRole(guild).orElseThrow()) + .reason(reason); + } + + @Override + public @NotNull FailureIdentification handleRevokeFailure(@NotNull Throwable failure, + long targetId) { + if (failure instanceof ErrorResponseException errorResponseException) { + if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_USER) { + logger.info( + "Attempted to revoke a temporary mute but user '{}' does not exist anymore.", + targetId); + return FailureIdentification.KNOWN; + } + } + return FailureIdentification.UNKNOWN; + } +} From d6bea33126e513a26f3800a881ad3569994f8d92 Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Wed, 15 Dec 2021 18:59:33 +0100 Subject: [PATCH 07/14] Temp action bugfix and code improvement * database returns multiple results, forgot limit(1) * logic mistake of using last expired action instead of last temp action (implicitly given by last action that passes the "not permanent" check) * can use `fetchOptional` with database * added note regarding startup race condition issue --- .../moderation/ModerationActionsStore.java | 22 ++++++++++--------- .../temp/TemporaryModerationRoutine.java | 21 ++++++++---------- 2 files changed, 21 insertions(+), 22 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java index 3f2b5f56cc..f0de5cc25c 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java @@ -95,13 +95,15 @@ public ModerationActionsStore(@NotNull Database database) { // FIXME javadoc public @NotNull Optional findLastActionAgainstTargetByType(long guildId, long targetId, @NotNull ModerationAction actionType) { - return Optional.of(database.read(context -> context - .selectFrom(ModerationActions.MODERATION_ACTIONS) - .where(ModerationActions.MODERATION_ACTIONS.GUILD_ID.eq(guildId) - .and(ModerationActions.MODERATION_ACTIONS.TARGET_ID.eq(targetId) - .and(ModerationActions.MODERATION_ACTIONS.ACTION_TYPE.eq(actionType.name())))) - .orderBy(ModerationActions.MODERATION_ACTIONS.ISSUED_AT.desc()) - .fetchOne())).map(ActionRecord::of); + return database + .read(context -> context.selectFrom(ModerationActions.MODERATION_ACTIONS) + .where(ModerationActions.MODERATION_ACTIONS.GUILD_ID.eq(guildId) + .and(ModerationActions.MODERATION_ACTIONS.TARGET_ID.eq(targetId)) + .and(ModerationActions.MODERATION_ACTIONS.ACTION_TYPE.eq(actionType.name()))) + .orderBy(ModerationActions.MODERATION_ACTIONS.ISSUED_AT.desc()) + .limit(1) + .fetchOptional()) + .map(ActionRecord::of); } /** @@ -111,10 +113,10 @@ public ModerationActionsStore(@NotNull Database database) { * @return the action with the given case id, if present */ public @NotNull Optional findActionByCaseId(int caseId) { - return Optional - .of(database.read(context -> context.selectFrom(ModerationActions.MODERATION_ACTIONS) + return database + .read(context -> context.selectFrom(ModerationActions.MODERATION_ACTIONS) .where(ModerationActions.MODERATION_ACTIONS.CASE_ID.eq(caseId)) - .fetchOne())) + .fetchOptional()) .map(ActionRecord::of); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java index 7c53780116..2dd2bf49aa 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java @@ -55,27 +55,22 @@ private void checkExpiredActions() { actionsStore.getExpiredActionsAscending() .stream() .filter(action -> typeToRevocableAction.containsKey(action.actionType())) - .collect(Collectors.groupingBy(RevocationGroupIdentifier::of)) + .map(RevocationGroupIdentifier::of) + .collect(Collectors.toSet()) .forEach(this::processGroupedActions); logger.debug("Finished checking expired temporary moderation actions to revoke."); } - private void processGroupedActions(@NotNull RevocationGroupIdentifier groupIdentifier, - @NotNull Collection expiredActions) { - // Last issued temporary action takes priority - ActionRecord actionToRevoke = expiredActions.stream() - .max(Comparator.comparing(ActionRecord::issuedAt)) - .orElseThrow(); - + private void processGroupedActions(@NotNull RevocationGroupIdentifier groupIdentifier) { // Do not revoke an action which was overwritten by a permanent action that was issued // afterwards // For example if a user was perm-banned after being temp-banned - ActionRecord lastAction = actionsStore + ActionRecord lastApplyAction = actionsStore .findLastActionAgainstTargetByType(groupIdentifier.guildId, groupIdentifier.targetId, groupIdentifier.type) .orElseThrow(); - if (lastAction.actionExpiresAt() == null) { + if (lastApplyAction.actionExpiresAt() == null) { return; } @@ -88,7 +83,7 @@ private void processGroupedActions(@NotNull RevocationGroupIdentifier groupIdent .findLastActionAgainstTargetByType(groupIdentifier.guildId, groupIdentifier.targetId, revokeActionType) .orElseThrow(); - if (lastRevokeAction.issuedAt().isAfter(actionToRevoke.issuedAt()) + if (lastRevokeAction.issuedAt().isAfter(lastApplyAction.issuedAt()) && (lastRevokeAction.actionExpiresAt() == null || lastRevokeAction.actionExpiresAt().isAfter(Instant.now()))) { return; @@ -149,7 +144,9 @@ private void handleFailure(@NotNull Throwable failure, public void start() { // TODO This should be registered at some sort of routine system instead (see GH issue #235 // which adds support for routines) - checkExpiredActionsService.scheduleWithFixedDelay(this::checkExpiredActions, 0, 5, + // NOTE The initial run has to be delayed until after the guild cache has been updated + // (during CommandSystem startup) + checkExpiredActionsService.scheduleWithFixedDelay(this::checkExpiredActions, 5, 5, TimeUnit.MINUTES); } From 169d131dce4e439593eae24011c5c77e4ac71aff Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Wed, 15 Dec 2021 19:10:20 +0100 Subject: [PATCH 08/14] Bugfix with temp ban/mute using weeks/months * cant Instant#plus weeks and months * also some improvements to the option order (UX) * added fixme for code duplication --- .../tjbot/commands/moderation/BanCommand.java | 6 ++---- .../tjbot/commands/moderation/MuteCommand.java | 9 ++++----- .../moderation/temp/TemporaryModerationRoutine.java | 2 -- 3 files changed, 6 insertions(+), 11 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java index 83cea60c1c..12444a307d 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java @@ -48,7 +48,7 @@ public final class BanCommand extends SlashCommandAdapter { private static final String ACTION_VERB = "ban"; private static final String PERMANENT_DURATION = "permanent"; private static final List DURATIONS = List.of(PERMANENT_DURATION, "1 hour", "3 hours", - "1 day", "2 days", "3 days", "7 days", "1 month"); + "1 day", "2 days", "3 days", "7 days", "30 days"); private final Predicate hasRequiredRole; private final ModerationActionsStore actionsStore; @@ -151,15 +151,13 @@ private static Optional> handleNotAlreadyBannedRespo return Optional.empty(); } - // 1 day, 1 days, 1 month, ... + // 1 minute, 1 day, 2 days, ... String[] data = durationText.split(" ", 2); int duration = Integer.parseInt(data[0]); ChronoUnit unit = switch (data[1]) { case "minute", "minutes" -> ChronoUnit.MINUTES; case "hour", "hours" -> ChronoUnit.HOURS; case "day", "days" -> ChronoUnit.DAYS; - case "week", "weeks" -> ChronoUnit.WEEKS; - case "month", "months" -> ChronoUnit.MONTHS; default -> throw new IllegalArgumentException( "Unsupported ban duration: " + durationText); }; 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 d2545bdbbc..dfdbf099c7 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 @@ -40,8 +40,8 @@ public final class MuteCommand extends SlashCommandAdapter { private static final String COMMAND_NAME = "mute"; private static final String ACTION_VERB = "mute"; private static final String PERMANENT_DURATION = "permanent"; - private static final List DURATIONS = List.of(PERMANENT_DURATION, "1 hour", "3 hours", - "1 day", "2 days", "3 days", "7 days", "1 month"); + private static final List DURATIONS = List.of("10 minutes", "30 minutes", "1 hour", + "3 hours", "1 day", "3 days", "7 days", PERMANENT_DURATION); private final Predicate hasRequiredRole; private final ModerationActionsStore actionsStore; @@ -106,21 +106,20 @@ private static RestAction sendDm(@NotNull ISnowflake target, target.getUser(), durationText + dmNoticeText, reason); } + // FIXME Code duplication with BanCommand, get rid of it private static @NotNull Optional computeTemporaryMuteData( @NotNull String durationText) { if (PERMANENT_DURATION.equals(durationText)) { return Optional.empty(); } - // 1 day, 1 days, 1 month, ... + // 1 minute, 1 day, 2 days, ... String[] data = durationText.split(" ", 2); int duration = Integer.parseInt(data[0]); ChronoUnit unit = switch (data[1]) { case "minute", "minutes" -> ChronoUnit.MINUTES; case "hour", "hours" -> ChronoUnit.HOURS; case "day", "days" -> ChronoUnit.DAYS; - case "week", "weeks" -> ChronoUnit.WEEKS; - case "month", "months" -> ChronoUnit.MONTHS; default -> throw new IllegalArgumentException( "Unsupported mute duration: " + durationText); }; diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java index 2dd2bf49aa..63940cf99c 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java @@ -12,8 +12,6 @@ import org.togetherjava.tjbot.commands.moderation.ModerationActionsStore; import java.time.Instant; -import java.util.Collection; -import java.util.Comparator; import java.util.Map; import java.util.Objects; import java.util.concurrent.Executors; From a04914d1143da14316b0ac5a0ae85cf92612a0ab Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Thu, 16 Dec 2021 09:17:12 +0100 Subject: [PATCH 09/14] Reduced code duplication * moved temporary data computation into util --- .../tjbot/commands/moderation/BanCommand.java | 61 ++++++------------- .../commands/moderation/ModerationUtils.java | 26 ++++++++ .../commands/moderation/MuteCommand.java | 57 +++++------------ 3 files changed, 58 insertions(+), 86 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java index 12444a307d..737ac7869e 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java @@ -23,7 +23,6 @@ import org.togetherjava.tjbot.config.Config; import java.time.Instant; -import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -46,9 +45,8 @@ public final class BanCommand extends SlashCommandAdapter { private static final String REASON_OPTION = "reason"; private static final String COMMAND_NAME = "ban"; private static final String ACTION_VERB = "ban"; - private static final String PERMANENT_DURATION = "permanent"; - private static final List DURATIONS = List.of(PERMANENT_DURATION, "1 hour", "3 hours", - "1 day", "2 days", "3 days", "7 days", "30 days"); + private static final List DURATIONS = List.of(ModerationUtils.PERMANENT_DURATION, + "1 hour", "3 hours", "1 day", "2 days", "3 days", "7 days", "30 days"); private final Predicate hasRequiredRole; private final ModerationActionsStore actionsStore; @@ -88,10 +86,10 @@ private static RestAction handleAlreadyBanned(@NotNull Guild.Ba } private static RestAction sendDm(@NotNull ISnowflake target, - @Nullable TemporaryBanData temporaryBanData, @NotNull String reason, + @Nullable ModerationUtils.TemporaryData temporaryData, @NotNull String reason, @NotNull Guild guild, @NotNull GenericEvent event) { String durationMessage = - temporaryBanData == null ? "permanently" : "for " + temporaryBanData.duration; + temporaryData == null ? "permanently" : "for " + temporaryData.duration(); String dmMessage = """ Hey there, sorry to tell you but unfortunately you have been banned %s from the server %s. @@ -108,12 +106,10 @@ private static RestAction sendDm(@NotNull ISnowflake target, } private static @NotNull MessageEmbed sendFeedback(boolean hasSentDm, @NotNull User target, - @NotNull Member author, @Nullable TemporaryBanData temporaryBanData, + @NotNull Member author, @Nullable ModerationUtils.TemporaryData temporaryData, @NotNull String reason) { - @SuppressWarnings("java:S1192") // this is not the name of the option but the user-friendly - // display text String durationText = "The ban duration is: " - + (temporaryBanData == null ? "permanent" : temporaryBanData.duration); + + (temporaryData == null ? "permanent" : temporaryData.duration()); String dmNoticeText = ""; if (!hasSentDm) { dmNoticeText = "\n(Unable to send them a DM.)"; @@ -145,48 +141,28 @@ private static Optional> handleNotAlreadyBannedRespo .setEphemeral(true)); } - private static @NotNull Optional computeTemporaryBanData( - @NotNull String durationText) { - if (PERMANENT_DURATION.equals(durationText)) { - return Optional.empty(); - } - - // 1 minute, 1 day, 2 days, ... - String[] data = durationText.split(" ", 2); - int duration = Integer.parseInt(data[0]); - ChronoUnit unit = switch (data[1]) { - case "minute", "minutes" -> ChronoUnit.MINUTES; - case "hour", "hours" -> ChronoUnit.HOURS; - case "day", "days" -> ChronoUnit.DAYS; - default -> throw new IllegalArgumentException( - "Unsupported ban duration: " + durationText); - }; - - return Optional.of(new TemporaryBanData(Instant.now().plus(duration, unit), durationText)); - } - @SuppressWarnings("MethodWithTooManyParameters") private RestAction banUserFlow(@NotNull User target, @NotNull Member author, - @Nullable TemporaryBanData temporaryBanData, @NotNull String reason, + @Nullable ModerationUtils.TemporaryData temporaryData, @NotNull String reason, int deleteHistoryDays, @NotNull Guild guild, @NotNull SlashCommandEvent event) { - return sendDm(target, temporaryBanData, reason, guild, event) - .flatMap(hasSentDm -> banUser(target, author, temporaryBanData, reason, - deleteHistoryDays, guild).map(banResult -> hasSentDm)) - .map(hasSentDm -> sendFeedback(hasSentDm, target, author, temporaryBanData, reason)) + return sendDm(target, temporaryData, reason, guild, event) + .flatMap(hasSentDm -> banUser(target, author, temporaryData, reason, deleteHistoryDays, + guild).map(banResult -> hasSentDm)) + .map(hasSentDm -> sendFeedback(hasSentDm, target, author, temporaryData, reason)) .flatMap(event::replyEmbeds); } private AuditableRestAction banUser(@NotNull User target, @NotNull Member author, - @Nullable TemporaryBanData temporaryBanData, @NotNull String reason, + @Nullable ModerationUtils.TemporaryData temporaryData, @NotNull String reason, int deleteHistoryDays, @NotNull Guild guild) { String durationMessage = - temporaryBanData == null ? "permanently" : "for " + temporaryBanData.duration; + temporaryData == null ? "permanently" : "for " + temporaryData.duration(); logger.info( "'{}' ({}) banned the user '{}' ({}) {} from guild '{}' and deleted their message history of the last {} days, for reason '{}'.", author.getUser().getAsTag(), author.getId(), target.getAsTag(), target.getId(), durationMessage, guild.getName(), deleteHistoryDays, reason); - Instant expiresAt = temporaryBanData == null ? null : temporaryBanData.unbanTime; + Instant expiresAt = temporaryData == null ? null : temporaryData.expiresAt(); actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), ModerationAction.BAN, expiresAt, reason); @@ -230,7 +206,8 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { Guild guild = Objects.requireNonNull(event.getGuild()); Member bot = guild.getSelfMember(); - Optional temporaryBanData = computeTemporaryBanData(duration); + Optional temporaryData = + ModerationUtils.computeTemporaryData(duration); if (!handleChecks(bot, author, targetOption.getAsMember(), reason, guild, event)) { return; @@ -247,12 +224,8 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { return handleNotAlreadyBannedResponse( Objects.requireNonNull(alreadyBanned.getFailure()), event, guild, target) - .orElseGet(() -> banUserFlow(target, author, temporaryBanData.orElse(null), + .orElseGet(() -> banUserFlow(target, author, temporaryData.orElse(null), reason, deleteHistoryDays, guild, event)); }).queue(); } - - - private record TemporaryBanData(@NotNull Instant unbanTime, @NotNull String duration) { - } } 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 c1fab54b70..e536291243 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 @@ -12,6 +12,8 @@ import java.awt.*; import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.time.temporal.TemporalUnit; import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Pattern; @@ -28,7 +30,10 @@ public enum ModerationUtils { * {@link Guild#ban(User, int, String)}. */ private static final int REASON_MAX_LENGTH = 512; + // FIXME Javadoc + static final String PERMANENT_DURATION = "permanent"; static final Color AMBIENT_COLOR = Color.decode("#895FE8"); + // FIXME Javadoc public static final Predicate isMuteRole = Pattern.compile(Config.getInstance().getMutedRolePattern()).asMatchPredicate(); @@ -326,4 +331,25 @@ static boolean handleHasAuthorRole(@NotNull String actionVerb, return guild.getRoles().stream().filter(role -> isMuteRole.test(role.getName())).findAny(); } + static @NotNull Optional computeTemporaryData(@NotNull String durationText) { + if (PERMANENT_DURATION.equals(durationText)) { + return Optional.empty(); + } + + // 1 minute, 1 day, 2 days, ... + String[] data = durationText.split(" ", 2); + int duration = Integer.parseInt(data[0]); + ChronoUnit unit = switch (data[1]) { + case "minute", "minutes" -> ChronoUnit.MINUTES; + case "hour", "hours" -> ChronoUnit.HOURS; + case "day", "days" -> ChronoUnit.DAYS; + default -> throw new IllegalArgumentException( + "Unsupported mute duration: " + durationText); + }; + + return Optional.of(new TemporaryData(Instant.now().plus(duration, unit), durationText)); + } + + record TemporaryData(@NotNull Instant expiresAt, @NotNull String duration) { + } } 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 dfdbf099c7..7574139345 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 @@ -18,7 +18,6 @@ import org.togetherjava.tjbot.config.Config; import java.time.Instant; -import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -39,9 +38,8 @@ public final class MuteCommand extends SlashCommandAdapter { private static final String REASON_OPTION = "reason"; private static final String COMMAND_NAME = "mute"; private static final String ACTION_VERB = "mute"; - private static final String PERMANENT_DURATION = "permanent"; private static final List DURATIONS = List.of("10 minutes", "30 minutes", "1 hour", - "3 hours", "1 day", "3 days", "7 days", PERMANENT_DURATION); + "3 hours", "1 day", "3 days", "7 days", ModerationUtils.PERMANENT_DURATION); private final Predicate hasRequiredRole; private final ModerationActionsStore actionsStore; @@ -72,10 +70,10 @@ private static void handleAlreadyMutedTarget(@NotNull Interaction event) { } private static RestAction sendDm(@NotNull ISnowflake target, - @Nullable TemporaryMuteData temporaryMuteData, @NotNull String reason, + @Nullable ModerationUtils.TemporaryData temporaryData, @NotNull String reason, @NotNull Guild guild, @NotNull GenericEvent event) { String durationMessage = - temporaryMuteData == null ? "permanently" : "for " + temporaryMuteData.duration; + 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. @@ -92,12 +90,10 @@ private static RestAction sendDm(@NotNull ISnowflake target, } private static @NotNull MessageEmbed sendFeedback(boolean hasSentDm, @NotNull Member target, - @NotNull Member author, @Nullable TemporaryMuteData temporaryMuteData, + @NotNull Member author, @Nullable ModerationUtils.TemporaryData temporaryData, @NotNull String reason) { - @SuppressWarnings("java:S1192") // this is not the name of the option but the user-friendly - // display text String durationText = "The mute duration is: " - + (temporaryMuteData == null ? "permanent" : temporaryMuteData.duration); + + (temporaryData == null ? "permanent" : temporaryData.duration()); String dmNoticeText = ""; if (!hasSentDm) { dmNoticeText = "\n(Unable to send them a DM.)"; @@ -106,37 +102,16 @@ private static RestAction sendDm(@NotNull ISnowflake target, target.getUser(), durationText + dmNoticeText, reason); } - // FIXME Code duplication with BanCommand, get rid of it - private static @NotNull Optional computeTemporaryMuteData( - @NotNull String durationText) { - if (PERMANENT_DURATION.equals(durationText)) { - return Optional.empty(); - } - - // 1 minute, 1 day, 2 days, ... - String[] data = durationText.split(" ", 2); - int duration = Integer.parseInt(data[0]); - ChronoUnit unit = switch (data[1]) { - case "minute", "minutes" -> ChronoUnit.MINUTES; - case "hour", "hours" -> ChronoUnit.HOURS; - case "day", "days" -> ChronoUnit.DAYS; - default -> throw new IllegalArgumentException( - "Unsupported mute duration: " + durationText); - }; - - return Optional.of(new TemporaryMuteData(Instant.now().plus(duration, unit), durationText)); - } - private AuditableRestAction muteUser(@NotNull Member target, @NotNull Member author, - @Nullable TemporaryMuteData temporaryMuteData, @NotNull String reason, + @Nullable ModerationUtils.TemporaryData temporaryData, @NotNull String reason, @NotNull Guild guild) { String durationMessage = - temporaryMuteData == null ? "permanently" : "for " + temporaryMuteData.duration; + temporaryData == null ? "permanently" : "for " + temporaryData.duration(); logger.info("'{}' ({}) muted the user '{}' ({}) {} in guild '{}' for reason '{}'.", author.getUser().getAsTag(), author.getId(), target.getUser().getAsTag(), target.getId(), durationMessage, guild.getName(), reason); - Instant expiresAt = temporaryMuteData == null ? null : temporaryMuteData.unmuteTime; + Instant expiresAt = temporaryData == null ? null : temporaryData.expiresAt(); actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), ModerationAction.MUTE, expiresAt, reason); @@ -145,12 +120,12 @@ private AuditableRestAction muteUser(@NotNull Member target, @NotNull Memb } private void muteUserFlow(@NotNull Member target, @NotNull Member author, - @Nullable TemporaryMuteData temporaryMuteData, @NotNull String reason, + @Nullable ModerationUtils.TemporaryData temporaryData, @NotNull String reason, @NotNull Guild guild, @NotNull SlashCommandEvent event) { - sendDm(target, temporaryMuteData, reason, guild, event) - .flatMap(hasSentDm -> muteUser(target, author, temporaryMuteData, reason, guild) + sendDm(target, temporaryData, reason, guild, event) + .flatMap(hasSentDm -> muteUser(target, author, temporaryData, reason, guild) .map(banResult -> hasSentDm)) - .map(hasSentDm -> sendFeedback(hasSentDm, target, author, temporaryMuteData, reason)) + .map(hasSentDm -> sendFeedback(hasSentDm, target, author, temporaryData, reason)) .flatMap(event::replyEmbeds) .queue(); } @@ -188,16 +163,14 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { Guild guild = Objects.requireNonNull(event.getGuild()); Member bot = guild.getSelfMember(); - Optional temporaryMuteData = computeTemporaryMuteData(duration); + Optional temporaryData = + ModerationUtils.computeTemporaryData(duration); if (!handleChecks(bot, author, target, reason, guild, event)) { return; } - muteUserFlow(Objects.requireNonNull(target), author, temporaryMuteData.orElse(null), reason, + muteUserFlow(Objects.requireNonNull(target), author, temporaryData.orElse(null), reason, guild, event); } - - private record TemporaryMuteData(@NotNull Instant unmuteTime, @NotNull String duration) { - } } From 58e10d35b3f7d961f51db13f9a5eef8c130a8d7b Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Thu, 16 Dec 2021 09:41:45 +0100 Subject: [PATCH 10/14] Javadoc, Linter --- .../tjbot/commands/moderation/BanCommand.java | 2 + .../moderation/ModerationActionsStore.java | 18 +++++++- .../commands/moderation/ModerationUtils.java | 30 +++++++++++- .../commands/moderation/MuteCommand.java | 2 + .../temp/RevocableModerationAction.java | 46 ++++++++++++++++++- .../moderation/temp/TemporaryBanAction.java | 6 ++- .../temp/TemporaryModerationRoutine.java | 15 ++++-- .../moderation/temp/TemporaryMuteAction.java | 19 ++++---- 8 files changed, 121 insertions(+), 17 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java index 737ac7869e..f11d15772c 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java @@ -45,6 +45,7 @@ public final class BanCommand extends SlashCommandAdapter { private static final String REASON_OPTION = "reason"; private static final String COMMAND_NAME = "ban"; private static final String ACTION_VERB = "ban"; + @SuppressWarnings("StaticCollection") private static final List DURATIONS = List.of(ModerationUtils.PERMANENT_DURATION, "1 hour", "3 hours", "1 day", "2 days", "3 days", "7 days", "30 days"); private final Predicate hasRequiredRole; @@ -152,6 +153,7 @@ private RestAction banUserFlow(@NotNull User target, @NotNull M .flatMap(event::replyEmbeds); } + @SuppressWarnings("MethodWithTooManyParameters") private AuditableRestAction banUser(@NotNull User target, @NotNull Member author, @Nullable ModerationUtils.TemporaryData temporaryData, @NotNull String reason, int deleteHistoryDays, @NotNull Guild guild) { diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java index f0de5cc25c..3ee603b93a 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java @@ -39,7 +39,12 @@ public ModerationActionsStore(@NotNull Database database) { this.database = Objects.requireNonNull(database); } - // FIXME javadoc + /** + * Gets all already expired actions, measured by the current time, which have been written to + * the store, chronologically ascending with the action issued the earliest first. + * + * @return a list of all expired actions, chronologically ascending + */ public @NotNull List getExpiredActionsAscending() { return getActionsAscendingWhere( ModerationActions.MODERATION_ACTIONS.ACTION_EXPIRES_AT.isNotNull() @@ -92,7 +97,16 @@ public ModerationActionsStore(@NotNull Database database) { ModerationActions.MODERATION_ACTIONS.AUTHOR_ID.eq(authorId)); } - // FIXME javadoc + /** + * Gets the action of the given type that was issued the latest against the given target, if + * present. + * + * @param guildId the id of the guild, only actions that happened in the context of that guild + * will be retrieved + * @param targetId the id of the target user to filter for + * @param actionType the type of the action + * @return the last action issued against the given user of the given type, if present + */ public @NotNull Optional findLastActionAgainstTargetByType(long guildId, long targetId, @NotNull ModerationAction actionType) { return database 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 e536291243..fcb916be95 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 @@ -30,10 +30,20 @@ public enum ModerationUtils { * {@link Guild#ban(User, int, String)}. */ private static final int REASON_MAX_LENGTH = 512; - // FIXME Javadoc + /** + * Human-readable text representing the duration of a permanent action, will be shown to the + * user as option for selection. + */ static final String PERMANENT_DURATION = "permanent"; + /** + * The ambient color used by moderation actions, often used to streamline the color theme of + * embeds. + */ static final Color AMBIENT_COLOR = Color.decode("#895FE8"); - // FIXME Javadoc + /** + * Matches the name of the role that is used to mute users, as used by {@link MuteCommand} and + * similar. + */ public static final Predicate isMuteRole = Pattern.compile(Config.getInstance().getMutedRolePattern()).asMatchPredicate(); @@ -331,6 +341,15 @@ static boolean handleHasAuthorRole(@NotNull String actionVerb, return guild.getRoles().stream().filter(role -> isMuteRole.test(role.getName())).findAny(); } + /** + * Computes a temporary data wrapper representing the action with the given duration. + * + * @param durationText the duration of the action, either {@code "permanent"} or a time window + * such as {@code 1 day} or {@code 2 minutes}. Supports all units supported by + * {@link Instant#plus(long, TemporalUnit)}. + * @return the temporary data represented by the given duration or empty if the duration is + * {@code "permanent"} + */ static @NotNull Optional computeTemporaryData(@NotNull String durationText) { if (PERMANENT_DURATION.equals(durationText)) { return Optional.empty(); @@ -350,6 +369,13 @@ static boolean handleHasAuthorRole(@NotNull String actionVerb, return Optional.of(new TemporaryData(Instant.now().plus(duration, unit), durationText)); } + /** + * Wrapper to hold data relevant to temporary actions, for example the time it expires. + * + * @param expiresAt the time the temporary action expires + * @param duration a human-readable text representing the duration of the temporary action, such + * as {@code "1 day"}. + */ record TemporaryData(@NotNull Instant expiresAt, @NotNull String duration) { } } 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 7574139345..f10606c8a4 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 @@ -38,6 +38,7 @@ public final class MuteCommand extends SlashCommandAdapter { private static final String REASON_OPTION = "reason"; private static final String COMMAND_NAME = "mute"; private static final String ACTION_VERB = "mute"; + @SuppressWarnings("StaticCollection") private static final List DURATIONS = List.of("10 minutes", "30 minutes", "1 hour", "3 hours", "1 day", "3 days", "7 days", ModerationUtils.PERMANENT_DURATION); private final Predicate hasRequiredRole; @@ -119,6 +120,7 @@ private AuditableRestAction muteUser(@NotNull Member target, @NotNull Memb .reason(reason); } + @SuppressWarnings("MethodWithTooManyParameters") private void muteUserFlow(@NotNull Member target, @NotNull Member author, @Nullable ModerationUtils.TemporaryData temporaryData, @NotNull String reason, @NotNull Guild guild, @NotNull SlashCommandEvent event) { diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/RevocableModerationAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/RevocableModerationAction.java index 70f6b2bf93..b2cedc3007 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/RevocableModerationAction.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/RevocableModerationAction.java @@ -6,23 +6,67 @@ import org.jetbrains.annotations.NotNull; import org.togetherjava.tjbot.commands.moderation.ModerationAction; -// FIXME Javadoc +/** + * Represents revocable moderation actions, such as temporary bans. Primarily used by + * {@link TemporaryModerationRoutine} to identify and revoke such actions. + */ interface RevocableModerationAction { + /** + * Classification of a revocation failure. + */ + @SuppressWarnings("PublicInnerClass") enum FailureIdentification { + /** + * Acknowledges that the failure is known and has been handled. Hence, further error + * handling should not be continued. + */ KNOWN, + /** + * The failure is unknown and has not been handled. Hence, further error handling should be + * continued. + */ UNKNOWN } + /** + * The type to apply the temporary action, such as + * {@link net.dv8tion.jda.api.audit.ActionType#BAN}. + * + * @return the type to apply the temporary action + */ @NotNull ModerationAction getApplyType(); + /** + * The type to revoke the temporary action, such as + * {@link net.dv8tion.jda.api.audit.ActionType#UNBAN}. + * + * @return the type to revoke the temporary action + */ @NotNull ModerationAction getRevokeType(); + /** + * Revokes the temporary action against the given target. + * + * @param guild the guild the user belongs to + * @param target the target to revoke the action against + * @param reason why the action is revoked + * @return the unsubmitted revocation action + */ @NotNull RestAction revokeAction(@NotNull Guild guild, @NotNull User target, @NotNull String reason); + /** + * Handle a failure that might occur during revocation, i.e. execution of the action returned by + * {@link #revokeAction(Guild, User, String)}. + * + * @param failure the failure to handle + * @param targetId the id of the user who is targeted by the revocation + * @return a classification of the failure, decides whether the surrounding flow will continue + * to handle the error further or not + */ @NotNull FailureIdentification handleRevokeFailure(@NotNull Throwable failure, long targetId); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryBanAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryBanAction.java index ddee6a5064..cb2cf97340 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryBanAction.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryBanAction.java @@ -10,7 +10,11 @@ import org.slf4j.LoggerFactory; import org.togetherjava.tjbot.commands.moderation.ModerationAction; -// FIXME Javadoc +/** + * Action to revoke temporary bans, as applied by + * {@link org.togetherjava.tjbot.commands.moderation.BanCommand} and executed by + * {@link TemporaryModerationRoutine}. + */ final class TemporaryBanAction implements RevocableModerationAction { private static final Logger logger = LoggerFactory.getLogger(TemporaryBanAction.class); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java index 63940cf99c..ac01dc1a0e 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java @@ -21,7 +21,16 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -// FIXME javadoc +/** + * Routine that revokes temporary moderation actions, such as temporary bans, as listed by + * {@link ModerationActionsStore}. + *

+ * The routine is started by using {@link #start()} and then automatically executes on a schedule. + *

+ * Revoked actions are compatible with {@link ModerationActionsStore} and commands such as + * {@link org.togetherjava.tjbot.commands.moderation.UnbanCommand} and + * {@link org.togetherjava.tjbot.commands.moderation.AuditCommand}. + */ public final class TemporaryModerationRoutine { private static final Logger logger = LoggerFactory.getLogger(TemporaryModerationRoutine.class); @@ -142,7 +151,7 @@ private void handleFailure(@NotNull Throwable failure, public void start() { // TODO This should be registered at some sort of routine system instead (see GH issue #235 // which adds support for routines) - // NOTE The initial run has to be delayed until after the guild cache has been updated + // TODO The initial run has to be delayed until after the guild cache has been updated // (during CommandSystem startup) checkExpiredActionsService.scheduleWithFixedDelay(this::checkExpiredActions, 5, 5, TimeUnit.MINUTES); @@ -150,7 +159,7 @@ public void start() { private record RevocationGroupIdentifier(long guildId, long targetId, @NotNull ModerationAction type) { - public static RevocationGroupIdentifier of(@NotNull ActionRecord actionRecord) { + static RevocationGroupIdentifier of(@NotNull ActionRecord actionRecord) { return new RevocationGroupIdentifier(actionRecord.guildId(), actionRecord.targetId(), actionRecord.actionType()); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryMuteAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryMuteAction.java index 006423987b..8bbf38984b 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryMuteAction.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryMuteAction.java @@ -11,7 +11,11 @@ import org.togetherjava.tjbot.commands.moderation.ModerationAction; import org.togetherjava.tjbot.commands.moderation.ModerationUtils; -// FIXME Javadoc +/** + * Action to revoke temporary mutes, as applied by + * {@link org.togetherjava.tjbot.commands.moderation.MuteCommand} and executed by + * {@link TemporaryModerationRoutine}. + */ final class TemporaryMuteAction implements RevocableModerationAction { private static final Logger logger = LoggerFactory.getLogger(TemporaryMuteAction.class); @@ -37,13 +41,12 @@ final class TemporaryMuteAction implements RevocableModerationAction { @Override public @NotNull FailureIdentification handleRevokeFailure(@NotNull Throwable failure, long targetId) { - if (failure instanceof ErrorResponseException errorResponseException) { - if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_USER) { - logger.info( - "Attempted to revoke a temporary mute but user '{}' does not exist anymore.", - targetId); - return FailureIdentification.KNOWN; - } + if (failure instanceof ErrorResponseException errorResponseException + && errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_USER) { + logger.info( + "Attempted to revoke a temporary mute but user '{}' does not exist anymore.", + targetId); + return FailureIdentification.KNOWN; } return FailureIdentification.UNKNOWN; } From 99c416c6e78ec15eff0757a282a5fd21e589ba21 Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Thu, 16 Dec 2021 10:07:33 +0100 Subject: [PATCH 11/14] Bugfix with missing unmute/unban record --- .../temp/TemporaryModerationRoutine.java | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java index ac01dc1a0e..78428742aa 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java @@ -14,6 +14,7 @@ import java.time.Instant; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -86,14 +87,15 @@ private void processGroupedActions(@NotNull RevocationGroupIdentifier groupIdent // but also if the system automatically revoked a temp-ban already itself ModerationAction revokeActionType = getRevocableActionByType(groupIdentifier.type).getRevokeType(); - ActionRecord lastRevokeAction = actionsStore - .findLastActionAgainstTargetByType(groupIdentifier.guildId, groupIdentifier.targetId, - revokeActionType) - .orElseThrow(); - if (lastRevokeAction.issuedAt().isAfter(lastApplyAction.issuedAt()) - && (lastRevokeAction.actionExpiresAt() == null - || lastRevokeAction.actionExpiresAt().isAfter(Instant.now()))) { - return; + Optional lastRevokeActionOpt = actionsStore.findLastActionAgainstTargetByType( + groupIdentifier.guildId, groupIdentifier.targetId, revokeActionType); + if (lastRevokeActionOpt.isPresent()) { + ActionRecord lastRevokeAction = lastRevokeActionOpt.orElseThrow(); + if (lastRevokeAction.issuedAt().isAfter(lastApplyAction.issuedAt()) + && (lastRevokeAction.actionExpiresAt() == null + || lastRevokeAction.actionExpiresAt().isAfter(Instant.now()))) { + return; + } } revokeAction(groupIdentifier); @@ -102,7 +104,7 @@ private void processGroupedActions(@NotNull RevocationGroupIdentifier groupIdent private void revokeAction(@NotNull RevocationGroupIdentifier groupIdentifier) { Guild guild = jda.getGuildById(groupIdentifier.guildId); if (guild == null) { - logger.info( + logger.debug( "Attempted to revoke a temporary moderation action but the bot is not connected to the guild '{}' anymore, skipping revoking.", groupIdentifier.guildId); return; From 8f94ccaa5f258b7596d61314e655d2bdca0c31f8 Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Thu, 16 Dec 2021 10:06:52 +0100 Subject: [PATCH 12/14] Improved error handling and logging levels --- .../moderation/temp/TemporaryBanAction.java | 9 ++++-- .../moderation/temp/TemporaryMuteAction.java | 31 +++++++++++++++---- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryBanAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryBanAction.java index cb2cf97340..0941224872 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryBanAction.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryBanAction.java @@ -39,18 +39,23 @@ final class TemporaryBanAction implements RevocableModerationAction { long targetId) { if (failure instanceof ErrorResponseException errorResponseException) { if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_USER) { - logger.info( + logger.debug( "Attempted to revoke a temporary ban but user '{}' does not exist anymore.", targetId); return FailureIdentification.KNOWN; } if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_BAN) { - logger.info( + logger.debug( "Attempted to revoke a temporary ban but the user '{}' is not banned anymore.", targetId); return FailureIdentification.KNOWN; } + + if (errorResponseException.getErrorResponse() == ErrorResponse.MISSING_PERMISSIONS) { + logger.warn("Attempted to revoke a temporary ban but the bot lacks permission."); + return FailureIdentification.KNOWN; + } } return FailureIdentification.UNKNOWN; } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryMuteAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryMuteAction.java index 8bbf38984b..0edd9f3308 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryMuteAction.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryMuteAction.java @@ -41,12 +41,31 @@ final class TemporaryMuteAction implements RevocableModerationAction { @Override public @NotNull FailureIdentification handleRevokeFailure(@NotNull Throwable failure, long targetId) { - if (failure instanceof ErrorResponseException errorResponseException - && errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_USER) { - logger.info( - "Attempted to revoke a temporary mute but user '{}' does not exist anymore.", - targetId); - return FailureIdentification.KNOWN; + if (failure instanceof ErrorResponseException errorResponseException) { + if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_USER) { + logger.debug( + "Attempted to revoke a temporary mute but user '{}' does not exist anymore.", + targetId); + return FailureIdentification.KNOWN; + } + + if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_MEMBER) { + logger.debug( + "Attempted to revoke a temporary mute but user '{}' is not a member of the guild anymore.", + targetId); + return FailureIdentification.KNOWN; + } + + if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_ROLE) { + logger.warn( + "Attempted to revoke a temporary mute but the mute role can not be found."); + return FailureIdentification.KNOWN; + } + + if (errorResponseException.getErrorResponse() == ErrorResponse.MISSING_PERMISSIONS) { + logger.warn("Attempted to revoke a temporary mute but the bot lacks permission."); + return FailureIdentification.KNOWN; + } } return FailureIdentification.UNKNOWN; } From 771e0eedca98ffeb4b829e7d2a8d23f0ba6d419f Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Thu, 16 Dec 2021 10:31:47 +0100 Subject: [PATCH 13/14] Bugfix with reapplying expired mutes after rejoin * also, simplification of the queries in the rejoin listener --- .../moderation/RejoinMuteListener.java | 27 ++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/RejoinMuteListener.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/RejoinMuteListener.java index 793126513e..2fa0ff438f 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/RejoinMuteListener.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/RejoinMuteListener.java @@ -10,6 +10,7 @@ import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; +import java.time.Instant; import java.util.*; /** @@ -45,6 +46,11 @@ private static void muteMember(@NotNull Member member) { .queue(); } + private static boolean isActionEffective(@NotNull ActionRecord action) { + // Effective if permanent or expires in the future + return action.actionExpiresAt() == null || action.actionExpiresAt().isAfter(Instant.now()); + } + @Override public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { Member member = event.getMember(); @@ -55,27 +61,24 @@ public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { } private boolean shouldMemberBeMuted(@NotNull IPermissionHolder member) { - List actions = new ArrayList<>(actionsStore - .getActionsByTargetAscending(member.getGuild().getIdLong(), member.getIdLong())); - Collections.reverse(actions); - - Optional lastMute = actions.stream() - .filter(action -> action.actionType() == ModerationAction.MUTE) - .findFirst(); + Optional lastMute = actionsStore.findLastActionAgainstTargetByType( + member.getGuild().getIdLong(), member.getIdLong(), ModerationAction.MUTE); if (lastMute.isEmpty()) { // User was never muted return false; } - Optional lastUnmute = actions.stream() - .filter(action -> action.actionType() == ModerationAction.UNMUTE) - .findFirst(); + Optional lastUnmute = actionsStore.findLastActionAgainstTargetByType( + member.getGuild().getIdLong(), member.getIdLong(), ModerationAction.UNMUTE); if (lastUnmute.isEmpty()) { // User was never unmuted - return true; + return isActionEffective(lastMute.orElseThrow()); } // The last issued action takes priority - return lastMute.orElseThrow().issuedAt().isAfter(lastUnmute.orElseThrow().issuedAt()); + if (lastMute.orElseThrow().issuedAt().isAfter(lastUnmute.orElseThrow().issuedAt())) { + return isActionEffective(lastMute.orElseThrow()); + } + return false; } } From d9ac5d9528b6825571ba2e2b4264d0fd4bfb937b Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Wed, 29 Dec 2021 18:08:19 +0100 Subject: [PATCH 14/14] Rebase on develop * added /warn action that was added in the meantime --- .../tjbot/commands/moderation/ModerationAction.java | 4 ++++ .../togetherjava/tjbot/commands/moderation/WarnCommand.java | 6 +++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationAction.java index fe9e9c774d..505830864e 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationAction.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationAction.java @@ -18,6 +18,10 @@ public enum ModerationAction { * When a user kicks another user. */ KICK("kicked"), + /** + * When a user warns another user. + */ + WARN("warned"), /** * When a user mutes another user. */ 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 b7943a065f..2b2c8265c2 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 @@ -84,7 +84,7 @@ private void warnUser(@NotNull User target, @NotNull Member author, @NotNull Str reason); actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationUtils.Action.WARN, null, reason); + ModerationAction.WARN, null, reason); } private static @NotNull MessageEmbed sendFeedback(boolean hasSentDm, @NotNull User target, @@ -93,8 +93,8 @@ private void warnUser(@NotNull User target, @NotNull Member author, @NotNull Str if (!hasSentDm) { dmNoticeText = "(Unable to send them a DM.)"; } - return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.WARN, - target, dmNoticeText, reason); + return ModerationUtils.createActionResponse(author.getUser(), ModerationAction.WARN, target, + dmNoticeText, reason); } @Override