1414import discord
1515from core import Invocation , is_user_opted_out_of_data_processing
1616import datetime as dt
17+ import posthog
1718from somsiad import Somsiad , SomsiadMixin
1819
1920from discord .ext import commands
@@ -41,6 +42,21 @@ async def on_command(self, ctx: commands.Context):
4142 )
4243 session .add (invocation )
4344
45+ # Track command invocation in PostHog
46+ posthog .capture (
47+ distinct_id = str (ctx .author .id ),
48+ event = 'command_invoked' ,
49+ properties = {
50+ 'command' : ctx .command .qualified_name ,
51+ 'root_command' : ctx .command .root_parent or ctx .command .qualified_name ,
52+ 'prefix' : ctx .prefix ,
53+ 'server_id' : ctx .guild .id if ctx .guild else None ,
54+ 'server_name' : ctx .guild .name if ctx .guild else None ,
55+ 'channel_id' : ctx .channel .id ,
56+ 'is_dm' : ctx .guild is None ,
57+ }
58+ )
59+
4460 @commands .Cog .listener ()
4561 async def on_command_completion (self , ctx : commands .Context ):
4662 with data .session (commit = True ) as session :
@@ -50,6 +66,19 @@ async def on_command_completion(self, ctx: commands.Context):
5066 if invocation is not None :
5167 invocation .exited_at = dt .datetime .now ()
5268
69+ # Track command completion in PostHog
70+ duration_ms = (invocation .exited_at - invocation .created_at ).total_seconds () * 1000
71+ posthog .capture (
72+ distinct_id = str (ctx .author .id ),
73+ event = 'command_completed' ,
74+ properties = {
75+ 'command' : ctx .command .qualified_name ,
76+ 'root_command' : ctx .command .root_parent or ctx .command .qualified_name ,
77+ 'duration_ms' : duration_ms ,
78+ 'server_id' : ctx .guild .id if ctx .guild else None ,
79+ }
80+ )
81+
5382 @commands .Cog .listener ()
5483 async def on_command_error (self , ctx : commands .Context , error : commands .CommandError ):
5584 with data .session (commit = True ) as session :
@@ -58,9 +87,23 @@ async def on_command_error(self, ctx: commands.Context, error: commands.CommandE
5887 invocation = session .query (Invocation ).get (ctx .message .id )
5988 if invocation is not None :
6089 invocation .exited_at = dt .datetime .now ()
61- invocation . error = text_snippet (
90+ error_message = text_snippet (
6291 str (error ).replace ('Command raised an exception: ' , '' ), Invocation .MAX_ERROR_LENGTH
6392 )
93+ invocation .error = error_message
94+
95+ # Track command error in PostHog
96+ posthog .capture (
97+ distinct_id = str (ctx .author .id ),
98+ event = 'command_error' ,
99+ properties = {
100+ 'command' : ctx .command .qualified_name if ctx .command else 'unknown' ,
101+ 'root_command' : ctx .command .root_parent or ctx .command .qualified_name if ctx .command else 'unknown' ,
102+ 'error_type' : type (error ).__name__ ,
103+ 'error_message' : error_message ,
104+ 'server_id' : ctx .guild .id if ctx .guild else None ,
105+ }
106+ )
64107
65108
66109async def setup (bot : Somsiad ):
0 commit comments