How to Build an AI Chatbot with Facebook Messenger, OpenAI, and Twilio Programmable Messaging using Python

October 06, 2025
Written by

How to Build an AI Chatbot with Facebook Messenger, OpenAI, and Twilio Programmable Messaging using Python

AI chatbots on Facebook Messenger offer businesses a scalable way to engage with customers where they already spend their time. Whether you're handling common questions, providing business information, or routing complex inquiries, an AI chatbot can significantly improve response times and customer satisfaction. 

In this tutorial, you'll learn how to build an AI-powered chatbot that responds to Facebook Messenger conversations using Python, FastAPI, OpenAI, and Twilio Programmable Messaging. By combining these technologies, you can create an intelligent assistant that automatically responds to customer inquiries on your Facebook Page, providing 24/7 support without manual intervention.

Prerequisites

To follow along with this tutorial, you'll need:

Building the application

Project setup

Open your terminal and create your project directory with the necessary structure:

mkdir facebook-messenger-chatbot
cd facebook-messenger-chatbot

Create a virtual environment to isolate your project dependencies:

python -m venv venv
source venv/bin/activate
# On Windows, use `venv\Scripts\activate`

Create a file named requirements.txt in your project root and add the following dependencies:

fastapi
twilio
openai
uvicorn
python-multipart
Python-dotenv

Install all dependencies:

pip install -r requirements.txt

Setting up environment variables

Create a .env file in your project root to store your credentials securely:

TWILIO_ACCOUNT_SID=your_account_sid
TWILIO_AUTH_TOKEN=your_auth_token
OPENAI_API_KEY=your_openai_api_key

You can find your Twilio credentials in your Twilio Console. After logging in, scroll down to the Account Info section on the main dashboard where you'll see your Account SID and Auth Token.

For your OpenAI API key, visit your OpenAI API keys page, create a new key, and copy it into your .env file.

Configuring Facebook Messenger with Twilio

Before writing code, you need to connect your Facebook Page to Twilio.

Navigate to the Channels page in the Twilio Console and click Facebook Messenger. Click Install, agree to the terms of service, and click Agree & Install. Click Connect with Facebook and log in to authorize Twilio to access your Facebook Pages.

After authorization, you'll configure your Facebook Page as a sender. Select your Facebook Page from the dropdown menu. In the Callback URL field, you'll enter your webhook URL once your application is running. For now, leave this blank and click Save.

Facebook Messenger is a user-initiated channel, meaning users must message your Facebook Page first before you can respond. Once a user sends a message, you have 24 hours to reply.

Building the FastAPI application

Create a file named main.py in your project root. This file will contain your FastAPI application that handles incoming messages and generates AI responses.

Start by importing the necessary libraries and initializing your clients:

import os
from fastapi import FastAPI, Request
from twilio.rest import Client
from openai import OpenAI
import uvicorn
from dotenv import load_dotenv

load_dotenv()

app = FastAPI(title="Facebook Messenger Chatbot")

twilio_client = Client(
    os.getenv("TWILIO_ACCOUNT_SID"),
    os.getenv("TWILIO_AUTH_TOKEN")
)

openai_client = OpenAI(
    api_key=os.getenv("OPENAI_API_KEY")
)

The load_dotenv() function loads your environment variables from the .env file. You initialize three clients: FastAPI for your web server, Twilio for sending messages, and OpenAI for generating AI responses.

Handling incoming messages

Create the webhook endpoint that receives messages from Twilio when users send messages to your Facebook Page:

@app.post("/webhook")
async def webhook(request: Request):
    try:
        form_data = await request.form()
        message_body = form_data.get("Body", "")
        from_number = form_data.get("From", "")
        to_number = form_data.get("To", "")
        print(f"Received message: '{message_body}' from {from_number}")
        if not message_body:
            return {"status": "ok"}

When a user sends a message to your Facebook Page, Twilio forwards it to this webhook as form data. The Body parameter contains the message text, From contains the sender's Messenger ID in the format messenger:<user_id>, and To contains your Facebook Page ID in the format messenger:<page_id>.

Generating AI responses with OpenAI

Add the OpenAI integration to generate intelligent responses to user messages:

response = openai_client.chat.completions.create(
    model="gpt-5-mini",
    messages=[
        {"role": "system", "content": """You are a helpful assistant for [Your Business Name], a [business type/description].

            Business Information:
            - Location: [Your address/city]
            - Hours: Monday to Friday, 9am to 5pm
            - Services: [What you offer]
            - Phone: [Your phone number]
            - Website: [Your website]
            - Email: [Your email]

            Keep responses concise and friendly. If someone asks about our business, provide relevant information from above. For general questions, be helpful as usual."""},
        {"role": "user", "content": message_body}
    ]
)

ai_message = response.choices[0].message.content
print(f"AI response: {ai_message}")

The system message customizes the AI's behavior to act as a business assistant with specific information about your company. You can modify this system prompt to match your business details and desired chatbot personality. The model processes the user's message and generates an appropriate response based on the context you've provided.

Sending responses back via Twilio

Complete the webhook by sending the AI-generated response back to the user through Twilio:

message = twilio_client.messages.create(
        body=ai_message,
        from=to_number,
        to=from_number
    )
    print(f"Sent message SID: {message.sid}")
except Exception as e:
    print(f"Error processing webhook: {e}")
return {"status": "ok"}

The from parameter uses the to_number from the incoming webhook (your Facebook Page ID), and the to parameter uses the from_number (the user's Messenger ID). This reversal sends the response back to the correct user. Always return a 200 status code to Twilio to acknowledge receipt of the webhook, even if errors occur during processing.

Adding the application entry point

Add the final lines to run your FastAPI application:

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

This allows you to run your application directly with python main.py.

Testing your chatbot

Now you'll verify your chatbot works correctly by exposing your local server to the internet and configuring Twilio to use it.

Starting your server

Run your FastAPI application:

python main.py

You should see output indicating the server is running on http://0.0.0.0:8000.

Exposing your webhook with ngrok

In a new terminal window, start ngrok to create a public URL:

ngrok http 8000

Copy the https forwarding URL from the ngrok output. It will look like https://abc123.ngrok.io.

Configuring your Twilio webhook

Return to the Channels page in the Twilio Console and click Facebook Messenger. Find your configured Facebook Page and click to edit it. In the Callback URL field, enter your ngrok URL followed by /webhook:

https://your-ngrok-url.ngrok.io/webhook

Click Save to update your configuration.

Sending test messages

Open Facebook Messenger on your phone or computer and search for your Facebook Page. Send a message to your page, such as "What are your business hours?" Your chatbot should respond within a few seconds with an AI-generated answer based on the system prompt you configured.

Chat with ACME Testing Services displaying business hours and contact info on a smartphone screen at 5
Chat with ACME Testing Services displaying business hours and contact info on a smartphone screen at 5

Check your terminal running the FastAPI application to see the logged messages showing the received text, AI response, and sent message SID.

Troubleshooting

Bot not responding to messages

If your chatbot doesn't respond when you message your Facebook Page, verify the following:

  • Your ngrok URL is correctly entered in the Twilio Console webhook configuration
  • Your FastAPI application is running without errors
  • All environment variables in your .env file are set correctly
  • You're messaging the correct Facebook Page that's connected to Twilio

Check your terminal logs for error messages that might indicate what's failing.

OpenAI API errors

If you see OpenAI-related errors in your logs, confirm that your OpenAI API key is valid and that your OpenAI account has available credits. You can check your usage and billing at platform.openai.com.

Twilio authentication failures

If you receive authentication errors from Twilio, double-check that your Account SID and Auth Token in your .env file exactly match the credentials shown in your Twilio Console. Make sure there are no extra spaces or characters.

Next steps

Your basic chatbot is working, but there are several ways you could enhance it for production use. Consider adding conversation history by integrating the Twilio Conversations API to maintain context across multiple messages. You could implement webhook signature validation to verify requests actually come from Twilio, protecting your endpoint from unauthorized access.

For handling higher volumes of messages, add rate limiting to prevent abuse and manage OpenAI API costs. You might also store conversations in a database for analytics and training purposes. To support richer interactions, explore handling media messages like images and videos that users might send.

Wrapping Up

In this post, you built an AI-powered chatbot that integrates Facebook Messenger, OpenAI, and Twilio using Python and FastAPI. You learned how to receive messages through Twilio's webhook, generate intelligent responses with OpenAI's GPT model, and send replies back to users on Facebook Messenger. This foundation gives you a scalable starting point for building sophisticated conversational experiences.

To learn more about Twilio's Facebook Messenger integration, check out the Facebook Messenger documentation and explore additional Twilio Programmable Messaging features.

Happy building!

Dylan Frankcom is a Python Software Engineer on Twilio's Developer Voices team. He's passionate about building tools that help developers learn, create, and ship faster. You can reach him at dfrankcom [at] twilio.com or find him on LinkedIn .