-
-
Notifications
You must be signed in to change notification settings - Fork 116
Added /audit button to reports (moderation) #1499
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: develop
Are you sure you want to change the base?
Changes from 10 commits
b4a2d5e
27d66db
4b9b662
ece6dbf
9c71eca
940e390
9681b28
3def321
6e1805f
c919cd9
7ab5a46
9804c59
5cea235
189463b
2e2336d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,7 @@ | ||
| package org.togetherjava.tjbot.features.moderation; | ||
|
|
||
| import net.dv8tion.jda.api.EmbedBuilder; | ||
| 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.IPermissionHolder; | ||
|
|
@@ -25,11 +26,17 @@ | |
|
|
||
| import java.awt.Color; | ||
| import java.time.Instant; | ||
| import java.time.ZoneOffset; | ||
| import java.time.temporal.ChronoUnit; | ||
| import java.time.temporal.TemporalUnit; | ||
| import java.util.ArrayList; | ||
| import java.util.Collection; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Optional; | ||
| import java.util.function.Predicate; | ||
| import java.util.regex.Pattern; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| /** | ||
| * Utility class offering helpers revolving around user moderation, such as banning or kicking. | ||
|
|
@@ -45,6 +52,10 @@ private ModerationUtils() { | |
| * {@link AuditableRestAction#reason(String)}. | ||
| */ | ||
| private static final int REASON_MAX_LENGTH = 512; | ||
| /** | ||
| * The maximum amount of moderation actions displayed on a single page | ||
| */ | ||
| private static final int MAX_PAGE_LENGTH = 10; | ||
| /** | ||
| * Human-readable text representing the duration of a permanent action, will be shown to the | ||
| * user as option for selection. | ||
|
|
@@ -273,7 +284,7 @@ static boolean handleHasAuthorPermissions(String actionVerb, Permission permissi | |
| * Creates a message to be displayed as response to a moderation action. | ||
| * <p> | ||
| * Essentially, it informs others about the action, such as "John banned Bob for playing with | ||
| * the fire.". | ||
| * the fire". | ||
| * | ||
| * @param author the author executing the action | ||
| * @param action the action that is executed | ||
|
|
@@ -442,4 +453,85 @@ static RestAction<Boolean> sendModActionDm(RestAction<EmbedBuilder> embedBuilder | |
| */ | ||
| record TemporaryData(Instant expiresAt, String duration) { | ||
| } | ||
|
|
||
| /** | ||
| * Splits a list of moderation records into discrete pages capped at 10 items each. | ||
| * | ||
| * @param actions the list of chronological actions against a target | ||
| * @return a list of sub-lists where each sub-list contains a maximum of 10 items | ||
| */ | ||
| public static List<List<ActionRecord>> groupActionsByPages(List<ActionRecord> actions) { | ||
| List<List<ActionRecord>> groupedActions = new ArrayList<>(); | ||
|
|
||
| for (int i = 0; i < actions.size(); i++) { | ||
| if (i % MAX_PAGE_LENGTH == 0) { | ||
| groupedActions.add(new ArrayList<>(MAX_PAGE_LENGTH)); | ||
| } | ||
| groupedActions.getLast().add(actions.get(i)); | ||
| } | ||
|
|
||
| return groupedActions; | ||
| } | ||
|
|
||
| /** | ||
| * Generates a structural text overview outlining the count total of each action type. | ||
| * | ||
| * @param actions a collection of history records | ||
| * @return a formatted markdown description summary | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. NIT: The "markdown" word should be capitalized, considering you are referring to the formatting language. |
||
| */ | ||
| public static String createSummaryMessageDescription(Collection<ActionRecord> actions) { | ||
| int actionAmount = actions.size(); | ||
|
|
||
| String shortSummary = "There are **%s actions** against the user." | ||
| .formatted(actionAmount == 0 ? "no" : actionAmount); | ||
|
|
||
| if (actionAmount == 0) { | ||
| return shortSummary; | ||
| } | ||
|
|
||
| Map<ModerationAction, Long> actionTypeToCount = actions.stream() | ||
| .collect(Collectors.groupingBy(ActionRecord::actionType, Collectors.counting())); | ||
|
|
||
| String typeCountSummary = actionTypeToCount.entrySet() | ||
| .stream() | ||
| .filter(typeAndCount -> typeAndCount.getValue() > 0) | ||
| .sorted(Map.Entry.<ModerationAction, Long>comparingByValue().reversed()) | ||
| .map(typeAndCount -> "- **%s**: %d".formatted(typeAndCount.getKey(), | ||
| typeAndCount.getValue())) | ||
| .collect(Collectors.joining("\n")); | ||
|
|
||
| return shortSummary + "\n" + typeCountSummary; | ||
| } | ||
|
|
||
| /** | ||
| * Converts an action record item asynchronously into a formatted embed data field. | ||
| * | ||
| * @param actionRecord the moderation action history record to convert | ||
| * @param jda the active JDA instance used to resolve the moderator's handle | ||
| * @return a rest action that resolves to the embed field representing the moderation action | ||
| */ | ||
| public static RestAction<MessageEmbed.Field> actionToEmbedField(ActionRecord actionRecord, | ||
| JDA jda) { | ||
| return jda.retrieveUserById(actionRecord.authorId()) | ||
| .map(author -> author == null ? "(unknown user)" : author.getName()) | ||
| .map(authorText -> { | ||
| String expiresAtFormatted = actionRecord.actionExpiresAt() == null ? "" | ||
| : "\nTemporary action, expires at: " | ||
| + net.dv8tion.jda.api.utils.TimeUtil.getDateTimeString( | ||
| actionRecord.actionExpiresAt().atOffset(ZoneOffset.UTC)); | ||
|
|
||
| String embedFieldName = | ||
| "%s by %s".formatted(actionRecord.actionType().name(), authorText); | ||
| String embedFieldDescription = """ | ||
| %s | ||
| Issued at: %s%s | ||
| """.formatted(actionRecord.reason(), | ||
| net.dv8tion.jda.api.utils.TimeUtil | ||
| .getDateTimeString(actionRecord.issuedAt().atOffset(ZoneOffset.UTC)), | ||
| expiresAtFormatted); | ||
|
|
||
| return new MessageEmbed.Field(embedFieldName, embedFieldDescription, false); | ||
| }); | ||
| } | ||
|
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,19 +3,18 @@ | |
| import com.github.benmanes.caffeine.cache.Cache; | ||
| import com.github.benmanes.caffeine.cache.Caffeine; | ||
| import net.dv8tion.jda.api.EmbedBuilder; | ||
| import net.dv8tion.jda.api.entities.Guild; | ||
| import net.dv8tion.jda.api.entities.Message; | ||
| import net.dv8tion.jda.api.entities.MessageEmbed; | ||
| import net.dv8tion.jda.api.entities.Role; | ||
| import net.dv8tion.jda.api.entities.*; | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Star import |
||
| 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.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.RestAction; | ||
| import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; | ||
| import net.dv8tion.jda.api.utils.Result; | ||
| import org.slf4j.Logger; | ||
|
|
@@ -25,14 +24,13 @@ | |
| import org.togetherjava.tjbot.features.BotCommandAdapter; | ||
| import org.togetherjava.tjbot.features.CommandVisibility; | ||
| import org.togetherjava.tjbot.features.MessageContextCommand; | ||
| import org.togetherjava.tjbot.features.componentids.Lifespan; | ||
| import org.togetherjava.tjbot.features.utils.MessageUtils; | ||
|
|
||
| import java.awt.Color; | ||
| import java.time.Instant; | ||
| import java.time.temporal.ChronoUnit; | ||
| import java.util.List; | ||
| import java.util.Objects; | ||
| import java.util.Optional; | ||
| import java.util.*; | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Star import |
||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.function.Predicate; | ||
| import java.util.regex.Pattern; | ||
|
|
@@ -53,15 +51,20 @@ public final class ReportCommand extends BotCommandAdapter implements MessageCon | |
| private final Predicate<String> modMailChannelNamePredicate; | ||
| private final Predicate<String> configModGroupPattern; | ||
| private final String configModMailChannelPattern; | ||
| private final ModerationActionsStore moderationActionsStore; | ||
|
|
||
| /** | ||
| * Creates a new instance. | ||
| * | ||
| * @param config to get the channel to forward reports to | ||
| * @param moderationActionsStore to get the history of moderation actions against the reported | ||
| * user | ||
| */ | ||
| public ReportCommand(Config config) { | ||
| public ReportCommand(Config config, ModerationActionsStore moderationActionsStore) { | ||
| super(Commands.message(COMMAND_NAME), CommandVisibility.GUILD); | ||
|
|
||
| this.moderationActionsStore = Objects.requireNonNull(moderationActionsStore); | ||
|
|
||
| modMailChannelNamePredicate = | ||
| Pattern.compile(config.getModMailChannelPattern()).asMatchPredicate(); | ||
|
|
||
|
|
@@ -182,9 +185,13 @@ private MessageCreateAction createModMessage(String reportReason, | |
| .setColor(AMBIENT_COLOR) | ||
| .build(); | ||
|
|
||
| String historyButtonId = | ||
| generateComponentId(Lifespan.REGULAR, reportedMessage.authorId, "0"); | ||
|
|
||
| MessageCreateAction message = | ||
| modMailAuditLog.sendMessageEmbeds(reportedMessageEmbed, reportReasonEmbed) | ||
| .addActionRow(Button.link(reportedMessage.jumpUrl, "Go to message")); | ||
| .addActionRow(Button.link(reportedMessage.jumpUrl, "Go to message"), | ||
| Button.primary(historyButtonId, "Audit")); | ||
|
|
||
| Optional<Role> moderatorRole = guild.getRoles() | ||
| .stream() | ||
|
|
@@ -222,7 +229,7 @@ private static String createUserReply(Result<Message> result) { | |
| } | ||
|
|
||
| private record ReportedMessage(String content, String id, String jumpUrl, String channelID, | ||
| Instant timestamp, String authorName, String authorAvatarUrl) { | ||
| Instant timestamp, String authorName, String authorAvatarUrl, String authorId) { | ||
| static ReportedMessage ofArgs(List<String> args) { | ||
| String content = args.getFirst(); | ||
| String id = args.get(1); | ||
|
|
@@ -231,8 +238,91 @@ static ReportedMessage ofArgs(List<String> args) { | |
| Instant timestamp = Instant.parse(args.get(4)); | ||
| String authorName = args.get(5); | ||
| String authorAvatarUrl = args.get(6); | ||
| String authorId = args.get(7); | ||
| return new ReportedMessage(content, id, jumpUrl, channelID, timestamp, authorName, | ||
| authorAvatarUrl); | ||
| authorAvatarUrl, authorId); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void onButtonClick(ButtonInteractionEvent event, List<String> args) { | ||
| event.deferReply(true).queue(); | ||
|
|
||
| Guild guild = | ||
| Objects.requireNonNull(event.getGuild(), "Guild cannot be null for this command."); | ||
| long guildId = guild.getIdLong(); | ||
|
|
||
| long reportedUserId = Long.parseLong(args.get(0)); | ||
| int targetPage = Integer.parseInt(args.get(1)); | ||
|
|
||
| List<ActionRecord> actions = new ArrayList<>( | ||
| moderationActionsStore.getActionsByTargetAscending(guildId, reportedUserId)); | ||
| Collections.reverse(actions); | ||
| List<List<ActionRecord>> pages = ModerationUtils.groupActionsByPages(actions); | ||
|
|
||
| event.getJDA() | ||
| .retrieveUserById(reportedUserId) | ||
| .flatMap(user -> prepareAuditEmbedTasks(event, user, actions, pages, targetPage)) | ||
| .onErrorFlatMap(_ -> event.getHook() | ||
| .sendMessage("Could not load audit data for this user.") | ||
| .map(msg -> null)) | ||
|
Zabuzard marked this conversation as resolved.
Outdated
Zabuzard marked this conversation as resolved.
Outdated
|
||
| .queue(); | ||
| } | ||
|
|
||
| private RestAction<List<MessageEmbed.Field>> prepareAuditEmbedTasks( | ||
| ButtonInteractionEvent event, User user, List<ActionRecord> actions, | ||
| List<List<ActionRecord>> pages, int targetPage) { | ||
|
|
||
| EmbedBuilder auditEmbed = | ||
| new EmbedBuilder().setTitle("Audit log of **%s**".formatted(user.getName())) | ||
| .setAuthor(user.getName(), null, user.getEffectiveAvatarUrl()) | ||
| .setColor(Color.BLACK) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please make use of the recently introduced |
||
| .setDescription(ModerationUtils.createSummaryMessageDescription(actions)); | ||
|
|
||
| if (pages.isEmpty()) { | ||
| return event.getHook() | ||
| .editOriginalEmbeds(auditEmbed.build()) | ||
| .setComponents(List.of()) | ||
| .map(_ -> List.of()); | ||
| } | ||
|
|
||
| int currentPageIndex = Math.clamp(targetPage, 0, pages.size() - 1); | ||
|
|
||
| List<RestAction<MessageEmbed.Field>> fetchFieldActions = pages.get(currentPageIndex) | ||
| .stream() | ||
| .map(actionRecord -> ModerationUtils.actionToEmbedField(actionRecord, event.getJDA())) | ||
| .toList(); | ||
|
|
||
| return RestAction.allOf(fetchFieldActions).map(embedFields -> { | ||
| finalizeAndSendEmbed(event, auditEmbed, embedFields, user.getIdLong(), currentPageIndex, | ||
| pages.size()); | ||
| return embedFields; | ||
| }); | ||
|
Zabuzard marked this conversation as resolved.
|
||
| } | ||
|
|
||
| private void finalizeAndSendEmbed(ButtonInteractionEvent event, EmbedBuilder auditEmbed, | ||
| List<MessageEmbed.Field> embedFields, long reportedUserId, int currentPageIndex, | ||
| int totalPages) { | ||
| auditEmbed.clearFields(); | ||
| embedFields.forEach(auditEmbed::addField); | ||
|
|
||
| auditEmbed.setFooter( | ||
| "Page %d/%d (Most recent first)".formatted(currentPageIndex + 1, totalPages)); | ||
|
|
||
| String prevButtonId = generateComponentId(Lifespan.REGULAR, String.valueOf(reportedUserId), | ||
| String.valueOf(currentPageIndex - 1)); | ||
| String nextButtonId = generateComponentId(Lifespan.REGULAR, String.valueOf(reportedUserId), | ||
| String.valueOf(currentPageIndex + 1)); | ||
|
|
||
| Button prevButton = | ||
| Button.primary(prevButtonId, "◀ Previous").withDisabled(currentPageIndex == 0); | ||
| Button nextButton = Button.primary(nextButtonId, "Next ▶") | ||
| .withDisabled(currentPageIndex == totalPages - 1); | ||
|
|
||
| event.getHook() | ||
| .editOriginalEmbeds(auditEmbed.build()) | ||
| .setActionRow(prevButton, nextButton) | ||
| .queue(); | ||
| } | ||
|
|
||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.