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

# 20.1 WhatsApp Channel (Baileys)

> **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`)

***

WhatsApp is one of the most widely used instant messaging applications globally. OpenClaw implements the WhatsApp channel through the **Baileys** library—an unofficial Node.js implementation based on the WhatsApp Web protocol. This section will deeply analyze the complete flow from QR code login to message sending and receiving.

***

## 20.1.1 Introduction to Baileys Library

> **Sidebar: Baileys and WhatsApp Web Protocol**
>
> WhatsApp officially does not provide a public Bot API (unlike Telegram). Baileys (`@whiskeysockets/baileys`) is a community-maintained open-source library that implements programmatic message sending and receiving through reverse engineering of WhatsApp Web's WebSocket protocol. It simulates the browser-side WhatsApp Web client, using the "Linked Devices" mechanism to connect to WhatsApp servers.
>
> This means:
>
> * Uses **real WhatsApp phone numbers**, not dedicated Bot accounts
> * Connection method is QR code scanning for **device pairing**
> * Subject to WhatsApp's terms of service, with risk of account suspension
> * Recommended to use independent SIM cards/eSIM numbers

OpenClaw's WhatsApp module is primarily located in the `src/web/` directory (for historical reasons, "web" refers to WhatsApp Web).

## 20.1.2 WhatsApp Web Login and QR Code Pairing

### Socket Creation

The core of the login flow is the `createWaSocket` function (`src/web/session.ts`), which wraps Baileys' `makeWASocket`:

```typescript
// src/web/session.ts (simplified)
export async function createWaSocket(
  printQr: boolean,
  verbose: boolean,
  opts: { authDir?: string; onQr?: (qr: string) => void } = {},
) {
  const { state, saveCreds } = await useMultiFileAuthState(authDir);
  const { version } = await fetchLatestBaileysVersion();

  const sock = makeWASocket({
    version,
    auth: { creds: state.creds, keys: makeCacheableSignalKeyStore(state.keys, logger) },
    printQRInTerminal: printQr,
    // ...
  });

  // Auto-save credentials on update
  sock.ev.on("creds.update", () => {
    enqueueSaveCreds(authDir, saveCreds, logger);
  });

  // QR code callback
  sock.ev.on("connection.update", (update) => {
    if (update.qr && opts.onQr) {
      opts.onQr(update.qr);
    }
  });

  return sock;
}
```

Baileys uses the **Signal Protocol** key storage mechanism (`useMultiFileAuthState`) to persist credentials to disk. `makeCacheableSignalKeyStore` caches key operations to reduce filesystem I/O.

> **Sidebar: Signal Protocol**
>
> The Signal Protocol is an end-to-end encryption communication protocol developed by the Signal Foundation. WhatsApp adopted the Signal Protocol to encrypt user messages. Baileys needs to maintain a set of Signal Protocol keys (identity keys, pre-keys, session keys, etc.), which are stored in the `authDir` directory.

### QR Code Login Flow

`startWebLoginWithQr` (`src/web/login-qr.ts`) implements the complete QR code login:

```typescript
// src/web/login-qr.ts (simplified)
export async function startWebLoginWithQr(opts): Promise<{ qrDataUrl?; message }> {
  const account = resolveWhatsAppAccount({ cfg, accountId });

  // Prompt if already logged in
  if (await webAuthExists(account.authDir) && !opts.force) {
    return { message: `WhatsApp is already linked (${who}).` };
  }

  // Reuse unexpired active login
  const existing = activeLogins.get(account.accountId);
  if (existing && isLoginFresh(existing) && existing.qrDataUrl) {
    return { qrDataUrl: existing.qrDataUrl, message: "QR already active." };
  }

  // Create new Socket and wait for QR code
  const sock = await createWaSocket(false, verbose, {
    authDir: account.authDir,
    onQr: (qr) => { resolveQr(qr); },
  });

  // Render QR as PNG base64 Data URL
  const qr = await qrPromise;
  const base64 = await renderQrPngBase64(qr);
  login.qrDataUrl = `data:image/png;base64,${base64}`;

  return { qrDataUrl: login.qrDataUrl, message: "Scan this QR in WhatsApp → Linked Devices." };
}
```

Active logins have a 3-minute TTL (`ACTIVE_LOGIN_TTL_MS = 3 * 60_000`); after expiration, a new QR code must be generated.

### Connection Waiting and Error Recovery

`waitForWebLogin` waits for scanning completion and handles various errors:

```typescript
// src/web/login-qr.ts (simplified)
export async function waitForWebLogin(opts): Promise<{ connected; message }> {
  while (true) {
    await Promise.race([login.waitPromise, timeout]);

    if (login.error) {
      // Logged out by WhatsApp—clear cached credentials
      if (login.errorStatus === DisconnectReason.loggedOut) {
        await logoutWeb({ authDir: login.authDir });
        return { connected: false, message: "Session logged out. Please scan a new QR." };
      }
      // 515 error—WhatsApp requires reconnection
      if (login.errorStatus === 515) {
        const restarted = await restartLoginSocket(login, runtime);
        if (restarted) continue;   // Wait again
      }
      return { connected: false, message: `Login failed: ${login.error}` };
    }

    if (login.connected) {
      return { connected: true, message: "✅ Linked! WhatsApp is ready." };
    }
  }
}
```

Particularly noteworthy is the **515 error handling**: WhatsApp servers sometimes require clients to restart the connection after pairing (status code 515). OpenClaw implements **one-time automatic reconnection** for this (the `restartAttempted` flag prevents infinite retries).

## 20.1.3 Inbound Message Monitoring

Inbound message monitoring is implemented through `monitorWebInbox` (`src/web/inbound/monitor.ts`), which subscribes to Baileys Socket message events, converts WhatsApp messages to `WebInboundMessage` structures, and feeds them into the unified `MsgContext` pipeline.

Key extraction functions include:

* `extractText`: Extracts plain text from WhatsApp message objects (handling conversation, extendedTextMessage, imageMessage.caption, and other formats)
* `extractMediaPlaceholder`: Extracts media placeholder information
* `extractLocationData`: Extracts location information

Inbound messages pass through allowlist filtering (`allowFrom` list) before entering the processing pipeline.

## 20.1.4 Outbound Message Sending

`sendMessageWhatsApp` (`src/web/outbound.ts`) is responsible for sending AI replies to WhatsApp:

```typescript
// src/web/outbound.ts (simplified)
export async function sendMessageWhatsApp(to, body, options) {
  let text = body;
  const { listener: active } = requireActiveWebListener(options.accountId);

  // Markdown table conversion
  const tableMode = resolveMarkdownTableMode({ cfg, channel: "whatsapp" });
  text = convertMarkdownTables(text, tableMode);

  const jid = toWhatsappJid(to);

  // Media handling
  if (options.mediaUrl) {
    const media = await loadWebMedia(options.mediaUrl);
    // ...set sending parameters based on media type
  }

  // Send "typing" status first
  await active.sendComposingTo(to);

  // Send message
  const result = await active.sendMessage(to, text, mediaBuffer, mediaType);
  return { messageId, toJid: jid };
}
```

Additionally supports `sendReactionWhatsApp` (emoji reactions) and `sendPollWhatsApp` (polls). WhatsApp polls support a maximum of 12 options.

## 20.1.5 Auto-Reply System

The core of WhatsApp's auto-reply is in `src/web/auto-reply/monitor.ts` (`monitorWebChannel`), which connects inbound message monitoring with AI agent scheduling, forming a complete "receive message → AI processing → send reply" loop.

## 20.1.6 Session Reconnection

`src/web/reconnect.ts` defines the reconnection strategy:

```typescript
// src/web/reconnect.ts
export const DEFAULT_RECONNECT_POLICY: ReconnectPolicy = {
  initialMs: 2_000,     // Initial reconnection delay: 2 seconds
  maxMs: 30_000,        // Maximum delay: 30 seconds
  factor: 1.8,          // Exponential backoff factor
  jitter: 0.25,         // 25% random jitter
  maxAttempts: 12,       // Maximum 12 retries
};
```

> **Sidebar: Exponential Backoff**
>
> Exponential backoff is a retry strategy where wait time grows exponentially after each failure: 1st wait 2s, 2nd wait 3.6s (2×1.8), 3rd wait 6.48s...up to maximum delay. Adding random jitter (jitter) prevents multiple clients from initiating reconnection at the same moment (the "thundering herd" problem).

## 20.1.7 Media Handling

`loadWebMedia` (`src/web/media.ts`) handles media file loading and optimization:

```typescript
// src/web/media.ts (simplified)
export async function loadWebMedia(mediaUrl, maxBytes?): Promise<WebMediaResult> {
  // Supports file:// URLs, HTTP URLs, and local paths
  // MIME type detection via magic number sniffing
  // Automatic image optimization (HEIC→JPEG, size scaling, quality adjustment)
  // Size/quality grid search: sides=[2048,1536,1280,1024,800] × qualities=[80,70,60,50,40]
}
```

Image optimization uses a grid search strategy—trying different size and quality combinations to find the first one meeting the size limit. Also supports **HEIC → JPEG** conversion (photos taken on iPhones are typically HEIC format), and special handling for transparent PNGs (preserving alpha channel).

***

## Section Summary

1. **Baileys** is an unofficial library based on WhatsApp Web protocol, using real phone numbers with QR code pairing login.
2. **QR code login** has a 3-minute TTL, supports 515 error auto-reconnection and secure credential backup.
3. **Inbound messages** pass through format extraction and allowlist filtering before entering the unified processing pipeline.
4. **Outbound messages** automatically perform Markdown table conversion, supporting text, media, reactions, and polls.
5. **Reconnection** uses exponential backoff with jitter, retrying up to 12 times.
6. **Media handling** supports automatic image optimization, HEIC to JPEG conversion, MIME sniffing, etc., finding optimal quality meeting size limits through grid search.
