Skip to content
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

Feat/delete messages upto 24 hrs #945

Closed
wants to merge 29 commits into from
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
1c12b9d
new table to hold message history
ankitsmt211 Nov 5, 2023
d368324
add package for purge command feature
ankitsmt211 Nov 5, 2023
79277c9
message listener to store message data in db
ankitsmt211 Nov 5, 2023
093aa32
add routine to clear message history and purge command
ankitsmt211 Nov 5, 2023
bde724c
adding to features
ankitsmt211 Nov 5, 2023
f6757a9
refactor based on suggestions
ankitsmt211 Nov 6, 2023
357d41d
refactor variables
ankitsmt211 Nov 6, 2023
b25ee1e
fix doc
ankitsmt211 Nov 6, 2023
a6627ba
improve doc
ankitsmt211 Nov 6, 2023
117c0cc
method to ignore messages from bot or webhooks
ankitsmt211 Nov 6, 2023
650388e
refactor stream using try-with-resource
ankitsmt211 Nov 6, 2023
ec443d3
updated catch block
ankitsmt211 Nov 6, 2023
5feb1e6
add try-with-resource and logger
ankitsmt211 Nov 6, 2023
0bdc627
minor improvements
ankitsmt211 Nov 6, 2023
672d319
method to handle reasons
ankitsmt211 Nov 6, 2023
c3f3532
minor improvements
ankitsmt211 Nov 7, 2023
c6e81af
update privacy policy
ankitsmt211 Nov 7, 2023
45bda14
improved message for user and delete already pulled records
ankitsmt211 Nov 7, 2023
d38d874
adds option for duration, message expiration from db increased
ankitsmt211 Nov 8, 2023
b9f5aed
add an atomic counter as safety brake
ankitsmt211 Nov 12, 2023
0700661
refactor variable name
ankitsmt211 Nov 12, 2023
8e80ba0
refactor counter methods
ankitsmt211 Nov 12, 2023
20a2eb3
update record limit from 7 to 7.5k
ankitsmt211 Nov 12, 2023
fedb8c6
refactor classes to be final
ankitsmt211 Nov 12, 2023
53a5b72
log level from warn to debug on record limit
ankitsmt211 Nov 12, 2023
cdc511f
Merge branch 'develop' into feat/delete-last-hour-messages
ankitsmt211 Nov 14, 2023
5813ae3
auto trim routine and minor improvements
ankitsmt211 Nov 14, 2023
9a2c3da
add choices for duration, better UX
ankitsmt211 Nov 17, 2023
10d3664
add duration enum for constants and fix
ankitsmt211 Nov 25, 2023
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 @@ -31,6 +31,9 @@
import org.togetherjava.tjbot.features.moderation.audit.AuditCommand;
import org.togetherjava.tjbot.features.moderation.audit.ModAuditLogRoutine;
import org.togetherjava.tjbot.features.moderation.audit.ModAuditLogWriter;
import org.togetherjava.tjbot.features.moderation.history.MessageHistoryRoutine;
import org.togetherjava.tjbot.features.moderation.history.MessageListener;
import org.togetherjava.tjbot.features.moderation.history.PurgeHistoryCommand;
import org.togetherjava.tjbot.features.moderation.modmail.ModMailCommand;
import org.togetherjava.tjbot.features.moderation.scam.ScamBlocker;
import org.togetherjava.tjbot.features.moderation.scam.ScamHistoryPurgeRoutine;
Expand Down Expand Up @@ -106,6 +109,7 @@ public static Collection<Feature> createFeatures(JDA jda, Database database, Con
.add(new AutoPruneHelperRoutine(config, helpSystemHelper, modAuditLogWriter, database));
features.add(new HelpThreadAutoArchiver(helpSystemHelper));
features.add(new LeftoverBookmarksCleanupRoutine(bookmarksSystem));
features.add(new MessageHistoryRoutine(database));

// Message receivers
features.add(new TopHelpersMessageListener(database, config));
Expand All @@ -119,6 +123,7 @@ public static Collection<Feature> createFeatures(JDA jda, Database database, Con
features.add(new CodeMessageManualDetection(codeMessageHandler));
features.add(new SlashCommandEducator());
features.add(new PinnedNotificationRemover(config));
features.add(new MessageListener(database));

// Event receivers
features.add(new RejoinModerationRoleListener(actionsStore, config));
Expand Down Expand Up @@ -159,6 +164,7 @@ public static Collection<Feature> createFeatures(JDA jda, Database database, Con
features.add(new BookmarksCommand(bookmarksSystem));
features.add(new ChatGptCommand(chatGptService));
features.add(new JShellCommand(jshellEval));
features.add(new PurgeHistoryCommand(database));

FeatureBlacklist<Class<?>> blacklist = blacklistConfig.normal();
return features.stream().filter(f -> blacklist.isEnabled(f.getClass())).toList();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package org.togetherjava.tjbot.features.moderation.history;

import static org.togetherjava.tjbot.db.generated.Tables.MESSAGE_HISTORY;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;
import net.dv8tion.jda.api.JDA;
import org.jooq.impl.UpdatableRecordImpl;
import org.togetherjava.tjbot.db.Database;
import org.togetherjava.tjbot.features.Routine;

/**
* Routine that records some metadata for every message received.
*/
public class MessageHistoryRoutine implements Routine {

private static final int SCHEDULE_INTERVAL_SECONDS = 30;
private final Database database;

/**
* Creates a new instance.
*
* @param database the database that records some metadata on each message received.
*/
public MessageHistoryRoutine(Database database) {
this.database = database;
}


@Override
public Schedule createSchedule() {
return new Schedule(ScheduleMode.FIXED_RATE, 0, SCHEDULE_INTERVAL_SECONDS,
TimeUnit.SECONDS);
}

@Override
public void runRoutine(JDA jda) {
Instant now = Instant.now();
Instant twoHourBack = now.minus(2, ChronoUnit.HOURS);
ankitsmt211 marked this conversation as resolved.
Show resolved Hide resolved

database.write(context -> context.selectFrom(MESSAGE_HISTORY)
.where(MESSAGE_HISTORY.SENT_AT.lessThan(twoHourBack))
.stream()
.forEach(UpdatableRecordImpl::delete));
ankitsmt211 marked this conversation as resolved.
Show resolved Hide resolved
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package org.togetherjava.tjbot.features.moderation.history;

import static org.togetherjava.tjbot.db.generated.Tables.MESSAGE_HISTORY;

import java.time.Instant;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.togetherjava.tjbot.db.Database;
import org.togetherjava.tjbot.features.MessageReceiverAdapter;

/**
* Listens for new message throughout the guild, then stores some metadata for each message in a
* database.
*/
public class MessageListener extends MessageReceiverAdapter {
ankitsmt211 marked this conversation as resolved.
Show resolved Hide resolved
private final Database database;

/**
* Creates a new instance.
*
* @param database this database to record some metadata for each message received throughout
* guild.
*/
public MessageListener(Database database) {
this.database = database;
}

@Override
public void onMessageReceived(MessageReceivedEvent event) {
updateHistory(event);
}

private void updateHistory(MessageReceivedEvent event) {
long guildId = event.getGuild().getIdLong();
long channelId = event.getChannel().getIdLong();
long messageId = event.getMessageIdLong();
long authorId = event.getAuthor().getIdLong();

database.write(context -> context.newRecord(MESSAGE_HISTORY)
.setSentAt(Instant.now())
.setGuildId(guildId)
.setChannelId(channelId)
.setMessageId(messageId)
.setAuthorId(authorId)
.insert());
}
ankitsmt211 marked this conversation as resolved.
Show resolved Hide resolved
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package org.togetherjava.tjbot.features.moderation.history;

import static org.togetherjava.tjbot.db.generated.Tables.MESSAGE_HISTORY;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.InteractionHook;
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import org.togetherjava.tjbot.db.Database;
import org.togetherjava.tjbot.features.CommandVisibility;
import org.togetherjava.tjbot.features.SlashCommandAdapter;

public class PurgeHistoryCommand extends SlashCommandAdapter {

private static final String USER_OPTION = "user";
private static final String REASON_OPTION = "reason";
private static final String COMMAND_NAME = "purge";
private final Database database;

/**
* Creates an instance of the command.
*
* @param database the database to retrieve message records of a target user
*/

public PurgeHistoryCommand(Database database) {
super(COMMAND_NAME, "delete user message history upto an hour", CommandVisibility.GUILD);
ankitsmt211 marked this conversation as resolved.
Show resolved Hide resolved
getData()
.addOption(OptionType.USER, USER_OPTION,
"user who's messages you want to purge within an hour", true)
.addOption(OptionType.STRING, REASON_OPTION, "Reason for purging user messages", true);
ankitsmt211 marked this conversation as resolved.
Show resolved Hide resolved
this.database = database;
}

@Override
public void onSlashCommand(SlashCommandInteractionEvent event) {
event.deferReply().queue();

OptionMapping targetOption =
Objects.requireNonNull(event.getOption(USER_OPTION), "target is null");
Member author = Objects.requireNonNull(event.getMember(), "author is null");
String reason = Objects.requireNonNull(event.getOption(REASON_OPTION).getAsString(),
"reason is null");

handleHistory(event, author, reason, targetOption, event.getHook());
}

private void handleHistory(SlashCommandInteractionEvent event, Member author, String reason,
OptionMapping targetOption, InteractionHook hook) {
Instant now = Instant.now();
Instant oneHourBack = now.minus(1, ChronoUnit.HOURS);
ankitsmt211 marked this conversation as resolved.
Show resolved Hide resolved

User target = targetOption.getAsUser();
String sourceChannelId = event.getChannel().getId();

if (!validateHierarchy(author, targetOption)) {
hook.sendMessage("Target user has a higher role than you").setEphemeral(true).queue();
ankitsmt211 marked this conversation as resolved.
Show resolved Hide resolved
return;
}

List<String> messageIdsForDeletion = new ArrayList<>();

database.write(context -> context.selectFrom(MESSAGE_HISTORY)
.where(MESSAGE_HISTORY.AUTHOR_ID.equal(target.getIdLong())
.and(MESSAGE_HISTORY.CHANNEL_ID.equal(Long.valueOf(sourceChannelId)))
.and(MESSAGE_HISTORY.SENT_AT.greaterOrEqual(oneHourBack)))
.stream()
ankitsmt211 marked this conversation as resolved.
Show resolved Hide resolved
.forEach(messageHistoryRecord -> {
messageIdsForDeletion.add(String.valueOf(messageHistoryRecord.getMessageId()));
messageHistoryRecord.delete();
}));

handleDelete(messageIdsForDeletion, event.getJDA(), event.getChannel(), event.getHook());
}

private void handleDelete(List<String> messageIdsForDeletion, JDA jda,
MessageChannelUnion channel, InteractionHook hook) {

if (messageIdsForDeletion.isEmpty()) {
handleEmptyMessageHistory(hook);
return;
}

if (hasSingleElement(messageIdsForDeletion)) {
String messageId = messageIdsForDeletion.get(0);

Objects.requireNonNull(jda.getTextChannelById(channel.getId()), "channel was not found")
.deleteMessageById(messageId)
.queue();
}

channel.purgeMessagesById(messageIdsForDeletion);
hook.sendMessage("Messages purged from user").setEphemeral(true).queue();
}

private boolean hasSingleElement(List<String> messageIdsForDeletion) {
return messageIdsForDeletion.size() == 1;
}

private void handleEmptyMessageHistory(InteractionHook hook) {
hook.sendMessage("User has no message history in this channel within last one hour")
.setEphemeral(true)
.queue();
}

private boolean validateHierarchy(Member author, OptionMapping target) {
int highestRole = 0;
Role targetUserRole = target.getAsMember().getRoles().get(highestRole);
Role authorRole = author.getRoles().get(highestRole);

return targetUserRole.getPosition() >= authorRole.getPosition();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* This package offers moderation command to delete messages from a user within last hour.
ankitsmt211 marked this conversation as resolved.
Show resolved Hide resolved
*/
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
package org.togetherjava.tjbot.features.moderation.history;

import javax.annotation.ParametersAreNonnullByDefault;
import org.togetherjava.tjbot.annotations.MethodsReturnNonnullByDefault;
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
CREATE TABLE message_history
(
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
sent_at TIMESTAMP NOT NULL,
guild_id BIGINT NOT NULL,
channel_id BIGINT NOT NULL,
message_id BIGINT NOT NULL,
author_id BIGINT NOT NULL
)