Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import net.dv8tion.jda.api.entities.Guild;
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.User;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.exceptions.ErrorResponseException;
Expand All @@ -15,7 +14,6 @@
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.requests.ErrorResponse;
import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.requests.restaction.AuditableRestAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -25,11 +23,9 @@

import javax.annotation.Nullable;

import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
* This command can ban users and optionally remove their messages from the past days. Banning can
Expand All @@ -47,7 +43,6 @@ public final class BanCommand extends SlashCommandAdapter {
private static final String REASON_OPTION = "reason";
private static final String COMMAND_NAME = "ban";
private static final String ACTION_VERB = "ban";
private static final String ACTION_TITLE = "Ban";
@SuppressWarnings("StaticCollection")
private static final List<String> DURATIONS =
List.of(ModerationUtils.PERMANENT_DURATION, "1 hour", "3 hours", "1 day", "2 days",
Expand Down Expand Up @@ -88,30 +83,6 @@ private static RestAction<Message> handleAlreadyBanned(Guild.Ban ban, Interactio
return hook.sendMessage(message).setEphemeral(true);
}

private static RestAction<Boolean> sendDm(User target,
@Nullable ModerationUtils.TemporaryData temporaryData, String reason, Guild guild) {
String durationMessage = temporaryData == null ? "Permanently" : temporaryData.duration();
String description =
"""
Hey there, sorry to tell you but unfortunately you have been banned from the server.
If you think this was a mistake, please contact a moderator or admin of this server.""";

return ModerationUtils.sendModActionDm(ModerationUtils.getModActionEmbed(guild,
ACTION_TITLE, description, reason, durationMessage, false), target);
}

private static MessageEmbed sendFeedback(boolean hasSentDm, User target, Member author,
@Nullable ModerationUtils.TemporaryData temporaryData, String reason) {
String durationText = "The ban duration is: "
+ (temporaryData == null ? "permanent" : temporaryData.duration());
String dmNoticeText = "";
if (!hasSentDm) {
dmNoticeText = "\n(Unable to send them a DM.)";
}
return ModerationUtils.createActionResponse(author.getUser(), ModerationAction.BAN, target,
durationText + dmNoticeText, reason);
}

private static Optional<RestAction<Message>> handleNotAlreadyBannedResponse(
Throwable alreadyBannedFailure, InteractionHook hook, Guild guild, User target) {
if (alreadyBannedFailure instanceof ErrorResponseException errorResponseException) {
Expand All @@ -135,34 +106,6 @@ private static Optional<RestAction<Message>> handleNotAlreadyBannedResponse(
.setEphemeral(true));
}

private RestAction<Message> banUserFlow(User target, Member author,
@Nullable ModerationUtils.TemporaryData temporaryData, String reason,
int deleteHistoryDays, Guild guild, SlashCommandInteractionEvent event) {
return sendDm(target, temporaryData, reason, guild)
.flatMap(hasSentDm -> banUser(target, author, temporaryData, reason, deleteHistoryDays,
guild)
.map(banResult -> hasSentDm))
.map(hasSentDm -> sendFeedback(hasSentDm, target, author, temporaryData, reason))
.flatMap(event.getHook()::sendMessageEmbeds);
}

private AuditableRestAction<Void> banUser(User target, Member author,
@Nullable ModerationUtils.TemporaryData temporaryData, String reason,
int deleteHistoryDays, Guild guild) {
String durationMessage =
temporaryData == null ? "permanently" : "for " + temporaryData.duration();
logger.info(LogMarkers.SENSITIVE,
"'{}' ({}) banned the user '{}' ({}) {} from guild '{}' and deleted their message history of the last {} days, for reason '{}'.",
author.getUser().getName(), author.getId(), target.getName(), target.getId(),
durationMessage, guild.getName(), deleteHistoryDays, reason);

Instant expiresAt = temporaryData == null ? null : temporaryData.expiresAt();
actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(),
ModerationAction.BAN, expiresAt, reason);

return guild.ban(target, deleteHistoryDays, TimeUnit.DAYS).reason(reason);
}

@SuppressWarnings({"BooleanMethodNameMustStartWithQuestion", "MethodWithTooManyParameters"})
private boolean handleChecks(Member bot, Member author, @Nullable Member target,
CharSequence reason, Guild guild, IReplyCallback event) {
Expand Down Expand Up @@ -216,8 +159,10 @@ public void onSlashCommand(SlashCommandInteractionEvent event) {

return handleNotAlreadyBannedResponse(
Objects.requireNonNull(alreadyBanned.getFailure()), hook, guild, target)
.orElseGet(() -> banUserFlow(target, author, temporaryData.orElse(null), reason,
deleteHistoryDays, guild, event));
.orElseGet(() -> ModerationUtils
.banUser(guild, target, author, temporaryData.orElse(null), reason,
deleteHistoryDays, actionsStore)
.flatMap(hook::sendMessageEmbeds));
}).queue();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.togetherjava.tjbot.features.utils.AmbientColors;
import org.togetherjava.tjbot.features.utils.Guilds;
import org.togetherjava.tjbot.features.utils.MessageUtils;
import org.togetherjava.tjbot.logging.LogMarkers;

import javax.annotation.Nullable;

Expand All @@ -33,8 +34,10 @@
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -62,6 +65,7 @@ private ModerationUtils() {
* user as option for selection.
*/
static final String PERMANENT_DURATION = "permanent";
private static final Pattern BAN_DURATION_PATTERN = Pattern.compile("([1-9]\\d*)\\s*([hd])");

/**
* Checks whether the given reason is valid. If not, it will handle the situation and respond to
Expand Down Expand Up @@ -381,6 +385,87 @@ static Optional<TemporaryData> computeTemporaryData(String durationText) {
return Optional.of(new TemporaryData(Instant.now().plus(duration, unit), durationText));
}

/**
* Parses a ban duration: empty or zero for permanent, or positive hours/days such as {@code 3h}
* or {@code 7d}.
*
* @throws IllegalArgumentException if the duration is invalid or exceeds the supported range
*/
static Optional<TemporaryData> parseBanDuration(String input) {
String duration = input.strip().toLowerCase(Locale.ROOT);
if (duration.isEmpty() || duration.equals("0")) {
return Optional.empty();
}
var matcher = BAN_DURATION_PATTERN.matcher(duration);
if (!matcher.matches()) {
throw new IllegalArgumentException("Invalid ban duration: " + input);
}
return computeTemporaryData(
matcher.group(1) + (matcher.group(2).equals("h") ? " hours" : " days"));
}

/**
* Bans a user, optionally deletes message history, sends a DM, and records the successful
* action. The caller must check permissions, role hierarchy, reason, and whether the user is
* banned.
*/
static RestAction<MessageEmbed> banUser(Guild guild, User target, Member moderator,
@Nullable TemporaryData temporaryData, String reason, int deleteHistoryDays,
ModerationActionsStore actionsStore) {
String duration = temporaryData == null ? PERMANENT_DURATION : temporaryData.duration();
String description =
"""
Hey there, sorry to tell you but unfortunately you have been banned from the server.
If you think this was a mistake, please contact a moderator or admin of this server.""";
return sendModActionDm(getModActionEmbed(guild, "Ban", description, reason,
temporaryData == null ? "Permanently" : duration, false), target)
.flatMap(hasSentDm -> guild.ban(target, deleteHistoryDays, TimeUnit.DAYS)
.reason(reason)
.map(_ -> {
recordAction(guild, target, moderator, ModerationAction.BAN,
temporaryData == null ? null : temporaryData.expiresAt(), reason,
actionsStore);
logger.info(LogMarkers.SENSITIVE,
"Ban of user '{}' in guild '{}' has duration '{}' and deletes {} days of message history.",
target.getId(), guild.getId(), duration, deleteHistoryDays);
return createActionResponse(moderator.getUser(), ModerationAction.BAN, target,
"The ban duration is: " + duration
+ (Boolean.TRUE.equals(hasSentDm) ? ""
: "\n(Unable to send them a DM.)"),
reason);
}));
}

/**
* Warns a user, sends a DM, and records the action. The caller must check role hierarchy and
* the reason.
*/
static RestAction<MessageEmbed> warnUser(Guild guild, User target, Member moderator,
String reason, ModerationActionsStore actionsStore) {
String description =
"Hey there, sorry to tell you but unfortunately you have been warned in the server.";
return sendModActionDm(getModActionEmbed(guild, "Warning", description, reason, true),
target)
.map(hasSentDm -> {
recordAction(guild, target, moderator, ModerationAction.WARN, null, reason,
actionsStore);
return createActionResponse(moderator.getUser(), ModerationAction.WARN, target,
Boolean.TRUE.equals(hasSentDm) ? "" : "(Unable to send them a DM.)",
reason);
});
}

private static void recordAction(Guild guild, User target, Member moderator,
ModerationAction action, @Nullable Instant expiresAt, String reason,
ModerationActionsStore actionsStore) {
logger.info(LogMarkers.SENSITIVE,
"'{}' ({}) executed '{}' against user '{}' ({}) in guild '{}' for reason '{}'.",
moderator.getUser().getName(), moderator.getId(), action, target.getName(),
target.getId(), guild.getId(), reason);
actionsStore.addAction(guild.getIdLong(), moderator.getIdLong(), target.getIdLong(), action,
expiresAt, reason);
}

/**
* Creates a nice looking embed for the mod action taken.
*
Expand Down
Loading
Loading