|
| 1 | +package org.togetherjava.tjbot.features.analytics; |
| 2 | + |
| 3 | +import net.dv8tion.jda.api.entities.emoji.CustomEmoji; |
| 4 | +import net.dv8tion.jda.api.entities.emoji.Emoji; |
| 5 | +import net.dv8tion.jda.api.entities.emoji.EmojiUnion; |
| 6 | +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; |
| 7 | +import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent; |
| 8 | + |
| 9 | +import org.togetherjava.tjbot.features.MessageReceiverAdapter; |
| 10 | + |
| 11 | +/** |
| 12 | + * Listener that tracks custom emoji usage across all channels for analytics purposes. |
| 13 | + * <p> |
| 14 | + * Counts custom emojis used in messages and reactions so admins can see which emojis are unused and |
| 15 | + * should be removed. |
| 16 | + * <p> |
| 17 | + * Custom emojis are tracked by their Discord ID (e.g. {@code emoji-custom-123456789}). Animated |
| 18 | + * custom emojis are tracked separately (e.g. {@code emoji-custom-animated-123456789}). |
| 19 | + */ |
| 20 | +public final class EmojiTrackerListener extends MessageReceiverAdapter { |
| 21 | + private final Metrics metrics; |
| 22 | + |
| 23 | + /** |
| 24 | + * Creates a new listener to track emoji usage across all channels. |
| 25 | + * |
| 26 | + * @param metrics to track emoji usage events |
| 27 | + */ |
| 28 | + public EmojiTrackerListener(Metrics metrics) { |
| 29 | + super(); |
| 30 | + |
| 31 | + this.metrics = metrics; |
| 32 | + } |
| 33 | + |
| 34 | + @Override |
| 35 | + public void onMessageReceived(MessageReceivedEvent event) { |
| 36 | + if (event.isWebhookMessage()) { |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + event.getMessage().getMentions().getCustomEmojis().forEach(this::trackCustomEmoji); |
| 41 | + } |
| 42 | + |
| 43 | + @Override |
| 44 | + public void onMessageReactionAdd(MessageReactionAddEvent event) { |
| 45 | + EmojiUnion emoji = event.getEmoji(); |
| 46 | + if (emoji.getType() != Emoji.Type.CUSTOM) { |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + trackCustomEmoji(emoji.asCustom()); |
| 51 | + } |
| 52 | + |
| 53 | + private void trackCustomEmoji(CustomEmoji emoji) { |
| 54 | + String prefix = emoji.isAnimated() ? "emoji-custom-animated-" : "emoji-custom-"; |
| 55 | + metrics.count(prefix + emoji.getIdLong()); |
| 56 | + } |
| 57 | +} |
0 commit comments