Skip to main content
Version: Next

PostHog Analytics

PostHog is an open-source product analytics platform that helps you understand user behavior. CommandKit provides a simple way to integrate PostHog into your Discord bot.

Setup

  1. First, install the analytics package:
npm install @commandkit/analytics
  1. Configure PostHog in your CommandKit config:
import { posthog } from '@commandkit/analytics/posthog';

export default defineConfig({
plugins: [
posthog({
posthogOptions: {
apiKey: 'YOUR_POSTHOG_API_KEY',
},
}),
],
});

Usage

Once configured, you can track anonymous events using the track function:

import { track } from 'commandkit/analytics';

// Track a custom event with anonymous data
await track({
name: 'command_executed',
data: {
commandName: 'ban',
// Track performance metrics
executionTime: 150, // ms
// Track anonymous usage patterns
timeOfDay: new Date().getHours(),
dayOfWeek: new Date().getDay(),
},
});

Identifying Anonymous Sessions

You can identify anonymous sessions in PostHog using the identify function:

import { useAnalytics } from 'commandkit/analytics';

const analytics = useAnalytics();
await analytics.identify({
// Use a hashed or anonymous identifier
distinctId: 'session_' + Math.random().toString(36).substring(7),
properties: {
// Track anonymous session properties
sessionStart: Date.now(),
environment: process.env.NODE_ENV,
version: '1.0.0',
},
});

Automatic Events

CommandKit automatically tracks the following anonymous events in PostHog:

  • command_execution: Command execution events
  • cache_hit: Cache hit events
  • cache_miss: Cache miss events
  • cache_revalidated: Cache revalidation events
  • feature_flag_metrics: Feature flag metrics
  • feature_flag_decision: Feature flag decision events

Best Practices

  1. Use consistent event names across your bot
  2. Only track anonymous, aggregated data
  3. Avoid storing personal information
  4. Use hashed identifiers when necessary
  5. Be transparent about what data you collect
  6. Respect user privacy and Discord's Terms of Service

Next Steps