Skip to content
MYZATECHSOLUTIONS
Agentic AI

How to build a WhatsApp AI assistant for a small business

A practical guide to building a WhatsApp AI assistant: the Cloud API setup, a working webhook, voice notes, replying in the customer's language, costs, Meta's rules, and the traps that waste days.

Osama GhafoorFounder, MYZATECH10 min read
On this page

For many small businesses, WhatsApp is the real front desk. Customers ask about prices, opening hours, delivery and stock there, often late at night and often by voice note. Answering every message by hand takes hours each week, and slow replies lose sales.

A WhatsApp AI assistant can answer the routine questions in seconds and pass the rest to a person. This guide shows how to build one. It is based on our own WhatsApp AI Assistant project, which understands text and voice notes in English or Roman Urdu and replies in the same language. We cover the architecture, a working webhook in Python, voice notes, costs, Meta's rules, and the problems that cost us the most time.

What a good WhatsApp assistant does

Before you write any code, decide what the assistant is for. The useful ones are narrow:

  • Answer common questions about prices, opening hours, delivery areas and return rules, using your own information instead of the model's general knowledge.
  • Collect details for an order, booking or quote, then hand them to a person.
  • Look up simple facts such as order status or stock, if you connect it to your systems.
  • Hand over to a human when the question is unclear, the customer is unhappy, or money is involved.

A narrow scope is not only good design. Meta's WhatsApp Business terms, updated for January 2026, bar general-purpose AI assistants (ChatGPT-style bots that answer anything) from the platform, except where Meta is legally required to allow them. Bots that serve a specific business function, such as support, sales or bookings, are still allowed. An assistant that only talks about your business is both more useful and more compliant.

The architecture

Every WhatsApp AI assistant built on Meta's official platform has the same basic shape:

  1. A customer sends a text or voice note to your business number.
  2. Meta's WhatsApp Cloud API sends that message to your webhook, a public HTTPS address on your server.
  3. Your app works out what was said. For voice notes, it downloads the audio and turns it into text with a speech-to-text service.
  4. An LLM writes a reply using your business information and the conversation so far.
  5. Your app sends the reply back through the Cloud API.

Our project used Python with Flask for the webhook, the Anthropic Claude API for replies, Azure AI Speech for voice notes, and Azure App Service with a GitHub Actions pipeline for hosting. Any web framework, model provider or cloud works in the same way.

Build it in phases

We built the assistant in three phases. Each one was useful on its own, and each one cut the risk for the next.

  1. Keyword bot. A webhook that answers a handful of keywords such as "price", "timing" or "location". This proves the whole pipe works: Meta to your server and back.
  2. LLM assistant. Swap the keyword logic for an LLM with a clear system prompt and your business facts. Answers become natural, and customers can word questions any way they like.
  3. Voice and language. Add voice-note transcription and language detection, so a customer who speaks Urdu gets an Urdu reply.

If phase 1 doesn't work, nothing after it will. Don't skip it.

Setting up the WhatsApp Cloud API

In outline, you need:

  • A Meta Business account and a developer app with the WhatsApp product added.
  • A phone number registered to the WhatsApp Business Platform. Meta provides a test number to start with.
  • A webhook URL and a verify token that you choose, entered in the app's WhatsApp configuration, with the messages field subscribed.
  • An access token that your server uses to send replies.

Two setup details caused us real trouble, so they get their own section further down.

A minimal webhook in Python

This Flask app shows the core loop. It handles Meta's verification request, checks that each incoming request really came from Meta, ignores repeats, asks Claude for a reply and sends it back.

app.py
import hashlib
import hmac
import os
 
import anthropic
import requests
from flask import Flask, abort, request
 
app = Flask(__name__)
claude = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY
 
GRAPH = f"https://graph.facebook.com/{os.environ['GRAPH_API_VERSION']}"
PHONE_ID = os.environ["WHATSAPP_PHONE_NUMBER_ID"]
TOKEN = os.environ["WHATSAPP_TOKEN"]
VERIFY_TOKEN = os.environ["WHATSAPP_VERIFY_TOKEN"]
APP_SECRET = os.environ["META_APP_SECRET"].encode()
 
SYSTEM = """You are the WhatsApp assistant for Example Bakery, Lahore.
Only answer questions about the bakery, using the facts below.
If you don't know, or the customer wants to order, say a team member
will reply soon. Keep answers short. Reply in the customer's language.
 
Facts: open 9am-10pm daily. Delivery within 5 km. Custom cakes need
48 hours' notice."""
 
seen_ids: set[str] = set()  # use Redis or a database in production
 
 
@app.get("/webhook")
def verify():
    if request.args.get("hub.verify_token") == VERIFY_TOKEN:
        return request.args.get("hub.challenge", "")
    abort(403)
 
 
@app.post("/webhook")
def receive():
    signature = request.headers.get("X-Hub-Signature-256", "")
    expected = "sha256=" + hmac.new(
        APP_SECRET, request.get_data(), hashlib.sha256
    ).hexdigest()
    if not hmac.compare_digest(signature, expected):
        abort(403)
 
    for entry in request.json.get("entry", []):
        for change in entry.get("changes", []):
            for msg in change["value"].get("messages", []):
                if msg["id"] in seen_ids or msg["type"] != "text":
                    continue
                seen_ids.add(msg["id"])
                reply = ask_claude(msg["text"]["body"])
                send_text(msg["from"], reply)
    return "ok", 200
 
 
def ask_claude(text: str) -> str:
    response = claude.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=400,
        system=SYSTEM,
        messages=[{"role": "user", "content": text}],
    )
    return response.content[0].text
 
 
def send_text(to: str, body: str) -> None:
    requests.post(
        f"{GRAPH}/{PHONE_ID}/messages",
        headers={"Authorization": f"Bearer {TOKEN}"},
        json={
            "messaging_product": "whatsapp",
            "to": to,
            "type": "text",
            "text": {"body": body},
        },
        timeout=15,
    ).raise_for_status()

A few points that matter in production:

  • Check the signature. Your webhook is a public URL. Without the X-Hub-Signature-256 check, anyone could send it fake messages.
  • Ignore repeats. Meta retries a delivery if your server is slow or fails, so the same message can arrive twice. Store message IDs and skip any you have seen.
  • Reply to Meta quickly. For slow work such as transcription, return 200 first and do the work in a background job.
  • Keep conversation history. The example sends only the latest message. A real assistant stores recent messages for each customer, so "and on Sunday?" makes sense.
  • Set the Graph API version yourself. Meta releases new versions regularly. Keep the version in configuration and check the changelog when you upgrade.

Adding voice notes

Many customers would rather speak than type. A voice note arrives as a message of type audio with a media ID. Your app asks the Graph API for the media URL, downloads the file with the same access token, and sends it to a speech-to-text service.

WhatsApp voice notes are usually OGG files with Opus audio. Converting them to 16 kHz mono WAV with ffmpeg before transcription avoids format problems with many speech services.

We used Azure AI Speech and learned two things:

  • Pick the right locale. For Urdu speech-to-text we had to use ur-IN. The ur-PK locale supported text-to-speech only at the time we built it. Check the service's current language support table before you assume a locale works.
  • Detect the language by comparing confidence. We ran recognition with both English and Urdu and kept the result with the higher confidence score. This was more reliable for our mixed-language users than trusting a single guess.

Replying in the right language took more than "reply in the user's language" in the prompt. Customers mix English and Roman Urdu in the same sentence. Explicit rules in the system prompt, for example "if the customer writes Urdu words in Latin letters, reply in Roman Urdu, not Urdu script", gave consistent results.

The setup traps that cost us days

These problems don't show up as clear errors. You just stop receiving messages, or replies fail without an obvious reason.

  1. Subscribe your app to the WhatsApp Business Account. Without this step, incoming messages silently stop arriving at your webhook, even though the configuration screen looks correct.
  2. Temporary tokens expire after 24 hours. The token on the getting-started page is for testing only. For anything that runs unattended, create a system user in Meta Business settings and generate a long-lived token with only the WhatsApp permissions you need.
  3. Long tokens can get cut off. Pasting a very long token into a terminal sometimes truncated it for us. Put secrets in environment variables or your host's secret store, and check the length.
  4. The 24-hour customer service window. You can send free-form replies only within 24 hours of the customer's last message. Outside that window, you can only send pre-approved template messages. Design follow-ups around this rule from the start.

What it costs to run

There are three running costs: WhatsApp messages, the AI model, and hosting.

WhatsApp. Meta has charged per delivered message since July 2025. Messages from customers to you are not charged. From 1 October 2026, replies inside the customer service window became paid again after a free tier of 1,000 service messages per business phone number each month. Templates (marketing, utility and authentication) are charged at rates that depend on the category and the customer's country. Prices change, so check Meta's pricing page for your market before you estimate a budget.

The AI model. Short, focused replies are cheap per message, but costs grow with long conversation histories and long system prompts. Set max_tokens, trim old history, and consider a smaller model for simple questions.

Hosting. A webhook needs very little power, but it must always be online. Our cloud deployment was paused when a free tier ran out, so plan for a small paid plan if customers depend on the bot.

Guardrails before you go live

An assistant that talks to your customers speaks for your business. Before launch:

  • Ground it in your facts. Put prices, hours and policies in the prompt or in a knowledge base. Tell it to say "I don't know" rather than guess.
  • Hand over to a human. Give customers a clear way to reach a person, and have the bot pass on complaints, payments and anything unusual.
  • Never let it promise money. Refunds, discounts and custom prices should be confirmed by a person.
  • Protect customer data. Store only what you need, restrict who can read conversation logs, and say in your privacy policy that an AI handles first replies.
  • Test with awkward messages. Try rude messages, off-topic requests, mixed languages, and attempts to make it ignore its instructions.

If the assistant will later look up orders or update records, give it narrow, read-only tools first. Our guides on what makes an AI system agentic and MCP explain how to give an AI tools safely, and the California v. OpenAI case shows why testing matters.

Frequently asked questions

Can I use the normal WhatsApp Business app for an AI assistant?

Not reliably. The free WhatsApp Business app has quick replies and away messages but no supported way to connect an AI model. For automation, use the WhatsApp Business Platform (Cloud API).

Does the assistant need my own server?

You need a public HTTPS webhook. That can be a small cloud app, a serverless function, or a platform from a WhatsApp Business Solution Provider that hosts the webhook for you.

Can it understand voice notes?

Yes. Download the audio through the Graph API, transcribe it with a speech-to-text service, then handle the text like any other message.

Is a WhatsApp AI chatbot allowed under Meta's rules?

Assistants that serve your own business, such as answering customer questions, taking bookings or giving order updates, are allowed. Meta's terms bar general-purpose AI assistants that are not tied to a business function, except where the law requires Meta to allow them.

Takeaways

  • Keep the assistant narrow: your business, your facts, and a clear handover to a person.
  • Build in phases: a keyword bot first, then the LLM, then voice and languages.
  • Verify webhook signatures, ignore repeated messages, and use a long-lived system user token.
  • Plan around the 24-hour customer service window and Meta's per-message pricing.
  • Test with difficult and mixed-language messages before customers see it.

A WhatsApp assistant is one of the quickest ways for a small business to get real value from AI. It works best when it is built carefully and kept to a clear purpose.

Tags

  • #whatsapp
  • #chatbots
  • #ai-agents
  • #python
  • #customer-support

Written by

Osama Ghafoor, Founder, MYZATECH

Founder of MYZATECH, a founder-led studio building practical solutions with AI, automation, software, and cloud.

More about the founder

Keep reading

Have an idea worth building?

Let's explore how technology can help turn it into reality.

Start a Conversation