Skip to content

Commit

Permalink
Use Cache
Browse files Browse the repository at this point in the history
  • Loading branch information
java-coding-prodigy committed Oct 1, 2023
1 parent 35b6f05 commit 5267e3f
Showing 1 changed file with 14 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.togetherjava.tjbot.features.basic;

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.Permission;
import net.dv8tion.jda.api.entities.Guild;
Expand All @@ -20,6 +22,7 @@
import org.togetherjava.tjbot.features.EventReceiver;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

import static org.togetherjava.tjbot.db.generated.tables.StarboardMessages.STARBOARD_MESSAGES;

Expand All @@ -29,17 +32,23 @@ public class Starboard extends ListenerAdapter implements EventReceiver {
private final StarboardConfig config;
private final Database database;

private final Cache<Long, Object> messageCache;

public Starboard(Config config, Database database) {
this.config = config.getStarboard();
this.database = database;
this.messageCache = Caffeine.newBuilder()
.maximumSize(100)
.expireAfterAccess(24, TimeUnit.HOURS) // TODO make these constants
.build();
}

@Override
public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) {
String emojiName = event.getEmoji().asCustom().getName();
Guild guild = event.getGuild();
if (shouldIgnoreMessage(emojiName, guild, event.getGuildChannel(),
event.getMessageIdLong())) {
long messageId = event.getMessageIdLong();
if (shouldIgnoreMessage(emojiName, guild, event.getGuildChannel(), messageId)) {
return;
}
Optional<TextChannel> starboardChannel = getStarboardChannel(guild);
Expand All @@ -48,8 +57,8 @@ public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) {
config.channelPattern());
return;
}
database.write(context -> context.newRecord(STARBOARD_MESSAGES)
.setMessageId(event.getMessageIdLong()));
database.write(context -> context.newRecord(STARBOARD_MESSAGES).setMessageId(messageId));
messageCache.put(messageId, new Object());
event.retrieveMessage()
.flatMap(
message -> starboardChannel.orElseThrow().sendMessageEmbeds(formEmbed(message)))
Expand All @@ -60,6 +69,7 @@ private boolean shouldIgnoreMessage(String emojiName, Guild guild, GuildChannel
long messageId) {
return !config.emojiNames().contains(emojiName)
|| !guild.getPublicRole().hasPermission(channel, Permission.VIEW_CHANNEL)
|| messageCache.getIfPresent(messageId) != null
|| database
.read(context -> context.fetchExists(context.selectFrom(STARBOARD_MESSAGES)
.where(STARBOARD_MESSAGES.MESSAGE_ID.eq(messageId))));
Expand Down

0 comments on commit 5267e3f

Please sign in to comment.