npm package: @pioneer-platform/discord
Description: Discord integration for Pioneer platform - Redis to Discord bridge
Author: KeepKey
Latest version: 1.2.0

# @pioneer-platform/discord

Discord integration for Pioneer Platform - Redis to Discord event bridge.

## Overview

This module subscribes to Redis pub/sub channels and forwards events to Discord channels. It's designed to monitor server health, errors, and important events in real-time.

## Features

- 🔄 **Redis → Discord Bridge**: Subscribe to Redis channels, forward to Discord
- 🎨 **Rich Embeds**: Color-coded messages with severity levels
- 📊 **Event Formatting**: Structured event display with fields
- ⚡ **Real-time**: Instant notification delivery
- 🛡️ **Error Handling**: Robust error recovery

## Installation

```bash
bun install
bun run build
```

## Configuration

Required environment variables:

```bash
# Discord Bot Configuration
KEEPKEY_DISCORD_BOT_TOKEN=<your-bot-token>
KEEPKEY_BOT_NAME=pioneer
KEEPKEY_DISCORD_BOT_CHANNEL=keepkey-events

# Optional
DISCORD_ADMIN_USERID=<discord-user-id>

# Redis Connection
REDIS_CONNECTION=redis://localhost:6379
# or
REDIS_CONNECTION_PROD=rediss://...
```

## Usage

### Basic Usage

```typescript
import { createDiscordBridge } from '@pioneer-platform/discord';
import Redis from 'ioredis';

const redis = new Redis(process.env.REDIS_CONNECTION);

const bridge = await createDiscordBridge({
  botToken: process.env.KEEPKEY_DISCORD_BOT_TOKEN!,
  botName: 'pioneer',
  defaultChannel: 'keepkey-events',
  redisChannels: ['keepkey-events']
}, redis);

// Bridge is now listening and will forward events
```

### Publishing Events

```typescript
import { publisher } from '@pioneer-platform/default-redis';

// Publish an event
await publisher.publish('keepkey-events', JSON.stringify({
  type: 'server_startup',
  service: 'pioneer-server',
  level: 'success',
  message: 'Server started successfully',
  timestamp: new Date().toISOString(),
  details: {
    port: '9001',
    environment: 'production'
  }
}));
```

## Event Format

Events should follow this structure:

```typescript
interface DiscordEvent {
  type: string;                  // Event type (e.g., 'server_startup', 'error')
  service?: string;              // Service name (e.g., 'pioneer-server')
  level?: 'info' | 'success' | 'warning' | 'error' | 'critical';
  message: string;               // Main message
  timestamp?: string;            // ISO timestamp
  details?: Record<string, any>; // Additional fields
}
```

### Severity Levels

| Level | Color | Icon | Use Case |
|-------|-------|------|----------|
| `info` | Blue | ℹ️ | General information |
| `success` | Green | ✅ | Successful operations |
| `warning` | Orange | ⚠️ | Non-critical issues |
| `error` | Red | ❌ | Errors |
| `critical` | Dark Red | 🚨 | Critical failures |

## Testing

### Standalone Test

```bash
# Set environment variables in .env file
KEEPKEY_DISCORD_BOT_TOKEN=...
REDIS_CONNECTION_PROD=...

# Run the test
bun run src/test.ts
```

This will:
1. Connect to Discord
2. Subscribe to `keepkey-events` Redis channel
3. Publish 5 test events with different severity levels
4. Verify they appear in Discord

### Example Events

**Server Startup:**
```json
{
  "type": "server_startup",
  "service": "pioneer-server",
  "level": "success",
  "message": "Pioneer Server started successfully",
  "details": {
    "port": "9001",
    "environment": "production"
  }
}
```

**Error:**
```json
{
  "type": "database_error",
  "service": "pioneer-server",
  "level": "error",
  "message": "Failed to connect to MongoDB",
  "details": {
    "error": "Connection timeout",
    "retries": 3
  }
}
```

## Discord Bot Setup

1. **Create Discord Application**:
   - Go to https://discord.com/developers/applications
   - Click "New Application"
   - Name it "Pioneer Bot"

2. **Create Bot**:
   - Go to "Bot" tab
   - Click "Add Bot"
   - Copy the token → `KEEPKEY_DISCORD_BOT_TOKEN`

3. **Bot Permissions**:
   - Enable "Message Content Intent"
   - Required permissions:
     - Send Messages
     - Embed Links
     - Read Message History

4. **Invite Bot to Server**:
   - Go to "OAuth2" → "URL Generator"
   - Select scopes: `bot`
   - Select permissions: `2048` (Send Messages), `16384` (Embed Links)
   - Use generated URL to invite bot

5. **Create Channel**:
   - Create `#keepkey-events` channel in your Discord server
   - Bot will automatically find it by name

## Integration with Pioneer Server

See `../../services/pioneer-server/docs/DISCORD_INTEGRATION.md` for server integration details.

## API Reference

### DiscordBridge

```typescript
class DiscordBridge {
  constructor(config: DiscordConfig, redis: Redis)
  async start(): Promise<void>
  async stop(): Promise<void>
  isConnected(): boolean
  getClient(): Client
}
```

### createDiscordBridge

```typescript
function createDiscordBridge(
  config: DiscordConfig,
  redis: Redis
): Promise<DiscordBridge>
```

## Troubleshooting

### Bot doesn't connect
- Verify `KEEPKEY_DISCORD_BOT_TOKEN` is correct
- Check bot has "Message Content Intent" enabled
- Ensure bot is invited to server

### Messages don't appear in Discord
- Verify channel name matches `KEEPKEY_DISCORD_BOT_CHANNEL`
- Check bot has permissions in the channel
- Look for errors in logs

### Redis connection fails
- Verify `REDIS_CONNECTION_PROD` is correct
- Check Redis server is accessible
- Confirm Redis channels match configuration

## License

MIT