> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch20-core-channel-implementations/20.3-discord-channel.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 20.3 Discord Channel

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~600k tokens, Output \~55k tokens (chapter total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

Discord is a communication platform centered on communities and servers (Guilds), widely used in gaming, technology, and education. OpenClaw's Discord channel supports multiple conversation scenarios including DMs (private messages), server channels, and threads.

***

## 20.3.1 discord.js / Carbon Library Usage

OpenClaw's Discord module is located in `src/discord/`, using discord.js ecosystem client libraries to connect to Discord Gateway (WebSocket API).

Core architecture:

```
Discord Gateway (WebSocket)
    │
    ▼
discord.js Client
    │
    ├── monitorDiscordProvider()     ← Message monitoring entry
    │     ├── registerDiscordListener()
    │     └── createDiscordMessageHandler()
    │
    ├── send.ts                     ← Message sending
    │     ├── send.messages.ts      ← Channel messages
    │     ├── send.guild.ts         ← Server messages
    │     └── send.outbound.ts      ← Outbound delivery
    │
    └── resolve-channels.ts         ← Channel resolution
```

Discord uses **Snowflake IDs** as unique identifiers for all entities (users, messages, channels, servers)—a 64-bit integer encoding timestamp, worker node ID, and sequence number.

> **Sidebar: Snowflake ID**
>
> Snowflake is a distributed unique ID generation algorithm invented by Twitter (now X). A Snowflake ID contains: 41-bit timestamp (\~69 years) + 10-bit machine ID + 12-bit sequence number. Discord adopted a similar scheme with its epoch starting January 1, 2015. This means Snowflake IDs are not only unique but also implicitly contain creation time information.

## 20.3.2 Guild Management and DM Policy

Discord's permission model revolves around **Guilds (servers)**. OpenClaw's Discord configuration supports fine-grained access control:

```typescript
// src/discord/monitor/allow-list.ts (conceptual)
export function isDiscordGroupAllowedByPolicy(params): boolean {
  // Check if Guild ID is in allowlist
  // Check if channel is allowed
  // Check sender role permissions
}

export function resolveDiscordCommandAuthorized(params): boolean {
  // Command-level permission check
}
```

DM (private message) policy controls who can send private messages to the Bot:

| Policy                 | Description                  |
| ---------------------- | ---------------------------- |
| `allowFrom: ["*"]`     | Allow everyone               |
| `allowFrom: ["12345"]` | Allow only specified user ID |
| Not configured         | Default deny all DMs         |

Guild message processing also involves **@mention detection**—in group channels, the Bot typically only responds when @mentioned:

```typescript
// src/channels/dock.ts (Discord section)
mentions: {
  stripPatterns: () => ["<@!?\\d+>"],   // Discord mention format
},
```

Discord's mention format is `<@user_id>` or `<@!user_id>`, different from Telegram's `@username` and WhatsApp's `@phone_number`.

## 20.3.3 Native Slash Commands and Text Commands

Discord supports **native Slash Commands** (Application Commands), where users see a command list and parameter hints when typing `/` in the chat box. OpenClaw registers these commands via `createDiscordNativeCommand`.

Similar to Telegram's custom commands, Discord's Slash commands must also be registered with the Discord API, but the implementation is more complex—Discord requires creating commands through the Application Commands API and supports advanced features like subcommands, option types, and autocomplete.

OpenClaw's Discord channel also supports regular text commands (starting with a configured prefix), providing a compatible entry point for users unfamiliar with Slash commands.

## 20.3.4 Lines Per Message Limit

Discord clients have special rendering behavior for long messages—messages exceeding a certain line count are collapsed. OpenClaw's Discord chunker (`src/discord/chunk.ts`) considers both **character count** and **line count** dimensions:

```typescript
// src/discord/chunk.ts (simplified)
const DEFAULT_MAX_CHARS = 2000;    // Discord message character limit
const DEFAULT_MAX_LINES = 17;      // Soft line count limit

export function chunkDiscordText(text, opts): string[] {
  const maxChars = opts.maxChars ?? DEFAULT_MAX_CHARS;
  const maxLines = opts.maxLines ?? DEFAULT_MAX_LINES;

  // Fast path
  if (body.length <= maxChars && countLines(body) <= maxLines) {
    return [body];
  }

  // Process line by line, tracking code block (fence) state
  let openFence: OpenFence | null = null;

  for (const line of lines) {
    // Detect code block open/close
    const fenceInfo = parseFenceLine(line);
    if (fenceInfo) {
      if (!openFence) openFence = fenceInfo;         // Open code block
      else if (fenceInfo.markerLen >= openFence.markerLen)
        openFence = null;                             // Close code block
    }

    // Chunk when exceeding character/line limits
    if ((wouldExceedChars || wouldExceedLines) && current.length > 0) {
      flush();    // Automatically close/reopen code blocks on flush
    }
    // ...
  }
}
```

The most elegant design of this chunker is **code block balancing**: when the chunk point falls inside a code block, it inserts a closing marker (` ``` `) at the end of the current chunk and reopens the code block at the start of the next chunk:

````
Original message:
  ```python
  def hello():
      print("hello")
  def world():      ← Chunk point here
      print("world")
````

After chunking: Chunk 1: `python def hello(): print("hello")` ← Auto-closed

Chunk 2: `python ← Auto-reopened def world(): print("world")`

```

There's also a `rebalanceReasoningItalics` function that specifically handles italic marker balancing for reasoning text—when reasoning text (italic wrapped in `_`) is chunked, it ensures each chunk renders correctly independently.

---

## Section Summary

1. Discord channel uses discord.js to connect to Gateway WebSocket, supporting multiple conversation scenarios including DMs, channels, and threads.
2. **Guild permission model** supports fine-grained access control at server, channel, and user levels.
3. Supports both **native Slash commands** and **text prefix commands** interaction methods.
4. Discord chunker considers both **character count** (2000) and **line count** (17) dimensions, and can automatically balance code blocks and italic markers when chunking.
```
