Build a 24/7 WhatsApp AI Assistant in 4 Simple Steps

In the last article, we discussed the game-changing impact of having an AI assistant that handles customer queries and closes deals on WhatsApp while you sleep. The response was overwhelming, with one common question: "How do I actually build it?"

Build-WhatsApp-AI-Assistant-in-4 Simple-Steps
Image by Author | Created with AI

This guide will demystify the process. While it involves a few technical steps, the tools available today have made it more accessible than ever. We're going to build a foundational version of your AI assistant that you can then expand and customize over time.

The procedure may be divided into three fundamental parts:

  • "Brain": The Large Language Model (LLM) that produces responses (e.g., OpenAI's GPT).
  • "Mouth": The official WhatsApp Business API for sending and receiving messages.
  • "Nervous System": The code that links the brain to the mouth.

Prerequisites: What You'll Need

{inAds}

Before we start, let’s collect the required elements:

  • A dedicated phone number — It must not already be used by any WhatsApp personal or business account.

  • A Meta for Developers Account — Free to create at developers.facebook.com.

  • An OpenAI API Account — Needed to get your API key; you can create one at platform.openai.com.

  • A Platform for Your Code — We’ll use Replit, a free service that includes both a server and code editor.

Step 1: Set Up Your "Mouth" (WhatsApp Business API)

First, we need to connect to WhatsApp. We’ll start by using a temporary test number provided by Meta — perfect for development.

  1. Create a Meta App: Visit developers.facebook.com, go to “My Apps,” then “Create App.” Choose “Other” as the use case and select “Business.”

  2. Add the WhatsApp Product: On your new app’s dashboard, scroll down to find “WhatsApp” and click “Set up.”

  3. Get Your Credentials: After setup, you’ll land on the “API Setup” page. Keep it open — it includes three essential details:

    • A test phone number for sending messages

    • A Phone Number ID (unique to your bot’s number — required for sending replies)

    • A temporary Access Token (your app’s password)

You can now use this interface to send a test message to your personal WhatsApp number and verify that it’s working.

Step 2: Prepare Your AI "Brain" (OpenAI)

{inAds}

Now it’s time to give your AI the ability to think and talk.

  1. Get Your OpenAI API Key: Log in to platform.openai.com, go to “API Keys,” create a new secret key, and store it securely.

  2. Create Your System Prompt: This is crucial — it defines your AI’s personality and behavior. Write a clear, specific instruction that shapes how your assistant responds.

Example System Prompt:

You are a warm and efficient support and sales assistant for GlowUp Skincare, a brand that sells organic, vegan skincare products.
Your tone is friendly, informative, and a little enthusiastic.
You answer product questions, help customers choose the right items, and share order updates.
If you’re unsure or the customer is upset, say: “That’s a great question, I’ll transfer you to a human team member who can help.”

Step 3: Build the "Nervous System" (The Code)

{inAds}

This connects everything. The following corrected code handles text messages only, ignoring images or stickers to prevent crashes.

  1. Set Up on Replit: Create a free account, then start a new “Python (with Flask)” project.

  2. Store Your Secrets: In Replit, use the Secrets tab (on the left sidebar) to safely save your credentials:

    • OPENAI_API_KEY: Your OpenAI key

    • WHATSAPP_TOKEN: Your temporary Access Token

    • WHATSAPP_PHONE_NUMBER_ID: Your Meta phone number ID

  3. Replace the Default Code in main.py with:

from flask import Flask, request, jsonify
import openai
import requests
import os
import time

app = Flask(__name__)

# --- Load Your Secure Credentials ---
# Best practice: handle cases where secrets might not be set
try:
    OPENAI_API_KEY = os.environ['OPENAI_API_KEY']
    WHATSAPP_TOKEN = os.environ['WHATSAPP_TOKEN']
    WHATSAPP_PHONE_NUMBER_ID = os.environ['WHATSAPP_PHONE_NUMBER_ID']
    # It's better to store this as a secret too
    VERIFY_TOKEN = os.environ.get('VERIFY_TOKEN', "your-strong-random-verify-token")
except KeyError as e:
    print(f"ERROR: Missing environment variable {e}. Please set it in Replit Secrets.")
    # You might want to exit or handle this more gracefully
    exit()


# --- System Configuration ---
SYSTEM_PROMPT = """
You are a warm and efficient support and sales assistant for GlowUp Skincare, a brand that sells organic, vegan skincare products.
Your tone is friendly, informative, and a little enthusiastic.
You answer product questions, help customers choose the right items, and share order updates.
If you’re unsure or the customer is upset, say: “That’s a great question, I’ll transfer you to a human team member who can help.”
Keep your answers concise and clear, suitable for a WhatsApp chat.
"""

# In-memory storage for conversation history.
# For production, you would replace this with a database like Redis or Firestore.
conversation_history = {}

openai.api_key = OPENAI_API_KEY

@app.route('/webhook', methods=['GET', 'POST'])
def webhook():
    if request.method == 'GET':
        # --- Webhook Verification from Meta ---
        if request.args.get('hub.verify_token') == VERIFY_TOKEN:
            return request.args.get('hub.challenge')
        return "Verification token mismatch", 403

    # --- Handle Incoming WhatsApp Messages ---
    try:
        data = request.get_json()
       
        # A more robust way to parse the incoming payload
        changes = data.get('entry', [])[0].get('changes', [])[0]
        message_data = changes.get('value', {}).get('messages', [{}])[0]

        # Ignore notifications or non-text messages
        if message_data.get('type') != 'text':
            return jsonify({"status": "ok"}), 200

        user_phone_number = message_data['from']
        user_message = message_data['text']['body']

        # --- Manage Conversation History ---
        now = time.time()
        if user_phone_number not in conversation_history:
            conversation_history[user_phone_number] = {'messages': [], 'last_seen': now}

        # Reset conversation if user was inactive for more than 10 minutes (600 seconds)
        if now - conversation_history[user_phone_number]['last_seen'] > 600:
            conversation_history[user_phone_number]['messages'] = []
           
        conversation_history[user_phone_number]['messages'].append({"role": "user", "content": user_message})
        conversation_history[user_phone_number]['last_seen'] = now

        # Keep the history to a reasonable length (e.g., last 10 messages)
        final_messages = conversation_history[user_phone_number]['messages'][-10:]


        # --- Get AI Response ---
        response = openai.chat.completions.create(
            model="gpt-4-turbo",
            messages=[
                {"role": "system", "content": SYSTEM_PROMPT},
                *final_messages  # Unpack the conversation history
            ]
        )
        ai_response = response.choices[0].message.content

        # Add AI response to history
        conversation_history[user_phone_number]['messages'].append({"role": "assistant", "content": ai_response})

        # --- Send AI Response via WhatsApp API ---
        url = f"https://graph.facebook.com/v19.0/{WHATSAPP_PHONE_NUMBER_ID}/messages"
        headers = {
            "Authorization": f"Bearer {WHATSAPP_TOKEN}",
            "Content-Type": "application/json"
        }
        payload = {
            "messaging_product": "whatsapp",
            "to": user_phone_number,
            "text": {"body": ai_response}
        }
       
        # Use a session object for potentially better performance
        with requests.Session() as s:
            s.post(url, headers=headers, json=payload)

    except Exception as e:
        # Log the error for debugging
        print(f"Error processing webhook: {e}")
        # It's good practice to still return a 200 OK to WhatsApp
        # to prevent it from resending the webhook.
   
    return jsonify({"status": "ok"}), 200

if __name__ == '__main__':
    # Replit runs on port 81 by default when using host='0.0.0.0'
    app.run(host='0.0.0.0', port=81)

Step 4: Connect and Test!

{inAds}

Time to bring your bot to life:

  1. Run your Replit app — click the green “Run” button. Replit will generate a public URL (e.g., https://your-project-name.replit.dev).

  2. Set Up Your Webhook — go back to your Meta App’s WhatsApp dashboard:

    • Click “Configuration.”

    • In the “Webhook” section, click “Edit.”

    • Add your Replit URL (ending with /webhook).

    • Enter your exact VERIFY_TOKEN value.

  3. Subscribe to Messages — click “Manage” next to the webhook and enable the “messages” field.

  4. Test It! — Send a WhatsApp message to your test number.

If everything is configured properly, your AI assistant will respond within seconds! The try...except block ensures your bot won’t crash if an error occurs.

×