Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions application/config.json.template
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"downVoteEmoteName": "peepo_no"
},
"quarantinedRolePattern": "Quarantined",
"quarantineChannelPattern": "quarantine-zone",
"scamBlocker": {
"mode": "AUTO_DELETE_BUT_APPROVE_QUARANTINE",
"reportChannelPattern": "commands",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -617,4 +623,78 @@ public static RestAction<MessageEmbed.Field> 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.
* <p>
* 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 <a href="https://github.com/Together-Java/TJ-Bot/issues/1594">Issue #1594</a>
*/
public static RestAction<Void> quarantine(Config config,
Supplier<String> 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);
Comment on lines +651 to +654

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use findLastActionAgainstTargetByType and rename isFirsttime to isFirstTime

Suggested change
boolean isFirsttime =
actionsStore.getActionsByTargetAscending(guild.getIdLong(), target.getIdLong())
.stream()
.noneMatch(action -> action.actionType() == ModerationAction.QUARANTINE);
boolean isFirstTime = actionsStore
.findLastActionAgainstTargetByType(guild.getIdLong(), target.getIdLong(),
ModerationAction.QUARANTINE)
.isEmpty();


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) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (!isFirsttime) {
if (!isFirstTime) {

Corresponding to above

logger.warn("Unable to offer self-service unquarantine to '{}' in guild '{}'.",
targetId, guildId);
return;
}

Optional<TextChannel> 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));

});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand All @@ -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;

Expand Down Expand Up @@ -85,29 +89,15 @@ private static MessageEmbed sendFeedback(boolean hasSentDm, Member target, Membe
target.getUser(), dmNoticeText, reason);
}

private AuditableRestAction<Void> 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();
Expand Down Expand Up @@ -148,4 +138,36 @@ public void onSlashCommand(SlashCommandInteractionEvent event) {

quarantineUserFlow(Objects.requireNonNull(target), author, reason, guild, event);
}

@Override
public void onButtonClick(ButtonInteractionEvent event, List<String> 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();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
event.reply("You are not quarantined anymore!").setEphemeral(true).queue();
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());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -121,6 +124,8 @@ public UserInteractionType getInteractionType() {
@Override
public void acceptComponentIdGenerator(ComponentIdGenerator generator) {
componentIdInteractor.acceptComponentIdGenerator(generator);
quarantineComponentIds.acceptComponentIdGenerator(generator);

}

@Override
Expand Down Expand Up @@ -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;
}
Comment on lines +234 to +239

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The only channels that are read are TextChannel's (a MessageChannel specifically for Guilds), that said if the user is not a Member of the guild we would have a shitton of NPE's before we arrive at this point. See ScamBlocker:142


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();
}

Expand Down Expand Up @@ -356,7 +368,7 @@ public void onButtonClick(ButtonInteractionEvent event, List<String> argsRaw) {
}

Consumer<Member> onRetrieveAuthorSuccess = author -> {
quarantineAuthor(guild, author, event.getJDA().getSelfUser());
quarantineAuthor(guild, author);
dmUser(guild, args.authorId, event.getJDA());

// Delete all messages like this
Expand Down
Loading