Skip to main content

Prerequisites

  • A phone with WhatsApp installed
  • OrcBot installed and configured
  • Node.js 18+ installed
  • Stable internet connection
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.

How It Works

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

Initial Setup

1

Configure Session Path

Set where WhatsApp auth data is stored:
# ~/.orcbot/orcbot.config.yaml
whatsappEnabled: true
whatsappSessionPath: ~/.orcbot/whatsapp-session
2

Start OrcBot

cd ~/orcbot
npm run build
npm run start
3

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
4

Connection Established

You’ll see:
WhatsApp: Connection opened successfully. Owner: 1234567890@s.whatsapp.net
OrcBot is now connected!

Configuration Options

Basic Settings

# ~/.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

whatsappAutoReplyEnabled: true
OrcBot responds to all incoming messages automatically.

Media Handling

Receiving Media

OrcBot automatically downloads and analyzes media:
// 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..."

Sending Media

Use the send_file skill:
// 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:
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:
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:
// From a custom skill
const results = whatsappChannel.searchContacts('John');
// Returns: [{ jid: '1234567890@s.whatsapp.net', name: 'John Doe' }]

Get Recent Contacts

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

Reply Context & Threads

OrcBot preserves conversation threads:
// 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

whatsappAutoReplyEnabled: true  # Reply to all group messages
Or mention-based:
whatsappAutoReplyEnabled: false  # Only reply when mentioned

Group Message Detection

const isGroup = senderId?.endsWith('@g.us');

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

WhatsApp Status Updates

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

Enable Status Replies

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

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

# Stop OrcBot first
orcbot daemon stop

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

# Restart
orcbot run

Restore Session

orcbot daemon stop
rm -rf ~/.orcbot/whatsapp-session
cp -r ~/.orcbot/whatsapp-session.backup ~/.orcbot/whatsapp-session
orcbot run
If you lose your session files, you’ll need to re-scan the QR code.

Reconnection Handling

OrcBot automatically reconnects on disconnection:
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:
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:
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:
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:
// 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

1

Check Logs

tail -f ~/.orcbot/logs/orcbot.log | grep -i whatsapp
2

Verify Config

whatsappEnabled: true
whatsappSessionPath: ~/.orcbot/whatsapp-session
3

Clear Session

rm -rf ~/.orcbot/whatsapp-session
orcbot run
4

Check Terminal

Make sure your terminal supports QR code rendering. If not, check logs for the QR code event.

Connection Keeps Dropping

Possible causes:
  1. Network instability
    # 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

# 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

// 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
rm -rf ~/.orcbot/whatsapp-session
orcbot run
# Scan new QR code

Best Practices

Reliability

  • Keep your phone connected to internet
  • Don’t log out of linked devices
  • Back up session files regularly
  • Monitor connection status in logs

Privacy

  • 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

Performance

  • Limit media auto-downloads in busy groups
  • Set reasonable message processing limits
  • Use whatsappAutoReplyEnabled: false in high-traffic groups
  • Clean up old downloads periodically

Compliance

  • Follow WhatsApp Terms of Service
  • Don’t spam or send unsolicited messages
  • Respect user privacy and consent
  • Use business accounts for commercial purposes

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"