A WhatsApp bot that integrates with CustomGPT's API to provide intelligent responses from your agent's knowledge base.
More information on GitHub - https://github.com/Poll-The-People/customgpt-integrations
Get your CustomGPT.ai RAG API key here, needed to use this integration.
Features
- AI-Powered Responses: Uses CustomGPT's knowledge base
- Security: Rate limiting, user authentication, query validation
- Rich Interactions: Starter questions, inline buttons, media support
- Analytics: Usage tracking and statistics
- Multi-language Support: Configurable response language
- Performance: Response caching, session management
- Easy Deployment: Multiple free hosting options
Prerequisites
- Python 3.8+
- CustomGPT API credentials (API key and Agent ID)
- Twilio account with WhatsApp sandbox access
Quick Start (15 minutes)
1. Clone and Install
cd whatsapp
pip install -r requirements.txt2. Configuration
Create a .env file:
# CustomGPT Configuration
CUSTOMGPT_API_KEY=your_api_key_here
CUSTOMGPT_PROJECT_ID=your_agent_id_here
CUSTOMGPT_API_URL=https://app.customgpt.ai
# Twilio Configuration
TWILIO_ACCOUNT_SID=your_account_sid_here
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_WHATSAPP_NUMBER=whatsapp:+14155238886
# Rate Limiting
RATE_LIMIT_DAILY=100
RATE_LIMIT_MINUTE=5
RATE_LIMIT_HOUR=30
# Security
ALLOWED_NUMBERS=+1234567890,+0987654321 # Optional: Whitelist specific numbers
BLOCKED_NUMBERS=+1111111111 # Optional: Block specific numbers
MAX_MESSAGE_LENGTH=500
# Redis (for production)
REDIS_URL=redis://localhost:6379 # Optional: For persistent rate limiting
# Features
ENABLE_VOICE_MESSAGES=true
ENABLE_MEDIA_RESPONSES=true
ENABLE_LOCATION_SHARING=false
DEFAULT_LANGUAGE=en3. Set Up Twilio WhatsApp Sandbox
Get Twilio Credentials
- Sign up at twilio.com (free trial with $15 credit)
- Log in to Twilio Console
- Go to "Account" → "API keys & tokens" OR click Phone Number section (choose "developer" when logging in)
- Note your:
- Account SID (starts with "AC")
- Auth Token
- WhatsApp number
Join WhatsApp Sandbox
- In Twilio Console, go to "Messaging" → "Try it out" → "Send a WhatsApp message"
- Follow instructions to join the sandbox
- You'll send "join [your-keyword]" to the Twilio WhatsApp number
- Note your sandbox number (e.g.,
whatsapp:+14155238886)
4. Run the Bot
Important: You need TWO terminal windows for local development:
Terminal 1 - Run the bot:
# Development mode
python bot.py
# OR Production mode with uvicorn
uvicorn bot:app --host 0.0.0.0 --port 8000Terminal 2 - Run ngrok (for local testing):
# First time: Sign up at https://dashboard.ngrok.com and get your authtoken
ngrok config add-authtoken YOUR_AUTH_TOKEN
# Then expose your local server
ngrok http 8000📌 Both must be running simultaneously for the bot to work!
5. Configure Twilio Webhook
- Copy the HTTPS URL from ngrok (e.g.,
https://abc123.ngrok-free.app) - In Twilio Console, go to Messaging → Try it out → Send a WhatsApp message
- In "Sandbox Configuration", set webhook URL to:
https://YOUR-NGROK-URL.ngrok-free.app/webhook/whatsapp - Method: POST
- Save the configuration
- Test by sending a message!
⚠️ Note: ngrok URL changes each time you restart it. Update Twilio webhook accordingly.
6. Test Your Bot
- Send "Hi" to your Twilio WhatsApp number
- You should receive a welcome message
- Try asking questions related to your CustomGPT knowledge base
ngrok Setup Guide (Detailed)
Step 1: Create ngrok Account
- Go to https://dashboard.ngrok.com/signup
- Sign up for a free account (no credit card required)
- Verify your email
Step 2: Get Your Auth Token
- After signing in, go to: https://dashboard.ngrok.com/get-started/your-authtoken
- Copy your authtoken (looks like:
2abc123XYZ...)
Step 3: Configure ngrok
ngrok config add-authtoken YOUR_AUTH_TOKEN_HEREStep 4: Start ngrok
ngrok http 8000You'll see output like:
Session Status online
Account [email protected]
Forwarding https://abc123.ngrok-free.app -> http://localhost:8000
Troubleshooting ngrok
Bot not responding?
- Check ngrok is still running
- Check your bot is running (
python bot.py) - Check Twilio webhook URL is correct
- Look for errors in bot terminal
ngrok URL changed?
- ngrok free tier gives you a new URL each time
- When you restart ngrok: copy new URL → update in Twilio Console → save
Want a permanent URL?
- Upgrade to ngrok paid plan for custom domains
- Or use deployment options (Railway, Render, etc.)
WhatsApp Sandbox Limitations
You're currently using the FREE Twilio WhatsApp Sandbox, which has these limitations:
- Join Required: Users must first send "join [your-keyword]" to activate
- 24-Hour Window: You can only reply within 24 hours of receiving a message
- Shared Number: Messages come from Twilio's number, not your own
- Development Only: Not suitable for production use
After 24 hours of inactivity, you can only send pre-approved template messages (requires paid account).
Sandbox vs Production Comparison
| Feature | Sandbox (Free) | Production (Paid) |
|---|---|---|
| Cost | Free | ~$15/month + $0.005/message |
| Phone Number | Twilio's shared number | Your own business number |
| User Onboarding | Must send "join [keyword]" | Direct messaging |
| Message Window | 24 hours after user message | 24 hours + templates |
| Business Profile | Twilio's profile | Your verified business |
| Suitable For | Development & testing | Real customers |
| Account Type | Trial account OK | Paid account required |
| Setup Time | 5 minutes | 2-5 days (verification) |
Getting Your Own WhatsApp Business Number
To get your own WhatsApp Business number (Required for production):
- Upgrade to paid Twilio account (trial accounts can't register WhatsApp senders)
- Register your WhatsApp Business Profile
- Get Facebook Business verification
- Submit message templates for approval
- Monthly fees apply + per-message costs
Learn more: Twilio WhatsApp API Docs
Deployment Options
Complete guide for deploying your CustomGPT WhatsApp bot to various free hosting providers.
Option 1: Railway (Recommended)
Free Tier: 500 hours/month, $5 credit
Steps:
-
Sign up at railway.app
-
Install Railway CLI (optional):
npm install -g @railway/cli -
Deploy via GitHub:
- Push your code to GitHub
- Click "New Project" → "Deploy from GitHub repo"
- Select your repository
- Railway auto-detects Python
-
Configure Environment Variables:
- Go to your project → Variables
- Add all variables from
.env:CUSTOMGPT_API_KEY=your_key CUSTOMGPT_PROJECT_ID=your_id TWILIO_ACCOUNT_SID=your_sid TWILIO_AUTH_TOKEN=your_token TWILIO_WHATSAPP_NUMBER=whatsapp:+14155238886 RATE_LIMIT_DAILY=100 # ... add all other variables
-
Get your URL:
- Go to Settings → Domains
- Your URL will be like:
https://your-app.up.railway.app
-
Configure Twilio Webhook:
- In Twilio Sandbox settings
- Set webhook URL:
https://your-app.up.railway.app/webhook/whatsapp - Method: POST
- Save
CLI Deployment:
# Login
railway login
# Initialize project
railway init
# Link to existing project
railway link
# Deploy
railway up
# View logs
railway logsOption 2: Render
Free Tier: 750 hours/month
Steps:
-
Sign up at render.com
-
Create New Web Service:
- Click "New +" → "Web Service"
- Connect GitHub repository
- Select your repo
-
Configure Service:
- Name:
customgpt-whatsapp-bot - Environment:
Python 3 - Build Command:
pip install -r requirements.txt - Start Command:
python bot.py
- Name:
-
Add Environment Variables:
- Go to Environment tab
- Add all variables from
.env
-
Deploy:
- Click "Create Web Service"
- Wait for deployment
- Note your URL:
https://your-app.onrender.com
-
Configure Twilio:
- Set webhook:
https://your-app.onrender.com/webhook/whatsapp
- Set webhook:
Option 3: Fly.io
Free Tier: 3 shared-cpu-1x VMs
Steps:
-
Install Fly CLI:
curl -L https://fly.io/install.sh | sh -
Sign up and login:
fly auth signup # or fly auth login -
Launch app:
cd whatsapp fly launch- Choose app name
- Select region (closest to you)
- Don't deploy yet
-
Configure secrets:
fly secrets set CUSTOMGPT_API_KEY="your_key" fly secrets set CUSTOMGPT_PROJECT_ID="your_id" fly secrets set TWILIO_ACCOUNT_SID="your_sid" fly secrets set TWILIO_AUTH_TOKEN="your_token" fly secrets set TWILIO_WHATSAPP_NUMBER="whatsapp:+14155238886" # Set all other secrets -
Deploy:
fly deploy -
Get URL:
fly status # Your URL: https://your-app.fly.dev -
Configure Twilio:
- Set webhook:
https://your-app.fly.dev/webhook/whatsapp
- Set webhook:
Option 4: Google Apps Script
Free Tier: Unlimited (with quotas)
Simplest option - no server needed!
Steps:
-
Go to script.google.com
-
Create new project
-
Copy code from
google-apps-script/Code.gs -
Set Script Properties:
- Project Settings → Script Properties
- Add all required properties
-
Deploy:
- Deploy → New Deployment
- Type: Web app
- Execute as: Me
- Access: Anyone
-
Get URL and configure in Twilio
⚠️ Warning: May timeout with complex queries (only "Thinking..." message sent)
See detailed instructions in google-apps-script/README.md
Other Free Alternatives
Koyeb
Free Tier: 2 services, 1 vCPU, 256MB RAM
# Install CLI
curl -fsSL https://cli.koyeb.com/install.sh | sh
# Deploy
koyeb app create customgpt-whatsapp
koyeb service create customgpt-whatsapp \
--git github.com/yourusername/yourrepo \
--git-branch main \
--ports 8000:http \
--routes /:8000Cyclic.sh
Free Tier: 10,000 requests/month
- Connect GitHub at cyclic.sh
- Select repository
- Add environment variables
- Deploy
Deta Space
Free Tier: Always free, 10GB storage
# Install Space CLI
curl -fsSL https://get.deta.dev/space-cli.sh | sh
# Deploy
space new
space pushDeployment Comparison
| Platform | Free Tier | Best For | Persistent Storage | Setup Time |
|---|---|---|---|---|
| Railway | $5 credit/month | Production | Yes | 10 min |
| Render | 750 hrs/month | Web services | Yes | 15 min |
| Fly.io | 3 shared VMs | Performance | Yes | 10 min |
| Google Apps Script | Unlimited* | Simple bots | No | 5 min |
| Koyeb | 2 services | Small projects | Yes | 10 min |
*With quotas
Post-Deployment
1. Test Your Bot
- Send "Hi" to your Twilio WhatsApp number
- Check for welcome message
- Test all commands
2. Monitor Logs
- Railway:
railway logs - Render: Dashboard → Logs
- Fly.io:
fly logs - Apps Script: View → Logs
3. Set Up Monitoring
-
Uptime monitoring:
- Use uptimerobot.com (free)
- Monitor:
https://your-app.com/health
-
Error tracking:
- Add Sentry (free tier)
- Or use built-in logging
4. Configure Production WhatsApp
Once tested, apply for WhatsApp Business API:
- Apply through Twilio
- Get approved number
- Update webhook URL
Bot Commands
/start- Start conversation and show menu/help- Show available commands/examples- Show example questions/stats- View usage statistics/language [code]- Change response language/clear- Clear conversation history/feedback- Submit feedback
Implementation Options
Option 1: Twilio WhatsApp API (Currently Implemented) ✅
- Pros: Official API, reliable, quick setup, free sandbox
- Cons: Costs for production, requires Twilio account
- Best for: Rapid development, business use, production deployments
Option 2: Meta WhatsApp Business API (Direct)
- Pros: Direct integration, no middleman fees
- Cons: Complex setup, business verification required (2-4 weeks), hosting requirements
- Best for: Large enterprises with dedicated infrastructure
Why Not Use Meta's Direct API?
You absolutely can! But consider:
- Business Verification: Meta requires extensive business documentation
- Setup Complexity: Multiple steps across Meta Business, Facebook App, WhatsApp Manager
- Hosting Requirements: Need HTTPS webhooks, SSL certificates
- Approval Process: Can take 2-4 weeks for production access
Twilio Alternatives:
- MessageBird - Similar to Twilio, good European option
- Vonage (Nexmo) - Enterprise-focused
- CM.com - Good for high-volume
- 360dialog - Direct WhatsApp BSP
- WATI - No-code option with UI
Option 3: Google Apps Script (Alternative Implementation)
- Pros: Free hosting, easy deployment, no server needed
- Cons: Limited features, requires Twilio, may timeout on long responses
- Best for: Simple bots, testing, short responses
Why Twilio and Redis?
Why Twilio for WhatsApp?
WhatsApp has strict policies about third-party integrations. There are only two official ways to create WhatsApp bots:
-
WhatsApp Business API (Direct)
- Requires business verification (can take weeks)
- Complex setup with Facebook Business Manager
- Need to host your own webhook server
- Monthly fees even for small usage
- Best for: Large enterprises
-
WhatsApp Business API (via Providers like Twilio)
- Quick setup (minutes, not weeks)
- Free sandbox for testing
- Twilio handles the complex Meta/WhatsApp integration
- Pay-as-you-go pricing
- Best for: Most businesses and developers
Why Redis?
Redis is OPTIONAL! The bot includes built-in memory storage that works perfectly for:
- Personal use
- Small teams (< 100 users)
- Single server deployments
- Testing and development
Redis is only beneficial when you need:
- Multiple bot instances (load balancing)
- Persistent rate limiting across restarts
- Shared session data between servers
- Very high user volumes (> 1000 users)
Running Without Redis
This is already implemented! Just run the bot without setting REDIS_URL:
# The bot automatically uses in-memory storage when Redis is not available
# No configuration needed - it just works!Cost Comparison
Twilio Costs (Pay as you go)
- Sandbox: FREE (perfect for testing)
- Production: ~$0.005 per message
- Monthly: $0 (no minimum fees)
Direct Meta API Costs
- API Access: FREE
- But you need:
- SSL certificate (~$10-100/year)
- Server hosting (~$5-20/month)
- Domain name (~$12/year)
- Time for verification (2-4 weeks)
Redis Costs
- Development: FREE (built-in memory storage)
- Production Options:
- Redis Cloud: FREE tier (30MB)
- Self-hosted: FREE (on your server)
- Only needed for high-scale deployments
Architecture & Development
Core Components
-
Bot Entry Point (
bot.py)- FastAPI application handling Twilio webhooks at
/webhook/whatsapp - Async message processing with
process_message()function - Health check endpoint at
/health
- FastAPI application handling Twilio webhooks at
-
CustomGPT Integration (
customgpt_client.py)- Async client for CustomGPT API
- Session creation and message handling
- Supports both streaming and regular responses
- OpenAI format compatibility
-
Security Layer (
security_manager.py)- Phone number whitelist/blocklist validation
- Message content validation (SQL injection, XSS, command injection)
- Rate limit multiplier for admin users
- Profanity filtering (optional)
-
Rate Limiting (
rate_limiter.py)- Redis-backed with in-memory fallback
- Daily, hourly, and minute limits
- Per-user tracking and statistics
-
Session Management (
session_manager.py)- Conversation context storage
- Language preferences
- TTL-based session expiry
Development Commands
Local Development
# Install dependencies
pip install -r requirements.txt
# Run locally (development mode)
python bot.py
# Run with uvicorn (production mode)
uvicorn bot:app --host 0.0.0.0 --port 8000 --reloadTesting
# Run all tests
pytest
# Run with coverage
pytest --cov=. --cov-report=html
# Run specific test file
pytest test_bot.py -vCode Quality
# Format code
black .
# Sort imports
isort .
# Lint code
flake8 .
# Type checking
mypy .Docker
# Build image
docker build -t customgpt-whatsapp-bot .
# Run container
docker run -p 8000:8000 --env-file .env customgpt-whatsapp-botTwilio Webhook Flow
- Twilio sends POST request to
/webhook/whatsappwith form data - Bot extracts message details from form data (From, Body, MessageSid)
- Returns immediate TwiML response to acknowledge receipt
- Processes message asynchronously to avoid timeout
CustomGPT API Integration
- Uses session-based conversations (session_id required)
- Conversation creation requires a "name" field
- Messages API endpoint:
/api/v1/projects/{project_id}/conversations/{session_id}/messages - Supports streaming responses (not currently used in WhatsApp implementation)
Security Features
-
Rate Limiting
- Per-user daily/hourly/minute limits
- Automatic reset at midnight
- Customizable limits per user tier
-
Message Validation
- Maximum message length enforcement
- Spam detection
- SQL injection prevention
- Profanity filtering (optional)
-
User Authentication
- Phone number whitelist/blacklist
- Admin commands protection
- Session management
-
Data Protection
- No message logging by default
- Encrypted session storage
- GDPR compliance ready
Advanced Features
Starter Questions
The bot automatically suggests relevant questions based on:
- Your CustomGPT agent's knowledge base
- User's previous queries
- Popular questions
Rich Media Support
- Send and receive images
- Voice message transcription
- Document handling
- Location-based queries
Multi-turn Conversations
- Context retention across messages
- Session management
- Conversation history
Analytics Dashboard
- User engagement metrics
- Popular queries
- Response times
- Error tracking
Troubleshooting
Common Issues
-
Webhook not receiving messages
- Verify webhook URL in Twilio console
- Check ngrok tunnel if testing locally
- Ensure bot is running and accessible
-
Authentication Error - Invalid Username
- Your Account SID should start with "AC" (not "US" or other prefixes)
- Verify credentials in Twilio Console
- Test with curl command below
-
Rate limit errors
- Check Redis connection (optional)
- Verify rate limit settings
- Admin numbers get 10x higher limits
-
CustomGPT API errors
- Verify API credentials
- Check agent ID
- Ensure agent is active
Testing Twilio Credentials
Test your Twilio setup with this curl command:
curl 'https://api.twilio.com/2010-04-01/Accounts/YOUR_ACCOUNT_SID/Messages.json' -X POST \
--data-urlencode 'To=whatsapp:+1234567890' \
--data-urlencode 'From=whatsapp:+14155238886' \
--data-urlencode 'Body=Your appointment is coming up on July 21 at 3PM' \
-u YOUR_ACCOUNT_SID:YOUR_AUTH_TOKENReplace:
YOUR_ACCOUNT_SID: Your Twilio Account SID (starts with AC)YOUR_AUTH_TOKEN: Your Twilio Auth Token+1234567890: Your WhatsApp number (recipient)+14155238886: Your Twilio sandbox number (or your WhatsApp Business number)
Example Response (201 - CREATED):
{
"account_sid": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"api_version": "2010-04-01",
"body": "Your appointment is coming up on July 21 at 3PM",
"status": "queued",
"to": "whatsapp:+917978307903",
"from": "whatsapp:+14155238886"
}Status Codes:
201 Created: Message successfully queued for delivery400 Bad Request: Invalid parameters (check phone number format)401 Unauthorized: Invalid credentials429 Too Many Requests: Rate limit exceeded
Debugging Tips
- Check logs: The bot logs all incoming messages
- Test health endpoint:
curl http://localhost:8000/health - Verify webhook: Messages should appear in terminal
- Check Twilio Console: Look for webhook logs and errors
Debugging Webhook Issues
# Test webhook locally
curl -X POST http://localhost:8000/webhook/whatsapp \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "From=whatsapp:+1234567890&Body=test&MessageSid=123"Bot Not Responding
-
Check webhook URL:
curl -X POST https://your-app.com/webhook/whatsapp \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "From=whatsapp:+1234567890&Body=test" -
Check logs for errors
-
Verify environment variables are set
-
Test Twilio connection:
# Test script from twilio.rest import Client client = Client(account_sid, auth_token) message = client.messages.create( to='whatsapp:+1234567890', from_='whatsapp:+14155238886', body='Test message' )
Rate Limiting Issues
- Increase limits in environment variables
- Implement Redis for production
- Monitor usage with
/statscommand
Memory Issues
- Add Redis for session/rate limit storage
- Optimize code:
- Remove unused imports
- Use connection pooling
- Implement caching
SSL/Security Issues
- All platforms provide free SSL
- Never expose sensitive credentials
- Use environment variables only
Scaling Considerations
When you outgrow free tiers:
-
Upgrade hosting:
- Railway: Pay as you go
- Render: $7/month starter
- Fly.io: Pay for additional resources
-
Add Redis:
- Redis Cloud free tier (30MB)
- Or upgrade to paid Redis
-
Implement queuing:
- For high message volume
- Use Redis + background workers
-
Multiple instances:
- Load balance across instances
- Share Redis for state
Security Best Practices
-
Environment Variables:
- Never commit
.envfile - Use platform secret management
- Never commit
-
Webhook Security:
- Validate Twilio signatures
- Implement request validation
-
Rate Limiting:
- Always enabled
- Monitor for abuse
-
Access Control:
- Implement phone number whitelist
- Admin commands protection
Quick Setup Checklist
Before troubleshooting, ensure:
- Bot is running (
python bot.py) - Terminal 1 - ngrok is running (
ngrok http 8000) - Terminal 2 - Webhook URL is updated in Twilio Console
- You've joined the sandbox (sent "join [keyword]")
- Your phone number is in
ALLOWED_NUMBERSin.env
Resources
CustomGPT Links
- CustomGPT Landing Page
- Live Demo
- CustomGPT Starter Kit
- CustomGPT Integrations
- API Documentation
- Postman Collection
- MCP Documentation
- Office Hours
- YouTube Channel
Platform Documentation
- Twilio WhatsApp API Documentation: twilio.com/docs/whatsapp/api
Contributing
Feel free to submit issues and enhancement requests!
License
MIT
