# Chat WebSocket API

> WebSocket API documentation for the Aphrodite Chat Service using Socket.io.

**WebSocket URL:** `wss://ws.aphrodite.example.com` **Port:** 5000 **Protocol:**
Socket.io v4

---

## Table of Contents

1. [Connection](#connection)
2. [Room Management](#room-management)
3. [Messaging](#messaging)
4. [Direct Messages](#direct-messages)
5. [Typing Indicators](#typing-indicators)
6. [Reactions](#reactions)
7. [Commands](#commands)
8. [Recovery](#recovery)

---

## Connection

### Establishing Connection

```typescript
import { io } from 'socket.io-client';

const socket = io('wss://ws.aphrodite.example.com', {
  auth: {
    token: '<access_token>',
  },
  transports: ['websocket'],
  reconnection: true,
  reconnectionAttempts: 5,
  reconnectionDelay: 1000,
});
```

### Connection Events

#### `connect`

Emitted when connection is established.

```typescript
socket.on('connect', () => {
  console.log('Connected:', socket.id);
});
```

#### `connect_error`

Emitted when connection fails.

```typescript
socket.on('connect_error', (error) => {
  console.error('Connection error:', error.message);
  // error.data contains additional info
  // { code: 'AUTH_FAILED', message: 'Invalid token' }
});
```

#### `disconnect`

Emitted when disconnected.

```typescript
socket.on('disconnect', (reason) => {
  console.log('Disconnected:', reason);
  // reason: 'io server disconnect' | 'io client disconnect' | 'ping timeout' | 'transport close' | 'transport error'
});
```

### Authentication Errors

| Code              | Description                      |
| ----------------- | -------------------------------- |
| `AUTH_FAILED`     | Invalid or expired token         |
| `AUTH_REQUIRED`   | No token provided                |
| `USER_BANNED`     | User is banned from the platform |
| `SESSION_EXPIRED` | Session has expired              |

---

## Room Management

### Join Room

Join a chat room (typically a stream's chat).

**Client Emit:** `room:join`

```typescript
socket.emit('room:join', {
  roomId: 'room_str_abc123',
  streamId: 'str_abc123', // optional, for stream rooms
});
```

**Server Response:** `room:joined`

```typescript
socket.on('room:joined', (data) => {
  console.log('Joined room:', data);
});
```

**Response Payload:**

```json
{
  "roomId": "room_str_abc123",
  "userId": "usr_abc123",
  "viewerCount": 1250,
  "settings": {
    "slowMode": { "enabled": true, "interval": 30 },
    "subscriberOnly": false,
    "followerOnly": { "enabled": false },
    "emoteOnly": false
  },
  "recentMessages": [
    {
      "id": "msg_1",
      "userId": "usr_xyz789",
      "username": "viewer1",
      "displayName": "Viewer One",
      "content": "Hello everyone!",
      "type": "text",
      "timestamp": "2026-01-18T20:00:00.000Z",
      "badges": ["subscriber"],
      "color": "#FF5733"
    }
  ],
  "emotes": [...],
  "badges": [...]
}
```

**Error Events:** `room:join:error`

```typescript
socket.on('room:join:error', (error) => {
  // { code: 'ROOM_NOT_FOUND', message: 'Room does not exist' }
  // { code: 'ACCESS_DENIED', message: 'Room is subscriber-only' }
  // { code: 'USER_BANNED', message: 'You are banned from this room' }
});
```

---

### Leave Room

**Client Emit:** `room:leave`

```typescript
socket.emit('room:leave', {
  roomId: 'room_str_abc123',
});
```

**Server Response:** `room:left`

```typescript
socket.on('room:left', (data) => {
  // { roomId: 'room_str_abc123' }
});
```

---

### Room Events

#### `room:viewer:count`

Viewer count update.

```typescript
socket.on('room:viewer:count', (data) => {
  // { roomId: 'room_str_abc123', count: 1255 }
});
```

#### `room:settings:updated`

Room settings changed by creator/moderator.

```typescript
socket.on('room:settings:updated', (data) => {
  // { roomId: 'room_str_abc123', settings: { slowMode: { enabled: true, interval: 60 } } }
});
```

---

## Messaging

### Send Message

**Client Emit:** `message:send`

```typescript
socket.emit(
  'message:send',
  {
    roomId: 'room_str_abc123',
    content: 'Hello everyone!',
    replyTo: null, // optional message ID to reply to
  },
  (response) => {
    if (response.success) {
      console.log('Message sent:', response.messageId);
    } else {
      console.error('Send failed:', response.error);
    }
  }
);
```

**Acknowledgment Response:**

```json
{
  "success": true,
  "messageId": "msg_abc123",
  "timestamp": "2026-01-18T20:01:00.000Z"
}
```

**Error Response:**

```json
{
  "success": false,
  "error": {
    "code": "RATE_LIMITED",
    "message": "Slow mode is enabled. Please wait 25 seconds.",
    "retryAfter": 25
  }
}
```

**Error Codes:**

| Code              | Description                      |
| ----------------- | -------------------------------- |
| `RATE_LIMITED`    | Slow mode or rate limit exceeded |
| `CONTENT_BLOCKED` | Message blocked by filter        |
| `USER_MUTED`      | User is muted/timed out          |
| `ROOM_CLOSED`     | Room is closed for messages      |
| `NOT_SUBSCRIBER`  | Subscriber-only mode enabled     |
| `NOT_FOLLOWER`    | Follower-only mode enabled       |

---

### Receive Message

**Server Event:** `message:broadcast`

```typescript
socket.on('message:broadcast', (message) => {
  console.log('New message:', message);
});
```

**Message Payload:**

```json
{
  "id": "msg_abc123",
  "roomId": "room_str_abc123",
  "userId": "usr_xyz789",
  "username": "viewer1",
  "displayName": "Viewer One",
  "avatarUrl": "https://cdn.aphrodite.example.com/avatars/usr_xyz789.jpg",
  "content": "Hello everyone!",
  "type": "text",
  "timestamp": "2026-01-18T20:01:00.000Z",
  "badges": [
    { "type": "subscriber", "tier": 2, "months": 6 },
    { "type": "vip" }
  ],
  "color": "#FF5733",
  "emotes": [{ "id": "emote_1", "name": "hello", "positions": [[0, 4]] }],
  "replyTo": null,
  "mentions": []
}
```

---

### Message Types

| Type        | Description                    |
| ----------- | ------------------------------ |
| `text`      | Regular text message           |
| `tip`       | Tip notification message       |
| `system`    | System announcement            |
| `action`    | Action message (/me)           |
| `highlight` | Highlighted/pinned message     |
| `raid`      | Raid notification              |
| `sub`       | Subscription notification      |
| `gift_sub`  | Gift subscription notification |

### Tip Message

```json
{
  "id": "msg_tip123",
  "type": "tip",
  "userId": "usr_tipper",
  "username": "generoustipper",
  "displayName": "Generous Tipper",
  "content": "Great stream! Keep it up!",
  "timestamp": "2026-01-18T20:05:00.000Z",
  "tip": {
    "amount": 100,
    "currency": "tokens"
  },
  "badges": ["top_tipper"]
}
```

### System Message

```json
{
  "id": "msg_sys123",
  "type": "system",
  "content": "Welcome to the stream! Please follow the chat rules.",
  "timestamp": "2026-01-18T20:00:00.000Z",
  "system": {
    "subtype": "welcome",
    "level": "info"
  }
}
```

---

### Delete Message

**Server Event:** `message:deleted`

```typescript
socket.on('message:deleted', (data) => {
  // { messageId: 'msg_abc123', roomId: 'room_str_abc123', deletedBy: 'usr_mod1' }
});
```

---

### Clear Chat

**Server Event:** `room:chat:cleared`

```typescript
socket.on('room:chat:cleared', (data) => {
  // { roomId: 'room_str_abc123', clearedBy: 'usr_creator' }
});
```

---

## Direct Messages

### Create Conversation

**Client Emit:** `dm:create-conversation`

```typescript
socket.emit(
  'dm:create-conversation',
  {
    participantId: 'usr_xyz789',
  },
  (response) => {
    console.log('Conversation:', response.conversationId);
  }
);
```

**Response:**

```json
{
  "success": true,
  "conversationId": "conv_abc123",
  "participant": {
    "id": "usr_xyz789",
    "username": "janedoe",
    "displayName": "Jane Doe",
    "avatarUrl": "..."
  },
  "createdAt": "2026-01-18T12:00:00.000Z"
}
```

---

### Send Direct Message

**Client Emit:** `dm:send`

```typescript
socket.emit(
  'dm:send',
  {
    conversationId: 'conv_abc123',
    content: 'Hey! Love your content!',
    attachments: [], // optional
  },
  (response) => {
    console.log('DM sent:', response.messageId);
  }
);
```

---

### Receive Direct Message

**Server Event:** `dm:message-received`

```typescript
socket.on('dm:message-received', (message) => {
  console.log('New DM:', message);
});
```

**Payload:**

```json
{
  "id": "dm_msg_123",
  "conversationId": "conv_abc123",
  "senderId": "usr_xyz789",
  "sender": {
    "username": "janedoe",
    "displayName": "Jane Doe",
    "avatarUrl": "..."
  },
  "content": "Thanks! Glad you enjoy it!",
  "timestamp": "2026-01-18T12:01:00.000Z",
  "read": false
}
```

---

### Get Conversations

**Client Emit:** `dm:get-conversations`

```typescript
socket.emit(
  'dm:get-conversations',
  {
    cursor: null,
    limit: 20,
  },
  (response) => {
    console.log('Conversations:', response.conversations);
  }
);
```

**Response:**

```json
{
  "success": true,
  "conversations": [
    {
      "id": "conv_abc123",
      "participant": {
        "id": "usr_xyz789",
        "username": "janedoe",
        "displayName": "Jane Doe",
        "avatarUrl": "...",
        "isOnline": true
      },
      "lastMessage": {
        "content": "Thanks! Glad you enjoy it!",
        "timestamp": "2026-01-18T12:01:00.000Z",
        "isFromMe": false
      },
      "unreadCount": 1,
      "updatedAt": "2026-01-18T12:01:00.000Z"
    }
  ],
  "pagination": {
    "cursor": "next_cursor",
    "hasMore": true
  }
}
```

---

### Get Messages

**Client Emit:** `dm:get-messages`

```typescript
socket.emit(
  'dm:get-messages',
  {
    conversationId: 'conv_abc123',
    cursor: null,
    limit: 50,
  },
  (response) => {
    console.log('Messages:', response.messages);
  }
);
```

---

### Mark as Read

**Client Emit:** `dm:mark-read`

```typescript
socket.emit('dm:mark-read', {
  conversationId: 'conv_abc123',
  messageId: 'dm_msg_123', // mark up to this message as read
});
```

**Server Event:** `dm:marked-read`

```typescript
socket.on('dm:marked-read', (data) => {
  // { conversationId: 'conv_abc123', readAt: '...' }
});
```

---

### Block/Unblock

**Client Emit:** `dm:block`

```typescript
socket.emit('dm:block', { conversationId: 'conv_abc123' }, (response) => {
  // { success: true }
});
```

**Client Emit:** `dm:unblock`

```typescript
socket.emit('dm:unblock', { conversationId: 'conv_abc123' }, (response) => {
  // { success: true }
});
```

---

## Typing Indicators

### Start Typing

**Client Emit:** `typing:start`

```typescript
socket.emit('typing:start', {
  roomId: 'room_str_abc123', // or conversationId for DMs
});
```

### Stop Typing

**Client Emit:** `typing:stop`

```typescript
socket.emit('typing:stop', {
  roomId: 'room_str_abc123',
});
```

### Typing Indicator Event

**Server Event:** `typing:indicator`

```typescript
socket.on('typing:indicator', (data) => {
  // {
  //   roomId: 'room_str_abc123',
  //   userId: 'usr_xyz789',
  //   username: 'viewer1',
  //   isTyping: true
  // }
});
```

---

## Reactions

### Send Emoji Reaction

**Client Emit:** `emoji:send`

```typescript
socket.emit('emoji:send', {
  roomId: 'room_str_abc123',
  emoji: '❤️',
});
```

### Receive Emoji Reactions

**Server Event:** `emoji:broadcast`

```typescript
socket.on('emoji:broadcast', (data) => {
  // {
  //   roomId: 'room_str_abc123',
  //   userId: 'usr_xyz789',
  //   emoji: '❤️',
  //   timestamp: '2026-01-18T20:05:00.000Z'
  // }
});
```

### Emoji Burst

**Server Event:** `emoji:burst`

Aggregated emoji reactions for performance.

```typescript
socket.on('emoji:burst', (data) => {
  // {
  //   roomId: 'room_str_abc123',
  //   emojis: [
  //     { emoji: '❤️', count: 15 },
  //     { emoji: '🔥', count: 8 }
  //   ],
  //   timestamp: '2026-01-18T20:05:00.000Z'
  // }
});
```

---

## Commands

### Execute Command

**Client Emit:** `command:execute`

```typescript
socket.emit(
  'command:execute',
  {
    roomId: 'room_str_abc123',
    command: 'timeout',
    args: ['troublemaker', '600', 'Spam'],
  },
  (response) => {
    console.log('Command result:', response);
  }
);
```

**Server Event:** `command:response`

```typescript
socket.on('command:response', (data) => {
  // {
  //   command: 'timeout',
  //   success: true,
  //   message: 'User troublemaker has been timed out for 10 minutes.'
  // }
});
```

### Available Commands

| Command           | Args                         | Description                  | Permissions |
| ----------------- | ---------------------------- | ---------------------------- | ----------- |
| `/timeout`        | `<user> <duration> [reason]` | Timeout user                 | Moderator   |
| `/ban`            | `<user> [reason]`            | Ban user from room           | Moderator   |
| `/unban`          | `<user>`                     | Unban user                   | Moderator   |
| `/mod`            | `<user>`                     | Make user a moderator        | Creator     |
| `/unmod`          | `<user>`                     | Remove moderator status      | Creator     |
| `/vip`            | `<user>`                     | Give VIP status              | Creator     |
| `/unvip`          | `<user>`                     | Remove VIP status            | Creator     |
| `/clear`          | -                            | Clear chat                   | Moderator   |
| `/slow`           | `<seconds>`                  | Enable slow mode             | Moderator   |
| `/slowoff`        | -                            | Disable slow mode            | Moderator   |
| `/subscribers`    | -                            | Enable subscriber-only mode  | Moderator   |
| `/subscribersoff` | -                            | Disable subscriber-only mode | Moderator   |
| `/me`             | `<message>`                  | Action message               | Everyone    |
| `/announce`       | `<message>`                  | Announcement (highlighted)   | Moderator   |

---

## Recovery

### Request Message Recovery

Request missed messages after reconnection.

**Client Emit:** `recovery:request`

```typescript
socket.emit(
  'recovery:request',
  {
    roomId: 'room_str_abc123',
    lastMessageId: 'msg_last123',
    lastTimestamp: '2026-01-18T20:00:00.000Z',
  },
  (response) => {
    console.log('Recovered messages:', response.messages);
  }
);
```

**Server Response:** `recovery:messages`

```typescript
socket.on('recovery:messages', (data) => {
  // {
  //   roomId: 'room_str_abc123',
  //   messages: [...],
  //   hasMore: false
  // }
});
```

---

## Moderation Events

### User Timed Out

**Server Event:** `moderation:timeout`

```typescript
socket.on('moderation:timeout', (data) => {
  // {
  //   roomId: 'room_str_abc123',
  //   userId: 'usr_trouble',
  //   username: 'troublemaker',
  //   duration: 600,
  //   reason: 'Spam',
  //   moderator: 'usr_mod1',
  //   expiresAt: '2026-01-18T20:15:00.000Z'
  // }
});
```

### User Banned

**Server Event:** `moderation:ban`

```typescript
socket.on('moderation:ban', (data) => {
  // {
  //   roomId: 'room_str_abc123',
  //   userId: 'usr_trouble',
  //   username: 'troublemaker',
  //   permanent: true,
  //   reason: 'Harassment',
  //   moderator: 'usr_mod1'
  // }
});
```

### User Unbanned

**Server Event:** `moderation:unban`

```typescript
socket.on('moderation:unban', (data) => {
  // {
  //   roomId: 'room_str_abc123',
  //   userId: 'usr_trouble',
  //   username: 'troublemaker',
  //   moderator: 'usr_mod1'
  // }
});
```

---

## Data Types

### Message Object

```typescript
interface ChatMessage {
  id: string;
  roomId: string;
  userId: string;
  username: string;
  displayName: string;
  avatarUrl?: string;
  content: string;
  type:
    | 'text'
    | 'tip'
    | 'system'
    | 'action'
    | 'highlight'
    | 'raid'
    | 'sub'
    | 'gift_sub';
  timestamp: string;
  badges: Badge[];
  color?: string;
  emotes?: Emote[];
  replyTo?: string;
  mentions?: string[];
  tip?: TipData;
  system?: SystemData;
}
```

### Badge Object

```typescript
interface Badge {
  type:
    | 'subscriber'
    | 'vip'
    | 'moderator'
    | 'creator'
    | 'verified'
    | 'top_tipper';
  tier?: number;
  months?: number;
  imageUrl?: string;
}
```

---

## Document History

| Date       | Version | Changes                         |
| ---------- | ------- | ------------------------------- |
| 2026-01-18 | 1.0.0   | Initial Chat WebSocket API docs |
