A lightweight, keyword-based FAQ chatbot for Facebook Messenger that automatically answers common customer questions. Perfect for e-commerce product pages and customer support.
- Keyword-based matching with synonym support
- 50 pre-configured FAQ answers covering common e-commerce scenarios
- Fuzzy matching handles typos and variations
- Score-based responses ensures relevant answers
- Facebook webhook integration with signature verification
- Lightweight & fast - No database required
- Easy deployment - Optimized for Railway.app free tier
- Customizable - Easy to modify FAQs and matching logic
- Quick Start
- Local Development Setup
- Facebook App & Page Setup
- Webhook Configuration
- Deployment to Railway
- Customizing FAQs
- Testing
- Troubleshooting
- Project Structure
- Python 3.11+
- Facebook Developer Account
- Facebook Page
- Railway.app account (for deployment)
-
Clone the repository
git clone https://github.com/yourusername/facebook-faq-bot.git cd facebook-faq-bot -
Create virtual environment
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies
pip install -r requirements.txt
-
Configure environment variables
cp .env.example .env # Edit .env with your credentials (see below) -
Run the application
python app.py
The bot will start on http://localhost:5000
- Go to Facebook Pages
- Choose a page type (Business/Brand)
- Fill in your page details
- Complete the setup
- Go to Facebook Developers
- Click "Create App"
- Select "Business" as app type
- Fill in app details:
- App Name: Your bot name
- Contact Email: Your email
- Click "Create App"
- In your app dashboard, click "Add Product"
- Find "Messenger" and click "Set Up"
- In Messenger Settings, scroll to "Access Tokens"
- Click "Add or Remove Pages" and select your page
- Click "Generate Token"
- Copy the Page Access Token (you'll need this for
.env)
- Go to Settings β Basic
- Click "Show" next to App Secret
- Copy the App Secret (you'll need this for
.env)
Edit your .env file:
# Get this from: Messenger Settings -> Access Tokens
FACEBOOK_PAGE_ACCESS_TOKEN=your_page_access_token_here
# Create a random string (e.g., "my_secure_verify_token_123")
FACEBOOK_VERIFY_TOKEN=your_custom_verify_token_here
# Get this from: Settings -> Basic -> App Secret
APP_SECRET=your_app_secret_here
# Matching threshold (0.0 to 1.0) - lower = more lenient
MATCH_THRESHOLD=0.3Before configuring webhooks, you need a public URL. See Deployment to Railway section below.
- Go to your app dashboard β Messenger β Settings
- Scroll to "Webhooks" section
- Click "Add Callback URL"
- Enter:
- Callback URL:
https://your-app-url.railway.app/webhook - Verify Token: Same as
FACEBOOK_VERIFY_TOKENin your.env
- Callback URL:
- Click "Verify and Save"
- In the same Webhooks section
- Click "Add Subscriptions"
- Select:
- β
messages - β
messaging_postbacks
- β
- Click "Save"
- Still in Webhooks section
- Under "Select a Page", choose your page
- Click "Subscribe"
Railway offers $5 free credit per month (enough for testing).
- Go to Railway.app
- Sign up with GitHub (recommended)
- Click "New Project"
- Select "Deploy from GitHub repo"
- Authorize Railway to access your repository
- Select your
facebook-faq-botrepository - Railway will automatically detect Python and deploy
- In your Railway project, go to "Variables"
- Add each variable from your
.envfile:FACEBOOK_PAGE_ACCESS_TOKENFACEBOOK_VERIFY_TOKENAPP_SECRETMATCH_THRESHOLD
- Click "Deploy" to restart with new variables
- Go to "Settings" in your Railway project
- Click "Generate Domain" to get a public URL
- Copy the URL (e.g.,
https://your-app.railway.app) - Use this URL in Facebook webhook configuration
# Install Railway CLI
npm install -g @railway/cli
# Login
railway login
# Link to project
railway link
# Deploy
railway upEdit faq_data.json:
{
"faqs": [
{
"id": 1,
"question": "Your question here?",
"answer": "Your detailed answer here.",
"keywords": ["keyword1", "keyword2", "synonym1"],
"category": "category_name"
}
]
}Tips for better matching:
- Add multiple keywords covering different ways users might ask
- Include synonyms and common variations
- Keep keywords lowercase
- Use specific keywords relevant to the question
In .env, modify MATCH_THRESHOLD:
MATCH_THRESHOLD=0.3 # Default: balanced
MATCH_THRESHOLD=0.2 # More lenient (more false positives)
MATCH_THRESHOLD=0.5 # Stricter (fewer false positives)Edit matcher.py and add to the synonyms dictionary:
self.synonyms = {
'cost': ['price', 'fee', 'charge', 'expense'],
'your_word': ['synonym1', 'synonym2'],
# Add more...
}-
Start the bot:
python app.py
-
Test health endpoint:
curl http://localhost:5000/health
-
Test matcher directly:
from matcher import FAQMatcher matcher = FAQMatcher('faq_data.json', threshold=0.3) answer = matcher.get_answer("How much is shipping?") print(answer)
- Go to your Facebook Page
- Click "Send Message"
- Type a question (e.g., "What are your shipping costs?")
- The bot should respond with the relevant FAQ answer
Try these example questions:
- "How much does shipping cost?"
- "Do you ship internationally?"
- "How do I return an item?"
- "What payment methods do you accept?"
- "How long does delivery take?"
Check webhook verification:
curl "https://your-app.railway.app/webhook?hub.mode=subscribe&hub.verify_token=YOUR_VERIFY_TOKEN&hub.challenge=test"Should return test if working.
Check logs:
- Railway: Go to project β "Deployments" β Click latest deployment β View logs
- Local: Check console output
Common issues:
- β Wrong
FACEBOOK_VERIFY_TOKEN- must match in Facebook and.env - β Wrong
FACEBOOK_PAGE_ACCESS_TOKEN- regenerate from Facebook - β Webhook not subscribed to page - check subscription in Facebook
- β App not approved - for testing, add yourself as tester in App Roles
- Check that
FACEBOOK_VERIFY_TOKENin.envmatches what you entered in Facebook - Check that your app is accessible at the callback URL
- Check app logs for error messages
- Lower threshold: Set
MATCH_THRESHOLD=0.2for more lenient matching - Add keywords: Edit
faq_data.jsonand add more keywords to relevant FAQs - Check logs: See what score the matcher calculated
- Check that
APP_SECRETis correctly set in.env - Make sure you're using the App Secret from Settings β Basic (not Page Access Token)
- Check that webhook signature header is being sent by Facebook
Build fails:
- Check
runtime.txthas correct Python version - Check all dependencies in
requirements.txtare valid
App crashes:
- Check environment variables are set in Railway
- Check logs for specific error messages
- Verify
Procfileis correct:web: gunicorn app:app
App doesn't respond:
- Railway free tier sleeps after inactivity - first request may be slow
- Check that domain is generated and accessible
- Verify app is using correct PORT (Railway sets this automatically)
facebook-faq-bot/
βββ app.py # Main Flask server with webhook endpoints
βββ matcher.py # Keyword matching logic with scoring
βββ config.py # Configuration management
βββ faq_data.json # 50 Q&A pairs (customize these!)
βββ requirements.txt # Python dependencies
βββ runtime.txt # Python version for deployment
βββ Procfile # Railway/Heroku deployment config
βββ .env.example # Environment variables template
βββ .gitignore # Git ignore rules
βββ README.md # This file
- β Webhook signature verification using HMAC SHA-256
- β Environment variables for sensitive credentials
- β No hardcoded secrets in code
- β Input sanitization for message processing
- β HTTPS enforced for webhook communication
The default faq_data.json includes 50 FAQs across these categories:
- Shipping (4 FAQs): Costs, delivery times, international shipping, tracking
- Payment (4 FAQs): Payment methods, security, COD, installments
- Returns (5 FAQs): Return policy, process, shipping costs, refunds, exchanges
- Product Info (5 FAQs): Products, authenticity, size guide, colors, restocking
- Order Tracking (4 FAQs): Tracking orders, tracking number, status updates, address changes
- Contact (3 FAQs): Customer service, business hours, physical store
- Account (4 FAQs): Create account, reset password, change email, delete account
- Warranty (2 FAQs): Warranty coverage, making claims
- Discounts (4 FAQs): Current promotions, promo codes, loyalty program, student discounts
- Issues (3 FAQs): Damaged items, wrong items, missing packages
- Orders (4 FAQs): Cancel, modify, gift wrapping, gift messages
- Pricing (5 FAQs): Price matching, price changes, sales tax, hidden fees, bulk pricing
- Reviews (2 FAQs): Leaving reviews, editing reviews
- Privacy (1 FAQ): Data security
Contributions are welcome! To contribute:
- Fork the repository
- Create a feature branch
- Make your changes
- Test thoroughly
- Submit a pull request
This project is provided as-is for educational and commercial use.
For issues or questions:
- Open an issue on GitHub
- Check the Troubleshooting section
- Review Facebook's Messenger Platform Documentation
Once your bot is running:
- Test thoroughly with various question phrasings
- Customize FAQs for your specific business
- Monitor logs to see what questions users ask
- Add more FAQs based on common queries
- Adjust threshold for optimal matching
- Add your team as testers in Facebook App Roles
- Submit for review when ready for public use
Made with β€οΈ for automated customer support