DEV Community

Midas Tools
Midas Tools

Posted on

How to Build a WhatsApp AI Bot for Your Business (2026 Complete Guide)

How to Build a WhatsApp AI Bot for Your Business (2026 Complete Guide)

WhatsApp has 2.7 billion users. In Latin America, Mexico, India, and most of Europe, it's not just an option — it's the default way customers reach businesses. If your business isn't on WhatsApp with fast, intelligent responses, you're losing customers to competitors who are.

Here's how to build a WhatsApp AI bot that handles inquiries, books appointments, and qualifies leads — running 24/7 without you.


What a WhatsApp AI Bot Can Do

A well-built WhatsApp bot isn't a scripted chatbot with button menus. It's a conversational AI that:

  • Understands natural language messages in any format
  • Answers questions about your business, services, and availability
  • Books appointments directly into your calendar
  • Qualifies leads (budget, timeline, decision-maker)
  • Sends documents, price lists, or location information
  • Escalates complex issues to your WhatsApp number
  • Remembers context within a conversation

For service businesses in Mexico and Latin America — dental practices, law firms, real estate agencies, beauty salons — WhatsApp AI dramatically cuts the time between "first message" and "booked appointment."


Architecture Overview

Customer sends WhatsApp message
         ↓
WhatsApp Business API (Meta)
         ↓
Your webhook server receives the message
         ↓
OpenAI / Claude processes with tools
         ↓
Your backend executes (check calendar, book, etc.)
         ↓
Response sent back via WhatsApp API
Enter fullscreen mode Exit fullscreen mode

You need: a Meta Business account, a WhatsApp Business API number, a webhook server, and an AI model.


Option 1: No-Code with Landbot or WATI (~$50–150/mo)

Best for: Non-technical business owners, simple Q&A + appointment flows

Tools:

  • WATI — WhatsApp-first platform, visual bot builder, built-in AI, $49/mo
  • Landbot — most polished visual flow builder, WhatsApp + web + Messenger, $50/mo
  • Respond.io — omnichannel (WhatsApp + Instagram + email), good for agencies

Setup with WATI (fastest path):

  1. Create WATI account → connect your WhatsApp Business number
  2. Go to "Bots" → Create bot from template → "FAQ Bot"
  3. Add your FAQ content (product/service questions)
  4. Connect ChatGPT-powered responses for freeform questions
  5. Add a booking trigger: if message contains "appointment/cita/agenda" → send Cal.com link or WATI booking widget
  6. Test → Go live

Limitation: Visual flow builders get complex fast. For simple Q&A and appointment booking for a single service type, they're great. For multi-service businesses with complex logic, you'll hit their limits.


Option 2: WhatsApp Cloud API + OpenAI (Full Control, ~$20–30/mo)

Best for: Developers, agencies building for clients, complex business logic

Step 1: Set Up Meta WhatsApp Business API

  1. Go to developers.facebook.com → Create App → Business
  2. Add "WhatsApp" product to your app
  3. Get a test phone number (free) or connect your own business number
  4. Note your Phone Number ID and WhatsApp Business Account ID
  5. Generate a permanent access token (System User → Generate token → whatsapp_business_messaging)

Step 2: Build the Webhook

Meta sends incoming messages to your HTTPS endpoint. Here's a complete FastAPI handler:

from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import PlainTextResponse
import httpx, json, os
from openai import AsyncOpenAI

app = FastAPI()
openai_client = AsyncOpenAI(api_key=os.environ["OPENAI_API_KEY"])

WHATSAPP_TOKEN = os.environ["WHATSAPP_ACCESS_TOKEN"]
PHONE_NUMBER_ID = os.environ["WHATSAPP_PHONE_NUMBER_ID"]
VERIFY_TOKEN = "your_webhook_verify_token"  # Set this yourself

# Webhook verification (Meta requires this)
@app.get("/webhook")
async def verify_webhook(request: Request):
    params = dict(request.query_params)
    if params.get("hub.verify_token") == VERIFY_TOKEN:
        return PlainTextResponse(params.get("hub.challenge", ""))
    raise HTTPException(status_code=403)

# Incoming messages
@app.post("/webhook")
async def receive_message(request: Request):
    body = await request.json()

    # Extract message details
    try:
        entry = body["entry"][0]["changes"][0]["value"]
        if "messages" not in entry:
            return {"status": "ok"}  # Status updates, not messages

        message = entry["messages"][0]
        from_number = message["from"]
        message_text = message.get("text", {}).get("body", "")

        if not message_text:
            return {"status": "ok"}  # Skip non-text messages for now

        # Process with AI
        response_text = await process_with_ai(from_number, message_text)

        # Send response
        await send_whatsapp_message(from_number, response_text)

    except (KeyError, IndexError):
        pass  # Malformed webhook, ignore

    return {"status": "ok"}

async def process_with_ai(phone: str, message: str) -> str:
    """Process message with OpenAI, return response text."""

    response = await openai_client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {
                "role": "system",
                "content": """You are Maya, the AI assistant for Sonrisa Dental on WhatsApp.

You help patients:
- Schedule and reschedule appointments
- Answer questions about our services and fees
- Provide our address and hours
- Understand what to expect at their first visit

Business details:
- Hours: Mon-Fri 9 AM - 7 PM, Sat 9 AM - 2 PM
- Address: Av. Insurgentes Sur 1234, CDMX
- Services: general dentistry, cleaning, whitening, implants, orthodontics
- Emergency line: +52 55 1234-5678

Rules:
- Keep responses short (1-3 sentences max)
- Use a warm, friendly tone
- For appointments: ask for preferred date/time and service needed
- If emergency: immediately give the emergency number
- Reply in the same language the patient uses (Spanish or English)
- For fees: "Our fees depend on the specific treatment — we're happy to give you an exact quote at your free consultation"
"""
            },
            {"role": "user", "content": message}
        ],
        max_tokens=200,
        temperature=0.4
    )

    return response.choices[0].message.content

async def send_whatsapp_message(to: str, text: str):
    """Send a message via WhatsApp Cloud API."""
    url = f"https://graph.facebook.com/v18.0/{PHONE_NUMBER_ID}/messages"

    async with httpx.AsyncClient() as client:
        await client.post(
            url,
            headers={
                "Authorization": f"Bearer {WHATSAPP_TOKEN}",
                "Content-Type": "application/json"
            },
            json={
                "messaging_product": "whatsapp",
                "to": to,
                "type": "text",
                "text": {"body": text}
            }
        )
Enter fullscreen mode Exit fullscreen mode

Step 3: Add Conversation Memory

The basic setup above doesn't remember previous messages. Add Redis (or a simple dict for small scale) to store conversation history:

from collections import defaultdict

# In-memory store (use Redis in production)
conversation_history: dict = defaultdict(list)

async def process_with_ai(phone: str, message: str) -> str:
    # Add user message to history
    conversation_history[phone].append({
        "role": "user",
        "content": message
    })

    # Keep last 10 messages (5 exchanges)
    recent_history = conversation_history[phone][-10:]

    response = await openai_client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT},
            *recent_history  # Inject conversation history
        ],
        max_tokens=200
    )

    reply = response.choices[0].message.content

    # Add AI response to history
    conversation_history[phone].append({
        "role": "assistant",
        "content": reply
    })

    return reply
Enter fullscreen mode Exit fullscreen mode

Step 4: Deploy

Deploy to any platform that gives you a public HTTPS URL:

# Railway (simplest, ~$5/mo)
railway init
railway up

# Or Fly.io
fly launch
fly deploy
Enter fullscreen mode Exit fullscreen mode

Register your webhook URL in Meta's developer console under your app's WhatsApp configuration.


Sending Proactive Messages (Templates)

WhatsApp only allows you to initiate conversations using pre-approved templates. For appointment reminders, follow-ups, and confirmations, you need these:

async def send_appointment_reminder(to: str, patient_name: str, appointment_time: str):
    """Send a template message for appointment reminder."""
    url = f"https://graph.facebook.com/v18.0/{PHONE_NUMBER_ID}/messages"

    async with httpx.AsyncClient() as client:
        await client.post(
            url,
            headers={"Authorization": f"Bearer {WHATSAPP_TOKEN}"},
            json={
                "messaging_product": "whatsapp",
                "to": to,
                "type": "template",
                "template": {
                    "name": "appointment_reminder",  # Must be pre-approved by Meta
                    "language": {"code": "es_MX"},
                    "components": [{
                        "type": "body",
                        "parameters": [
                            {"type": "text", "text": patient_name},
                            {"type": "text", "text": appointment_time}
                        ]
                    }]
                }
            }
        )
Enter fullscreen mode Exit fullscreen mode

Template approval takes 1–3 business days. Common templates to submit:

  • Appointment confirmation
  • 24-hour reminder
  • "We missed you" after a no-show
  • Post-visit review request

Connecting to Your Calendar

The most valuable feature: let the bot check real availability and book directly.

import httpx

CAL_API_KEY = os.environ["CAL_API_KEY"]

async def check_availability(date: str) -> str:
    """Check Cal.com availability for a given date."""
    async with httpx.AsyncClient() as client:
        resp = await client.get(
            "https://api.cal.com/v1/slots",
            params={
                "apiKey": CAL_API_KEY,
                "eventTypeId": YOUR_EVENT_TYPE_ID,
                "startTime": f"{date}T00:00:00",
                "endTime": f"{date}T23:59:00",
                "timeZone": "America/Mexico_City"
            }
        )
        data = resp.json()

    slots = data.get("slots", {}).get(date, [])
    if not slots:
        return f"No availability on {date}. Would you like to check another day?"

    # Format for WhatsApp readability
    times = [s["time"][11:16] for s in slots[:4]]  # Show max 4 options
    return f"Available times on {date}: {', '.join(times)}. Which works best for you?"
Enter fullscreen mode Exit fullscreen mode

Add this as a function that the AI can call when patients ask about scheduling.


Spanish-Language Prompting

For Mexico/LATAM businesses, your system prompt should explicitly handle Spanish:

Rules:
- Always respond in the same language the patient wrote in
- If they write in Spanish, respond in Spanish
- If they write in English, respond in English  
- For Spanish: use a warm, slightly formal tone appropriate for healthcare
  (use "usted" when addressing patients you haven't met, switch to "tú" only if they initiate)
- Avoid direct translation of English idioms — rephrase naturally
Enter fullscreen mode Exit fullscreen mode

Cost Breakdown

Component Monthly Cost
WhatsApp Cloud API Free (first 1,000 conversations/mo)
FastAPI on Railway $5
OpenAI GPT-4o (500 conversations) ~$15
Cal.com Free
Total ~$20/month

After 1,000 conversations/month: ~$0.04–0.08 per conversation depending on country.


The WhatsApp Advantage Over Other Channels

  • Open rates: WhatsApp messages get 98% open rate vs. 20% for email
  • Response time expectations: Customers expect responses within minutes on WhatsApp, not hours
  • LATAM adoption: In Mexico, Colombia, Brazil — WhatsApp IS the primary business communication channel. Many customers won't call or email; WhatsApp is their default.
  • Trust: A WhatsApp message from a business feels more personal than an automated email

For service businesses in Spanish-speaking markets, a WhatsApp AI bot often outperforms phone + email combined.


Getting This Set Up

The no-code path (WATI) takes about 2 hours and covers most small business needs. The custom API path gives you full control and lower costs but requires a developer or 1–2 days of focused setup time.

If you want a WhatsApp AI bot configured for your specific business — with your booking system, service list, FAQ, and language preferences — we set these up as part of our AI business automation service.


Rey Midas builds AI automations for service businesses at MidasTools — specializing in Spanish-language markets and local businesses in Mexico City.

Top comments (0)