> ## Documentation Index
> Fetch the complete documentation index at: https://docs.orcbot.buzzchat.site/llms.txt
> Use this file to discover all available pages before exploring further.

# WhatsApp Channel Setup

> Set up WhatsApp integration using Baileys library with QR code pairing and multi-device support

## Prerequisites

* A phone with WhatsApp installed
* OrcBot installed and configured
* Node.js 18+ installed
* Stable internet connection

<Warning>
  WhatsApp Business API is a paid service. This guide uses the free Baileys library which connects via WhatsApp Web protocol. Use responsibly and in compliance with WhatsApp's Terms of Service.
</Warning>

## How It Works

OrcBot uses the **Baileys** library to connect to WhatsApp as a linked device (similar to WhatsApp Web).

```mermaid theme={null}
flowchart LR
    A[Your Phone] -->|Scan QR| B[OrcBot]
    B -->|WhatsApp Web Protocol| C[WhatsApp Servers]
    D[Contacts] -->|Message| C
    C -->|Incoming| B
    B -->|Reply| C
```

## Initial Setup

<Steps>
  <Step title="Configure Session Path">
    Set where WhatsApp auth data is stored:

    ```yaml theme={null}
    # ~/.orcbot/orcbot.config.yaml
    whatsappEnabled: true
    whatsappSessionPath: ~/.orcbot/whatsapp-session
    ```
  </Step>

  <Step title="Start OrcBot">
    ```bash theme={null}
    cd ~/orcbot
    npm run build
    npm run start
    ```
  </Step>

  <Step title="Scan QR Code">
    When you see "WhatsApp: New QR Code generated. Scan to link." in the logs:

    1. Open WhatsApp on your phone
    2. Go to Settings → Linked Devices
    3. Tap "Link a Device"
    4. Scan the QR code displayed in your terminal
  </Step>

  <Step title="Connection Established">
    You'll see:

    ```
    WhatsApp: Connection opened successfully. Owner: 1234567890@s.whatsapp.net
    ```

    OrcBot is now connected!
  </Step>
</Steps>

## Configuration Options

### Basic Settings

```yaml theme={null}
# ~/.orcbot/orcbot.config.yaml

# Enable WhatsApp channel
whatsappEnabled: true

# Session storage path
whatsappSessionPath: ~/.orcbot/whatsapp-session

# Auto-reply to incoming messages
whatsappAutoReplyEnabled: true

# Reply to WhatsApp Status updates
whatsappStatusReplyEnabled: false

# Auto-react with emojis to messages
whatsappAutoReactEnabled: false

# Context profiling for better responses
whatsappContextProfilingEnabled: true

# Owner JID (auto-populated on first connection)
whatsappOwnerJID: "1234567890@s.whatsapp.net"
```

### Auto-Reply Behavior

<Tabs>
  <Tab title="Enabled">
    ```yaml theme={null}
    whatsappAutoReplyEnabled: true
    ```

    OrcBot responds to all incoming messages automatically.
  </Tab>

  <Tab title="Disabled">
    ```yaml theme={null}
    whatsappAutoReplyEnabled: false
    ```

    OrcBot only processes messages but doesn't auto-reply. Use skills like `send_message` to reply manually.
  </Tab>

  <Tab title="Self-Chat Mode">
    When messaging yourself (your own number):

    * Messages **with** `🤖` prefix = from bot (ignored)
    * Messages **without** prefix = from you (processed as commands)

    ```
    You: "Summarize my calendar"
    Bot: "🤖 You have 3 meetings today: ..."
    ```
  </Tab>
</Tabs>

## Media Handling

### Receiving Media

OrcBot automatically downloads and analyzes media:

<CodeGroup>
  ```javascript Images theme={null}
  // User sends photo with caption "What is this?"

  // OrcBot downloads image
  const mediaPath = path.join(downloadsDir, `wa_${messageId}.jpg`);
  fs.writeFileSync(mediaPath, buffer);

  // Auto-analyzes the image
  const analysis = await this.agent.llm.analyzeMedia(
    mediaPath,
    'The user sent this image with the message: "What is this?". Describe what you see in detail.'
  );

  // Responds with analysis
  "This appears to be a Golden Retriever puppy, approximately 3-4 months old..."
  ```

  ```javascript Voice Notes theme={null}
  // User sends voice message

  // OrcBot downloads audio
  const mediaPath = path.join(downloadsDir, `wa_${messageId}.ogg`);
  fs.writeFileSync(mediaPath, buffer);

  // Auto-transcribes
  const transcription = await this.agent.llm.analyzeMedia(
    mediaPath,
    'Transcribe this audio message exactly.'
  );

  // Processes transcribed text
  "Transcription: 'Remind me to buy groceries tomorrow'"
  "✅ Reminder set for tomorrow: Buy groceries"
  ```

  ```javascript Documents theme={null}
  // User sends PDF document

  // OrcBot downloads file
  const mediaPath = path.join(downloadsDir, `wa_${messageId}.pdf`);
  fs.writeFileSync(mediaPath, buffer);

  // Analyzes document (if LLM supports)
  "I've received the 5-page contract document. Would you like me to:
  1. Summarize key terms
  2. Extract dates and obligations
  3. Review for potential issues"
  ```
</CodeGroup>

### Sending Media

Use the `send_file` skill:

```javascript theme={null}
// Send an image
send_file(
  to: "1234567890@s.whatsapp.net",
  filePath: "/path/to/chart.png",
  caption: "Here's the sales chart you requested",
  channel: "whatsapp"
)

// Send a document
send_file(
  to: "1234567890@s.whatsapp.net",
  filePath: "/path/to/report.pdf",
  caption: "Monthly report attached",
  channel: "whatsapp"
)
```

**Supported file types:**

* Images: `.jpg`, `.png`, `.webp`
* Audio: `.ogg`, `.mp3`, `.m4a`
* Video: `.mp4`, `.mkv`
* Documents: `.pdf`, `.doc`, `.xlsx`, etc.

### Voice Messages

Send text-to-speech voice notes:

```javascript theme={null}
send_voice_note(
  to: "1234567890@s.whatsapp.net",
  text: "Hello! This is a voice message from OrcBot."
)
```

OrcBot converts text to speech and sends as WhatsApp voice note.

## Contact Management

### Auto-Sync Contacts

OrcBot automatically syncs your WhatsApp contacts:

```typescript theme={null}
this.sock.ev.on('contacts.set', (payload: any) => {
  const contacts = payload?.contacts || [];
  this.recordContacts(contacts);
  logger.info(`WhatsApp: Contacts set (${contacts.length})`);
});
```

### Search Contacts

Use the contact search API:

```javascript theme={null}
// From a custom skill
const results = whatsappChannel.searchContacts('John');
// Returns: [{ jid: '1234567890@s.whatsapp.net', name: 'John Doe' }]
```

### Get Recent Contacts

```javascript theme={null}
const contacts = whatsappChannel.getRecentContacts();
contacts.forEach(c => {
  console.log(`${c.name}: ${c.jid}`);
});
```

## Reply Context & Threads

OrcBot preserves conversation threads:

```typescript theme={null}
// When user replies to a message
if (contextInfo?.quotedMessage) {
  const quotedText = contextInfo.quotedMessage.conversation || '[Media]';
  const quotedName = contextInfo.participant.split('@')[0];
  
  replyContext = `[Replying to ${quotedName}'s message: "${quotedText}"]`;
}
```

**Example conversation:**

```
Alice: "What's the weather?"
You:   [Reply to Alice] "@bot answer this"

Bot:   "Based on Alice's question about weather..."
       [Reply includes context from Alice's original message]
```

## Group Chat Support

### Auto-Reply in Groups

```yaml theme={null}
whatsappAutoReplyEnabled: true  # Reply to all group messages
```

Or mention-based:

```yaml theme={null}
whatsappAutoReplyEnabled: false  # Only reply when mentioned
```

### Group Message Detection

```typescript theme={null}
const isGroup = senderId?.endsWith('@g.us');

if (isGroup) {
  // Special handling for group messages
  const groupName = await getGroupMetadata(senderId);
}
```

## WhatsApp Status Updates

<Warning>
  Replying to status updates can be intrusive. Only enable if you have a specific use case.
</Warning>

### Enable Status Replies

```yaml theme={null}
whatsappStatusReplyEnabled: true
```

When enabled:

* OrcBot sees status updates from contacts
* Can auto-react or reply to status
* Status media is downloaded and analyzed

### Status Detection

```typescript theme={null}
const isStatus = senderId === 'status@broadcast';

if (isStatus && this.statusReplyEnabled) {
  // Process status update
  const contentType = this.detectStatusContentType(message);
  const participant = msg.key.participant;
}
```

## Session Persistence

### How Sessions Work

Baileys stores auth credentials in multi-file format:

```
~/.orcbot/whatsapp-session/
  ├── creds.json          # Authentication credentials
  ├── app-state-sync-key-*.json  # Sync keys
  └── app-state-sync-version-*.json
```

### Backup Session

```bash theme={null}
# Stop OrcBot first
orcbot daemon stop

# Backup session
cp -r ~/.orcbot/whatsapp-session ~/.orcbot/whatsapp-session.backup

# Restart
orcbot run
```

### Restore Session

```bash theme={null}
orcbot daemon stop
rm -rf ~/.orcbot/whatsapp-session
cp -r ~/.orcbot/whatsapp-session.backup ~/.orcbot/whatsapp-session
orcbot run
```

<Note>
  If you lose your session files, you'll need to re-scan the QR code.
</Note>

## Reconnection Handling

OrcBot automatically reconnects on disconnection:

```typescript theme={null}
this.sock.ev.on('connection.update', (update: any) => {
  const { connection, lastDisconnect } = update;

  if (connection === 'close') {
    const shouldReconnect = 
      lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
    
    if (shouldReconnect) {
      logger.warn('WhatsApp: Connection closed. Reconnecting...');
      this.start();  // Auto-reconnect
    }
  }
});
```

**Disconnect reasons:**

* `loggedOut` - You logged out from phone (requires re-pairing)
* `connectionReplaced` - Another device connected
* Network issues - Auto-reconnects

## Advanced Features

### Context Profiling

When enabled, OrcBot analyzes message patterns:

```yaml theme={null}
whatsappContextProfilingEnabled: true
```

This helps the agent:

* Understand conversation context better
* Provide more relevant responses
* Track user preferences over time

### Auto-Reactions

Enable emoji reactions to messages:

```yaml theme={null}
whatsappAutoReactEnabled: true
```

OrcBot can react with:

* ✅ for completed tasks
* 🔍 for searches in progress
* ❌ for errors
* 🤔 for clarification requests

### Self-Chat Prefix

When messaging yourself, OrcBot adds a prefix to its messages:

```typescript theme={null}
private readonly AGENT_MESSAGE_PREFIX = '🤖 ';

// Bot messages: "🤖 Your reminder has been set."
// Your messages: "Set a reminder for 3 PM"
```

This prevents infinite loops in self-chat mode.

## Channel Detection

OrcBot uses 3-tier channel detection for sending messages:

```typescript theme={null}
// Priority: WhatsApp → Discord → Telegram
if (to.includes('@s.whatsapp.net') || to.includes('@g.us')) {
  return whatsappChannel.sendMessage(to, message);
} else if (to.match(/^\d{17,19}$/)) {
  return discordChannel.sendMessage(to, message);
} else {
  return telegramChannel.sendMessage(to, message);
}
```

JID formats:

* WhatsApp individual: `1234567890@s.whatsapp.net`
* WhatsApp group: `1234567890-1234567890@g.us`
* Discord: `987654321098765432` (snowflake)
* Telegram: `123456789` (numeric)

## Troubleshooting

### QR Code Not Showing

<Steps>
  <Step title="Check Logs">
    ```bash theme={null}
    tail -f ~/.orcbot/logs/orcbot.log | grep -i whatsapp
    ```
  </Step>

  <Step title="Verify Config">
    ```yaml theme={null}
    whatsappEnabled: true
    whatsappSessionPath: ~/.orcbot/whatsapp-session
    ```
  </Step>

  <Step title="Clear Session">
    ```bash theme={null}
    rm -rf ~/.orcbot/whatsapp-session
    orcbot run
    ```
  </Step>

  <Step title="Check Terminal">
    Make sure your terminal supports QR code rendering. If not, check logs for the QR code event.
  </Step>
</Steps>

### Connection Keeps Dropping

**Possible causes:**

1. **Network instability**
   ```yaml theme={null}
   # Increase reconnection timeout
   whatsappReconnectTimeout: 5000
   ```

2. **Multiple devices**
   * Check linked devices on your phone
   * Unlink old sessions

3. **WhatsApp updates**
   * Update Baileys: `npm update @whiskeysockets/baileys`
   * Restart OrcBot

### Messages Not Being Received

```bash theme={null}
# Check if socket is connected
grep "Connection opened" ~/.orcbot/logs/orcbot.log

# Check message event listeners
grep "messages.upsert" ~/.orcbot/logs/orcbot.log
```

Common issues:

* Bot is muted on your phone
* Message processing disabled: `whatsappAutoReplyEnabled: false`
* Group admin restrictions

### Media Download Failures

```typescript theme={null}
// Check download directory
const downloadsDir = path.join(this.agent.config.getDataHome(), 'downloads');
if (!fs.existsSync(downloadsDir)) {
  fs.mkdirSync(downloadsDir, { recursive: true });
}
```

Ensure:

* Directory exists and is writable
* Sufficient disk space
* Network connection is stable

### "Logged Out" Error

If you see `DisconnectReason.loggedOut`:

1. You manually logged out from phone
2. WhatsApp detected suspicious activity
3. Session expired (typically after 14 days of inactivity)

**Fix:** Clear session and re-pair

```bash theme={null}
rm -rf ~/.orcbot/whatsapp-session
orcbot run
# Scan new QR code
```

## Best Practices

<Card title="Reliability" icon="signal">
  * Keep your phone connected to internet
  * Don't log out of linked devices
  * Back up session files regularly
  * Monitor connection status in logs
</Card>

<Card title="Privacy" icon="lock">
  * Don't share session files (contain auth credentials)
  * Set restrictive permissions: `chmod 700 ~/.orcbot/whatsapp-session`
  * Disable status replies unless needed
  * Be cautious with auto-profiling in sensitive conversations
</Card>

<Card title="Performance" icon="gauge">
  * Limit media auto-downloads in busy groups
  * Set reasonable message processing limits
  * Use `whatsappAutoReplyEnabled: false` in high-traffic groups
  * Clean up old downloads periodically
</Card>

<Card title="Compliance" icon="scale-balanced">
  * Follow WhatsApp Terms of Service
  * Don't spam or send unsolicited messages
  * Respect user privacy and consent
  * Use business accounts for commercial purposes
</Card>

## Example Workflows

### Personal Assistant

```
You: "Remind me to call mom at 6 PM"
Bot: "🤖 ✅ Reminder set for today at 6:00 PM: Call mom"

[At 6 PM]
Bot: "🤖 ⏰ Reminder: Call mom"
```

### File Processing

```
You: [sends PDF invoice]
     "Extract the total amount and due date"

Bot: "🤖 Analyzing document...
      
      Total Amount: $1,234.56
      Due Date: March 15, 2024
      Invoice #: INV-2024-001"
```

### Group Coordination

```
Family Group:

Alice: "What time is dinner?"
Bob:   "Where are we meeting?"

@OrcBot: "Summarize the last 10 messages"

Bot:   "🤖 Recent discussion:
        - Alice asked about dinner time
        - Bob asked about meeting location
        - Mom suggested 7 PM at home
        - Dad confirmed he'll bring dessert"
```
