diff --git a/application/build.gradle b/application/build.gradle index 08282a6890..bbd4f804d4 100644 --- a/application/build.gradle +++ b/application/build.gradle @@ -46,7 +46,7 @@ dependencies { implementation project(':utils') implementation project(':formatter') - implementation 'net.dv8tion:JDA:5.1.0' + implementation 'net.dv8tion:JDA:5.1.2' implementation 'org.apache.logging.log4j:log4j-core:2.23.0' runtimeOnly 'org.apache.logging.log4j:log4j-slf4j18-impl:2.18.0' diff --git a/application/config.json.template b/application/config.json.template index a1aec8f470..3e361cbedc 100644 --- a/application/config.json.template +++ b/application/config.json.template @@ -115,5 +115,10 @@ "fallbackChannelPattern": "java-news-and-changes", "pollIntervalInMinutes": 10 }, + "coolMessagesConfig": { + "minimumReactions": 5, + "boardChannelPattern": "quotes", + "reactionEmoji": "U+2B50" + }, "memberCountCategoryPattern": "Info" } diff --git a/application/src/main/java/org/togetherjava/tjbot/config/Config.java b/application/src/main/java/org/togetherjava/tjbot/config/Config.java index e819f8e7d1..8d941d7e10 100644 --- a/application/src/main/java/org/togetherjava/tjbot/config/Config.java +++ b/application/src/main/java/org/togetherjava/tjbot/config/Config.java @@ -46,6 +46,7 @@ public final class Config { private final RSSFeedsConfig rssFeedsConfig; private final String selectRolesChannelPattern; private final String memberCountCategoryPattern; + private final CoolMessagesBoardConfig coolMessagesConfig; @SuppressWarnings("ConstructorWithTooManyParameters") @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) @@ -94,7 +95,9 @@ private Config(@JsonProperty(value = "token", required = true) String token, required = true) FeatureBlacklistConfig featureBlacklistConfig, @JsonProperty(value = "rssConfig", required = true) RSSFeedsConfig rssFeedsConfig, @JsonProperty(value = "selectRolesChannelPattern", - required = true) String selectRolesChannelPattern) { + required = true) String selectRolesChannelPattern, + @JsonProperty(value = "coolMessagesConfig", + required = true) CoolMessagesBoardConfig coolMessagesConfig) { this.token = Objects.requireNonNull(token); this.githubApiKey = Objects.requireNonNull(githubApiKey); this.databasePath = Objects.requireNonNull(databasePath); @@ -127,6 +130,7 @@ private Config(@JsonProperty(value = "token", required = true) String token, this.featureBlacklistConfig = Objects.requireNonNull(featureBlacklistConfig); this.rssFeedsConfig = Objects.requireNonNull(rssFeedsConfig); this.selectRolesChannelPattern = Objects.requireNonNull(selectRolesChannelPattern); + this.coolMessagesConfig = Objects.requireNonNull(coolMessagesConfig); } /** @@ -401,6 +405,15 @@ public String getSelectRolesChannelPattern() { return selectRolesChannelPattern; } + /** + * The configuration of the cool messages config. + * + * @return configuration of cool messages config + */ + public CoolMessagesBoardConfig getCoolMessagesConfig() { + return coolMessagesConfig; + } + /** * Gets the pattern matching the category that is used to display the total member count. * diff --git a/application/src/main/java/org/togetherjava/tjbot/config/CoolMessagesBoardConfig.java b/application/src/main/java/org/togetherjava/tjbot/config/CoolMessagesBoardConfig.java new file mode 100644 index 0000000000..bf2d1b57be --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/config/CoolMessagesBoardConfig.java @@ -0,0 +1,28 @@ +package org.togetherjava.tjbot.config; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonRootName; + +import java.util.Objects; + +/** + * Configuration for the cool messages board feature, see + * {@link org.togetherjava.tjbot.features.basic.CoolMessagesBoardManager}. + */ +@JsonRootName("coolMessagesConfig") +public record CoolMessagesBoardConfig( + @JsonProperty(value = "minimumReactions", required = true) int minimumReactions, + @JsonProperty(value = "boardChannelPattern", required = true) String boardChannelPattern, + @JsonProperty(value = "reactionEmoji", required = true) String reactionEmoji) { + + /** + * Creates a CoolMessagesBoardConfig. + * + * @param minimumReactions the minimum amount of reactions + * @param boardChannelPattern the pattern for the board channel + * @param reactionEmoji the emoji with which users should react to + */ + public CoolMessagesBoardConfig { + Objects.requireNonNull(boardChannelPattern); + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/features/Features.java b/application/src/main/java/org/togetherjava/tjbot/features/Features.java index 893adbc00f..e8cbfd84ef 100644 --- a/application/src/main/java/org/togetherjava/tjbot/features/Features.java +++ b/application/src/main/java/org/togetherjava/tjbot/features/Features.java @@ -6,6 +6,7 @@ import org.togetherjava.tjbot.config.FeatureBlacklist; import org.togetherjava.tjbot.config.FeatureBlacklistConfig; import org.togetherjava.tjbot.db.Database; +import org.togetherjava.tjbot.features.basic.CoolMessagesBoardManager; import org.togetherjava.tjbot.features.basic.MemberCountDisplayRoutine; import org.togetherjava.tjbot.features.basic.PingCommand; import org.togetherjava.tjbot.features.basic.RoleSelectCommand; @@ -150,6 +151,7 @@ public static Collection createFeatures(JDA jda, Database database, Con features.add(new CodeMessageManualDetection(codeMessageHandler)); features.add(new SlashCommandEducator()); features.add(new PinnedNotificationRemover(config)); + features.add(new CoolMessagesBoardManager(config)); // Event receivers features.add(new RejoinModerationRoleListener(actionsStore, config)); diff --git a/application/src/main/java/org/togetherjava/tjbot/features/MessageReceiver.java b/application/src/main/java/org/togetherjava/tjbot/features/MessageReceiver.java index c5b6358434..18a1adb023 100644 --- a/application/src/main/java/org/togetherjava/tjbot/features/MessageReceiver.java +++ b/application/src/main/java/org/togetherjava/tjbot/features/MessageReceiver.java @@ -3,6 +3,7 @@ import net.dv8tion.jda.api.events.message.MessageDeleteEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageUpdateEvent; +import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent; import java.util.regex.Pattern; @@ -56,4 +57,13 @@ public interface MessageReceiver extends Feature { * message that was deleted */ void onMessageDeleted(MessageDeleteEvent event); + + /** + * Triggered by the core system whenever a new reaction was added to a message in a text channel + * of a guild the bot has been added to. + * + * @param event the event that triggered this, containing information about the corresponding + * reaction that was added + */ + void onMessageReactionAdd(MessageReactionAddEvent event); } diff --git a/application/src/main/java/org/togetherjava/tjbot/features/MessageReceiverAdapter.java b/application/src/main/java/org/togetherjava/tjbot/features/MessageReceiverAdapter.java index 05280c97ab..6ceee951b9 100644 --- a/application/src/main/java/org/togetherjava/tjbot/features/MessageReceiverAdapter.java +++ b/application/src/main/java/org/togetherjava/tjbot/features/MessageReceiverAdapter.java @@ -3,6 +3,7 @@ import net.dv8tion.jda.api.events.message.MessageDeleteEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageUpdateEvent; +import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent; import java.util.regex.Pattern; @@ -57,4 +58,10 @@ public void onMessageUpdated(MessageUpdateEvent event) { public void onMessageDeleted(MessageDeleteEvent event) { // Adapter does not react by default, subclasses may change this behavior } + + @SuppressWarnings("NoopMethodInAbstractClass") + @Override + public void onMessageReactionAdd(MessageReactionAddEvent event) { + // Adapter does not react by default, subclasses may change this behavior + } } diff --git a/application/src/main/java/org/togetherjava/tjbot/features/basic/CoolMessagesBoardManager.java b/application/src/main/java/org/togetherjava/tjbot/features/basic/CoolMessagesBoardManager.java new file mode 100644 index 0000000000..c0168f7b27 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/features/basic/CoolMessagesBoardManager.java @@ -0,0 +1,115 @@ +package org.togetherjava.tjbot.features.basic; + +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.entities.Message; +import net.dv8tion.jda.api.entities.MessageReaction; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; +import net.dv8tion.jda.api.entities.emoji.Emoji; +import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent; +import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.togetherjava.tjbot.config.Config; +import org.togetherjava.tjbot.config.CoolMessagesBoardConfig; +import org.togetherjava.tjbot.features.MessageReceiverAdapter; + +import java.util.Optional; +import java.util.function.Predicate; +import java.util.regex.Pattern; + +/** + * Manager for the cool messages board. It appends highly-voted text messages to a separate channel + * where members of the guild can see a list of all of them. + */ +public final class CoolMessagesBoardManager extends MessageReceiverAdapter { + + private static final Logger logger = LoggerFactory.getLogger(CoolMessagesBoardManager.class); + private final Emoji coolEmoji; + private final Predicate boardChannelNamePredicate; + private final CoolMessagesBoardConfig config; + + /** + * Constructs a new instance of CoolMessagesBoardManager. + * + * @param config the configuration containing settings specific to the cool messages board, + * including the reaction emoji and the pattern to match board channel names + */ + public CoolMessagesBoardManager(Config config) { + this.config = config.getCoolMessagesConfig(); + this.coolEmoji = Emoji.fromUnicode(this.config.reactionEmoji()); + + boardChannelNamePredicate = + Pattern.compile(this.config.boardChannelPattern()).asMatchPredicate(); + } + + @Override + public void onMessageReactionAdd(MessageReactionAddEvent event) { + final MessageReaction messageReaction = event.getReaction(); + int originalReactionsCount = messageReaction.hasCount() ? messageReaction.getCount() : 0; + boolean isCoolEmoji = messageReaction.getEmoji().equals(coolEmoji); + long guildId = event.getGuild().getIdLong(); + Optional boardChannel = getBoardChannel(event.getJDA(), guildId); + + if (boardChannel.isEmpty()) { + logger.warn( + "Could not find board channel with pattern '{}' in server with ID '{}'. Skipping reaction handling...", + this.config.boardChannelPattern(), guildId); + return; + } + + // If the bot has already reacted to this message, then this means that + // the message has been quoted to the cool messages board, so skip it. + if (hasBotReacted(event.getJDA(), messageReaction)) { + return; + } + + final int newReactionsCount = originalReactionsCount + 1; + if (isCoolEmoji && newReactionsCount >= config.minimumReactions()) { + event.retrieveMessage() + .queue(message -> message.addReaction(coolEmoji) + .flatMap(v -> insertCoolMessage(boardChannel.get(), message)) + .queue(), + e -> logger.warn("Tried to retrieve cool message but got: {}", + e.getMessage())); + } + } + + /** + * Gets the board text channel where the quotes go to, wrapped in an optional. + * + * @param jda the JDA + * @param guildId the guild ID + * @return the board text channel + */ + private Optional getBoardChannel(JDA jda, long guildId) { + return jda.getGuildById(guildId) + .getTextChannelCache() + .stream() + .filter(channel -> boardChannelNamePredicate.test(channel.getName())) + .findAny(); + } + + /** + * Inserts a message to the specified text channel + * + * @return a {@link MessageCreateAction} of the call to make + */ + private static MessageCreateAction insertCoolMessage(TextChannel boardChannel, + Message message) { + return message.forwardTo(boardChannel); + } + + /** + * Checks a {@link MessageReaction} to see if the bot has reacted to it. + */ + private boolean hasBotReacted(JDA jda, MessageReaction messageReaction) { + if (!coolEmoji.equals(messageReaction.getEmoji())) { + return false; + } + + return messageReaction.retrieveUsers() + .parallelStream() + .anyMatch(user -> jda.getSelfUser().getIdLong() == user.getIdLong()); + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/features/system/BotCore.java b/application/src/main/java/org/togetherjava/tjbot/features/system/BotCore.java index 869e978a17..bbf71c54f6 100644 --- a/application/src/main/java/org/togetherjava/tjbot/features/system/BotCore.java +++ b/application/src/main/java/org/togetherjava/tjbot/features/system/BotCore.java @@ -13,6 +13,7 @@ import net.dv8tion.jda.api.events.message.MessageDeleteEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageUpdateEvent; +import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback; import net.dv8tion.jda.api.interactions.components.ComponentInteraction; @@ -238,6 +239,14 @@ public void onMessageDelete(final MessageDeleteEvent event) { } } + @Override + public void onMessageReactionAdd(final MessageReactionAddEvent event) { + if (event.isFromGuild()) { + getMessageReceiversSubscribedTo(event.getChannel()) + .forEach(messageReceiver -> messageReceiver.onMessageReactionAdd(event)); + } + } + private Stream getMessageReceiversSubscribedTo(Channel channel) { String channelName = channel.getName(); return channelNameToMessageReceiver.entrySet()