diff --git a/application/src/main/java/org/togetherjava/tjbot/features/moderation/BanCommand.java b/application/src/main/java/org/togetherjava/tjbot/features/moderation/BanCommand.java index 80c4073569..0c818c08dd 100644 --- a/application/src/main/java/org/togetherjava/tjbot/features/moderation/BanCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/features/moderation/BanCommand.java @@ -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; @@ -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; @@ -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 @@ -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 DURATIONS = List.of(ModerationUtils.PERMANENT_DURATION, "1 hour", "3 hours", "1 day", "2 days", @@ -88,30 +83,6 @@ private static RestAction handleAlreadyBanned(Guild.Ban ban, Interactio return hook.sendMessage(message).setEphemeral(true); } - private static RestAction 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> handleNotAlreadyBannedResponse( Throwable alreadyBannedFailure, InteractionHook hook, Guild guild, User target) { if (alreadyBannedFailure instanceof ErrorResponseException errorResponseException) { @@ -135,34 +106,6 @@ private static Optional> handleNotAlreadyBannedResponse( .setEphemeral(true)); } - private RestAction 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 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) { @@ -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(); } } 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 026b4a4ea0..74b6e6ceec 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 @@ -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; @@ -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; @@ -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 @@ -381,6 +385,87 @@ static Optional 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 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 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 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. * diff --git a/application/src/main/java/org/togetherjava/tjbot/features/moderation/ReportCommand.java b/application/src/main/java/org/togetherjava/tjbot/features/moderation/ReportCommand.java index 3e10533b7a..eb0d266ce8 100644 --- a/application/src/main/java/org/togetherjava/tjbot/features/moderation/ReportCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/features/moderation/ReportCommand.java @@ -11,11 +11,17 @@ 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.events.interaction.ModalInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.MessageContextInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.exceptions.ErrorHandler; +import net.dv8tion.jda.api.exceptions.ErrorResponseException; +import net.dv8tion.jda.api.interactions.InteractionHook; import net.dv8tion.jda.api.interactions.commands.build.Commands; import net.dv8tion.jda.api.interactions.components.buttons.Button; +import net.dv8tion.jda.api.interactions.components.text.TextInput; +import net.dv8tion.jda.api.interactions.components.text.TextInputStyle; +import net.dv8tion.jda.api.interactions.modals.Modal; import net.dv8tion.jda.api.requests.ErrorResponse; import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; @@ -31,6 +37,8 @@ import org.togetherjava.tjbot.features.utils.MessageUtils; import org.togetherjava.tjbot.logging.LogMarkers; +import javax.annotation.Nullable; + import java.awt.Color; import java.time.Duration; import java.time.Instant; @@ -55,14 +63,21 @@ * messages. *
  • Job-Ad: the author is warned, then banned and unbanned to delete their recent * messages.
  • + *
  • Ban: the author is banned for a custom reason and duration, optionally deleting their + * recent messages.
  • + *
  • Warn: the author is warned for a custom reason.
  • *
  • Dismiss: nothing happens, the alert is closed.
  • * - * The ban and unban only serves to delete the messages, the user is free to join back afterward. + * For Scam and Job-Ad, the ban and unban only serves to delete the messages, the user is free to + * join back afterward. */ public final class ReportCommand extends BotCommandAdapter implements MessageContextCommand { private static final Logger logger = LoggerFactory.getLogger(ReportCommand.class); private static final String COMMAND_NAME = "report"; + private static final String REASON_INPUT = "reason"; + private static final String DURATION_INPUT = "duration"; + private static final String DELETE_HISTORY_INPUT = "delete-history"; private static final String SCAM_REASON = "Message was reported and confirmed as scam"; private static final String JOB_AD_REASON = @@ -177,7 +192,7 @@ private MessageCreateAction reportToMods(Message message, TextChannel modMailCha .size(); String modActionsText = modActionCount == 0 ? "no" : String.valueOf(modActionCount); - MessageEmbed reportEmbed = new EmbedBuilder().setTitle("Reported Message") + MessageEmbed reportEmbed = new EmbedBuilder().setTitle("Message Reported") .setDescription( MessageUtils.abbreviate(description, MessageEmbed.DESCRIPTION_MAX_LENGTH)) .setAuthor(author.getName(), null, author.getEffectiveAvatarUrl()) @@ -196,7 +211,11 @@ private MessageCreateAction reportToMods(Message message, TextChannel modMailCha "Scam"), Button.success( generateComponentId(guildId, authorId, ReportAction.JOB_AD.name()), - "Job-Ad")) + "Job-Ad"), + Button.primary(generateComponentId(guildId, authorId, ReportAction.WARN.name()), + "Warn"), + Button.primary(generateComponentId(guildId, authorId, ReportAction.BAN.name()), + "Ban")) .addActionRow(Button.danger( generateComponentId(guildId, authorId, ReportAction.DISMISS.name()), "Dismiss"), Button.primary(generateComponentId(guildId, authorId, ReportAction.AUDIT.name(), @@ -229,6 +248,11 @@ public void onButtonClick(ButtonInteractionEvent event, List args) { long targetId = Long.parseLong(args.get(1)); ReportAction action = ReportAction.valueOf(args.get(2)); + if (action == ReportAction.BAN || action == ReportAction.WARN) { + openModerationModal(event, guildId, targetId, action); + return; + } + if (action == ReportAction.AUDIT || action == ReportAction.AUDIT_PAGE) { int page = Integer.parseInt(args.get(3)); onAuditButtonClick(event, guildId, targetId, page, action == ReportAction.AUDIT_PAGE); @@ -262,6 +286,205 @@ public void onButtonClick(ButtonInteractionEvent event, List args) { existingEmbeds), errorHandler); } + private void openModerationModal(ButtonInteractionEvent event, long guildId, long targetId, + ReportAction action) { + if (action == ReportAction.BAN && !ModerationUtils.handleHasAuthorPermissions("ban", + Permission.BAN_MEMBERS, Objects.requireNonNull(event.getMember()), event)) { + return; + } + + TextInput reason = TextInput.create(REASON_INPUT, "Reason", TextInputStyle.PARAGRAPH) + .setPlaceholder("Why should this user be " + + (action == ReportAction.BAN ? "banned?" : "warned?")) + .setRequired(true) + .setMaxLength(512) + .build(); + Modal.Builder modal = Modal + .create(generateComponentId(String.valueOf(guildId), String.valueOf(targetId), + action.name()), + action == ReportAction.BAN ? "Ban reported user" : "Warn reported user") + .addActionRow(reason); + if (action == ReportAction.BAN) { + modal.addActionRow(TextInput + .create(DURATION_INPUT, "Duration (0, h or d)", TextInputStyle.SHORT) + .setPlaceholder("Hours or days: 1h, 3h, 1d, 7d, 30d; empty or 0 = permanent") + .setRequired(false) + .setMaxLength(20) + .build()); + modal.addActionRow(TextInput + .create(DELETE_HISTORY_INPUT, "Delete messages (days)", TextInputStyle.SHORT) + .setPlaceholder("Empty or 0 = none, 1 = day, 7 = week") + .setValue("1") + .setRequired(false) + .setMaxLength(1) + .build()); + } + event.replyModal(modal.build()).queue(); + } + + @Override + public void onModalSubmitted(ModalInteractionEvent event, List args) { + long guildId = Long.parseLong(args.get(0)); + long targetId = Long.parseLong(args.get(1)); + ReportAction action = ReportAction.valueOf(args.get(2)); + if (action != ReportAction.BAN && action != ReportAction.WARN) { + throw new IllegalArgumentException("Unexpected modal action: " + action); + } + Guild guild = Objects.requireNonNull(event.getGuild()); + if (guild.getIdLong() != guildId) { + event.reply("This report belongs to a different server.").setEphemeral(true).queue(); + return; + } + Member moderator = Objects.requireNonNull(event.getMember()); + String reason = Objects.requireNonNull(event.getValue(REASON_INPUT)).getAsString().strip(); + if (reason.isBlank()) { + event.reply("Please enter a reason.").setEphemeral(true).queue(); + return; + } + if (!ModerationUtils.handleReason(reason, event)) { + return; + } + if (action == ReportAction.BAN && (!ModerationUtils.handleHasAuthorPermissions("ban", + Permission.BAN_MEMBERS, moderator, event) + || !ModerationUtils.handleHasBotPermissions("ban", Permission.BAN_MEMBERS, + guild.getSelfMember(), guild, event))) { + return; + } + Optional temporaryData; + try { + temporaryData = action == ReportAction.BAN + ? ModerationUtils.parseBanDuration( + Objects.requireNonNull(event.getValue(DURATION_INPUT)).getAsString()) + : Optional.empty(); + } catch (IllegalArgumentException _) { + event.reply( + "Invalid duration. Use a positive number followed by h or d (1h, 3h, 1d, 7d). Leave empty or enter 0 for permanent.") + .setEphemeral(true) + .queue(); + return; + } + + int deleteHistoryDays = readDeleteHistoryDays(event, action); + if (deleteHistoryDays == -1) { + return; + } + + ModalActionData actionData = + new ModalActionData(action, temporaryData.orElse(null), reason, deleteHistoryDays); + event.deferReply(true) + .queue(hook -> loadModalTarget(event, hook, guild, moderator, targetId, actionData)); + } + + private int readDeleteHistoryDays(ModalInteractionEvent event, ReportAction action) { + if (action != ReportAction.BAN) { + return 0; + } + String deleteHistory = + Objects.requireNonNull(event.getValue(DELETE_HISTORY_INPUT)).getAsString().strip(); + int deleteHistoryDays = switch (deleteHistory) { + case "", "0" -> 0; + case "1" -> 1; + case "7" -> 7; + default -> -1; + }; + if (deleteHistoryDays == -1) { + event.reply( + "Invalid message deletion option. Leave empty or enter 0 for none, 1 for one day, or 7 for one week.") + .setEphemeral(true) + .queue(); + } + return deleteHistoryDays; + } + + private void loadModalTarget(ModalInteractionEvent event, InteractionHook hook, Guild guild, + Member moderator, long targetId, ModalActionData actionData) { + guild.retrieveMemberById(targetId).mapToResult().flatMap(result -> { + if (result.isSuccess()) { + Member target = result.get(); + if (!moderator.canInteract(target) || !guild.getSelfMember().canInteract(target)) { + return hook.sendMessage( + "You or the bot cannot moderate this user because of their role hierarchy.") + .setEphemeral(true); + } + } else if (!(result.getFailure() instanceof ErrorResponseException failure) + || failure.getErrorResponse() != ErrorResponse.UNKNOWN_MEMBER) { + logger.warn(LogMarkers.SENSITIVE, + "Failed to retrieve reported member '{}' in guild '{}'.", targetId, + guild.getIdLong(), result.getFailure()); + return hook.sendMessage("Could not load the reported user. Please check the logs.") + .setEphemeral(true); + } + return event.getJDA().retrieveUserById(targetId).map(target -> { + executeModalAction(event, hook, guild, moderator, target, actionData); + return null; + }); + }).queue(null, failure -> { + logger.warn(LogMarkers.SENSITIVE, "Failed to load reported user '{}' in guild '{}'.", + targetId, guild.getIdLong(), failure); + hook.sendMessage("Could not load the reported user. Please check the logs.") + .setEphemeral(true) + .queue(); + }); + } + + private void executeModalAction(ModalInteractionEvent event, InteractionHook hook, Guild guild, + Member moderator, User target, ModalActionData actionData) { + Message report = Objects.requireNonNull(event.getMessage()); + if (report.getComponents().isEmpty()) { + hook.sendMessage("This report has already been handled.").setEphemeral(true).queue(); + return; + } + Consumer onSuccess = feedback -> { + List embeds = new ArrayList<>(report.getEmbeds()); + embeds.add(feedback); + report.editMessageEmbeds(embeds).setComponents().queue(null, failure -> { + logger.warn("The moderation action succeeded, but updating report '{}' failed.", + report.getId(), failure); + hook.sendMessage("The action succeeded, but the report could not be updated.") + .setEphemeral(true) + .queue(); + }); + }; + if (actionData.action() == ReportAction.BAN) { + guild.retrieveBan(target).mapToResult().queue(result -> { + if (result.isSuccess()) { + hook.sendMessage("This user is already banned.").setEphemeral(true).queue(); + } else if (result.getFailure() instanceof ErrorResponseException failure + && failure.getErrorResponse() == ErrorResponse.UNKNOWN_BAN) { + handleModalAction(hook, guild, moderator, target, actionData, onSuccess); + } else { + logger.warn(LogMarkers.SENSITIVE, "Could not check ban for reported user '{}'.", + target.getId(), result.getFailure()); + hook.sendMessage("Could not check whether this user is already banned.") + .setEphemeral(true) + .queue(); + } + }); + } else { + handleModalAction(hook, guild, moderator, target, actionData, onSuccess); + } + } + + private void handleModalAction(InteractionHook hook, Guild guild, Member moderator, User target, + ModalActionData actionData, Consumer onSuccess) { + RestAction handling = actionData.action() == ReportAction.BAN + ? ModerationUtils.banUser(guild, target, moderator, actionData.temporaryData(), + actionData.reason(), actionData.deleteHistoryDays(), actionsStore) + : ModerationUtils.warnUser(guild, target, moderator, actionData.reason(), + actionsStore); + handling.queue(feedback -> { + onSuccess.accept(feedback); + hook.sendMessageEmbeds(feedback).setEphemeral(true).queue(); + }, failure -> { + logger.warn(LogMarkers.SENSITIVE, "Failed to handle reported user '{}' in guild '{}'.", + target.getId(), guild.getId(), failure); + hook.sendMessage( + "The action failed. Please check the logs and handle the user manually.") + .setEphemeral(true) + .queue(); + }); + } + private void onAuditButtonClick(ButtonInteractionEvent event, long guildId, long targetId, int targetPage, boolean isPageButton) { if (isPageButton) { @@ -476,9 +699,16 @@ private static List createResponseEmbeds(List staged return embeds; } + private record ModalActionData(ReportAction action, + @Nullable ModerationUtils.TemporaryData temporaryData, String reason, + int deleteHistoryDays) { + } + private enum ReportAction { SCAM, JOB_AD, + BAN, + WARN, DISMISS, AUDIT, AUDIT_PAGE, diff --git a/application/src/main/java/org/togetherjava/tjbot/features/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/features/moderation/WarnCommand.java index 2aca00ca2c..96fc653f4a 100644 --- a/application/src/main/java/org/togetherjava/tjbot/features/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/features/moderation/WarnCommand.java @@ -2,18 +2,12 @@ import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; -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.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; -import net.dv8tion.jda.api.requests.RestAction; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.togetherjava.tjbot.features.CommandVisibility; import org.togetherjava.tjbot.features.SlashCommandAdapter; -import org.togetherjava.tjbot.logging.LogMarkers; import javax.annotation.Nullable; @@ -27,11 +21,9 @@ * to warn the specific given user (for example a moderator attempting to warn an admin). */ public final class WarnCommand extends SlashCommandAdapter { - private static final Logger logger = LoggerFactory.getLogger(WarnCommand.class); private static final String USER_OPTION = "user"; private static final String REASON_OPTION = "reason"; private static final String ACTION_VERB = "warn"; - private static final String ACTION_TITLE = "Warning"; private final ModerationActionsStore actionsStore; /** @@ -48,47 +40,6 @@ public WarnCommand(ModerationActionsStore actionsStore) { this.actionsStore = Objects.requireNonNull(actionsStore); } - private void warnUserFlow(User target, Member author, String reason, Guild guild, - SlashCommandInteractionEvent event) { - event.deferReply().queue(); - - sendDm(target, reason, guild).map(hasSentDm -> { - warnUser(target, author, reason, guild); - return hasSentDm; - }) - .map(hasSentDm -> sendFeedback(hasSentDm, target, author, reason)) - .flatMap(event.getHook()::sendMessageEmbeds) - .queue(); - } - - private static RestAction sendDm(User target, String reason, Guild guild) { - String description = - "Hey there, sorry to tell you but unfortunately you have been warned in the server."; - - return ModerationUtils.sendModActionDm( - ModerationUtils.getModActionEmbed(guild, ACTION_TITLE, description, reason, true), - target); - } - - private void warnUser(User target, Member author, String reason, Guild guild) { - logger.info(LogMarkers.SENSITIVE, "'{}' ({}) warned the user '{}' ({}) for reason '{}'.", - author.getUser().getName(), author.getId(), target.getName(), target.getId(), - reason); - - actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationAction.WARN, null, reason); - } - - private static MessageEmbed sendFeedback(boolean hasSentDm, User target, Member author, - String reason) { - String dmNoticeText = ""; - if (!hasSentDm) { - dmNoticeText = "(Unable to send them a DM.)"; - } - return ModerationUtils.createActionResponse(author.getUser(), ModerationAction.WARN, target, - dmNoticeText, reason); - } - @Override public void onSlashCommand(SlashCommandInteractionEvent event) { OptionMapping targetOption = @@ -103,7 +54,11 @@ public void onSlashCommand(SlashCommandInteractionEvent event) { return; } - warnUserFlow(targetOption.getAsUser(), author, reason, guild, event); + event.deferReply() + .queue(hook -> ModerationUtils + .warnUser(guild, targetOption.getAsUser(), author, reason, actionsStore) + .flatMap(hook::sendMessageEmbeds) + .queue()); } private boolean handleChecks(Member bot, Member author, @Nullable Member target, String reason,