Skip to content

Commit b9cab5a

Browse files
committed
add rate limit to staff activity monitor
1 parent 7b42953 commit b9cab5a

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/main/java/net/discordjug/javabot/systems/staff_activity/StaffActivityService.java

+25
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
package net.discordjug.javabot.systems.staff_activity;
22

3+
import java.time.Duration;
4+
import java.time.Instant;
5+
import java.time.temporal.ChronoUnit;
36
import java.time.temporal.TemporalAccessor;
47
import java.util.Iterator;
58
import java.util.List;
9+
import java.util.Map;
10+
import java.util.concurrent.ConcurrentHashMap;
611

712
import org.springframework.stereotype.Service;
813

@@ -29,6 +34,7 @@
2934
public class StaffActivityService {
3035
private final BotConfig botConfig;
3136
private final StaffActivityMessageRepository repository;
37+
private final Map<StaffActivityKey, Instant> lastActivities = new ConcurrentHashMap<>();
3238

3339
/**
3440
* Updates the staff activity message or creates it if necessary.
@@ -43,6 +49,17 @@ public void updateStaffActivity(StaffActivityType type, TemporalAccessor timesta
4349
if (staffActivityChannel == null) {
4450
return;
4551
}
52+
Instant now = Instant.now();
53+
Instant merged = lastActivities.merge(new StaffActivityKey(member.getGuild().getIdLong(), member.getIdLong(), type), now, (oldValue, currentInstant) -> {
54+
if (timeDifferenceIsBelowRateLimit(oldValue, currentInstant)) {
55+
// less than 5 minutes since insertion
56+
return oldValue;
57+
}
58+
return currentInstant;
59+
});
60+
if (!merged.equals(now)) {
61+
return;
62+
}
4663
Long msgId = repository.getMessageId(staffActivityChannel.getGuild().getIdLong(), member.getIdLong());
4764
if (msgId != null) {
4865
staffActivityChannel
@@ -53,6 +70,12 @@ public void updateStaffActivity(StaffActivityType type, TemporalAccessor timesta
5370
} else {
5471
createNewMessage(staffActivityChannel, member, type, timestamp);
5572
}
73+
lastActivities.entrySet()
74+
.removeIf(e -> !timeDifferenceIsBelowRateLimit(e.getValue(),now));
75+
}
76+
77+
private boolean timeDifferenceIsBelowRateLimit(Instant oldValue, Instant currentInstant) {
78+
return Duration.between(oldValue, currentInstant).minus(Duration.of(5, ChronoUnit.MINUTES)).isNegative();
5679
}
5780

5881
private void replaceActivityMessage(StaffActivityType type, TemporalAccessor timestamp, Message activityMessage, Member member) {
@@ -96,4 +119,6 @@ private MessageEmbed createEmptyStaffActivityEmbed(Member member) {
96119
.setFooter(member.getId())
97120
.build();
98121
}
122+
123+
private record StaffActivityKey(long guildId, long memberId, StaffActivityType type) {}
99124
}

0 commit comments

Comments
 (0)