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 2 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 @@ -22,7 +22,7 @@
public class MessageHistoryRoutine implements Routine {
private static final Logger logger = LoggerFactory.getLogger(MessageHistoryRoutine.class);
private static final int SCHEDULE_INTERVAL_SECONDS = 30;
private static final int EXPIRATION_HOURS = 2;
private static final int EXPIRATION_HOURS = 24;
private final Database database;

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package org.togetherjava.tjbot.features.moderation.history;

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;
Expand All @@ -9,6 +8,7 @@
import net.dv8tion.jda.api.interactions.InteractionHook;
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -34,7 +34,10 @@ public class PurgeHistoryCommand extends SlashCommandAdapter {
private static final String REASON_OPTION = "reason";
private static final String COMMAND_NAME = "purge-in-channel";
private static final int PURGE_MESSAGES_AFTER_LIMIT_HOURS = 1;
private static final String DURATION = "duration";
private static final int PURGE_MESSAGES_AFTER_LIMIT_MAX = 24;
private final Database database;
private final PurgeMessageListener purgeMessageListener;

/**
* Creates an instance of the command.
Expand All @@ -49,10 +52,19 @@ public PurgeHistoryCommand(Database database) {
String optionUserDescription = "user who's message history you want to purge within %s hr"
.formatted(PURGE_MESSAGES_AFTER_LIMIT_HOURS);

String optionDurationDescription = "duration in hours (default: %s, max: %s)"
.formatted(PURGE_MESSAGES_AFTER_LIMIT_HOURS, PURGE_MESSAGES_AFTER_LIMIT_MAX);

OptionData durationData =
new OptionData(OptionType.INTEGER, DURATION, optionDurationDescription, false);
durationData.setRequiredRange(0, PURGE_MESSAGES_AFTER_LIMIT_MAX);

getData().addOption(OptionType.USER, USER_OPTION, optionUserDescription, true)
.addOption(OptionType.STRING, REASON_OPTION,
"reason for purging user's message history", true);
"reason for purging user's message history", true)
.addOptions(durationData);
this.database = database;
this.purgeMessageListener = new PurgeMessageListener(database);
}

@Override
Expand All @@ -65,13 +77,17 @@ public void onSlashCommand(SlashCommandInteractionEvent event) {
String reason = Objects.requireNonNull(event.getOption(REASON_OPTION).getAsString(),
"reason is null");

handleHistory(event, author, reason, targetOption, event.getHook());
OptionMapping durationMapping = event.getOption(DURATION);
int duration = durationMapping == null ? PURGE_MESSAGES_AFTER_LIMIT_HOURS
: durationMapping.getAsInt();

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

private void handleHistory(SlashCommandInteractionEvent event, Member author, String reason,
OptionMapping targetOption, InteractionHook hook) {
OptionMapping targetOption, InteractionHook hook, int duration) {
Instant now = Instant.now();
Instant purgeMessagesAfter = now.minus(PURGE_MESSAGES_AFTER_LIMIT_HOURS, ChronoUnit.HOURS);
Instant purgeMessagesAfter = now.minus(duration, ChronoUnit.HOURS);

User targetUser = targetOption.getAsUser();
String sourceChannelId = event.getChannel().getId();
Expand All @@ -95,54 +111,52 @@ private void handleHistory(SlashCommandInteractionEvent event, Member author, St
String messageId = String.valueOf(messageHistoryRecord.getMessageId());
messageIdsForDeletion.add(messageId);
messageHistoryRecord.delete();

purgeMessageListener.decrementRecordsCounter();
});
} catch (DatabaseException exception) {
logger.error("unknown error during fetching message history records for {} command",
COMMAND_NAME, exception);
}

handleDelete(messageIdsForDeletion, event.getJDA(), event.getChannel(), event.getHook(),
targetUser, reason, author);
handleDelete(messageIdsForDeletion, event.getChannel(), event.getHook(), targetUser, reason,
author, duration);
}

private void handleDelete(List<String> messageIdsForDeletion, JDA jda,
MessageChannelUnion channel, InteractionHook hook, User targetUser, String reason,
Member author) {
private void handleDelete(List<String> messageIdsForDeletion, MessageChannelUnion channel,
InteractionHook hook, User targetUser, String reason, Member author, int duration) {

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

if (hasSingleElement(messageIdsForDeletion)) {
String messageId = messageIdsForDeletion.get(0);
String messageForMod =
"message purged from user %s in this channel.".formatted(targetUser.getName());
Objects.requireNonNull(jda.getTextChannelById(channel.getId()), "channel was not found")
.deleteMessageById(messageId)
.queue();

String messageForMod = "message purged from user %s in this channel in last %s hrs."
.formatted(targetUser.getName(), duration);
channel.deleteMessageById(messageId).queue();
hook.sendMessage(messageForMod).queue();
return;
}

int noOfMessagePurged = messageIdsForDeletion.size();
channel.purgeMessagesById(messageIdsForDeletion);

String messageForMod = "%s messages purged from user %s in this channel."
.formatted(noOfMessagePurged, targetUser.getName());
String messageForMod = "%s messages purged from user %s in this channel in last %s hrs."
.formatted(noOfMessagePurged, targetUser.getName(), duration);
hook.sendMessage(messageForMod)
.queue(onSuccess -> logger.info("{} purged messages from {} because: {}",
author.getUser(), targetUser, reason));
.queue(onSuccess -> logger.info("{} purged messages from {} in {} because: {}",
author.getUser(), targetUser, channel.getName(), reason));
}

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

private void handleEmptyMessageHistory(InteractionHook hook, User targetUser) {
String messageForMod = "%s has no message history in this channel within last %s hr."
.formatted(targetUser.getName(), PURGE_MESSAGES_AFTER_LIMIT_HOURS);
private void handleEmptyMessageHistory(InteractionHook hook, User targetUser, int duration) {
String messageForMod = "%s has no message history in this channel within last %s hrs."
.formatted(targetUser.getName(), duration);

hook.sendMessage(messageForMod).queue();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package org.togetherjava.tjbot.features.moderation.history;

import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.togetherjava.tjbot.db.Database;
import org.togetherjava.tjbot.features.MessageReceiverAdapter;

import java.time.Instant;
import java.util.concurrent.atomic.AtomicInteger;

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

Expand All @@ -14,6 +17,9 @@
* database.
*/
public class PurgeMessageListener extends MessageReceiverAdapter {
private static final Logger logger = LoggerFactory.getLogger(PurgeMessageListener.class);
private static final int MESSAGES_RECORDS_LIMIT = 7500;
static AtomicInteger recordsCounter = new AtomicInteger(0);
private final Database database;

/**
Expand Down Expand Up @@ -41,16 +47,35 @@ private void updateHistory(MessageReceivedEvent event) {
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());
if (canWriteToDB()) {
database.write(context -> context.newRecord(MESSAGE_HISTORY)
.setSentAt(Instant.now())
.setGuildId(guildId)
.setChannelId(channelId)
.setMessageId(messageId)
.setAuthorId(authorId)
.insert());

incrementRecordsCounter();
} else {
logger.warn("purge history reached limit");
Zabuzard marked this conversation as resolved.
Show resolved Hide resolved
}
}

private boolean shouldIgnoreMessages(MessageReceivedEvent event) {
return event.isWebhookMessage() || event.getAuthor().isBot();
}

private boolean canWriteToDB() {
return recordsCounter.get() <= MESSAGES_RECORDS_LIMIT;
}

private void incrementRecordsCounter() {
recordsCounter.getAndIncrement();
}

void decrementRecordsCounter() {
recordsCounter.decrementAndGet();
}

}
Loading