How to Build a Facebook Messenger AI Bot
Create a Messenger bot that qualifies leads and handles support.
Jay Banlasan
The AI Systems Guy
A facebook messenger ai chatbot for your business does two jobs at once: it handles support questions and qualifies leads while you sleep. I run these for clients who get a steady flow of Messenger inquiries from their Facebook ads. Instead of those messages sitting unread, the bot responds in seconds.
The architecture is similar to WhatsApp bots but uses Meta's Messenger Platform API. Same webhook pattern, same AI backend.
What You Need Before Starting
- A Facebook Page for your business
- A Meta Developer account with a Messenger app
- Python 3.8+ with Flask
- An AI API key (Anthropic or OpenAI)
- A public webhook URL
Step 1: Configure the Messenger Platform
In Meta Developer Portal, create an app and add the Messenger product. Subscribe to your Page and get a Page Access Token:
PAGE_ACCESS_TOKEN=your_page_token
VERIFY_TOKEN=your_verify_string
Subscribe to messages and messaging_postbacks webhook events.
Step 2: Build the Webhook Handler
from flask import Flask, request, jsonify
import requests
import anthropic
import os
app = Flask(__name__)
client = anthropic.Anthropic()
PAGE_TOKEN = os.getenv("PAGE_ACCESS_TOKEN")
@app.route("/webhook", methods=["GET"])
def verify():
if request.args.get("hub.verify_token") == os.getenv("VERIFY_TOKEN"):
return request.args.get("hub.challenge"), 200
return "Forbidden", 403
@app.route("/webhook", methods=["POST"])
def webhook():
data = request.json
for entry in data.get("entry", []):
for event in entry.get("messaging", []):
if event.get("message"):
sender_id = event["sender"]["id"]
text = event["message"].get("text", "")
if text:
handle_message(sender_id, text)
return "OK", 200
Step 3: Add Lead Qualification Logic
The bot classifies intent first. Support questions get answered. Buying signals get qualified:
SYSTEM_PROMPT = """You are an assistant for [Your Business] on Facebook Messenger.
Your two jobs:
1. Answer support questions using the knowledge base below.
2. Qualify leads by asking: What service they need, their timeline, and their budget range.
When someone shows buying intent (asks about pricing, availability, booking), switch to qualification mode.
When you have all three qualification answers, say: "Let me connect you with our team to get this set up."
KNOWLEDGE BASE:
[Your FAQ content here]"""
def handle_message(sender_id, text):
history = get_conversation(sender_id)
history.append({"role": "user", "content": text})
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=400,
system=SYSTEM_PROMPT,
messages=history
)
reply = response.content[0].text
save_message(sender_id, "user", text)
save_message(sender_id, "assistant", reply)
send_messenger_reply(sender_id, reply)
if "connect you with our team" in reply.lower():
notify_sales_team(sender_id, history)
Step 4: Send Replies Through the API
def send_messenger_reply(recipient_id, text):
url = "https://graph.facebook.com/v18.0/me/messages"
payload = {
"recipient": {"id": recipient_id},
"message": {"text": text},
"messaging_type": "RESPONSE"
}
headers = {"Authorization": f"Bearer {PAGE_TOKEN}"}
requests.post(url, json=payload, headers=headers)
Step 5: Notify Your Team on Qualified Leads
When the bot qualifies a lead, send the full context to your sales channel:
def notify_sales_team(sender_id, conversation):
summary = "\n".join([f"{m['role']}: {m['content']}" for m in conversation])
slack_webhook = os.getenv("SLACK_WEBHOOK_URL")
requests.post(slack_webhook, json={
"text": f"New qualified lead from Messenger:\n{summary}"
})
What to Build Next
Add quick reply buttons for common paths. Messenger supports structured messages with buttons, carousels, and templates. These guide users down specific flows and reduce the number of open-ended messages the AI has to handle.
Related Reading
- Lead Scoring with AI - how to score and prioritize leads from chat channels
- AI in Customer Service - the complete view of AI-powered customer interactions
- Automation Chains: When One Trigger Creates Twenty Actions - how a single Messenger message can trigger a full workflow
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