|
| 1 | +package org.togetherjava.tjbot.features.basic; |
| 2 | + |
| 3 | +import net.dv8tion.jda.api.JDA; |
| 4 | +import net.dv8tion.jda.api.entities.Guild; |
| 5 | +import net.dv8tion.jda.api.entities.Message; |
| 6 | +import net.dv8tion.jda.api.entities.MessageReaction; |
| 7 | +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; |
| 8 | +import net.dv8tion.jda.api.entities.emoji.Emoji; |
| 9 | +import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent; |
| 10 | +import net.dv8tion.jda.api.requests.RestAction; |
| 11 | +import org.slf4j.Logger; |
| 12 | +import org.slf4j.LoggerFactory; |
| 13 | + |
| 14 | +import org.togetherjava.tjbot.config.Config; |
| 15 | +import org.togetherjava.tjbot.config.QuoteBoardConfig; |
| 16 | +import org.togetherjava.tjbot.features.MessageReceiverAdapter; |
| 17 | + |
| 18 | +import java.util.List; |
| 19 | +import java.util.Optional; |
| 20 | +import java.util.function.Predicate; |
| 21 | +import java.util.regex.Pattern; |
| 22 | + |
| 23 | +/** |
| 24 | + * Listens for reaction-add events and turns popular messages into "quotes". |
| 25 | + * <p> |
| 26 | + * When someone reacts to a message with the configured emoji, the listener counts how many users |
| 27 | + * have used that same emoji. If the total meets or exceeds the minimum threshold and the bot has |
| 28 | + * not processed the message before, it copies (forwards) the message to the first text channel |
| 29 | + * whose name matches the configured quote-board pattern, then reacts to the original message itself |
| 30 | + * to mark it as handled (and to not let people spam react a message and give a way to the bot to |
| 31 | + * know that a message has been quoted before). |
| 32 | + * <p> |
| 33 | + * Key points: - Trigger emoji, minimum vote count and quote-board channel pattern are supplied via |
| 34 | + * {@code QuoteBoardConfig}. |
| 35 | + */ |
| 36 | +public final class QuoteBoardForwarder extends MessageReceiverAdapter { |
| 37 | + |
| 38 | + private static final Logger logger = LoggerFactory.getLogger(QuoteBoardForwarder.class); |
| 39 | + private final Emoji triggerReaction; |
| 40 | + private final Predicate<String> isQuoteBoardChannelName; |
| 41 | + private final QuoteBoardConfig config; |
| 42 | + |
| 43 | + /** |
| 44 | + * Constructs a new instance of QuoteBoardForwarder. |
| 45 | + * |
| 46 | + * @param config the configuration containing settings specific to the cool messages board, |
| 47 | + * including the reaction emoji and the pattern to match board channel names |
| 48 | + */ |
| 49 | + public QuoteBoardForwarder(Config config) { |
| 50 | + this.config = config.getQuoteBoardConfig(); |
| 51 | + this.triggerReaction = Emoji.fromUnicode(this.config.reactionEmoji()); |
| 52 | + |
| 53 | + this.isQuoteBoardChannelName = Pattern.compile(this.config.channel()).asMatchPredicate(); |
| 54 | + } |
| 55 | + |
| 56 | + @Override |
| 57 | + public void onMessageReactionAdd(MessageReactionAddEvent event) { |
| 58 | + logger.debug("Received MessageReactionAddEvent: messageId={}, channelId={}, userId={}", |
| 59 | + event.getMessageId(), event.getChannel().getId(), event.getUserId()); |
| 60 | + |
| 61 | + final MessageReaction messageReaction = event.getReaction(); |
| 62 | + |
| 63 | + if (!messageReaction.getEmoji().equals(triggerReaction)) { |
| 64 | + logger.debug("Reaction emoji '{}' does not match trigger emoji '{}'. Ignoring.", |
| 65 | + messageReaction.getEmoji(), triggerReaction); |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + if (hasAlreadyForwardedMessage(event.getJDA(), messageReaction)) { |
| 70 | + logger.debug("Message has already been forwarded by the bot. Skipping."); |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + long reactionCount = messageReaction.retrieveUsers().stream().count(); |
| 75 | + if (reactionCount < config.minimumReactions()) { |
| 76 | + logger.debug("Reaction count {} is less than minimum required {}. Skipping.", |
| 77 | + reactionCount, config.minimumReactions()); |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + final long guildId = event.getGuild().getIdLong(); |
| 82 | + |
| 83 | + Optional<TextChannel> boardChannel = findQuoteBoardChannel(event.getJDA(), guildId); |
| 84 | + |
| 85 | + if (boardChannel.isEmpty()) { |
| 86 | + logger.warn( |
| 87 | + "Could not find board channel with pattern '{}' in server with ID '{}'. Skipping reaction handling...", |
| 88 | + this.config.channel(), guildId); |
| 89 | + return; |
| 90 | + } |
| 91 | + |
| 92 | + logger.debug("Forwarding message to quote board channel: {}", boardChannel.get().getName()); |
| 93 | + |
| 94 | + event.retrieveMessage() |
| 95 | + .queue(message -> markAsProcessed(message) |
| 96 | + .flatMap(v -> message.forwardTo(boardChannel.orElseThrow())) |
| 97 | + .queue(_ -> logger.debug("Message forwarded to quote board channel: {}", |
| 98 | + boardChannel.get().getName())), |
| 99 | + |
| 100 | + e -> logger.warn( |
| 101 | + "Unknown error while attempting to retrieve and forward message for quote-board, message is ignored.", |
| 102 | + e)); |
| 103 | + |
| 104 | + } |
| 105 | + |
| 106 | + private RestAction<Void> markAsProcessed(Message message) { |
| 107 | + return message.addReaction(triggerReaction); |
| 108 | + } |
| 109 | + |
| 110 | + /** |
| 111 | + * Gets the board text channel where the quotes go to, wrapped in an optional. |
| 112 | + * |
| 113 | + * @param jda the JDA |
| 114 | + * @param guildId the guild ID |
| 115 | + * @return the board text channel |
| 116 | + */ |
| 117 | + private Optional<TextChannel> findQuoteBoardChannel(JDA jda, long guildId) { |
| 118 | + Guild guild = jda.getGuildById(guildId); |
| 119 | + |
| 120 | + if (guild == null) { |
| 121 | + throw new IllegalStateException( |
| 122 | + String.format("Guild with ID '%d' not found.", guildId)); |
| 123 | + } |
| 124 | + |
| 125 | + List<TextChannel> matchingChannels = guild.getTextChannelCache() |
| 126 | + .stream() |
| 127 | + .filter(channel -> isQuoteBoardChannelName.test(channel.getName())) |
| 128 | + .toList(); |
| 129 | + |
| 130 | + if (matchingChannels.size() > 1) { |
| 131 | + logger.warn( |
| 132 | + "Multiple quote board channels found matching pattern '{}' in guild with ID '{}'. Selecting the first one anyway.", |
| 133 | + this.config.channel(), guildId); |
| 134 | + } |
| 135 | + |
| 136 | + return matchingChannels.stream().findFirst(); |
| 137 | + } |
| 138 | + |
| 139 | + /** |
| 140 | + * Checks a {@link MessageReaction} to see if the bot has reacted to it. |
| 141 | + */ |
| 142 | + private boolean hasAlreadyForwardedMessage(JDA jda, MessageReaction messageReaction) { |
| 143 | + if (!triggerReaction.equals(messageReaction.getEmoji())) { |
| 144 | + return false; |
| 145 | + } |
| 146 | + |
| 147 | + return messageReaction.retrieveUsers() |
| 148 | + .parallelStream() |
| 149 | + .anyMatch(user -> jda.getSelfUser().getIdLong() == user.getIdLong()); |
| 150 | + } |
| 151 | +} |
0 commit comments