How to Create a WhatsApp AI Customer Service Bot
Build a WhatsApp bot that handles customer inquiries using AI.
Jay Banlasan
The AI Systems Guy
A whatsapp ai customer service bot for your business meets customers where they already are. WhatsApp has over 2 billion users, and for many markets it is the primary communication channel. I build these for service businesses that get flooded with the same questions on WhatsApp daily.
The setup uses Meta's WhatsApp Business API, a webhook server, and an AI model to generate responses grounded in your business data.
What You Need Before Starting
- A Meta Business account with WhatsApp Business API access
- A verified phone number for WhatsApp Business
- Python 3.8+ with Flask
- An Anthropic or OpenAI API key
- A public webhook URL (ngrok for testing)
Step 1: Set Up the WhatsApp Business API
Register your app in the Meta Developer Portal. Create a WhatsApp Business account and get your access token:
# Your WhatsApp credentials
WHATSAPP_TOKEN=your_access_token
WHATSAPP_PHONE_ID=your_phone_number_id
VERIFY_TOKEN=your_custom_verify_string
Step 2: Build the Webhook Receiver
Meta sends incoming messages to your webhook. Set up verification and message handling:
from flask import Flask, request, jsonify
import requests
import anthropic
import os
app = Flask(__name__)
client = anthropic.Anthropic()
WHATSAPP_TOKEN = os.getenv("WHATSAPP_TOKEN")
PHONE_ID = os.getenv("WHATSAPP_PHONE_ID")
@app.route("/webhook", methods=["GET"])
def verify():
mode = request.args.get("hub.mode")
token = request.args.get("hub.verify_token")
challenge = request.args.get("hub.challenge")
if mode == "subscribe" and token == os.getenv("VERIFY_TOKEN"):
return challenge, 200
return "Forbidden", 403
@app.route("/webhook", methods=["POST"])
def receive_message():
data = request.json
for entry in data.get("entry", []):
for change in entry.get("changes", []):
message = change["value"].get("messages", [None])[0]
if message and message["type"] == "text":
handle_message(message)
return "OK", 200
Step 3: Generate AI Responses
When a message comes in, send it through your AI model with your business context:
BUSINESS_CONTEXT = """You are a customer service agent for [Your Business].
Hours: Mon-Fri 9am-6pm. Location: [Your Address].
Services: [List your services and pricing].
Answer in the same language the customer writes in.
Keep responses under 300 words. Be friendly and direct."""
def handle_message(message):
sender = message["from"]
text = message["text"]["body"]
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=400,
system=BUSINESS_CONTEXT,
messages=[{"role": "user", "content": text}]
)
reply = response.content[0].text
send_whatsapp_message(sender, reply)
Step 4: Send Replies Back
Use the WhatsApp API to send the AI response:
def send_whatsapp_message(to, text):
url = f"https://graph.facebook.com/v18.0/{PHONE_ID}/messages"
headers = {
"Authorization": f"Bearer {WHATSAPP_TOKEN}",
"Content-Type": "application/json"
}
payload = {
"messaging_product": "whatsapp",
"to": to,
"type": "text",
"text": {"body": text}
}
requests.post(url, json=payload, headers=headers)
Step 5: Add Conversation Memory
Store recent messages per user so the bot has context across multiple messages:
import sqlite3
def save_message(phone, role, content):
conn = sqlite3.connect("whatsapp_chats.db")
conn.execute(
"INSERT INTO messages (phone, role, content, timestamp) VALUES (?, ?, ?, datetime('now'))",
(phone, role, content)
)
conn.commit()
def get_history(phone, limit=10):
conn = sqlite3.connect("whatsapp_chats.db")
rows = conn.execute(
"SELECT role, content FROM messages WHERE phone = ? ORDER BY timestamp DESC LIMIT ?",
(phone, limit)
).fetchall()
return [{"role": r[0], "content": r[1]} for r in reversed(rows)]
What to Build Next
Add template messages for common flows like appointment booking and order status. WhatsApp Business lets you send pre-approved templates outside the 24-hour window, so you can follow up with customers proactively.
Related Reading
- AI in Customer Service - the full landscape of AI-powered support channels
- The Automation Decision Tree - decide which support channels to automate first
- Connecting Two Systems with APIs: A Practical Guide - how webhook integrations work under the hood
Want this system built for your business?
Get a free assessment. We will map every system your business needs and show you the ROI.
Get Your Free Assessment