-
-
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 6 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. | ||
|
|
@@ -273,7 +280,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 +449,84 @@ 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<>(); | ||
| final int maxPageLength = 10; | ||
|
|
||
| for (int i = 0; i < actions.size(); i++) { | ||
| if (i % maxPageLength == 0) { | ||
| groupedActions.add(new ArrayList<>(maxPageLength)); | ||
| } | ||
| 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 action the record data item | ||
| * @param jda the active JDA instance used to resolve the moderator's handle | ||
| * @return a field representation task mapping out the execution card detail | ||
| */ | ||
| public static RestAction<MessageEmbed.Field> actionToField(ActionRecord action, JDA jda) { | ||
|
Zabuzard marked this conversation as resolved.
Outdated
|
||
| return jda.retrieveUserById(action.authorId()) | ||
| .map(author -> author == null ? "(unknown user)" : author.getName()) | ||
| .map(authorText -> { | ||
| String expiresAtFormatted = action.actionExpiresAt() == null ? "" | ||
| : "\nTemporary action, expires at: " + net.dv8tion.jda.api.utils.TimeUtil | ||
| .getDateTimeString(action.actionExpiresAt().atOffset(ZoneOffset.UTC)); | ||
|
|
||
| String fieldName = "%s by %s".formatted(action.actionType().name(), authorText); | ||
| String fieldDescription = | ||
| """ | ||
| %s | ||
| Issued at: %s%s | ||
| """.formatted(action.reason(), | ||
| net.dv8tion.jda.api.utils.TimeUtil | ||
| .getDateTimeString(action.issuedAt().atOffset(ZoneOffset.UTC)), | ||
| expiresAtFormatted); | ||
|
|
||
| return new MessageEmbed.Field(fieldName, fieldDescription, false); | ||
| }); | ||
| } | ||
|
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,6 +10,7 @@ | |
| 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; | ||
|
|
@@ -25,11 +26,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.Collections; | ||
| import java.util.List; | ||
| import java.util.Objects; | ||
| import java.util.Optional; | ||
|
|
@@ -53,15 +56,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 +190,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 +234,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 +243,92 @@ 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.deferEdit().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 java.util.ArrayList<>( | ||
| moderationActionsStore.getActionsByTargetAscending(guildId, reportedUserId)); | ||
|
Zabuzard marked this conversation as resolved.
Outdated
|
||
| Collections.reverse(actions); | ||
| List<List<ActionRecord>> pages = ModerationUtils.groupActionsByPages(actions); | ||
|
|
||
| event.getJDA() | ||
| .retrieveUserById(reportedUserId) | ||
| .queue(user -> renderAuditEmbed(event, user, actions, pages, targetPage), | ||
| _ -> event.getHook() | ||
| .sendMessage("Could not retrieve audit data for this user.") | ||
| .queue()); | ||
|
Zabuzard marked this conversation as resolved.
Outdated
|
||
| } | ||
|
|
||
| private void renderAuditEmbed(ButtonInteractionEvent event, | ||
| net.dv8tion.jda.api.entities.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()) { | ||
| event.getHook() | ||
| .editOriginalEmbeds(auditEmbed.build()) | ||
| .setComponents(Collections.emptyList()) | ||
| .queue(); | ||
| return; | ||
| } | ||
|
|
||
| int currentPageIndex = Math.clamp(targetPage, 0, pages.size() - 1); | ||
|
|
||
| List<net.dv8tion.jda.api.requests.RestAction<MessageEmbed.Field>> fieldTasks = | ||
| pages.get(currentPageIndex) | ||
| .stream() | ||
| .map(action -> ModerationUtils.actionToField(action, event.getJDA())) | ||
| .toList(); | ||
|
|
||
| net.dv8tion.jda.api.requests.RestAction.allOf(fieldTasks) | ||
| .queue(fields -> finalizeAndSendEmbed(event, auditEmbed, fields, user.getIdLong(), | ||
| currentPageIndex, pages.size()), | ||
| _ -> event.getHook() | ||
| .sendMessage("Could not load moderation history fields.") | ||
| .queue()); | ||
| } | ||
|
|
||
| private void finalizeAndSendEmbed(ButtonInteractionEvent event, EmbedBuilder auditEmbed, | ||
| List<MessageEmbed.Field> fields, long reportedUserId, int currentPageIndex, | ||
| int totalPages) { | ||
| auditEmbed.clearFields(); | ||
| fields.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.