---
title: Discord Analytics
---

Discord Analytics (hereinafter the "Application") is a TypeScript library package designed to integrate with Discord bots to provide automated analytics tracking and metrics collection. The Application pairs with the @nhcarrigan/logger tool to pipe Discord bot analytics and telemetry data.

## 1. User Documentation

This section is for those interacting with a live instance of the Application.

### Overview

Discord Analytics is distributed as an npm package and is designed to be integrated into Discord.js-based bots. The package is available at [@nhcarrigan/discord-analytics](https://www.npmjs.com/package/@nhcarrigan/discord-analytics).

### Features

The Application provides the following capabilities:

- **Automated Daily Metrics Collection**: Runs a CRON job at midnight (system time) to collect:
  - Total number of guilds (Discord servers) the bot is a member of
  - Total member count across all guilds
  - Approximate number of user installs for the application

- **Gateway Event Logging**: Allows logging of Discord gateway events with custom metadata for detailed analytics tracking

### Basic Usage

1. Install the package via npm:
   ```
   npm install @nhcarrigan/discord-analytics
   ```

2. Import and initialize the DiscordAnalytics class with your Discord client and logger instance:
   ```typescript
   import { DiscordAnalytics } from '@nhcarrigan/discord-analytics';

   const analytics = new DiscordAnalytics(client, logger);
   ```

3. Start the automated metrics collection:
   ```typescript
   analytics.startCron();
   ```

4. Log gateway events from your Discord event listeners:
   ```typescript
   client.on(Events.MessageCreate, async (message) => {
     await analytics.logGatewayEvent(Events.MessageCreate, {
       channelId: message.channelId
     });
   });
   ```

5. Stop the CRON job when needed:
   ```typescript
   analytics.stopCron();
   ```

## 2. Technical Documentation

This section is for those interested in running their own instance of the Application.

### Prerequisites

- Node.js (compatible with node-schedule 2.1.1)
- Discord.js v14.x or higher
- @nhcarrigan/logger v1.1.0-hotfix or higher

### Installation

The Application is installed as an npm package dependency:

```bash
npm install @nhcarrigan/discord-analytics
```

Or using pnpm:

```bash
pnpm add @nhcarrigan/discord-analytics
```

### Architecture

#### Core Components

The Application consists of a single main class located in `src/index.ts`:

**DiscordAnalytics Class** (src/index.ts:14-96)

The main class provides three public methods:

1. **`constructor(client: Client, logger: Logger)`** (src/index.ts:22-25)
   - Initializes the analytics instance with a Discord.js client and logger
   - Parameters:
     - `client`: The Discord.js client instance to monitor
     - `logger`: Instance of @nhcarrigan/logger for metric logging

2. **`startCron(): void`** (src/index.ts:33-65)
   - Starts a CRON job scheduled to run at midnight daily (0 0 * * *)
   - Collects and logs three metrics:
     - `user_installs`: Approximate count of user installs
     - `guilds`: Total number of guilds the bot is in
     - `members`: Total member count across all guilds
   - Includes error handling that logs failures via the logger

3. **`stopCron(): void`** (src/index.ts:70-76)
   - Cancels the running CRON job if active
   - Safely handles the case where no job is running

4. **`logGatewayEvent(event: Events, payload: Record<string, unknown>): Promise<void>`** (src/index.ts:85-95)
   - Logs Discord gateway events as metrics
   - Parameters:
     - `event`: The Discord.js event type (e.g., Events.MessageCreate)
     - `payload`: Custom metadata to attach to the metric

#### Dependencies

- **node-schedule** (2.1.1): Provides CRON job scheduling functionality
- **@nhcarrigan/logger** (peer dependency): Handles metric and error logging
- **discord.js** (peer dependency v14.x): Discord API wrapper

#### Build Process

The Application uses TypeScript and includes the following build scripts:

- `pnpm run lint`: Runs ESLint with zero warnings tolerance
- `pnpm run build`: Removes the `prod` directory and compiles TypeScript
- `pnpm prepublish`: Runs linting and build before publishing

The compiled output is located in the `prod` directory with `prod/index.js` as the main entry point.

### Configuration

The CRON schedule is hardcoded to run at midnight daily (system time). The schedule can be identified in the code at src/index.ts:37 as `"0 0 * * *"`.

### Data Collection

The Application collects the following metrics:

- **Guild Count**: Total number of Discord servers (src/index.ts:54)
- **Member Count**: Sum of all members across guilds (src/index.ts:55)
- **User Installs**: Approximate user installation count (src/index.ts:49-52)
- **Gateway Events**: Custom event tracking with metadata (src/index.ts:89-94)

All metrics are logged using the provided logger instance's `metric()` method.

### Error Handling

Errors during the CRON job execution are caught and logged via the logger's `error()` method (src/index.ts:57-62). The Application ensures errors are properly converted to Error instances before logging.

## 3. Legal Documentation

This section is for expansions to our legal policies specific to the Application.

### License

The Application is licensed under [Naomi's Public Licence](https://docs.nhcarrigan.com/#/license) (referenced as "global software licence").

Copyright is held by Naomi Carrigan.

### Privacy Considerations

The Application collects the following data from Discord:

- Guild (server) identifiers and counts
- Member counts (aggregate numbers, not individual user data)
- User installation counts (approximate numbers from Discord API)
- Gateway event data with optional custom metadata

Users integrating this Application should ensure their privacy policies adequately disclose the collection and logging of this telemetry data.

### Third-Party Services

The Application interacts with:

- Discord API (via discord.js)
- The configured logging service (@nhcarrigan/logger)

Data is transmitted to whatever backend service is configured with the logger instance.

## 4. Contributing Documentation

This section is for documentation related to contributing to the Application's codebase.

### Contributing Guidelines

Full contributing guidelines can be found at: https://docs.nhcarrigan.com/#/contributing

### Code of Conduct

Before interacting with the community, please review the Code of Conduct at: https://docs.nhcarrigan.com/#/coc

### Development Setup

1. Clone the repository
2. Install dependencies:
   ```bash
   pnpm install
   ```
3. Make your changes in the `src` directory
4. Run linting:
   ```bash
   pnpm run lint
   ```
5. Build the project:
   ```bash
   pnpm run build
   ```

### Code Style

The project uses:

- ESLint with @nhcarrigan/eslint-config (v5.2.0)
- TypeScript with @nhcarrigan/typescript-config (v4.0.0)
- Maximum warnings: 0 (strict mode)

### Pull Request Process

1. Create a Pull Request with your proposed changes
2. Ensure all linting passes
3. The maintainers will review as soon as possible

### Reporting Issues

If you have feedback or a bug report, please post in the #bug-reports forum channel on our Discord community.

### Contact

The maintainers may be contacted through:

- [Chat Server](https://chat.nhcarrigan.com)
- Email: contact@nhcarrigan.com

### Current Version

Version: 0.0.6

Recent changes can be viewed in the git commit history.
