Skip to content

Commit e64fd0b

Browse files
authored
Added metric events (#1433)
* added a bunch of metric events * adjusted tests * (merge conflict)
1 parent ddabd5e commit e64fd0b

23 files changed

Lines changed: 184 additions & 77 deletions

application/src/main/java/org/togetherjava/tjbot/features/Features.java

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -121,18 +121,18 @@ public static Collection<Feature> createFeatures(JDA jda, Database database, Con
121121
ModerationActionsStore actionsStore = new ModerationActionsStore(database);
122122
ModAuditLogWriter modAuditLogWriter = new ModAuditLogWriter(config);
123123
ScamHistoryStore scamHistoryStore = new ScamHistoryStore(database);
124-
GitHubReference githubReference = new GitHubReference(config);
124+
GitHubReference githubReference = new GitHubReference(config, metrics);
125125
CodeMessageHandler codeMessageHandler =
126-
new CodeMessageHandler(blacklistConfig.special(), jshellEval);
127-
ChatGptService chatGptService = new ChatGptService(config);
126+
new CodeMessageHandler(blacklistConfig.special(), jshellEval, metrics);
127+
ChatGptService chatGptService = new ChatGptService(config, metrics);
128128
HelpSystemHelper helpSystemHelper = new HelpSystemHelper(config, database, chatGptService);
129129
HelpThreadLifecycleListener helpThreadLifecycleListener =
130130
new HelpThreadLifecycleListener(helpSystemHelper, database);
131131
HelpThreadCreatedListener helpThreadCreatedListener =
132-
new HelpThreadCreatedListener(helpSystemHelper);
132+
new HelpThreadCreatedListener(helpSystemHelper, metrics);
133133
TopHelpersService topHelpersService = new TopHelpersService(database);
134134
TopHelpersAssignmentRoutine topHelpersAssignmentRoutine =
135-
new TopHelpersAssignmentRoutine(config, topHelpersService);
135+
new TopHelpersAssignmentRoutine(config, topHelpersService, metrics);
136136

137137
// NOTE The system can add special system relevant commands also by itself,
138138
// hence this list may not necessarily represent the full list of all commands actually
@@ -147,22 +147,22 @@ public static Collection<Feature> createFeatures(JDA jda, Database database, Con
147147
features.add(new ScamHistoryPurgeRoutine(scamHistoryStore));
148148
features.add(new HelpThreadMetadataPurger(database));
149149
features.add(new HelpThreadActivityUpdater(helpSystemHelper));
150-
features
151-
.add(new AutoPruneHelperRoutine(config, helpSystemHelper, modAuditLogWriter, database));
150+
features.add(new AutoPruneHelperRoutine(config, helpSystemHelper, modAuditLogWriter,
151+
database, metrics));
152152
features.add(new HelpThreadAutoArchiver(helpSystemHelper));
153153
features.add(new LeftoverBookmarksCleanupRoutine(bookmarksSystem));
154154
features.add(new MarkHelpThreadCloseInDBRoutine(database, helpThreadLifecycleListener));
155155
features.add(new MemberCountDisplayRoutine(config));
156-
features.add(new RSSHandlerRoutine(config, database));
156+
features.add(new RSSHandlerRoutine(config, database, metrics));
157157
features.add(topHelpersAssignmentRoutine);
158158

159159
// Message receivers
160160
features.add(new TopHelpersMessageListener(database, config));
161-
features.add(new SuggestionsUpDownVoter(config));
162-
features.add(new ScamBlocker(actionsStore, scamHistoryStore, config));
163-
features.add(new MediaOnlyChannelListener(config));
164-
features.add(new FileSharingMessageListener(config));
165-
features.add(new BlacklistedAttachmentListener(config, modAuditLogWriter));
161+
features.add(new SuggestionsUpDownVoter(config, metrics));
162+
features.add(new ScamBlocker(actionsStore, scamHistoryStore, config, metrics));
163+
features.add(new MediaOnlyChannelListener(config, metrics));
164+
features.add(new FileSharingMessageListener(config, metrics));
165+
features.add(new BlacklistedAttachmentListener(config, modAuditLogWriter, metrics));
166166
features.add(githubReference);
167167
features.add(codeMessageHandler);
168168
features.add(new CodeMessageAutoDetection(config, codeMessageHandler));
@@ -171,11 +171,11 @@ public static Collection<Feature> createFeatures(JDA jda, Database database, Con
171171
features.add(new QuoteBoardForwarder(config));
172172

173173
// Voice receivers
174-
features.add(new DynamicVoiceChat(config));
174+
features.add(new DynamicVoiceChat(config, metrics));
175175

176176
// Event receivers
177-
features.add(new RejoinModerationRoleListener(actionsStore, config));
178-
features.add(new GuildLeaveCloseThreadListener(config));
177+
features.add(new RejoinModerationRoleListener(actionsStore, config, metrics));
178+
features.add(new GuildLeaveCloseThreadListener(config, metrics));
179179
features.add(new LeftoverBookmarksListener(bookmarksSystem));
180180
features.add(helpThreadCreatedListener);
181181
features.add(new HelpThreadLifecycleListener(helpSystemHelper, database));
@@ -190,7 +190,7 @@ public static Collection<Feature> createFeatures(JDA jda, Database database, Con
190190
features.add(new LogLevelCommand());
191191
features.add(new PingCommand());
192192
features.add(new TeXCommand());
193-
features.add(new TagCommand(tagSystem));
193+
features.add(new TagCommand(tagSystem, metrics));
194194
features.add(new TagManageCommand(tagSystem, modAuditLogWriter));
195195
features.add(new TagsCommand(tagSystem));
196196
features.add(new WarnCommand(actionsStore));
@@ -210,7 +210,7 @@ public static Collection<Feature> createFeatures(JDA jda, Database database, Con
210210
features.add(new WolframAlphaCommand(config));
211211
features.add(new GitHubCommand(githubReference));
212212
features.add(new ModMailCommand(jda, config));
213-
features.add(new HelpThreadCommand(config, helpSystemHelper));
213+
features.add(new HelpThreadCommand(config, helpSystemHelper, metrics));
214214
features.add(new ReportCommand(config));
215215
features.add(new BookmarksCommand(bookmarksSystem));
216216
features.add(new ChatGptCommand(chatGptService, helpSystemHelper));

application/src/main/java/org/togetherjava/tjbot/features/basic/SuggestionsUpDownVoter.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import org.togetherjava.tjbot.config.Config;
1414
import org.togetherjava.tjbot.config.SuggestionsConfig;
1515
import org.togetherjava.tjbot.features.MessageReceiverAdapter;
16+
import org.togetherjava.tjbot.features.analytics.Metrics;
1617

1718
import java.util.Optional;
1819
import java.util.regex.Pattern;
@@ -28,16 +29,19 @@ public final class SuggestionsUpDownVoter extends MessageReceiverAdapter {
2829
private static final int THREAD_TITLE_MAX_LENGTH = 60;
2930

3031
private final SuggestionsConfig config;
32+
private final Metrics metrics;
3133

3234
/**
3335
* Creates a new listener to receive all message sent in suggestion channels.
3436
*
3537
* @param config the config to use for this
38+
* @param metrics to track events
3639
*/
37-
public SuggestionsUpDownVoter(Config config) {
40+
public SuggestionsUpDownVoter(Config config, Metrics metrics) {
3841
super(Pattern.compile(config.getSuggestions().getChannelPattern()));
3942

4043
this.config = config.getSuggestions();
44+
this.metrics = metrics;
4145
}
4246

4347
@Override
@@ -49,6 +53,7 @@ public void onMessageReceived(MessageReceivedEvent event) {
4953
Guild guild = event.getGuild();
5054
Message message = event.getMessage();
5155

56+
metrics.count("suggestion");
5257
createThread(message);
5358

5459
reactWith(config.getUpVoteEmoteName(), FALLBACK_UP_VOTE, guild, message);

application/src/main/java/org/togetherjava/tjbot/features/chatgpt/ChatGptService.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import org.slf4j.LoggerFactory;
1010

1111
import org.togetherjava.tjbot.config.Config;
12+
import org.togetherjava.tjbot.features.analytics.Metrics;
1213

1314
import javax.annotation.Nullable;
1415

@@ -28,14 +29,18 @@ public class ChatGptService {
2829

2930
private boolean isDisabled = false;
3031
private OpenAIClient openAIClient;
32+
private Metrics metrics;
3133

3234
/**
3335
* Creates instance of ChatGPTService
3436
*
3537
* @param config needed for token to OpenAI API.
38+
* @param metrics to track events
3639
*/
37-
public ChatGptService(Config config) {
40+
public ChatGptService(Config config, Metrics metrics) {
3841
String apiKey = config.getOpenaiApiKey();
42+
this.metrics = metrics;
43+
3944
boolean keyIsDefaultDescription = apiKey.startsWith("<") && apiKey.endsWith(">");
4045
if (apiKey.isBlank() || keyIsDefaultDescription) {
4146
isDisabled = true;
@@ -111,6 +116,7 @@ private Optional<String> sendPrompt(String prompt, ChatGptModel chatModel) {
111116
.build();
112117

113118
Response chatGptResponse = openAIClient.responses().create(params);
119+
metrics.count("chatgpt-prompted");
114120

115121
String response = chatGptResponse.output()
116122
.stream()

application/src/main/java/org/togetherjava/tjbot/features/code/CodeMessageHandler.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import org.togetherjava.tjbot.features.MessageReceiverAdapter;
1818
import org.togetherjava.tjbot.features.UserInteractionType;
1919
import org.togetherjava.tjbot.features.UserInteractor;
20+
import org.togetherjava.tjbot.features.analytics.Metrics;
2021
import org.togetherjava.tjbot.features.componentids.ComponentIdGenerator;
2122
import org.togetherjava.tjbot.features.componentids.ComponentIdInteractor;
2223
import org.togetherjava.tjbot.features.jshell.JShellEval;
@@ -52,6 +53,7 @@ public final class CodeMessageHandler extends MessageReceiverAdapter implements
5253
static final Color AMBIENT_COLOR = Color.decode("#FDFD96");
5354

5455
private final ComponentIdInteractor componentIdInteractor;
56+
private final Metrics metrics;
5557
private final Map<String, CodeAction> labelToCodeAction;
5658

5759
/**
@@ -71,9 +73,12 @@ public final class CodeMessageHandler extends MessageReceiverAdapter implements
7173
* @param blacklist the feature blacklist, used to test if certain code actions should be
7274
* disabled
7375
* @param jshellEval used to execute java code and build visual result
76+
* @param metrics to track events
7477
*/
75-
public CodeMessageHandler(FeatureBlacklist<String> blacklist, JShellEval jshellEval) {
78+
public CodeMessageHandler(FeatureBlacklist<String> blacklist, JShellEval jshellEval,
79+
Metrics metrics) {
7680
componentIdInteractor = new ComponentIdInteractor(getInteractionType(), getName());
81+
this.metrics = metrics;
7782

7883
List<CodeAction> codeActions = blacklist
7984
.filterStream(Stream.of(new FormatCodeCommand(), new EvalCodeCommand(jshellEval)),
@@ -183,6 +188,7 @@ public void onButtonClick(ButtonInteractionEvent event, List<String> args) {
183188
CodeFence code = extractCodeOrFallback(originalMessage.get().getContentRaw());
184189

185190
// Apply the selected action
191+
metrics.count("code_action-" + codeAction.getLabel());
186192
return event.getHook()
187193
.editOriginalEmbeds(codeAction.apply(code))
188194
.setActionRow(createButtons(originalMessageId, codeAction));

application/src/main/java/org/togetherjava/tjbot/features/filesharing/FileSharingMessageListener.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import org.togetherjava.tjbot.features.MessageReceiverAdapter;
1919
import org.togetherjava.tjbot.features.UserInteractionType;
2020
import org.togetherjava.tjbot.features.UserInteractor;
21+
import org.togetherjava.tjbot.features.analytics.Metrics;
2122
import org.togetherjava.tjbot.features.componentids.ComponentIdGenerator;
2223
import org.togetherjava.tjbot.features.componentids.ComponentIdInteractor;
2324
import org.togetherjava.tjbot.features.utils.Guilds;
@@ -46,6 +47,7 @@ public final class FileSharingMessageListener extends MessageReceiverAdapter
4647
new ComponentIdInteractor(getInteractionType(), getName());
4748

4849
private final String githubApiKey;
50+
private final Metrics metrics;
4951
private final Set<String> extensionFilter = Set.of("txt", "java", "gradle", "xml", "kt", "json",
5052
"fxml", "css", "c", "h", "cpp", "py", "yml");
5153

@@ -56,11 +58,13 @@ public final class FileSharingMessageListener extends MessageReceiverAdapter
5658
* Creates a new instance.
5759
*
5860
* @param config used to get api key and channel names.
61+
* @param metrics to track events
5962
* @see org.togetherjava.tjbot.features.Features
6063
*/
61-
public FileSharingMessageListener(Config config) {
64+
public FileSharingMessageListener(Config config, Metrics metrics) {
6265
super(Pattern.compile(".*"));
6366
githubApiKey = config.getGitHubApiKey();
67+
this.metrics = metrics;
6468
isHelpForumName =
6569
Pattern.compile(config.getHelpSystem().getHelpForumPattern()).asMatchPredicate();
6670
isSoftModRole = Pattern.compile(config.getSoftModerationRolePattern()).asMatchPredicate();
@@ -112,6 +116,7 @@ public void onButtonClick(ButtonInteractionEvent event, List<String> args) {
112116
new GitHubBuilder().withOAuthToken(githubApiKey).build().getGist(gistId).delete();
113117
event.deferEdit().queue();
114118
event.getHook().deleteOriginal().queue();
119+
metrics.count("file_sharing-deleted");
115120
} catch (IOException e) {
116121
logger.warn("Failed to delete gist with id {}", gistId, e);
117122
}
@@ -190,6 +195,7 @@ private void sendResponse(MessageReceivedEvent event, String url, String gistId)
190195
componentIdInteractor.generateComponentId(message.getAuthor().getId(), gistId),
191196
"Delete");
192197

198+
metrics.count("file_sharing-uploaded");
193199
message.reply(messageContent).setActionRow(gist, delete).queue();
194200
}
195201

application/src/main/java/org/togetherjava/tjbot/features/github/GitHubReference.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
import org.togetherjava.tjbot.config.Config;
2323
import org.togetherjava.tjbot.features.MessageReceiverAdapter;
24+
import org.togetherjava.tjbot.features.analytics.Metrics;
2425

2526
import java.awt.Color;
2627
import java.io.FileNotFoundException;
@@ -67,6 +68,7 @@ public final class GitHubReference extends MessageReceiverAdapter {
6768
DateTimeFormatter.ofPattern("dd MMM, yyyy").withZone(ZoneOffset.UTC);
6869
private final Predicate<String> hasGithubIssueReferenceEnabled;
6970
private final Config config;
71+
private final Metrics metrics;
7072

7173
/**
7274
* The repositories that are searched when looking for an issue.
@@ -80,9 +82,11 @@ public final class GitHubReference extends MessageReceiverAdapter {
8082
* a predicate for matching allowed channels for feature and acquires repositories.
8183
*
8284
* @param config The Config to get allowed channel pattern for feature.
85+
* @param metrics to track events
8386
*/
84-
public GitHubReference(Config config) {
87+
public GitHubReference(Config config, Metrics metrics) {
8588
this.config = config;
89+
this.metrics = metrics;
8690
this.hasGithubIssueReferenceEnabled =
8791
Pattern.compile(config.getGitHubReferencingEnabledChannelPattern())
8892
.asMatchPredicate();
@@ -142,6 +146,7 @@ private void replyBatchEmbeds(List<MessageEmbed> embeds, Message message,
142146
? message.getChannel().asThreadChannel()
143147
: message.getChannel().asTextChannel();
144148

149+
metrics.count("gh_reference");
145150
for (List<MessageEmbed> messageEmbeds : partition) {
146151
if (isFirstBatch) {
147152
message.replyEmbeds(messageEmbeds).mentionRepliedUser(mentionRepliedUser).queue();

application/src/main/java/org/togetherjava/tjbot/features/help/AutoPruneHelperRoutine.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import org.togetherjava.tjbot.config.HelperPruneConfig;
1313
import org.togetherjava.tjbot.db.Database;
1414
import org.togetherjava.tjbot.features.Routine;
15+
import org.togetherjava.tjbot.features.analytics.Metrics;
1516
import org.togetherjava.tjbot.features.moderation.audit.ModAuditLogWriter;
1617

1718
import javax.annotation.Nullable;
@@ -45,6 +46,7 @@ public final class AutoPruneHelperRoutine implements Routine {
4546
private final HelpSystemHelper helper;
4647
private final ModAuditLogWriter modAuditLogWriter;
4748
private final Database database;
49+
private final Metrics metrics;
4850
private final List<String> allCategories;
4951
private final Predicate<String> selectYourRolesChannelNamePredicate;
5052

@@ -55,13 +57,15 @@ public final class AutoPruneHelperRoutine implements Routine {
5557
* @param helper the helper to use
5658
* @param modAuditLogWriter to inform mods when manual pruning becomes necessary
5759
* @param database to determine whether a user is inactive
60+
* @param metrics to track events
5861
*/
5962
public AutoPruneHelperRoutine(Config config, HelpSystemHelper helper,
60-
ModAuditLogWriter modAuditLogWriter, Database database) {
63+
ModAuditLogWriter modAuditLogWriter, Database database, Metrics metrics) {
6164
allCategories = config.getHelpSystem().getCategories();
6265
this.helper = helper;
6366
this.modAuditLogWriter = modAuditLogWriter;
6467
this.database = database;
68+
this.metrics = metrics;
6569

6670
HelperPruneConfig helperPruneConfig = config.getHelperPruneConfig();
6771
roleFullLimit = helperPruneConfig.roleFullLimit();
@@ -108,6 +112,7 @@ private void pruneRoleIfFull(List<Member> members, Role targetRole,
108112

109113
if (isRoleFull(withRole)) {
110114
logger.debug("Helper role {} is full, starting to prune.", targetRole.getName());
115+
metrics.count("autoprune_helper-" + targetRole.getName());
111116
pruneRole(targetRole, withRole, selectRoleChannel, when);
112117
}
113118
}

application/src/main/java/org/togetherjava/tjbot/features/help/GuildLeaveCloseThreadListener.java

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,24 @@
77

88
import org.togetherjava.tjbot.config.Config;
99
import org.togetherjava.tjbot.features.EventReceiver;
10+
import org.togetherjava.tjbot.features.analytics.Metrics;
1011

1112
/**
1213
* Remove all thread channels associated to a user when they leave the guild.
1314
*/
1415
public final class GuildLeaveCloseThreadListener extends ListenerAdapter implements EventReceiver {
1516
private final String helpForumPattern;
17+
private final Metrics metrics;
1618

1719
/**
1820
* Creates a new instance.
1921
*
2022
* @param config the config to get help forum channel pattern from
23+
* @param metrics to track events
2124
*/
22-
public GuildLeaveCloseThreadListener(Config config) {
25+
public GuildLeaveCloseThreadListener(Config config, Metrics metrics) {
2326
this.helpForumPattern = config.getHelpSystem().getHelpForumPattern();
27+
this.metrics = metrics;
2428
}
2529

2630
@Override
@@ -35,8 +39,11 @@ public void onGuildMemberRemove(GuildMemberRemoveEvent event) {
3539
.queue(threads -> threads.stream()
3640
.filter(thread -> thread.getOwnerIdLong() == event.getUser().getIdLong())
3741
.filter(thread -> thread.getParentChannel().getName().matches(helpForumPattern))
38-
.forEach(thread -> thread.sendMessageEmbeds(embed)
39-
.flatMap(_ -> thread.getManager().setArchived(true))
40-
.queue()));
42+
.forEach(thread -> {
43+
metrics.count("op_left_thread");
44+
thread.sendMessageEmbeds(embed)
45+
.flatMap(_ -> thread.getManager().setArchived(true))
46+
.queue();
47+
}));
4148
}
4249
}

application/src/main/java/org/togetherjava/tjbot/features/help/HelpSystemHelper.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,6 @@ private RestAction<Message> useChatGptFallbackMessage(ThreadChannel threadChanne
236236
}
237237

238238
void writeHelpThreadToDatabase(long authorId, ThreadChannel threadChannel) {
239-
240239
Instant createdAt = threadChannel.getTimeCreated().toInstant();
241240

242241
String appliedTags = threadChannel.getAppliedTags()

0 commit comments

Comments
 (0)