Skip to content

itemuln/facebook-faq-bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

16 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Facebook Messenger FAQ Bot

A lightweight, keyword-based FAQ chatbot for Facebook Messenger that automatically answers common customer questions. Perfect for e-commerce product pages and customer support.

🌟 Features

  • 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

πŸ“‹ Table of Contents

πŸš€ Quick Start

Prerequisites

  • Python 3.11+
  • Facebook Developer Account
  • Facebook Page
  • Railway.app account (for deployment)

Local Development Setup

  1. Clone the repository

    git clone https://github.com/yourusername/facebook-faq-bot.git
    cd facebook-faq-bot
  2. Create virtual environment

    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
  3. Install dependencies

    pip install -r requirements.txt
  4. Configure environment variables

    cp .env.example .env
    # Edit .env with your credentials (see below)
  5. Run the application

    python app.py

The bot will start on http://localhost:5000

πŸ”§ Facebook App & Page Setup

Step 1: Create a Facebook Page

  1. Go to Facebook Pages
  2. Choose a page type (Business/Brand)
  3. Fill in your page details
  4. Complete the setup

Step 2: Create a Facebook App

  1. Go to Facebook Developers
  2. Click "Create App"
  3. Select "Business" as app type
  4. Fill in app details:
    • App Name: Your bot name
    • Contact Email: Your email
  5. Click "Create App"

Step 3: Configure Messenger

  1. In your app dashboard, click "Add Product"
  2. Find "Messenger" and click "Set Up"
  3. In Messenger Settings, scroll to "Access Tokens"
  4. Click "Add or Remove Pages" and select your page
  5. Click "Generate Token"
  6. Copy the Page Access Token (you'll need this for .env)

Step 4: Get App Secret

  1. Go to Settings β†’ Basic
  2. Click "Show" next to App Secret
  3. Copy the App Secret (you'll need this for .env)

Step 5: Configure Environment Variables

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.3

πŸ”— Webhook Configuration

Step 1: Deploy Your Bot

Before configuring webhooks, you need a public URL. See Deployment to Railway section below.

Step 2: Set Up Webhook in Facebook

  1. Go to your app dashboard β†’ Messenger β†’ Settings
  2. Scroll to "Webhooks" section
  3. Click "Add Callback URL"
  4. Enter:
    • Callback URL: https://your-app-url.railway.app/webhook
    • Verify Token: Same as FACEBOOK_VERIFY_TOKEN in your .env
  5. Click "Verify and Save"

Step 3: Subscribe to Page Events

  1. In the same Webhooks section
  2. Click "Add Subscriptions"
  3. Select:
    • βœ… messages
    • βœ… messaging_postbacks
  4. Click "Save"

Step 4: Subscribe Your Page

  1. Still in Webhooks section
  2. Under "Select a Page", choose your page
  3. Click "Subscribe"

πŸš‚ Deployment to Railway

Railway offers $5 free credit per month (enough for testing).

Step 1: Create Railway Account

  1. Go to Railway.app
  2. Sign up with GitHub (recommended)

Step 2: Deploy from GitHub

  1. Click "New Project"
  2. Select "Deploy from GitHub repo"
  3. Authorize Railway to access your repository
  4. Select your facebook-faq-bot repository
  5. Railway will automatically detect Python and deploy

Step 3: Configure Environment Variables

  1. In your Railway project, go to "Variables"
  2. Add each variable from your .env file:
    • FACEBOOK_PAGE_ACCESS_TOKEN
    • FACEBOOK_VERIFY_TOKEN
    • APP_SECRET
    • MATCH_THRESHOLD
  3. Click "Deploy" to restart with new variables

Step 4: Get Your Public URL

  1. Go to "Settings" in your Railway project
  2. Click "Generate Domain" to get a public URL
  3. Copy the URL (e.g., https://your-app.railway.app)
  4. Use this URL in Facebook webhook configuration

Alternative: Manual Deployment

# Install Railway CLI
npm install -g @railway/cli

# Login
railway login

# Link to project
railway link

# Deploy
railway up

πŸ“ Customizing FAQs

Modify Existing FAQs

Edit 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

Adjust Matching Sensitivity

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)

Add Custom Synonyms

Edit matcher.py and add to the synonyms dictionary:

self.synonyms = {
    'cost': ['price', 'fee', 'charge', 'expense'],
    'your_word': ['synonym1', 'synonym2'],
    # Add more...
}

πŸ§ͺ Testing

Test Locally

  1. Start the bot:

    python app.py
  2. Test health endpoint:

    curl http://localhost:5000/health
  3. 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)

Test on Facebook Messenger

  1. Go to your Facebook Page
  2. Click "Send Message"
  3. Type a question (e.g., "What are your shipping costs?")
  4. The bot should respond with the relevant FAQ answer

Test Different Questions

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?"

πŸ› Troubleshooting

Bot Not Responding

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

Webhook Verification Failed

  1. Check that FACEBOOK_VERIFY_TOKEN in .env matches what you entered in Facebook
  2. Check that your app is accessible at the callback URL
  3. Check app logs for error messages

Bot Responds with Wrong Answers

  1. Lower threshold: Set MATCH_THRESHOLD=0.2 for more lenient matching
  2. Add keywords: Edit faq_data.json and add more keywords to relevant FAQs
  3. Check logs: See what score the matcher calculated

Signature Verification Errors

  1. Check that APP_SECRET is correctly set in .env
  2. Make sure you're using the App Secret from Settings β†’ Basic (not Page Access Token)
  3. Check that webhook signature header is being sent by Facebook

Railway Deployment Issues

Build fails:

  • Check runtime.txt has correct Python version
  • Check all dependencies in requirements.txt are valid

App crashes:

  • Check environment variables are set in Railway
  • Check logs for specific error messages
  • Verify Procfile is 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)

πŸ“ Project Structure

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

πŸ” Security

  • βœ… 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

πŸ“Š FAQ Categories Included

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

🀝 Contributing

Contributions are welcome! To contribute:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Test thoroughly
  5. Submit a pull request

πŸ“„ License

This project is provided as-is for educational and commercial use.

πŸ†˜ Support

For issues or questions:

🎯 Next Steps

Once your bot is running:

  1. Test thoroughly with various question phrasings
  2. Customize FAQs for your specific business
  3. Monitor logs to see what questions users ask
  4. Add more FAQs based on common queries
  5. Adjust threshold for optimal matching
  6. Add your team as testers in Facebook App Roles
  7. Submit for review when ready for public use

Made with ❀️ for automated customer support

About

Facebook Messenger FAQ Bot with Keyword Matching

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •