Before running the code:
1. **Create accounts**:
* [OpenAI](https://platform.openai.com/)
* [Twilio](https://www.twilio.com/whatsapp)
2. **Get your keys**:
* Twilio **Account SID**, **Auth Token**, and **WhatsApp sandbox number**
* OpenAI **API Key**
3. **Install dependencies**:
bash
pip install flask openai twilio python-dotenv
WhatsApp + GPT Chatbot –
app.py
python
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
import openai
import os
from dotenv import load_dotenv
load_dotenv() # Load .env file
# OpenAI API Key
openai.api_key = os.getenv("OPENAI_API_KEY")
app = Flask(__name__)
@app.route("/bot", methods=["POST"])
def bot():
incoming_msg = request.values.get("Body", "").strip()
print(f"Received: {incoming_msg}")
# Create GPT response
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", # or gpt-4
messages=[
{"role": "system", "content": "You are a helpful WhatsApp assistant."},
{"role": "user", "content": incoming_msg}
]
)
reply = response.choices[0].message['content'].strip()
# Send reply via Twilio
twilio_response = MessagingResponse()
twilio_response.message(reply)
return str(twilio_response)
if __name__ == "__main__":
app.run(port=5000)
.env
File
Create a
.env
file in the same directory:
env
OPENAI_API_KEY=your_openai_api_key_here
Twilio Setup
1. Go to Twilio Console → Programmable Messaging → WhatsApp
2. Use the sandbox number (e.g.,
whatsapp:+14155238886
)
3. Set **Webhook URL** (e.g., using [ngrok](https://ngrok.com/)):
bash
ngrok http 5000
Set the **inbound message webhook** to:
https://your-ngrok-url.ngrok.io/bot
Test It
Send a WhatsApp message to your Twilio sandbox number like:
> Hello, what can you do?
And you’ll receive an AI-generated response via WhatsApp!