From f0712ec9aedb75d067ce0dd6c42888c527440d30 Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Fri, 10 Dec 2021 09:18:47 +0100 Subject: [PATCH 1/9] Adding mute, unmute commands --- .../togetherjava/tjbot/commands/Commands.java | 2 + .../commands/moderation/ModerationUtils.java | 10 +- .../commands/moderation/MuteCommand.java | 154 ++++++++++++++++++ .../commands/moderation/UnmuteCommand.java | 153 +++++++++++++++++ 4 files changed, 318 insertions(+), 1 deletion(-) create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.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 7980e34733..596d4cd67b 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -57,6 +57,8 @@ public enum Commands { commands.add(new UnbanCommand(actionsStore)); commands.add(new FreeCommand()); commands.add(new AuditCommand(actionsStore)); + commands.add(new MuteCommand()); + commands.add(new UnmuteCommand()); return commands; } 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 deaa4a6c95..39440e7ac8 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 @@ -215,7 +215,15 @@ enum Action { /** * When a user kicks another user. */ - KICK("kicked"); + KICK("kicked"), + /** + * When a user mutes another user. + */ + MUTE("muted"), + /** + * When a user unmutes another user. + */ + UNMUTE("unmuted"); private final String 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 new file mode 100644 index 0000000000..de285e3001 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java @@ -0,0 +1,154 @@ +package org.togetherjava.tjbot.commands.moderation; + +import net.dv8tion.jda.api.Permission; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import net.dv8tion.jda.api.interactions.Interaction; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.SlashCommandVisibility; +import org.togetherjava.tjbot.config.Config; + +import java.util.Objects; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.regex.Pattern; + +/** + * This command can mute users. Muting can also be paired with a reason. The command will also try + * to DM the user to inform them about the action and the reason. + *

+ * The command fails if the user triggering it is lacking permissions to either mute other users or + * to mute the specific given user (for example a moderator attempting to mute an admin). + */ +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 REASON_OPTION = "reason"; + private static final String COMMAND_NAME = "mute"; + private static final String ACTION_VERB = "mute"; + private final Predicate hasRequiredRole; + private final Predicate isMuteRole; + + /** + * Constructs an instance. + */ + public MuteCommand() { + super(COMMAND_NAME, "Mutes the given user so that they can not send messages anymore", + SlashCommandVisibility.GUILD); + + getData().addOption(OptionType.USER, TARGET_OPTION, "The user who you want to mute", true) + .addOption(OptionType.STRING, REASON_OPTION, "Why the user should be muted", true); + + hasRequiredRole = Pattern.compile(Config.getInstance().getSoftModerationRolePattern()) + .asMatchPredicate(); + isMuteRole = Pattern.compile(Config.getInstance().getMutedRolePattern()).asMatchPredicate(); + } + + private static void handleAbsentTarget(@NotNull Interaction event) { + event.reply("I can not mute the given user since they are not part of the guild anymore.") + .setEphemeral(true) + .queue(); + } + + private static void handleAlreadyMutedTarget(@NotNull Interaction event) { + event.reply("The user is already muted.").setEphemeral(true).queue(); + } + + private void muteUser(@NotNull Member target, @NotNull Member author, @NotNull String reason, + @NotNull Guild guild, @NotNull SlashCommandEvent event) { + User targetUser = target.getUser(); + String dmMessage = + """ + Hey there, sorry to tell you but unfortunately you have been muted 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); + + Optional maybeMutedRole = getMutedRole(guild); + if (maybeMutedRole.isEmpty()) { + event.reply("Can not mute the user, unable to find a mute role on this server") + .setEphemeral(true) + .queue(); + logger.warn("The guild '{}' does not have a mute role.", guild.getName()); + return; + } + + event.getJDA() + .openPrivateChannelById(targetUser.getId()) + .flatMap(channel -> channel.sendMessage(dmMessage)) + .mapToResult() + .flatMap(sendDmResult -> { + logger.info("'{}' ({}) muted the user '{}' ({}) in guild '{}' for reason '{}'.", + author.getUser().getAsTag(), author.getId(), targetUser.getAsTag(), + targetUser.getId(), guild.getName(), reason); + return guild.addRoleToMember(target, maybeMutedRole.orElseThrow()) + .reason(reason) + .map(muteResult -> sendDmResult.isSuccess()); + }) + .map(hasSentDm -> { + String dmNotice = + Boolean.TRUE.equals(hasSentDm) ? "" : "(Unable to send them a DM.)"; + return ModerationUtils.createActionResponse(author.getUser(), + ModerationUtils.Action.MUTE, targetUser, dmNotice, reason); + }) + .flatMap(event::replyEmbeds) + .queue(); + } + + @SuppressWarnings({"BooleanMethodNameMustStartWithQuestion", "MethodWithTooManyParameters"}) + private boolean handleChecks(@NotNull Member bot, @NotNull Member author, + @Nullable Member target, @NotNull CharSequence reason, @NotNull Guild guild, + @NotNull Interaction event) { + // Member doesn't exist if attempting to mute a user who is not part of the guild anymore. + if (target == null) { + handleAbsentTarget(event); + return false; + } + if (!ModerationUtils.handleCanInteractWithTarget(ACTION_VERB, bot, author, target, event)) { + return false; + } + if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { + return false; + } + if (!ModerationUtils.handleHasBotPermissions(ACTION_VERB, Permission.MANAGE_ROLES, bot, + guild, event)) { + return false; + } + if (target.getRoles().stream().map(Role::getName).anyMatch(isMuteRole)) { + handleAlreadyMutedTarget(event); + return false; + } + return ModerationUtils.handleReason(reason, event); + } + + @Override + public void onSlashCommand(@NotNull SlashCommandEvent event) { + Member target = Objects.requireNonNull(event.getOption(TARGET_OPTION), "The target is null") + .getAsMember(); + Member author = Objects.requireNonNull(event.getMember(), "The author is null"); + String reason = Objects.requireNonNull(event.getOption(REASON_OPTION), "The reason is null") + .getAsString(); + + Guild guild = Objects.requireNonNull(event.getGuild()); + Member bot = guild.getSelfMember(); + + if (!handleChecks(bot, author, target, reason, guild, event)) { + return; + } + muteUser(Objects.requireNonNull(target), author, reason, guild, event); + } + + private @NotNull Optional getMutedRole(@NotNull Guild guild) { + return guild.getRoles().stream().filter(role -> isMuteRole.test(role.getName())).findAny(); + } +} 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 new file mode 100644 index 0000000000..027c721a79 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java @@ -0,0 +1,153 @@ +package org.togetherjava.tjbot.commands.moderation; + +import net.dv8tion.jda.api.Permission; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import net.dv8tion.jda.api.interactions.Interaction; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.SlashCommandVisibility; +import org.togetherjava.tjbot.config.Config; + +import java.util.Objects; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.regex.Pattern; + +/** + * This command can unmute muted users. Unmuting can also be paired with a reason. The command will + * also try to DM the user to inform them about the action and the reason. + *

+ * The command fails if the user triggering it is lacking permissions to either unmute other users + * or to unmute the specific given user (for example a moderator attempting to unmute an admin). + */ +public final class UnmuteCommand extends SlashCommandAdapter { + private static final Logger logger = LoggerFactory.getLogger(UnmuteCommand.class); + private static final String TARGET_OPTION = "user"; + private static final String REASON_OPTION = "reason"; + private static final String COMMAND_NAME = "unmute"; + private static final String ACTION_VERB = "unmute"; + private final Predicate hasRequiredRole; + private final Predicate isMuteRole; + + /** + * Constructs an instance. + */ + public UnmuteCommand() { + super(COMMAND_NAME, + "Unmutes the given already muted user so that they can send messages again", + SlashCommandVisibility.GUILD); + + getData().addOption(OptionType.USER, TARGET_OPTION, "The user who you want to unmute", true) + .addOption(OptionType.STRING, REASON_OPTION, "Why the user should be unmuted", true); + + hasRequiredRole = Pattern.compile(Config.getInstance().getSoftModerationRolePattern()) + .asMatchPredicate(); + isMuteRole = Pattern.compile(Config.getInstance().getMutedRolePattern()).asMatchPredicate(); + } + + private static void handleAbsentTarget(@NotNull Interaction event) { + event.reply("I can not unmute the given user since they are not part of the guild anymore.") + .setEphemeral(true) + .queue(); + } + + private static void handleNotMutedTarget(@NotNull Interaction event) { + event.reply("The user is not muted.").setEphemeral(true).queue(); + } + + private void unmuteUser(@NotNull Member target, @NotNull Member author, @NotNull String reason, + @NotNull Guild guild, @NotNull SlashCommandEvent event) { + User targetUser = target.getUser(); + String dmMessage = """ + Hey there, you have been unmuted in the server %s. + This means you can now send messages in the server again. + The reason for the unmute is: %s + """.formatted(guild.getName(), reason); + + Optional maybeMutedRole = getMutedRole(guild); + if (maybeMutedRole.isEmpty()) { + event.reply("Can not unmute the user, unable to find a mute role on this server") + .setEphemeral(true) + .queue(); + logger.warn("The guild '{}' does not have a mute role.", guild.getName()); + return; + } + + event.getJDA() + .openPrivateChannelById(targetUser.getId()) + .flatMap(channel -> channel.sendMessage(dmMessage)) + .mapToResult() + .flatMap(sendDmResult -> { + logger.info("'{}' ({}) unmuted the user '{}' ({}) in guild '{}' for reason '{}'.", + author.getUser().getAsTag(), author.getId(), targetUser.getAsTag(), + targetUser.getId(), guild.getName(), reason); + + return guild.removeRoleFromMember(target, maybeMutedRole.orElseThrow()) + .reason(reason) + .map(unmuteResult -> sendDmResult.isSuccess()); + }) + .map(hasSentDm -> { + String dmNotice = + Boolean.TRUE.equals(hasSentDm) ? "" : "(Unable to send them a DM.)"; + return ModerationUtils.createActionResponse(author.getUser(), + ModerationUtils.Action.UNMUTE, targetUser, dmNotice, reason); + }) + .flatMap(event::replyEmbeds) + .queue(); + } + + @SuppressWarnings({"BooleanMethodNameMustStartWithQuestion", "MethodWithTooManyParameters"}) + private boolean handleChecks(@NotNull Member bot, @NotNull Member author, + @Nullable Member target, @NotNull CharSequence reason, @NotNull Guild guild, + @NotNull Interaction event) { + // Member doesn't exist if attempting to mute a user who is not part of the guild anymore. + if (target == null) { + handleAbsentTarget(event); + return false; + } + if (!ModerationUtils.handleCanInteractWithTarget(ACTION_VERB, bot, author, target, event)) { + return false; + } + if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { + return false; + } + if (!ModerationUtils.handleHasBotPermissions(ACTION_VERB, Permission.MANAGE_ROLES, bot, + guild, event)) { + return false; + } + if (target.getRoles().stream().map(Role::getName).noneMatch(isMuteRole)) { + handleNotMutedTarget(event); + return false; + } + return ModerationUtils.handleReason(reason, event); + } + + @Override + public void onSlashCommand(@NotNull SlashCommandEvent event) { + Member target = Objects.requireNonNull(event.getOption(TARGET_OPTION), "The target is null") + .getAsMember(); + Member author = Objects.requireNonNull(event.getMember(), "The author is null"); + String reason = Objects.requireNonNull(event.getOption(REASON_OPTION), "The reason is null") + .getAsString(); + + Guild guild = Objects.requireNonNull(event.getGuild()); + Member bot = guild.getSelfMember(); + + if (!handleChecks(bot, author, target, reason, guild, event)) { + return; + } + unmuteUser(Objects.requireNonNull(target), author, reason, guild, event); + } + + private @NotNull Optional getMutedRole(@NotNull Guild guild) { + return guild.getRoles().stream().filter(role -> isMuteRole.test(role.getName())).findAny(); + } +} From 79873e360c0a04c4558ecd5d2f762ddc900eabc2 Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Mon, 8 Nov 2021 12:38:56 +0100 Subject: [PATCH 2/9] Bugfix with missing perms to interact with role --- .../commands/moderation/ModerationUtils.java | 35 +++++++++++++++++++ .../commands/moderation/MuteCommand.java | 24 +++++++------ .../commands/moderation/UnmuteCommand.java | 24 +++++++------ 3 files changed, 63 insertions(+), 20 deletions(-) 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 39440e7ac8..b9efc77bd0 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 @@ -85,6 +85,41 @@ static boolean handleCanInteractWithTarget(@NotNull String actionVerb, @NotNull return true; } + /** + * Checks whether the given author and bot can interact with the given role. For example whether + * they have enough permissions to add or remove this role to users. + *

+ * If not, it will handle the situation and respond to the user. + * + * @param bot the bot attempting to interact with the user + * @param author the author triggering the command + * @param role the role to interact with + * @param event the event used to respond to the user + * @return Whether the author and bot can interact with the role + */ + @SuppressWarnings("BooleanMethodNameMustStartWithQuestion") + static boolean handleCanInteractWithRole(@NotNull Member bot, @NotNull Member author, + @NotNull Role role, @NotNull Interaction event) { + if (!author.canInteract(role)) { + event + .reply("The role %s is too powerful for you to interact with." + .formatted(role.getAsMention())) + .setEphemeral(true) + .queue(); + return false; + } + + if (!bot.canInteract(role)) { + event + .reply("The role %s is too powerful for me to interact with." + .formatted(role.getAsMention())) + .setEphemeral(true) + .queue(); + return false; + } + return true; + } + /** * Checks whether the given bot has enough permission to execute the given action. For example * whether it has enough permissions to ban users. 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 de285e3001..da339cd1c4 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 @@ -74,15 +74,6 @@ private void muteUser(@NotNull Member target, @NotNull Member author, @NotNull S """ .formatted(guild.getName(), reason); - Optional maybeMutedRole = getMutedRole(guild); - if (maybeMutedRole.isEmpty()) { - event.reply("Can not mute the user, unable to find a mute role on this server") - .setEphemeral(true) - .queue(); - logger.warn("The guild '{}' does not have a mute role.", guild.getName()); - return; - } - event.getJDA() .openPrivateChannelById(targetUser.getId()) .flatMap(channel -> channel.sendMessage(dmMessage)) @@ -91,7 +82,7 @@ private void muteUser(@NotNull Member target, @NotNull Member author, @NotNull S logger.info("'{}' ({}) muted the user '{}' ({}) in guild '{}' for reason '{}'.", author.getUser().getAsTag(), author.getId(), targetUser.getAsTag(), targetUser.getId(), guild.getName(), reason); - return guild.addRoleToMember(target, maybeMutedRole.orElseThrow()) + return guild.addRoleToMember(target, getMutedRole(guild).orElseThrow()) .reason(reason) .map(muteResult -> sendDmResult.isSuccess()); }) @@ -109,6 +100,15 @@ private void muteUser(@NotNull Member target, @NotNull Member author, @NotNull S private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @Nullable Member target, @NotNull CharSequence reason, @NotNull Guild guild, @NotNull Interaction event) { + Optional maybeMutedRole = getMutedRole(guild); + if (maybeMutedRole.isEmpty()) { + event.reply("Can not mute the user, unable to find a mute role on this server") + .setEphemeral(true) + .queue(); + logger.warn("The guild '{}' does not have a mute role.", guild.getName()); + return false; + } + // Member doesn't exist if attempting to mute a user who is not part of the guild anymore. if (target == null) { handleAbsentTarget(event); @@ -117,6 +117,10 @@ private boolean handleChecks(@NotNull Member bot, @NotNull Member author, if (!ModerationUtils.handleCanInteractWithTarget(ACTION_VERB, bot, author, target, event)) { return false; } + if (!ModerationUtils.handleCanInteractWithRole(bot, author, maybeMutedRole.orElseThrow(), + event)) { + return false; + } if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { return false; } 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 027c721a79..7b8cdfddd6 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 @@ -72,15 +72,6 @@ private void unmuteUser(@NotNull Member target, @NotNull Member author, @NotNull The reason for the unmute is: %s """.formatted(guild.getName(), reason); - Optional maybeMutedRole = getMutedRole(guild); - if (maybeMutedRole.isEmpty()) { - event.reply("Can not unmute the user, unable to find a mute role on this server") - .setEphemeral(true) - .queue(); - logger.warn("The guild '{}' does not have a mute role.", guild.getName()); - return; - } - event.getJDA() .openPrivateChannelById(targetUser.getId()) .flatMap(channel -> channel.sendMessage(dmMessage)) @@ -90,7 +81,7 @@ private void unmuteUser(@NotNull Member target, @NotNull Member author, @NotNull author.getUser().getAsTag(), author.getId(), targetUser.getAsTag(), targetUser.getId(), guild.getName(), reason); - return guild.removeRoleFromMember(target, maybeMutedRole.orElseThrow()) + return guild.removeRoleFromMember(target, getMutedRole(guild).orElseThrow()) .reason(reason) .map(unmuteResult -> sendDmResult.isSuccess()); }) @@ -108,6 +99,15 @@ private void unmuteUser(@NotNull Member target, @NotNull Member author, @NotNull private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @Nullable Member target, @NotNull CharSequence reason, @NotNull Guild guild, @NotNull Interaction event) { + Optional maybeMutedRole = getMutedRole(guild); + if (maybeMutedRole.isEmpty()) { + event.reply("Can not mute the user, unable to find a mute role on this server") + .setEphemeral(true) + .queue(); + logger.warn("The guild '{}' does not have a mute role.", guild.getName()); + return false; + } + // Member doesn't exist if attempting to mute a user who is not part of the guild anymore. if (target == null) { handleAbsentTarget(event); @@ -116,6 +116,10 @@ private boolean handleChecks(@NotNull Member bot, @NotNull Member author, if (!ModerationUtils.handleCanInteractWithTarget(ACTION_VERB, bot, author, target, event)) { return false; } + if (!ModerationUtils.handleCanInteractWithRole(bot, author, maybeMutedRole.orElseThrow(), + event)) { + return false; + } if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { return false; } From e776e79c5bb30f3e4b4804adf4e46683489c839b Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Mon, 8 Nov 2021 13:12:55 +0100 Subject: [PATCH 3/9] Getting rid of some code duplication --- .../commands/moderation/ModerationUtils.java | 77 ++++++++++++++++++- .../commands/moderation/MuteCommand.java | 43 ++--------- .../commands/moderation/UnmuteCommand.java | 43 ++--------- 3 files changed, 92 insertions(+), 71 deletions(-) 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 b9efc77bd0..823a1e71e8 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 @@ -150,6 +150,81 @@ static boolean handleHasBotPermissions(@NotNull String actionVerb, return true; } + private static void handleAbsentTarget(@NotNull String actionVerb, @NotNull Interaction event) { + event + .reply("I can not %s the given user since they are not part of the guild anymore." + .formatted(actionVerb)) + .setEphemeral(true) + .queue(); + } + + /** + * Checks whether the given bot and author have enough permission to change the roles of a given + * target. For example whether they have enough permissions to add a role to a user. + *

+ * If not, it will handle the situation and respond to the user. + *

+ * The checks include: + *

+ * + * @param role the role to change, or {@code null} if it does not exist on the guild + * @param actionVerb the interaction as verb, for example {@code "mute"} or {@code "unmute"} + * @param target the target user to change roles from, or {@code null} if the user is not member + * of the guild + * @param bot the bot executing this interaction + * @param author the author attempting to interact with the target + * @param guild the guild this interaction is executed on + * @param hasRequiredRole a predicate used to identify required roles by their name + * @param reason the reason for this interaction + * @param event the event used to respond to the user + * @return Whether the bot and the author have enough permission + */ + @SuppressWarnings({"MethodWithTooManyParameters", "BooleanMethodNameMustStartWithQuestion", + "squid:S107"}) + static boolean handleRoleChangeChecks(@Nullable Role role, @NotNull String actionVerb, + @Nullable Member target, @NotNull Member bot, @NotNull Member author, + @NotNull Guild guild, @NotNull Predicate hasRequiredRole, + @NotNull CharSequence reason, @NotNull Interaction event) { + if (role == null) { + event + .reply("Can not %s the user, unable to find the corresponding role on this server" + .formatted(actionVerb)) + .setEphemeral(true) + .queue(); + logger.warn("The guild '{}' does not have a role to {} users.", guild.getName(), + actionVerb); + return false; + } + + // Member doesn't exist if attempting to change roles of a user who is not part of the guild + // anymore. + if (target == null) { + handleAbsentTarget(actionVerb, event); + return false; + } + if (!handleCanInteractWithTarget(actionVerb, bot, author, target, event)) { + return false; + } + if (!handleCanInteractWithRole(bot, author, role, event)) { + return false; + } + if (!handleHasAuthorRole(actionVerb, hasRequiredRole, author, event)) { + return false; + } + if (!handleHasBotPermissions(actionVerb, Permission.MANAGE_ROLES, bot, guild, event)) { + return false; + } + return ModerationUtils.handleReason(reason, event); + } + /** * Checks whether the given author has enough permission to execute the given action. For * example whether they have enough permissions to ban users. @@ -206,7 +281,7 @@ static boolean handleHasAuthorRole(@NotNull String actionVerb, /** * Creates a message to be displayed as response to a moderation action. - * + *

* Essentially, it informs others about the action, such as "John banned Bob for playing with * the fire.". * 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 da339cd1c4..5b763145e0 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 @@ -1,6 +1,5 @@ package org.togetherjava.tjbot.commands.moderation; -import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Role; @@ -52,12 +51,6 @@ public MuteCommand() { isMuteRole = Pattern.compile(Config.getInstance().getMutedRolePattern()).asMatchPredicate(); } - private static void handleAbsentTarget(@NotNull Interaction event) { - event.reply("I can not mute the given user since they are not part of the guild anymore.") - .setEphemeral(true) - .queue(); - } - private static void handleAlreadyMutedTarget(@NotNull Interaction event) { event.reply("The user is already muted.").setEphemeral(true).queue(); } @@ -100,39 +93,19 @@ private void muteUser(@NotNull Member target, @NotNull Member author, @NotNull S private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @Nullable Member target, @NotNull CharSequence reason, @NotNull Guild guild, @NotNull Interaction event) { - Optional maybeMutedRole = getMutedRole(guild); - if (maybeMutedRole.isEmpty()) { - event.reply("Can not mute the user, unable to find a mute role on this server") - .setEphemeral(true) - .queue(); - logger.warn("The guild '{}' does not have a mute role.", guild.getName()); - return false; - } - - // Member doesn't exist if attempting to mute a user who is not part of the guild anymore. - if (target == null) { - handleAbsentTarget(event); - return false; - } - if (!ModerationUtils.handleCanInteractWithTarget(ACTION_VERB, bot, author, target, event)) { - return false; - } - if (!ModerationUtils.handleCanInteractWithRole(bot, author, maybeMutedRole.orElseThrow(), - event)) { - return false; - } - if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { - return false; - } - if (!ModerationUtils.handleHasBotPermissions(ACTION_VERB, Permission.MANAGE_ROLES, bot, - guild, event)) { + if (!ModerationUtils.handleRoleChangeChecks(getMutedRole(guild).orElse(null), ACTION_VERB, + target, bot, author, guild, hasRequiredRole, reason, event)) { return false; } - if (target.getRoles().stream().map(Role::getName).anyMatch(isMuteRole)) { + if (Objects.requireNonNull(target) + .getRoles() + .stream() + .map(Role::getName) + .anyMatch(isMuteRole)) { handleAlreadyMutedTarget(event); return false; } - return ModerationUtils.handleReason(reason, event); + return true; } @Override 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 7b8cdfddd6..f6ca3e2467 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 @@ -1,6 +1,5 @@ package org.togetherjava.tjbot.commands.moderation; -import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Role; @@ -53,12 +52,6 @@ public UnmuteCommand() { isMuteRole = Pattern.compile(Config.getInstance().getMutedRolePattern()).asMatchPredicate(); } - private static void handleAbsentTarget(@NotNull Interaction event) { - event.reply("I can not unmute the given user since they are not part of the guild anymore.") - .setEphemeral(true) - .queue(); - } - private static void handleNotMutedTarget(@NotNull Interaction event) { event.reply("The user is not muted.").setEphemeral(true).queue(); } @@ -99,39 +92,19 @@ private void unmuteUser(@NotNull Member target, @NotNull Member author, @NotNull private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @Nullable Member target, @NotNull CharSequence reason, @NotNull Guild guild, @NotNull Interaction event) { - Optional maybeMutedRole = getMutedRole(guild); - if (maybeMutedRole.isEmpty()) { - event.reply("Can not mute the user, unable to find a mute role on this server") - .setEphemeral(true) - .queue(); - logger.warn("The guild '{}' does not have a mute role.", guild.getName()); - return false; - } - - // Member doesn't exist if attempting to mute a user who is not part of the guild anymore. - if (target == null) { - handleAbsentTarget(event); - return false; - } - if (!ModerationUtils.handleCanInteractWithTarget(ACTION_VERB, bot, author, target, event)) { - return false; - } - if (!ModerationUtils.handleCanInteractWithRole(bot, author, maybeMutedRole.orElseThrow(), - event)) { - return false; - } - if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { - return false; - } - if (!ModerationUtils.handleHasBotPermissions(ACTION_VERB, Permission.MANAGE_ROLES, bot, - guild, event)) { + if (!ModerationUtils.handleRoleChangeChecks(getMutedRole(guild).orElse(null), ACTION_VERB, + target, bot, author, guild, hasRequiredRole, reason, event)) { return false; } - if (target.getRoles().stream().map(Role::getName).noneMatch(isMuteRole)) { + if (Objects.requireNonNull(target) + .getRoles() + .stream() + .map(Role::getName) + .noneMatch(isMuteRole)) { handleNotMutedTarget(event); return false; } - return ModerationUtils.handleReason(reason, event); + return true; } @Override From 0f6c35ed22ee5550dc64c4104983bb6e2ded11cd Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Tue, 16 Nov 2021 10:13:00 +0100 Subject: [PATCH 4/9] Simplified mute/unmute flow using individual methods (CR Tais) --- .../commands/moderation/MuteCommand.java | 63 ++++++++++-------- .../commands/moderation/UnmuteCommand.java | 64 +++++++++++-------- 2 files changed, 76 insertions(+), 51 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 5b763145e0..159d9b410e 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 @@ -1,12 +1,13 @@ package org.togetherjava.tjbot.commands.moderation; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Role; -import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.entities.*; +import net.dv8tion.jda.api.events.GenericEvent; 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.requests.RestAction; +import net.dv8tion.jda.api.requests.restaction.AuditableRestAction; +import net.dv8tion.jda.api.utils.Result; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; @@ -55,9 +56,8 @@ private static void handleAlreadyMutedTarget(@NotNull Interaction event) { event.reply("The user is already muted.").setEphemeral(true).queue(); } - private void muteUser(@NotNull Member target, @NotNull Member author, @NotNull String reason, - @NotNull Guild guild, @NotNull SlashCommandEvent event) { - User targetUser = target.getUser(); + private static RestAction sendDm(@NotNull ISnowflake target, @NotNull String reason, + @NotNull Guild guild, @NotNull GenericEvent event) { String dmMessage = """ Hey there, sorry to tell you but unfortunately you have been muted in the server %s. @@ -66,25 +66,37 @@ private void muteUser(@NotNull Member target, @NotNull Member author, @NotNull S The reason for the mute is: %s """ .formatted(guild.getName(), reason); - - event.getJDA() - .openPrivateChannelById(targetUser.getId()) + return event.getJDA() + .openPrivateChannelById(target.getId()) .flatMap(channel -> channel.sendMessage(dmMessage)) .mapToResult() - .flatMap(sendDmResult -> { - logger.info("'{}' ({}) muted the user '{}' ({}) in guild '{}' for reason '{}'.", - author.getUser().getAsTag(), author.getId(), targetUser.getAsTag(), - targetUser.getId(), guild.getName(), reason); - return guild.addRoleToMember(target, getMutedRole(guild).orElseThrow()) - .reason(reason) - .map(muteResult -> sendDmResult.isSuccess()); - }) - .map(hasSentDm -> { - String dmNotice = - Boolean.TRUE.equals(hasSentDm) ? "" : "(Unable to send them a DM.)"; - return ModerationUtils.createActionResponse(author.getUser(), - ModerationUtils.Action.MUTE, targetUser, dmNotice, reason); - }) + .map(Result::isSuccess); + } + + private static @NotNull MessageEmbed sendFeedback(boolean hasSentDm, @NotNull Member target, + @NotNull Member author, @NotNull String reason) { + String dmNoticeText = ""; + if (!hasSentDm) { + dmNoticeText = "(Unable to send them a DM.)"; + } + return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.MUTE, + target.getUser(), dmNoticeText, reason); + } + + private AuditableRestAction muteUser(@NotNull Member target, @NotNull Member author, + @NotNull String reason, @NotNull Guild guild) { + logger.info("'{}' ({}) muted the user '{}' ({}) in guild '{}' for reason '{}'.", + author.getUser().getAsTag(), author.getId(), target.getUser().getAsTag(), + target.getId(), guild.getName(), reason); + return guild.addRoleToMember(target, 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) + .map(banResult -> hasSentDm)) + .map(hasSentDm -> sendFeedback(hasSentDm, target, author, reason)) .flatMap(event::replyEmbeds) .queue(); } @@ -122,7 +134,8 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { if (!handleChecks(bot, author, target, reason, guild, event)) { return; } - muteUser(Objects.requireNonNull(target), author, reason, guild, event); + + muteUserFlow(Objects.requireNonNull(target), author, reason, guild, event); } private @NotNull Optional getMutedRole(@NotNull Guild guild) { 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 f6ca3e2467..4c7c95b84f 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 @@ -1,12 +1,13 @@ package org.togetherjava.tjbot.commands.moderation; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Role; -import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.entities.*; +import net.dv8tion.jda.api.events.GenericEvent; 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.requests.RestAction; +import net.dv8tion.jda.api.requests.restaction.AuditableRestAction; +import net.dv8tion.jda.api.utils.Result; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; @@ -56,34 +57,45 @@ private static void handleNotMutedTarget(@NotNull Interaction event) { event.reply("The user is not muted.").setEphemeral(true).queue(); } - private void unmuteUser(@NotNull Member target, @NotNull Member author, @NotNull String reason, - @NotNull Guild guild, @NotNull SlashCommandEvent event) { - User targetUser = target.getUser(); + private static RestAction sendDm(@NotNull ISnowflake target, @NotNull String reason, + @NotNull Guild guild, @NotNull GenericEvent event) { String dmMessage = """ Hey there, you have been unmuted in the server %s. This means you can now send messages in the server again. The reason for the unmute is: %s """.formatted(guild.getName(), reason); - - event.getJDA() - .openPrivateChannelById(targetUser.getId()) + return event.getJDA() + .openPrivateChannelById(target.getId()) .flatMap(channel -> channel.sendMessage(dmMessage)) .mapToResult() - .flatMap(sendDmResult -> { - logger.info("'{}' ({}) unmuted the user '{}' ({}) in guild '{}' for reason '{}'.", - author.getUser().getAsTag(), author.getId(), targetUser.getAsTag(), - targetUser.getId(), guild.getName(), reason); - - return guild.removeRoleFromMember(target, getMutedRole(guild).orElseThrow()) - .reason(reason) - .map(unmuteResult -> sendDmResult.isSuccess()); - }) - .map(hasSentDm -> { - String dmNotice = - Boolean.TRUE.equals(hasSentDm) ? "" : "(Unable to send them a DM.)"; - return ModerationUtils.createActionResponse(author.getUser(), - ModerationUtils.Action.UNMUTE, targetUser, dmNotice, reason); - }) + .map(Result::isSuccess); + } + + private static @NotNull MessageEmbed sendFeedback(boolean hasSentDm, @NotNull Member target, + @NotNull Member author, @NotNull String reason) { + String dmNoticeText = ""; + if (!hasSentDm) { + dmNoticeText = "(Unable to send them a DM.)"; + } + return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.UNMUTE, + target.getUser(), dmNoticeText, reason); + } + + private AuditableRestAction unmuteUser(@NotNull Member target, @NotNull Member author, + @NotNull String reason, @NotNull Guild guild) { + logger.info("'{}' ({}) unmuted the user '{}' ({}) in guild '{}' for reason '{}'.", + author.getUser().getAsTag(), author.getId(), target.getUser().getAsTag(), + target.getId(), guild.getName(), reason); + + return guild.removeRoleFromMember(target, getMutedRole(guild).orElseThrow()).reason(reason); + } + + private void unmuteUserFlow(@NotNull Member target, @NotNull Member author, + @NotNull String reason, @NotNull Guild guild, @NotNull SlashCommandEvent event) { + sendDm(target, reason, guild, event) + .flatMap(hasSentDm -> unmuteUser(target, author, reason, guild) + .map(banResult -> hasSentDm)) + .map(hasSentDm -> sendFeedback(hasSentDm, target, author, reason)) .flatMap(event::replyEmbeds) .queue(); } @@ -121,7 +133,7 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { if (!handleChecks(bot, author, target, reason, guild, event)) { return; } - unmuteUser(Objects.requireNonNull(target), author, reason, guild, event); + unmuteUserFlow(Objects.requireNonNull(target), author, reason, guild, event); } private @NotNull Optional getMutedRole(@NotNull Guild guild) { From 7cf277d4089cde31eba8a2778709de3f2b1a2819 Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Fri, 10 Dec 2021 09:23:17 +0100 Subject: [PATCH 5/9] Integrated ModerationActionsStore into Mute/Unmute --- .../java/org/togetherjava/tjbot/commands/Commands.java | 4 ++-- .../tjbot/commands/moderation/MuteCommand.java | 10 +++++++++- .../tjbot/commands/moderation/UnmuteCommand.java | 9 ++++++++- 3 files changed, 19 insertions(+), 4 deletions(-) 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 596d4cd67b..75a35dde02 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -57,8 +57,8 @@ public enum Commands { commands.add(new UnbanCommand(actionsStore)); commands.add(new FreeCommand()); commands.add(new AuditCommand(actionsStore)); - commands.add(new MuteCommand()); - commands.add(new UnmuteCommand()); + commands.add(new MuteCommand(actionsStore)); + commands.add(new UnmuteCommand(actionsStore)); return commands; } 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 159d9b410e..3e2f0755b5 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 @@ -36,11 +36,14 @@ public final class MuteCommand extends SlashCommandAdapter { private static final String ACTION_VERB = "mute"; private final Predicate hasRequiredRole; private final Predicate isMuteRole; + private final ModerationActionsStore actionsStore; /** * Constructs an instance. + * + * @param actionsStore used to store actions issued by this command */ - public MuteCommand() { + public MuteCommand(@NotNull ModerationActionsStore actionsStore) { super(COMMAND_NAME, "Mutes the given user so that they can not send messages anymore", SlashCommandVisibility.GUILD); @@ -50,6 +53,7 @@ public MuteCommand() { hasRequiredRole = Pattern.compile(Config.getInstance().getSoftModerationRolePattern()) .asMatchPredicate(); isMuteRole = Pattern.compile(Config.getInstance().getMutedRolePattern()).asMatchPredicate(); + this.actionsStore = Objects.requireNonNull(actionsStore); } private static void handleAlreadyMutedTarget(@NotNull Interaction event) { @@ -88,6 +92,10 @@ private AuditableRestAction muteUser(@NotNull Member target, @NotNull Memb logger.info("'{}' ({}) muted the user '{}' ({}) in guild '{}' for reason '{}'.", author.getUser().getAsTag(), author.getId(), target.getUser().getAsTag(), target.getId(), guild.getName(), reason); + + actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), + ModerationUtils.Action.MUTE, null, reason); + return guild.addRoleToMember(target, getMutedRole(guild).orElseThrow()).reason(reason); } 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 4c7c95b84f..1a2f85a75b 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 @@ -36,11 +36,14 @@ public final class UnmuteCommand extends SlashCommandAdapter { private static final String ACTION_VERB = "unmute"; private final Predicate hasRequiredRole; private final Predicate isMuteRole; + private final ModerationActionsStore actionsStore; /** * Constructs an instance. + * + * @param actionsStore used to store actions issued by this command */ - public UnmuteCommand() { + public UnmuteCommand(@NotNull ModerationActionsStore actionsStore) { super(COMMAND_NAME, "Unmutes the given already muted user so that they can send messages again", SlashCommandVisibility.GUILD); @@ -51,6 +54,7 @@ public UnmuteCommand() { hasRequiredRole = Pattern.compile(Config.getInstance().getSoftModerationRolePattern()) .asMatchPredicate(); isMuteRole = Pattern.compile(Config.getInstance().getMutedRolePattern()).asMatchPredicate(); + this.actionsStore = Objects.requireNonNull(actionsStore); } private static void handleNotMutedTarget(@NotNull Interaction event) { @@ -87,6 +91,9 @@ private AuditableRestAction unmuteUser(@NotNull Member target, @NotNull Me author.getUser().getAsTag(), author.getId(), target.getUser().getAsTag(), target.getId(), guild.getName(), reason); + actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), + ModerationUtils.Action.UNMUTE, null, reason); + return guild.removeRoleFromMember(target, getMutedRole(guild).orElseThrow()).reason(reason); } From 3ad978fc999b5f8f991052366a3e70c2f9f57d74 Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Fri, 10 Dec 2021 10:27:58 +0100 Subject: [PATCH 6/9] Moved routines and listeners inside Commands this change is not super nice design but it is necessary for now, since routines and listeners need access to systems such as `TagSystem`, `ModAuditLogStore` and similar, which are created there. the plan is to make all of this nicer with #235 and #236 --- .../java/org/togetherjava/tjbot/Application.java | 8 +++----- .../org/togetherjava/tjbot/commands/Commands.java | 12 ++++++++++-- .../tjbot/commands/system/CommandSystem.java | 6 ++++-- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/Application.java b/application/src/main/java/org/togetherjava/tjbot/Application.java index e6326df1d5..3b107985db 100644 --- a/application/src/main/java/org/togetherjava/tjbot/Application.java +++ b/application/src/main/java/org/togetherjava/tjbot/Application.java @@ -2,6 +2,7 @@ import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; +import net.dv8tion.jda.api.requests.GatewayIntent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.togetherjava.tjbot.commands.Commands; @@ -77,15 +78,12 @@ public static void runBot(String token, Path databasePath) { Database database = new Database("jdbc:sqlite:" + databasePath.toAbsolutePath()); JDA jda = JDABuilder.createDefault(token) - .addEventListeners(new CommandSystem(database)) + .enableIntents(GatewayIntent.GUILD_MEMBERS) .build(); + jda.addEventListener(new CommandSystem(jda, database)); jda.awaitReady(); logger.info("Bot is ready"); - // 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(); - Runtime.getRuntime().addShutdownHook(new Thread(Application::onShutdown)); } catch (LoginException e) { logger.error("Failed to login", e); 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 75a35dde02..92a99737c6 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -1,5 +1,6 @@ package org.togetherjava.tjbot.commands; +import net.dv8tion.jda.api.JDA; import org.jetbrains.annotations.NotNull; import org.togetherjava.tjbot.commands.basic.DatabaseCommand; import org.togetherjava.tjbot.commands.basic.PingCommand; @@ -12,6 +13,7 @@ import org.togetherjava.tjbot.commands.tags.TagSystem; import org.togetherjava.tjbot.commands.tags.TagsCommand; import org.togetherjava.tjbot.db.Database; +import org.togetherjava.tjbot.routines.ModAuditLogRoutine; import java.util.ArrayList; import java.util.Collection; @@ -22,7 +24,7 @@ * pick it up from and register it with the system. *

* To add a new slash command, extend the commands returned by - * {@link #createSlashCommands(Database)}. + * {@link #createSlashCommands(JDA, Database)}. */ public enum Commands { ; @@ -33,13 +35,19 @@ public enum Commands { * Calling this method multiple times will result in multiple commands being created, which * generally should be avoided. * + * @param jda the JDA instance commands will be registered at * @param database the database of the application, which commands can use to persist data * @return a collection of all slash commands */ - public static @NotNull Collection createSlashCommands( + public static @NotNull Collection createSlashCommands(@NotNull JDA jda, @NotNull Database database) { TagSystem tagSystem = new TagSystem(database); ModerationActionsStore actionsStore = new ModerationActionsStore(database); + + // 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(); + // NOTE The command system can add special system relevant commands also by itself, // hence this list may not necessarily represent the full list of all commands actually // available. diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/system/CommandSystem.java b/application/src/main/java/org/togetherjava/tjbot/commands/system/CommandSystem.java index e829790546..4be65e20ae 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/system/CommandSystem.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/system/CommandSystem.java @@ -1,5 +1,6 @@ package org.togetherjava.tjbot.commands.system; +import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.TextChannel; @@ -55,11 +56,12 @@ public final class CommandSystem extends ListenerAdapter implements SlashCommand *

* Commands are fetched from {@link Commands}. * + * @param jda the JDA instance that this command system will be used with * @param database the database that commands may use to persist data */ @SuppressWarnings("ThisEscapedInObjectConstruction") - public CommandSystem(@NotNull Database database) { - nameToSlashCommands = Commands.createSlashCommands(database) + public CommandSystem(@NotNull JDA jda, @NotNull Database database) { + nameToSlashCommands = Commands.createSlashCommands(jda, database) .stream() .collect(Collectors.toMap(SlashCommand::getName, Function.identity())); From ec401569039fc63153cc649182de1cc43d80986a Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Fri, 10 Dec 2021 10:28:42 +0100 Subject: [PATCH 7/9] Moved isMutedRole logic into utility class to reduce duplication --- .../commands/moderation/ModerationUtils.java | 17 ++++++++++++++++- .../tjbot/commands/moderation/MuteCommand.java | 16 ++++++---------- .../commands/moderation/UnmuteCommand.java | 16 ++++++---------- .../tjbot/routines/ModAuditLogRoutine.java | 15 +++++++-------- 4 files changed, 35 insertions(+), 29 deletions(-) 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 823a1e71e8..339541f8e0 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 @@ -8,15 +8,18 @@ import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.config.Config; import java.awt.*; import java.time.Instant; +import java.util.Optional; import java.util.function.Predicate; +import java.util.regex.Pattern; /** * Utility class offering helpers revolving around user moderation, such as banning or kicking. */ -enum ModerationUtils { +public enum ModerationUtils { ; private static final Logger logger = LoggerFactory.getLogger(ModerationUtils.class); @@ -26,6 +29,8 @@ enum ModerationUtils { */ private static final int REASON_MAX_LENGTH = 512; static final Color AMBIENT_COLOR = Color.decode("#895FE8"); + public static final Predicate isMuteRole = + Pattern.compile(Config.getInstance().getMutedRolePattern()).asMatchPredicate(); /** * Checks whether the given reason is valid. If not, it will handle the situation and respond to @@ -310,6 +315,16 @@ static boolean handleHasAuthorRole(@NotNull String actionVerb, .build(); } + /** + * Gets the role used to mute a member in a guild. + * + * @param guild the guild to get the muted role from + * @return the muted role, if found + */ + public static @NotNull Optional getMutedRole(@NotNull Guild guild) { + return guild.getRoles().stream().filter(role -> isMuteRole.test(role.getName())).findAny(); + } + /** * All available moderation actions. */ 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 3e2f0755b5..5ec13205f4 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 @@ -35,7 +35,6 @@ public final class MuteCommand extends SlashCommandAdapter { private static final String COMMAND_NAME = "mute"; private static final String ACTION_VERB = "mute"; private final Predicate hasRequiredRole; - private final Predicate isMuteRole; private final ModerationActionsStore actionsStore; /** @@ -52,7 +51,6 @@ public MuteCommand(@NotNull ModerationActionsStore actionsStore) { hasRequiredRole = Pattern.compile(Config.getInstance().getSoftModerationRolePattern()) .asMatchPredicate(); - isMuteRole = Pattern.compile(Config.getInstance().getMutedRolePattern()).asMatchPredicate(); this.actionsStore = Objects.requireNonNull(actionsStore); } @@ -96,7 +94,8 @@ private AuditableRestAction muteUser(@NotNull Member target, @NotNull Memb actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), ModerationUtils.Action.MUTE, null, reason); - return guild.addRoleToMember(target, getMutedRole(guild).orElseThrow()).reason(reason); + return guild.addRoleToMember(target, ModerationUtils.getMutedRole(guild).orElseThrow()) + .reason(reason); } private void muteUserFlow(@NotNull Member target, @NotNull Member author, @@ -113,15 +112,16 @@ private void muteUserFlow(@NotNull Member target, @NotNull Member author, private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @Nullable Member target, @NotNull CharSequence reason, @NotNull Guild guild, @NotNull Interaction event) { - if (!ModerationUtils.handleRoleChangeChecks(getMutedRole(guild).orElse(null), ACTION_VERB, - target, bot, author, guild, hasRequiredRole, reason, event)) { + if (!ModerationUtils.handleRoleChangeChecks( + ModerationUtils.getMutedRole(guild).orElse(null), ACTION_VERB, target, bot, author, + guild, hasRequiredRole, reason, event)) { return false; } if (Objects.requireNonNull(target) .getRoles() .stream() .map(Role::getName) - .anyMatch(isMuteRole)) { + .anyMatch(ModerationUtils.isMuteRole)) { handleAlreadyMutedTarget(event); return false; } @@ -145,8 +145,4 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { muteUserFlow(Objects.requireNonNull(target), author, reason, guild, event); } - - private @NotNull Optional getMutedRole(@NotNull Guild guild) { - return guild.getRoles().stream().filter(role -> isMuteRole.test(role.getName())).findAny(); - } } 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 1a2f85a75b..ed809b8981 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 @@ -35,7 +35,6 @@ public final class UnmuteCommand extends SlashCommandAdapter { private static final String COMMAND_NAME = "unmute"; private static final String ACTION_VERB = "unmute"; private final Predicate hasRequiredRole; - private final Predicate isMuteRole; private final ModerationActionsStore actionsStore; /** @@ -53,7 +52,6 @@ public UnmuteCommand(@NotNull ModerationActionsStore actionsStore) { hasRequiredRole = Pattern.compile(Config.getInstance().getSoftModerationRolePattern()) .asMatchPredicate(); - isMuteRole = Pattern.compile(Config.getInstance().getMutedRolePattern()).asMatchPredicate(); this.actionsStore = Objects.requireNonNull(actionsStore); } @@ -94,7 +92,8 @@ private AuditableRestAction unmuteUser(@NotNull Member target, @NotNull Me actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), ModerationUtils.Action.UNMUTE, null, reason); - return guild.removeRoleFromMember(target, getMutedRole(guild).orElseThrow()).reason(reason); + return guild.removeRoleFromMember(target, ModerationUtils.getMutedRole(guild).orElseThrow()) + .reason(reason); } private void unmuteUserFlow(@NotNull Member target, @NotNull Member author, @@ -111,15 +110,16 @@ private void unmuteUserFlow(@NotNull Member target, @NotNull Member author, private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @Nullable Member target, @NotNull CharSequence reason, @NotNull Guild guild, @NotNull Interaction event) { - if (!ModerationUtils.handleRoleChangeChecks(getMutedRole(guild).orElse(null), ACTION_VERB, - target, bot, author, guild, hasRequiredRole, reason, event)) { + if (!ModerationUtils.handleRoleChangeChecks( + ModerationUtils.getMutedRole(guild).orElse(null), ACTION_VERB, target, bot, author, + guild, hasRequiredRole, reason, event)) { return false; } if (Objects.requireNonNull(target) .getRoles() .stream() .map(Role::getName) - .noneMatch(isMuteRole)) { + .noneMatch(ModerationUtils.isMuteRole)) { handleNotMutedTarget(event); return false; } @@ -142,8 +142,4 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { } unmuteUserFlow(Objects.requireNonNull(target), author, reason, guild, event); } - - private @NotNull Optional getMutedRole(@NotNull Guild guild) { - return guild.getRoles().stream().filter(role -> isMuteRole.test(role.getName())).findAny(); - } } diff --git a/application/src/main/java/org/togetherjava/tjbot/routines/ModAuditLogRoutine.java b/application/src/main/java/org/togetherjava/tjbot/routines/ModAuditLogRoutine.java index e4ef54ce36..c32b8b5d10 100644 --- a/application/src/main/java/org/togetherjava/tjbot/routines/ModAuditLogRoutine.java +++ b/application/src/main/java/org/togetherjava/tjbot/routines/ModAuditLogRoutine.java @@ -15,6 +15,7 @@ import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.moderation.ModerationUtils; import org.togetherjava.tjbot.config.Config; import org.togetherjava.tjbot.db.Database; import org.togetherjava.tjbot.db.generated.tables.ModAuditLogGuildProcess; @@ -49,7 +50,6 @@ public final class ModAuditLogRoutine { private static final Color AMBIENT_COLOR = Color.decode("#4FC3F7"); private final Predicate isAuditLogChannel; - private final Predicate isMutedRole; private final Database database; private final JDA jda; private final ScheduledExecutorService checkAuditLogService = @@ -67,8 +67,6 @@ public ModAuditLogRoutine(@NotNull JDA jda, @NotNull Database database) { .asMatchPredicate(); isAuditLogChannel = channel -> isAuditLogChannelName.test(channel.getName()); - isMutedRole = - Pattern.compile(Config.getInstance().getMutedRolePattern()).asMatchPredicate(); this.database = database; this.jda = jda; } @@ -293,8 +291,8 @@ private void handleAuditLogs(@NotNull MessageChannel auditLogChannel, }); } - private Optional> handleAuditLog(@NotNull MessageChannel auditLogChannel, - @NotNull AuditLogEntry entry) { + private static Optional> handleAuditLog( + @NotNull MessageChannel auditLogChannel, @NotNull AuditLogEntry entry) { Optional> maybeMessage = switch (entry.getType()) { case BAN -> handleBanEntry(entry); case UNBAN -> handleUnbanEntry(entry); @@ -306,7 +304,7 @@ private Optional> handleAuditLog(@NotNull MessageChannel aud return maybeMessage.map(message -> message.flatMap(auditLogChannel::sendMessageEmbeds)); } - private @NotNull Optional> handleRoleUpdateEntry( + private static @NotNull Optional> handleRoleUpdateEntry( @NotNull AuditLogEntry entry) { if (containsMutedRole(entry, AuditLogKey.MEMBER_ROLES_ADD)) { return handleMuteEntry(entry); @@ -317,7 +315,8 @@ private Optional> handleAuditLog(@NotNull MessageChannel aud return Optional.empty(); } - private boolean containsMutedRole(@NotNull AuditLogEntry entry, @NotNull AuditLogKey key) { + private static boolean containsMutedRole(@NotNull AuditLogEntry entry, + @NotNull AuditLogKey key) { List> roleChanges = Optional.ofNullable(entry.getChangeByKey(key)) .>>map(AuditLogChange::getNewValue) .orElse(List.of()); @@ -326,7 +325,7 @@ private boolean containsMutedRole(@NotNull AuditLogEntry entry, @NotNull AuditLo .flatMap(Collection::stream) .filter(changeEntry -> "name".equals(changeEntry.getKey())) .map(Map.Entry::getValue) - .anyMatch(isMutedRole); + .anyMatch(ModerationUtils.isMuteRole); } private Optional getModAuditLogChannel(@NotNull Guild guild) { From c5cdc1e4c4e2ab84f8b73998775229217bc72f74 Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Fri, 10 Dec 2021 10:29:04 +0100 Subject: [PATCH 8/9] Added RejoinMuted listener to fix mute-bypass-exploit --- .../togetherjava/tjbot/commands/Commands.java | 4 + .../moderation/RejoinMuteListener.java | 84 +++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/moderation/RejoinMuteListener.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 92a99737c6..c748f68bf0 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -48,6 +48,10 @@ public enum Commands { // which adds support for routines) new ModAuditLogRoutine(jda, database).start(); + // TODO This should be moved into some proper command system instead (see GH issue #236 + // which adds support for listeners) + jda.addEventListener(new RejoinMuteListener(actionsStore)); + // NOTE The command system can add special system relevant commands also by itself, // hence this list may not necessarily represent the full list of all commands actually // available. 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 new file mode 100644 index 0000000000..ed96141a54 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/RejoinMuteListener.java @@ -0,0 +1,84 @@ +package org.togetherjava.tjbot.commands.moderation; + +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.IPermissionHolder; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nonnull; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** + * Reapplies existing mutes to users who have left and rejoined a guild. + *

+ * Mutes are realized with roles and roles are removed upon leaving a guild, making it possible for + * users to otherwise bypass a mute by simply leaving and rejoining a guild. This class listens for + * join events and reapplies the mute role in case the user is supposed to be muted still (according + * to the {@link ModerationActionsStore}). + */ +public final class RejoinMuteListener extends ListenerAdapter { + private static final Logger logger = LoggerFactory.getLogger(RejoinMuteListener.class); + + private final ModerationActionsStore actionsStore; + + /** + * Constructs an instance. + * + * @param actionsStore used to store actions issued by this command and to retrieve whether a + * user should be muted + */ + public RejoinMuteListener(@NotNull ModerationActionsStore actionsStore) { + this.actionsStore = Objects.requireNonNull(actionsStore); + } + + private static void muteMember(@NotNull Member member) { + Guild guild = member.getGuild(); + logger.info("Reapplied existing mute to user '{}' ({}) in guild '{}' after rejoining.", + member.getUser().getAsTag(), member.getId(), guild.getName()); + + guild.addRoleToMember(member, ModerationUtils.getMutedRole(guild).orElseThrow()) + .reason("Reapplied existing mute after rejoining the server") + .queue(); + } + + @Override + public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { + Member member = event.getMember(); + if (!shouldMemberBeMuted(member)) { + return; + } + muteMember(member); + } + + private boolean shouldMemberBeMuted(@NotNull IPermissionHolder member) { + List actions = actionsStore + .getActionsByTargetAscending(member.getGuild().getIdLong(), member.getIdLong()); + Collections.reverse(actions); + + Optional lastMute = actions.stream() + .filter(action -> action.actionType() == ModerationUtils.Action.MUTE) + .findFirst(); + if (lastMute.isEmpty()) { + // User was never muted + return false; + } + + Optional lastUnmute = actions.stream() + .filter(action -> action.actionType() == ModerationUtils.Action.UNMUTE) + .findFirst(); + if (lastUnmute.isEmpty()) { + // User was never unmuted + return true; + } + + // The last issued action takes priority + return lastMute.orElseThrow().issuedAt().isAfter(lastUnmute.orElseThrow().issuedAt()); + } +} From 92fc9d629f44e36070799ec342c294a2acfdd90c Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Fri, 10 Dec 2021 11:15:28 +0100 Subject: [PATCH 9/9] Cleanup and bugfix with unmodifable list --- .../main/java/org/togetherjava/tjbot/Application.java | 1 - .../tjbot/commands/moderation/MuteCommand.java | 1 - .../tjbot/commands/moderation/RejoinMuteListener.java | 9 +++------ .../tjbot/commands/moderation/UnmuteCommand.java | 1 - 4 files changed, 3 insertions(+), 9 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/Application.java b/application/src/main/java/org/togetherjava/tjbot/Application.java index 3b107985db..fb4b93baae 100644 --- a/application/src/main/java/org/togetherjava/tjbot/Application.java +++ b/application/src/main/java/org/togetherjava/tjbot/Application.java @@ -9,7 +9,6 @@ import org.togetherjava.tjbot.commands.system.CommandSystem; import org.togetherjava.tjbot.config.Config; import org.togetherjava.tjbot.db.Database; -import org.togetherjava.tjbot.routines.ModAuditLogRoutine; import javax.security.auth.login.LoginException; import java.io.IOException; 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 5ec13205f4..cb363190fc 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 @@ -17,7 +17,6 @@ import org.togetherjava.tjbot.config.Config; import java.util.Objects; -import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Pattern; 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 ed96141a54..0278ce1c7c 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,10 +10,7 @@ import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Optional; +import java.util.*; /** * Reapplies existing mutes to users who have left and rejoined a guild. @@ -58,8 +55,8 @@ public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { } private boolean shouldMemberBeMuted(@NotNull IPermissionHolder member) { - List actions = actionsStore - .getActionsByTargetAscending(member.getGuild().getIdLong(), member.getIdLong()); + List actions = new ArrayList<>(actionsStore + .getActionsByTargetAscending(member.getGuild().getIdLong(), member.getIdLong())); Collections.reverse(actions); Optional lastMute = actions.stream() 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 ed809b8981..6828981c68 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 @@ -17,7 +17,6 @@ import org.togetherjava.tjbot.config.Config; import java.util.Objects; -import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Pattern;