> 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.4-slack-channel.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 20.4 Slack Channel (Bolt)

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

***

Slack is the benchmark for enterprise collaboration platforms and one of the "heaviest" channels supported by OpenClaw—its permission model, event system, and interaction components are far more complex than other instant messaging platforms. OpenClaw's Slack module is located in `src/slack/` with 65 files, making it the largest implementation among all channels. This section will deeply analyze Slack channel's core implementation from three dimensions: Bolt SDK integration, dual Token architecture, and thread session management.

***

## 20.4.1 Slack Bolt SDK Integration

### Bolt Framework Introduction

> **Sidebar: Slack Bolt**
>
> Slack Bolt is the official application development framework provided by Slack (available in JavaScript, Python, and Java versions). It encapsulates the low-level communication details of Slack Events API, Web API, and Socket Mode, providing high-level APIs for event listening, command handling, and interaction responses. Bolt for Slack application development is similar to Express for HTTP service development—it's not mandatory, but greatly simplifies boilerplate code.

OpenClaw uses `@slack/bolt` (JavaScript version) as the core dependency for Slack integration. All Slack message sending/receiving, event handling, and slash commands are built on top of Bolt.

### monitorSlackProvider: Startup Entry

The entry function for the Slack channel is `monitorSlackProvider()`, located in `src/slack/monitor/provider.ts`, serving as the orchestration center for the entire Slack monitoring loop:

```typescript
// src/slack/monitor/provider.ts (simplified)
import SlackBolt from "@slack/bolt";

// Handle CJS/ESM compatibility: Bun can directly named import, Node ESM cannot
const slackBolt = slackBoltModule.App
  ? slackBoltModule : slackBoltModule.default ?? slackBoltModule;
const { App, HTTPReceiver } = slackBolt;

export async function monitorSlackProvider(opts: MonitorSlackOpts = {}) {
  const cfg = opts.config ?? loadConfig();
  const account = resolveSlackAccount({ cfg, accountId: opts.accountId });
  
  // 1. Parse configuration: Token, session scope, DM policy, group policy...
  const botToken = resolveSlackBotToken(opts.botToken ?? account.botToken);
  const appToken = resolveSlackAppToken(opts.appToken ?? account.appToken);
  const sessionScope: SessionScope = sessionCfg?.scope ?? "per-sender";
  
  // 2. Create Bolt App based on mode
  const app = new App(
    slackMode === "socket"
      ? { token: botToken, appToken, socketMode: true, clientOptions }
      : { token: botToken, receiver: receiver ?? undefined, clientOptions }
  );
  
  // 3. Authentication
  const auth = await app.client.auth.test({ token: botToken });
  botUserId = auth.user_id ?? "";
  teamId = auth.team_id ?? "";
  
  // 4. Build context → Register events → Register slash commands → Start
  const ctx = createSlackMonitorContext({ ... });
  const handleSlackMessage = createSlackMessageHandler({ ctx, account });
  registerSlackMonitorEvents({ ctx, account, handleSlackMessage });
  registerSlackMonitorSlashCommands({ ctx, account });
  
  // 5. Start connection
  if (slackMode === "socket") {
    await app.start();
    runtime.log?.("slack socket mode connected");
  }
}
```

The entire startup process can be summarized as follows:

| Step | Content                                        | Key Function                          |
| ---- | ---------------------------------------------- | ------------------------------------- |
| 1    | Load and merge configuration                   | `resolveSlackAccount()`               |
| 2    | Create Bolt App instance                       | `new App()`                           |
| 3    | Call `auth.test` to get Bot identity           | `app.client.auth.test()`              |
| 4    | Build monitoring context                       | `createSlackMonitorContext()`         |
| 5    | Create message handler                         | `createSlackMessageHandler()`         |
| 6    | Register all event listeners                   | `registerSlackMonitorEvents()`        |
| 7    | Register slash commands                        | `registerSlackMonitorSlashCommands()` |
| 8    | Asynchronously resolve channel/user allowlists | `resolveSlackChannelAllowlist()`      |
| 9    | Start Socket Mode / HTTP listener              | `app.start()`                         |

### Two Connection Modes

Slack provides two ways to receive events, both supported by OpenClaw:

**Socket Mode**: Receives events through WebSocket long connection. Suitable for development environments and deployments without public IP. Requires App Token.

**HTTP Mode**: Slack pushes events to a specified URL. Suitable for production, requires publicly accessible HTTPS endpoint and Signing Secret.

```typescript
// Choose receiver based on configuration
const receiver = slackMode === "http"
  ? new HTTPReceiver({
      signingSecret: signingSecret ?? "",
      endpoints: slackWebhookPath,
    })
  : null;
```

In HTTP mode, OpenClaw also registers an HTTP Handler to the Gateway server's routing system:

```typescript
if (slackMode === "http" && slackHttpHandler) {
  unregisterHttpHandler = registerSlackHttpHandler({
    path: slackWebhookPath,
    handler: slackHttpHandler,
    log: runtime.log,
    accountId: account.accountId,
  });
}
```

### Event Registration Architecture

Event registration is decomposed into five independent modules, each handling one class of Slack events:

```typescript
// src/slack/monitor/events.ts
export function registerSlackMonitorEvents(params) {
  registerSlackMessageEvents({ ctx, handleSlackMessage });  // message + app_mention
  registerSlackReactionEvents({ ctx });                      // reaction_added/removed
  registerSlackMemberEvents({ ctx });                        // member_joined/left_channel
  registerSlackChannelEvents({ ctx });                       // channel_created/renamed
  registerSlackPinEvents({ ctx });                           // pin_added/removed
}
```

The most critical is `registerSlackMessageEvents`, which listens to both `message` and `app_mention` events:

```typescript
// src/slack/monitor/events/messages.ts
ctx.app.event("message", async ({ event, body }) => {
  if (ctx.shouldDropMismatchedSlackEvent(body)) return;
  const message = event as SlackMessageEvent;
  
  // Handle subtypes: edits, deletes, thread broadcasts, etc.
  if (message.subtype === "message_changed") { /* system event */ }
  if (message.subtype === "message_deleted") { /* system event */ }
  if (message.subtype === "thread_broadcast") { /* system event */ }
  
  // Regular messages go to unified handler
  await handleSlackMessage(message, { source: "message" });
});

ctx.app.event("app_mention", async ({ event, body }) => {
  // @mention event directly marked as wasMentioned: true
  await handleSlackMessage(mention as SlackMessageEvent, {
    source: "app_mention",
    wasMentioned: true,
  });
});
```

> **Sidebar: Slack Message Events**
>
> In Slack, the `message` event covers almost all message-related scenarios (new messages, edits, deletes, file sharing, etc.), distinguished by the `subtype` field. The `app_mention` is a separate event, triggered only when a user @mentions your Bot. OpenClaw listens to both, ensuring no message requiring response is missed.

### Multi-Event Deduplication

Since `message` and `app_mention` may trigger simultaneously for the same message, OpenClaw uses a deduplication cache to avoid duplicate processing:

```typescript
// markMessageSeen in SlackMonitorContext
const seenMessages = createDedupeCache({ ttlMs: 60_000, maxSize: 500 });

const markMessageSeen = (channelId: string | undefined, ts?: string) => {
  if (!channelId || !ts) return false;
  return seenMessages.check(`${channelId}:${ts}`);
};
```

`check()` returns `true` if the key already exists (indicating seen), otherwise writes and returns `false`. A 60-second TTL is sufficient to cover Slack event delays.

### api\_app\_id Validation

When multiple Slack applications share the same receiver, OpenClaw filters non-self events via `api_app_id` and `team_id`:

```typescript
const shouldDropMismatchedSlackEvent = (body: unknown) => {
  const raw = body as { api_app_id?: unknown; team_id?: unknown };
  if (params.apiAppId && incomingApiAppId && incomingApiAppId !== params.apiAppId) {
    return true;  // Not this App's event
  }
  if (params.teamId && incomingTeamId && incomingTeamId !== params.teamId) {
    return true;  // Not this Team's event
  }
  return false;
};
```

***

## 20.4.2 App Token + Bot Token Dual Token Architecture

Slack application authentication uses two independent Token systems. Understanding their differences is prerequisite for correctly configuring the Slack channel.

### Token Type Comparison

| Token Type | Prefix  | Purpose                                              | Example Scenario                                    |
| ---------- | ------- | ---------------------------------------------------- | --------------------------------------------------- |
| Bot Token  | `xoxb-` | Call Slack Web API (send messages, query info, etc.) | `chat.postMessage`, `users.info`                    |
| App Token  | `xapp-` | Establish Socket Mode WebSocket connection           | Receive events in real-time, replace public Webhook |
| User Token | `xoxp-` | Call API as user (optional)                          | Resolve channel names, get user lists               |

OpenClaw requires Bot Token to be provided; App Token is required in Socket Mode but not in HTTP Mode.

### Token Resolution Chain

Token sources follow a priority chain: function parameters > configuration file > environment variables.

```typescript
// src/slack/accounts.ts
export function resolveSlackAccount(params) {
  const allowEnv = accountId === DEFAULT_ACCOUNT_ID;
  const envBot = allowEnv ? resolveSlackBotToken(process.env.SLACK_BOT_TOKEN) : undefined;
  const envApp = allowEnv ? resolveSlackAppToken(process.env.SLACK_APP_TOKEN) : undefined;
  const configBot = resolveSlackBotToken(merged.botToken);
  const configApp = resolveSlackAppToken(merged.appToken);
  
  // Configuration takes precedence over environment variables
  const botToken = configBot ?? envBot;
  const appToken = configApp ?? envApp;
  
  // Record Token source for debugging
  const botTokenSource: SlackTokenSource = configBot ? "config" : envBot ? "env" : "none";
}
```

> **Design Highlight**: The `botTokenSource` field records Token source (`"config"` / `"env"` / `"none"`), enabling precise error messages on send failure (e.g., "set `channels.slack.accounts.default.botToken` or environment variable `SLACK_BOT_TOKEN`").

### Token Consistency Validation

App Token encodes `api_app_id`. OpenClaw parses this ID from the App Token at startup and compares it with the `api_app_id` returned by `auth.test`:

```typescript
function parseApiAppIdFromAppToken(raw?: string) {
  const match = /^xapp-\d-([a-z0-9]+)-/i.exec(token);
  return match?.[1]?.toUpperCase();
}

// Validation at startup
if (apiAppId && expectedApiAppIdFromAppToken && apiAppId !== expectedApiAppIdFromAppToken) {
  runtime.error?.(
    `slack token mismatch: bot token api_app_id=${apiAppId} ` +
    `but app token looks like api_app_id=${expectedApiAppIdFromAppToken}`
  );
}
```

This validation can catch the configuration error "Bot Token and App Token belong to different Slack Apps" early.

### Multi-Account Support

Like other channels, Slack also supports multi-account configuration. `resolveSlackAccount()` merges global Slack configuration with account-specific configuration:

```typescript
function mergeSlackAccountConfig(cfg: OpenClawConfig, accountId: string): SlackAccountConfig {
  const { accounts: _ignored, ...base } = cfg.channels?.slack ?? {};
  const account = resolveAccountConfig(cfg, accountId) ?? {};
  return { ...base, ...account };  // Account-level config overrides global
}
```

Configuration structure example:

```yaml
channels:
  slack:
    groupPolicy: "open"           # Global default
    botToken: "xoxb-..."          # Global Bot Token
    accounts:
      customer-support:
        botToken: "xoxb-support-..."  # Override Bot Token
        groupPolicy: "allowlist"      # Override group policy
        channels:
          C0123456789:
            requireMention: true
```

### WebClient Configuration

All Slack API calls go through `@slack/web-api`'s `WebClient`. OpenClaw configures reasonable retry strategies:

```typescript
// src/slack/client.ts
export const SLACK_DEFAULT_RETRY_OPTIONS: RetryOptions = {
  retries: 2,        // Maximum 2 retries
  factor: 2,         // Exponential backoff factor
  minTimeout: 500,   // Minimum 500ms
  maxTimeout: 3000,  // Maximum 3 seconds
  randomize: true,   // Add random jitter
};

export function createSlackWebClient(token: string, options = {}) {
  return new WebClient(token, resolveSlackWebClientOptions(options));
}
```

***

## 20.4.3 Thread Session Management

Slack's Thread is its most distinctive interaction mode—sub-conversations can be opened under a message in a channel. OpenClaw's thread handling is the most elegant part of the entire Slack channel.

### Slack Thread Model

> **Sidebar: Slack Thread Model**
>
> In Slack, every message has a `ts` (timestamp ID, like `1716000000.123456`). If a message is a thread reply, it carries a `thread_ts` field pointing to the thread's root message. Therefore, `thread_ts` is actually the thread's unique identifier. Additionally, if a message replies to a thread started by the Bot, it also carries `parent_user_id` pointing to the root message's author.

### Thread Context Resolution

`resolveSlackThreadContext()` is the core function for thread handling, extracting all thread-related information from Slack messages:

```typescript
// src/slack/threading.ts
export function resolveSlackThreadContext(params: {
  message: SlackMessageEvent | SlackAppMentionEvent;
  replyToMode: ReplyToMode;
}): SlackThreadContext {
  const incomingThreadTs = params.message.thread_ts;
  const messageTs = params.message.ts ?? eventTs;
  const hasThreadTs = typeof incomingThreadTs === "string" && incomingThreadTs.length > 0;
  const isThreadReply =
    hasThreadTs && (incomingThreadTs !== messageTs || Boolean(params.message.parent_user_id));
  
  // Thread ID: if thread reply, use thread_ts; otherwise decide by replyToMode
  const messageThreadId = isThreadReply
    ? incomingThreadTs
    : params.replyToMode === "all"
      ? messageTs      // replyToMode=all: all replies open thread
      : undefined;     // replyToMode=off: no auto thread
  
  return { incomingThreadTs, messageTs, isThreadReply, replyToId, messageThreadId };
}
```

### Missing thread\_ts Recovery

Slack has edge cases where it sends messages with `parent_user_id` but missing `thread_ts` (known bug). OpenClaw's `createSlackThreadTsResolver` recovers missing `thread_ts` by querying the `conversations.history` API:

```typescript
// src/slack/monitor/thread-resolution.ts
export function createSlackThreadTsResolver(params) {
  const cache = new Map<string, ThreadTsCacheEntry>();
  const inflight = new Map<string, Promise<string | undefined>>();
  
  return {
    resolve: async (request) => {
      const { message } = request;
      // Only recover when parent_user_id exists but thread_ts is missing
      if (!message.parent_user_id || message.thread_ts || !message.ts) {
        return message;
      }
      
      // Check cache first
      const cached = getCached(cacheKey, now);
      if (cached !== undefined) {
        return cached ? { ...message, thread_ts: cached } : message;
      }
      
      // Deduplicate in-flight API requests (inflight dedup)
      let pending = inflight.get(cacheKey);
      if (!pending) {
        pending = resolveThreadTsFromHistory({
          client: params.client,
          channelId: message.channel,
          messageTs: message.ts,
        });
        inflight.set(cacheKey, pending);
      }
      
      const resolved = await pending;
      setCached(cacheKey, resolved ?? null, Date.now());
      return resolved ? { ...message, thread_ts: resolved } : message;
    }
  };
}
```

This design has three elegant aspects:

1. **LRU Cache** (60-second TTL, 500-entry limit): Avoids repeated API queries for the same message
2. **Inflight Deduplication**: Concurrent requests for the same message execute only one API call
3. **Graceful Degradation**: API call failures don't block message processing, just lose thread context

### Thread to Session Key Mapping

Thread context ultimately maps to OpenClaw's session system. Conversations within threads use independent Session Keys:

```typescript
// src/slack/monitor/message-handler/prepare.ts
const threadContext = resolveSlackThreadContext({ message, replyToMode: ctx.replyToMode });
const isThreadReply = threadContext.isThreadReply;

const threadKeys = resolveThreadSessionKeys({
  baseSessionKey,
  threadId: isThreadReply ? threadTs : undefined,
  parentSessionKey: isThreadReply && ctx.threadInheritParent ? baseSessionKey : undefined,
});
const sessionKey = threadKeys.sessionKey;
```

The `threadHistoryScope` configuration determines where thread reply history belongs:

| threadHistoryScope   | Behavior                                      |
| -------------------- | --------------------------------------------- |
| `"thread"` (default) | Replies within thread use independent history |
| `"channel"`          | Thread replies share channel-level history    |

### Reply Thread Target

The `replyToMode` configuration controls whether the Bot automatically creates/joins threads when replying:

```typescript
// src/slack/threading.ts
export function resolveSlackThreadTargets(params) {
  const { incomingThreadTs, messageTs } = resolveSlackThreadContext(params);
  const replyThreadTs = incomingThreadTs
    ?? (params.replyToMode === "all" ? messageTs : undefined);
  const statusThreadTs = replyThreadTs ?? messageTs;
  return { replyThreadTs, statusThreadTs };
}
```

| replyToMode | Effect                                                         |
| ----------- | -------------------------------------------------------------- |
| `"off"`     | No auto thread, reply directly in channel                      |
| `"first"`   | Only first reply enters thread, subsequent messages not forced |
| `"all"`     | All replies in thread                                          |

The `"first"` mode is implemented via shared `hasRepliedRef` reference:

```typescript
// src/slack/monitor/message-handler/dispatch.ts
const hasRepliedRef = { value: false };
const replyPlan = createSlackReplyDeliveryPlan({
  replyToMode: ctx.replyToMode,
  incomingThreadTs,
  messageTs,
  hasRepliedRef,
});

// Use in deliver callback
deliver: async (payload) => {
  const replyThreadTs = replyPlan.nextThreadTs();
  await deliverReplies({ ..., replyThreadTs });
  replyPlan.markSent();  // Mark first reply sent
}
```

### Thread Starter Content Injection

When users reply within a thread, OpenClaw attempts to fetch the thread root message's content as context injected into the Agent's input:

```typescript
if (isThreadReply && threadTs) {
  const starter = await resolveSlackThreadStarter({
    channelId: message.channel,
    threadTs,
    client: ctx.app.client,
  });
  if (starter?.text) {
    threadStarterBody = formatThreadStarterEnvelope({
      channel: "Slack",
      author: starterName,
      body: starterWithId,
      envelope: envelopeOptions,
    });
  }
  // If current message has no attachments but thread root does, fetch them too
  if (!media && starter.files && starter.files.length > 0) {
    threadStarterMedia = await resolveSlackMedia({ files: starter.files, ... });
  }
}
```

This ensures the Agent understands the entire conversation's starting context even when receiving only a mid-thread reply.

### Message Inbound Deduplication

The Slack channel reuses OpenClaw's generic inbound deduplication mechanism (see Chapter 14), but Slack's dedup key construction is more refined:

```typescript
buildKey: (entry) => {
  const senderId = entry.message.user ?? entry.message.bot_id;
  const threadKey = entry.message.thread_ts
    ? `${entry.message.channel}:${entry.message.thread_ts}`
    : entry.message.parent_user_id && messageTs
      ? `${entry.message.channel}:maybe-thread:${messageTs}`
      : entry.message.channel;
  return `slack:${ctx.accountId}:${threadKey}:${senderId}`;
}
```

The dedup key includes four dimensions: channel ID + account ID + thread/channel ID + sender ID. This ensures:

* Messages from different channels don't interfere
* Messages from different threads in the same channel deduplicate independently
* Messages from different users in the same thread deduplicate independently

### Markdown → mrkdwn Format Conversion

Slack uses custom `mrkdwn` format (note: not standard Markdown). OpenClaw performs format conversion:

````typescript
// src/slack/format.ts
export function markdownToSlackMrkdwn(markdown: string, options = {}): string {
  const ir = markdownToIR(markdown, {
    headingStyle: "bold",       // Slack doesn't support # headings, use bold instead
    blockquotePrefix: "> ",     // Quote format consistent
  });
  return renderMarkdownWithMarkers(ir, {
    styleMarkers: {
      bold: { open: "*", close: "*" },          // Slack: *bold*
      italic: { open: "_", close: "_" },        // Slack: _italic_
      strikethrough: { open: "~", close: "~" }, // Slack: ~strike~
      code: { open: "`", close: "`" },
      code_block: { open: "```\n", close: "```" },
    },
    escapeText: escapeSlackMrkdwnText,
    buildLink: buildSlackLink,  // [text](url) → <url|text>
  });
}
````

Particularly important: `<>` has special meaning in Slack mrkdwn (for links, @mentions, etc.), so these characters in user content must be escaped while preserving Slack's native angle bracket markers (like `<@U123456>`):

```typescript
function isAllowedSlackAngleToken(token: string): boolean {
  const inner = token.slice(1, -1);
  return (
    inner.startsWith("@") ||     // @mention
    inner.startsWith("#") ||     // #channel
    inner.startsWith("!") ||     // !special commands
    inner.startsWith("http://")  // links
    // ...
  );
}
```

### Slash Command System

Slack slash commands are another important way for Bots to interact with users. OpenClaw supports two modes:

1. **Unified Command**: All input received through one configured command name (e.g., `/openclaw`)
2. **Native Commands**: Register OpenClaw's built-in commands (e.g., `/reset`, `/model`, etc.) as independent Slack slash commands

```typescript
// src/slack/monitor/slash.ts
if (nativeCommands.length > 0) {
  for (const command of nativeCommands) {
    ctx.app.command(`/${command.name}`, async ({ command: cmd, ack, respond }) => {
      // Parse command arguments and dispatch
    });
  }
} else if (slashCommand.enabled) {
  // Use unified command name
  ctx.app.command(
    buildSlackSlashCommandMatcher(slashCommand.name),
    async ({ command, ack, respond }) => {
      await handleSlashCommand({ command, ack, respond, prompt: command.text });
    }
  );
}
```

Slash commands use `ephemeral` response mode (visible only to command initiator) and have independent Session Keys:

```typescript
SessionKey: `agent:${route.agentId}:${slashCommand.sessionPrefix}:${command.user_id}`
```

Additionally, OpenClaw supports interactive parameter menus—when commands have multiple optional parameters, the Bot presents users with Slack Block Kit button menus for selection rather than requiring manual parameter text input.

***

## Section Summary

1. **Slack channel is the most complex channel implementation in OpenClaw**, containing 65 source files, covering comprehensive integration of messages, reactions, member changes, channel events, and slash commands.
2. **Bolt SDK provides the foundation for event handling**; OpenClaw builds Socket Mode and HTTP Mode connection methods on top, unified through `monitorSlackProvider()`.
3. **In the dual Token architecture**, Bot Token (`xoxb-`) is used for API calls, App Token (`xapp-`) for Socket Mode connections; OpenClaw supports parsing Tokens from both configuration files and environment variables, with `api_app_id` consistency validation.
4. **Thread session management is the most elegant part of Slack channel**, including `thread_ts` missing recovery, thread-level Session Key isolation, `replyToMode` three-level control (off/first/all), thread Starter content injection, and other mechanisms.
5. **For message format conversion**, OpenClaw converts standard Markdown to Slack mrkdwn format through Markdown IR intermediate representation, precisely handling angle bracket marker escaping.
6. **Slash command system supports both unified and native command modes**, providing interactive parameter selection experience through Block Kit buttons.
