diff --git a/application/config.json.template b/application/config.json.template index 6deb4738ec..11fd628486 100644 --- a/application/config.json.template +++ b/application/config.json.template @@ -18,6 +18,7 @@ "downVoteEmoteName": "peepo_no" }, "quarantinedRolePattern": "Quarantined", + "quarantineChannelPattern": "quarantine-zone", "scamBlocker": { "mode": "AUTO_DELETE_BUT_APPROVE_QUARANTINE", "reportChannelPattern": "commands", diff --git a/application/src/main/java/org/togetherjava/tjbot/config/Config.java b/application/src/main/java/org/togetherjava/tjbot/config/Config.java index d465f09800..eb919779a6 100644 --- a/application/src/main/java/org/togetherjava/tjbot/config/Config.java +++ b/application/src/main/java/org/togetherjava/tjbot/config/Config.java @@ -31,6 +31,7 @@ public final class Config { private final String excludeCodeAutoDetectionRolePattern; private final SuggestionsConfig suggestions; private final String quarantinedRolePattern; + private final String quarantineChannelPattern; private final ScamBlockerConfig scamBlocker; private final String wolframAlphaAppId; private final HelpSystemConfig helpSystem; @@ -79,6 +80,8 @@ private Config(@JsonProperty(value = "token", required = true) String token, @JsonProperty(value = "suggestions", required = true) SuggestionsConfig suggestions, @JsonProperty(value = "quarantinedRolePattern", required = true) String quarantinedRolePattern, + @JsonProperty(value = "quarantineChannelPattern", + required = true) String quarantineChannelPattern, @JsonProperty(value = "scamBlocker", required = true) ScamBlockerConfig scamBlocker, @JsonProperty(value = "wolframAlphaAppId", required = true) String wolframAlphaAppId, @JsonProperty(value = "helpSystem", required = true) HelpSystemConfig helpSystem, @@ -131,6 +134,7 @@ private Config(@JsonProperty(value = "token", required = true) String token, Objects.requireNonNull(excludeCodeAutoDetectionRolePattern); this.suggestions = Objects.requireNonNull(suggestions); this.quarantinedRolePattern = Objects.requireNonNull(quarantinedRolePattern); + this.quarantineChannelPattern = Objects.requireNonNull(quarantineChannelPattern); this.scamBlocker = Objects.requireNonNull(scamBlocker); this.wolframAlphaAppId = Objects.requireNonNull(wolframAlphaAppId); this.helpSystem = Objects.requireNonNull(helpSystem); @@ -312,6 +316,15 @@ public String getQuarantinedRolePattern() { return quarantinedRolePattern; } + /** + * Gets the REGEX pattern used to identify the channel assigned to quarantined users. + * + * @return the channel name pattern + */ + public String getQuarantineChannelPattern() { + return quarantineChannelPattern; + } + /** * Gets the config for the scam blocker system. * diff --git a/application/src/main/java/org/togetherjava/tjbot/features/moderation/ModerationUtils.java b/application/src/main/java/org/togetherjava/tjbot/features/moderation/ModerationUtils.java index 74b6e6ceec..74c40cf788 100644 --- a/application/src/main/java/org/togetherjava/tjbot/features/moderation/ModerationUtils.java +++ b/application/src/main/java/org/togetherjava/tjbot/features/moderation/ModerationUtils.java @@ -9,11 +9,15 @@ import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback; +import net.dv8tion.jda.api.interactions.components.buttons.Button; import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.requests.restaction.AuditableRestAction; import net.dv8tion.jda.api.utils.Result; import net.dv8tion.jda.api.utils.TimeUtil; +import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; +import net.dv8tion.jda.api.utils.messages.MessageCreateData; import net.dv8tion.jda.internal.requests.CompletedRestAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,9 +40,11 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.NoSuchElementException; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; +import java.util.function.Supplier; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -617,4 +623,78 @@ public static RestAction moderationActionToEmbedField( }); } + /** + * Quarantines the given user by recording the action and assigning the quarantine role. If the + * user was never quarantined in this guild before, a message pinging them with an "Unquarantine + * me" button is then posted in the quarantine channel. + *

+ * The action is recorded when this method is called, the role is only assigned once the + * returned action is executed. The message is sent only after the role was applied, and + * problems offering it (e.g. missing channel) are logged and never fail the returned action. + * + * @param config the app's config, used to find the quarantine role and channel + * @param selfServiceComponentId supplies the button's component ID + * @param actionsStore the store to record the action in and to check the user's history + * @param guild the guild to quarantine the user in + * @param author the member issuing the quarantine + * @param target the member to quarantine + * @param reason the reason of the quarantine + * @return the action assigning the quarantine role to the target + * @throws java.util.NoSuchElementException if the quarantine role does not exist + * @see Issue #1594 + */ + public static RestAction quarantine(Config config, + Supplier selfServiceComponentId, ModerationActionsStore actionsStore, + Guild guild, Member author, Member target, String reason) + throws NoSuchElementException { + + boolean isFirsttime = + actionsStore.getActionsByTargetAscending(guild.getIdLong(), target.getIdLong()) + .stream() + .noneMatch(action -> action.actionType() == ModerationAction.QUARANTINE); + + recordAction(guild, target.getUser(), author, ModerationAction.QUARANTINE, null, reason, + actionsStore); + + return guild.addRoleToMember(target, getQuarantinedRole(guild, config).orElseThrow()) + .reason(reason) + .onSuccess(_ -> { + + final String guildId = guild.getId(); + final String targetId = target.getId(); + + if (!isFirsttime) { + logger.warn("Unable to offer self-service unquarantine to '{}' in guild '{}'.", + targetId, guildId); + return; + } + + Optional quarantineChannel = Guilds.findTextChannel(guild, + Pattern.compile(config.getQuarantineChannelPattern()).asMatchPredicate()); + + if (quarantineChannel.isEmpty()) { + logger.warn( + "Unable to offer self-service unquarantine, no channel matching '{}' in guild '{}'.", + config.getQuarantineChannelPattern(), guild.getName()); + return; + } + + MessageCreateData message = new MessageCreateBuilder() + .setContent( + """ + %s. + If you regained control over your account by now, feel free to click the button \ + below to get back into the server. Otherwise, a moderator will get back to you here. Cheers""" + .formatted(target.getAsMention())) + .mentionUsers(target.getIdLong()) + .setActionRow(Button.primary(selfServiceComponentId.get(), "Unquarantine me")) + .build(); + + quarantineChannel.orElseThrow().sendMessage(message).queue(_ -> { + }, failure -> logger.warn( + "unable to offer self-service unquarantine to '{}' in guild '{}'.", + targetId, guildId, failure)); + + }); + } } diff --git a/application/src/main/java/org/togetherjava/tjbot/features/moderation/QuarantineCommand.java b/application/src/main/java/org/togetherjava/tjbot/features/moderation/QuarantineCommand.java index 876d1bcc24..0f9efb12fa 100644 --- a/application/src/main/java/org/togetherjava/tjbot/features/moderation/QuarantineCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/features/moderation/QuarantineCommand.java @@ -6,20 +6,21 @@ import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.requests.RestAction; -import net.dv8tion.jda.api.requests.restaction.AuditableRestAction; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.togetherjava.tjbot.config.Config; import org.togetherjava.tjbot.features.CommandVisibility; import org.togetherjava.tjbot.features.SlashCommandAdapter; -import org.togetherjava.tjbot.logging.LogMarkers; +import org.togetherjava.tjbot.features.componentids.Lifespan; +import org.togetherjava.tjbot.features.utils.Guilds; +import org.togetherjava.tjbot.features.utils.MessageUtils; import javax.annotation.Nullable; +import java.util.List; import java.util.Objects; /** @@ -31,12 +32,15 @@ * an admin). */ public final class QuarantineCommand extends SlashCommandAdapter { - private static final Logger logger = LoggerFactory.getLogger(QuarantineCommand.class); private static final String TARGET_OPTION = "user"; private static final String REASON_OPTION = "reason"; - private static final String COMMAND_NAME = "quarantine"; + public static final String COMMAND_NAME = "quarantine"; private static final String ACTION_VERB = "quarantine"; private static final String ACTION_TITLE = "Quarantine"; + + private static final String SELF_UNQUARANTINE_REASON = + "User regained control and unquarantined themselves."; + private final ModerationActionsStore actionsStore; private final Config config; @@ -85,29 +89,15 @@ private static MessageEmbed sendFeedback(boolean hasSentDm, Member target, Membe target.getUser(), dmNoticeText, reason); } - private AuditableRestAction quarantineUser(Member target, Member author, String reason, - Guild guild) { - logger.info(LogMarkers.SENSITIVE, - "'{}' ({}) quarantined the user '{}' ({}) in guild '{}' for reason '{}'.", - author.getUser().getName(), author.getId(), target.getUser().getName(), - target.getId(), guild.getName(), reason); - - actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationAction.QUARANTINE, null, reason); - - return guild - .addRoleToMember(target, - ModerationUtils.getQuarantinedRole(guild, config).orElseThrow()) - .reason(reason); - } - private void quarantineUserFlow(Member target, Member author, String reason, Guild guild, SlashCommandInteractionEvent event) { event.deferReply().queue(); sendDm(target.getUser(), reason, guild) - .flatMap(hasSentDm -> quarantineUser(target, author, reason, guild) - .map(result -> hasSentDm)) + .flatMap(hasSentDm -> ModerationUtils + .quarantine(config, () -> generateComponentId(Lifespan.PERMANENT, target.getId()), + actionsStore, guild, author, target, reason) + .map(_ -> hasSentDm)) .map(hasSentDm -> sendFeedback(hasSentDm, target, author, reason)) .flatMap(event.getHook()::sendMessageEmbeds) .queue(); @@ -148,4 +138,36 @@ public void onSlashCommand(SlashCommandInteractionEvent event) { quarantineUserFlow(Objects.requireNonNull(target), author, reason, guild, event); } + + @Override + public void onButtonClick(ButtonInteractionEvent event, List args) { + + Guild guild = Objects.requireNonNull(event.getGuild()); + Member member = Objects.requireNonNull(event.getMember()); + + if (!Guilds.hasMemberRole(member, ModerationUtils.getIsQuarantinedRolePredicate(config))) { + event.reply("You are not quarantined anymore!").setEphemeral(true).queue(); + + MessageUtils.disableButtons(event.getMessage()); + return; + } + + event.deferEdit().queue(); + + guild + .removeRoleFromMember(member, + ModerationUtils.getQuarantinedRole(guild, config).orElseThrow()) + .reason(SELF_UNQUARANTINE_REASON) + .queue(_ -> { + actionsStore.addAction(guild.getIdLong(), guild.getSelfMember().getIdLong(), + event.getUser().getIdLong(), ModerationAction.UNQUARANTINE, null, + SELF_UNQUARANTINE_REASON); + + MessageUtils.disableButtons(event.getMessage()); + }, _ -> event.getHook() + .sendMessage( + "Something went wrong while trying to unquarantine your account, try to reach via /modmail.") + .setEphemeral(true) + .queue()); + } } diff --git a/application/src/main/java/org/togetherjava/tjbot/features/moderation/scam/ScamBlocker.java b/application/src/main/java/org/togetherjava/tjbot/features/moderation/scam/ScamBlocker.java index cbc38c7a75..ee4c8c0a46 100644 --- a/application/src/main/java/org/togetherjava/tjbot/features/moderation/scam/ScamBlocker.java +++ b/application/src/main/java/org/togetherjava/tjbot/features/moderation/scam/ScamBlocker.java @@ -6,7 +6,6 @@ import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageEmbed; -import net.dv8tion.jda.api.entities.SelfUser; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.channel.concrete.PrivateChannel; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; @@ -30,9 +29,10 @@ import org.togetherjava.tjbot.features.analytics.Metrics; import org.togetherjava.tjbot.features.componentids.ComponentIdGenerator; import org.togetherjava.tjbot.features.componentids.ComponentIdInteractor; -import org.togetherjava.tjbot.features.moderation.ModerationAction; +import org.togetherjava.tjbot.features.componentids.Lifespan; import org.togetherjava.tjbot.features.moderation.ModerationActionsStore; import org.togetherjava.tjbot.features.moderation.ModerationUtils; +import org.togetherjava.tjbot.features.moderation.QuarantineCommand; import org.togetherjava.tjbot.features.moderation.modmail.ModMailCommand; import org.togetherjava.tjbot.features.utils.AmbientColors; import org.togetherjava.tjbot.features.utils.Guilds; @@ -78,6 +78,9 @@ public final class ScamBlocker extends MessageReceiverAdapter implements UserInt private final Metrics metrics; private final ComponentIdInteractor componentIdInteractor; + private final ComponentIdInteractor quarantineComponentIds = new ComponentIdInteractor( + UserInteractionType.SLASH_COMMAND, QuarantineCommand.COMMAND_NAME); + /** * Creates a new listener to receive all message sent in any channel. * @@ -121,6 +124,8 @@ public UserInteractionType getInteractionType() { @Override public void acceptComponentIdGenerator(ComponentIdGenerator generator) { componentIdInteractor.acceptComponentIdGenerator(generator); + quarantineComponentIds.acceptComponentIdGenerator(generator); + } @Override @@ -223,19 +228,26 @@ private void deleteMessage(MessageReceivedEvent event) { } private void quarantineAuthor(MessageReceivedEvent event) { - quarantineAuthor(event.getGuild(), event.getMember(), event.getJDA().getSelfUser()); - } + Guild guild = event.getGuild(); + Member member = event.getMember(); - private void quarantineAuthor(Guild guild, Member author, SelfUser bot) { - String reason = "User posted scam that was automatically detected"; + if (member == null) { + logger.warn(LogMarkers.SENSITIVE, + "scam message detected from a user that is not a member of the guild '{}'.", + guild.getId()); + return; + } - actionsStore.addAction(guild.getIdLong(), bot.getIdLong(), author.getIdLong(), - ModerationAction.QUARANTINE, null, reason); + quarantineAuthor(guild, member); + } - guild - .addRoleToMember(author, - ModerationUtils.getQuarantinedRole(guild, config).orElseThrow()) - .reason(reason) + private void quarantineAuthor(Guild guild, Member author) { + ModerationUtils + .quarantine(config, + () -> quarantineComponentIds.generateComponentId(Lifespan.PERMANENT, + author.getId()), + actionsStore, guild, guild.getSelfMember(), author, + "User posted scam that was automatically detected") .queue(); } @@ -356,7 +368,7 @@ public void onButtonClick(ButtonInteractionEvent event, List argsRaw) { } Consumer onRetrieveAuthorSuccess = author -> { - quarantineAuthor(guild, author, event.getJDA().getSelfUser()); + quarantineAuthor(guild, author); dmUser(guild, args.authorId, event.getJDA()); // Delete all messages like this