Skip to content

WhatsApp Bot Tutorial

Build a simple auto-reply WhatsApp bot using SendAPI's WhatsApp API and webhooks.

Overview

With SendAPI's WhatsApp integration, you can build bots that automatically reply to incoming messages. This tutorial walks you through:

  1. Creating a WhatsApp session
  2. Setting up a webhook endpoint
  3. Processing incoming messages
  4. Sending automated replies

Prerequisites

  • A SendAPI account with an active subscription
  • A WhatsApp phone number to connect
  • A server with a public URL for webhooks (or use ngrok for local development)

Step 1: Create a Session

bash
curl -X POST https://sendapi.co/v1/whatsapp/sessions \
  -H "Authorization: Bearer sk_live_YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "Support Bot", "webhook_url": "https://yourserver.com/webhook"}'

Scan the returned QR code with WhatsApp on your phone to pair the session.

Step 2: Set Up Your Webhook Server

Create a simple Express.js server to receive incoming messages:

javascript
const express = require('express');
const app = express();
app.use(express.json());

const API_KEY = process.env.SENDAPI_KEY;

app.post('/webhook', async (req, res) => {
  const event = req.body;

  // Only process incoming messages
  if (event.type !== 'whatsapp.message.received') {
    return res.json({ received: true });
  }

  const { from, text, session_id } = event.data;
  console.log(`Message from ${from}: ${text}`);

  // Send an auto-reply
  await fetch('https://sendapi.co/v1/whatsapp/send', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      session_id,
      to: from,
      type: 'text',
      text: { body: `Thanks for your message! We received: "${text}"` }
    })
  });

  res.json({ received: true });
});

app.listen(3000, () => console.log('Bot running on port 3000'));

Step 3: Test It

Send a WhatsApp message to your connected number. Your bot should automatically reply!

Adding Intelligence

You can expand the bot with keyword-based routing:

javascript
function getReply(message) {
  const lower = message.toLowerCase();

  if (lower.includes('price') || lower.includes('pricing')) {
    return 'Our plans start at $9.99/month. Visit https://sendapi.co/pricing for details.';
  }
  if (lower.includes('help') || lower.includes('support')) {
    return 'Our support team is available Mon-Fri, 9am-5pm. Email us at support@sendapi.co.';
  }
  if (lower.includes('hours') || lower.includes('open')) {
    return 'We are open Monday to Friday, 9:00 AM to 5:00 PM (UTC).';
  }

  return 'Thanks for reaching out! How can we help you today?';
}

Rate Limits

Remember that WhatsApp sessions are limited to 30 messages per minute per session. For high-volume bots, consider using multiple sessions and distributing load.

Released under the MIT License.