Skip to content

Anand2842/WHATSAPP_API_PSAI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Plant Saathi WhatsApp AI Disease Detection Bot

A production-ready WhatsApp bot that provides AI-powered plant disease detection for farmers and gardeners.

🌟 Features

  • WhatsApp Integration: Seamless messaging via Twilio
  • AI Disease Detection: Powered by Plant Saathi AI API
  • Rate Limiting: 5 free scans per day per user
  • User Management: Automatic user creation and tracking
  • Image Processing: Validates image format and size
  • Professional Messaging: Clean, formatted responses
  • Scalable Architecture: Ready for thousands of users
  • Admin Dashboard: User statistics and management

πŸš€ Quick Start

1. Environment Setup

# Copy environment file
cp .env.example .env

# Install dependencies
pip install -r requirements.txt

2. Configure Environment Variables

Edit .env file with your credentials:

# Twilio WhatsApp API
TWILIO_ACCOUNT_SID=your_twilio_account_sid
TWILIO_AUTH_TOKEN=your_twilio_auth_token  
TWILIO_PHONE_NUMBER=+1234567890

# Plant Saathi API
PLANT_SAATHI_API_URL=https://plant-saathi-api.onrender.com/detect
PLANT_SAATHI_API_KEY=49732e55cc53907929bb896e25df0111de11f6b01a038c7217f8805f6a29f04d

# Your app URLs
WEB_APP_URL=https://plantSaathi.com
MOBILE_APP_URL=https://plantSaathi.com/app

3. Run the Server

# Development
python -m uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

# Production
python app/main.py

4. Setup Twilio Webhook

πŸ§ͺ Local Testing Setup

Local Testing (WebContainer Compatible)

# 1. Start the bot
python start_bot.py

# 2. In another terminal, test the endpoints
python test_bot.py

Expose Publicly (Required for Twilio)

# Install ngrok (if not installed)
npm install -g ngrok

# Expose your local bot
ngrok http 8000

Update Twilio Webhook

  1. Copy the ngrok HTTPS URL (e.g., https://abc123.ngrok.io)
  2. Go to Twilio Console
  3. Update webhook URL to: https://YOUR-NGROK-URL.ngrok.io/webhook/whatsapp
  4. Keep method as POST
  5. Click Save

Test Your Bot

1. Join sandbox: Send "join <sandbox-keyword>" to +1 415 523 8886
2. Send "hi" to +17622528098
3. Send a plant image
4. Test the 5-scan daily limit

πŸš€ Railway Production Deployment

Deploy to Railway

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

# 2. Login to Railway
railway login

# 3. Deploy your bot
railway up

# 4. Set environment variables in Railway dashboard
# 5. Get your Railway URL: https://your-app.railway.app

Update Twilio for Production

In your Twilio Console:

  1. When a message comes in:

    • URL: https://your-app.railway.app/webhook/whatsapp
    • Method: POST
  2. Status callback URL: (optional)

    • URL: https://your-app.railway.app/webhook/status
    • Method: POST

πŸ“± How It Works

User Flow

  1. User sends "Hi" β†’ Gets welcome message
  2. User sends plant image β†’ AI analyzes and responds with diagnosis
  3. After 5 scans β†’ Directed to web/mobile app for unlimited access
  4. Premium users β†’ Unlimited WhatsApp scans

Message Types

  • Welcome: Introduction and instructions
  • Disease Detection: Detailed diagnosis with remedies
  • Limit Exceeded: Upgrade options and alternatives
  • Error Handling: Clear error messages and solutions

πŸ—οΈ Architecture

app/
β”œβ”€β”€ main.py              # FastAPI application & webhooks
β”œβ”€β”€ config.py            # Environment configuration
β”œβ”€β”€ database.py          # SQLAlchemy models & DB setup
β”œβ”€β”€ models.py            # Pydantic models
└── services/
    β”œβ”€β”€ whatsapp_service.py    # WhatsApp messaging
    β”œβ”€β”€ user_service.py        # User management & tracking
    └── detection_service.py   # AI API integration

πŸ› οΈ API Endpoints

Webhook

  • POST /webhook/whatsapp - Twilio WhatsApp webhook

Admin

  • GET /stats/user/{phone_number} - User statistics
  • GET /admin/users - List all users
  • GET /health - Health check

πŸ“Š Database Schema

Users Table

  • phone_number - Unique user identifier
  • daily_scan_count - Scans used today
  • total_scans - Lifetime scan count
  • is_premium - Premium subscription status
  • last_scan_date - Last activity tracking

Scan History Table

  • user_phone - User reference
  • image_url - Processed image URL
  • detection_result - AI analysis result
  • confidence_score - Detection confidence
  • scan_timestamp - Processing time

βš™οΈ Configuration

Rate Limiting

  • Default: 5 scans per day
  • Resets: Every 24 hours
  • Premium: Unlimited scans

Image Processing

  • Max size: 10MB
  • Formats: JPEG, PNG, WEBP
  • Min resolution: 100x100px

Message Templates

  • Professional formatting
  • Emoji usage for engagement
  • Clear call-to-actions
  • Multilingual ready

πŸš€ Deployment

Docker (Recommended)

FROM python:3.11-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY app/ ./app/
EXPOSE 8000

CMD ["python", "app/main.py"]

Railway/Render

  1. Connect your GitHub repo
  2. Set environment variables
  3. Deploy automatically

Traditional VPS

# Install dependencies
pip install -r requirements.txt

# Run with gunicorn
gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000

πŸ“ˆ Monitoring & Analytics

Built-in Tracking

  • User registration and activity
  • Scan success/failure rates
  • API response times
  • Daily/monthly usage trends

Logs

  • Structured logging with timestamps
  • Error tracking and debugging
  • User action audit trail
  • Performance metrics

πŸ”’ Security

Input Validation

  • Image format verification
  • File size limits
  • Phone number sanitization
  • SQL injection prevention

Rate Limiting

  • Per-user daily limits
  • API timeout handling
  • Abuse detection ready

πŸ›£οΈ Phase 2 Features (Coming Next)

  • PDF Reports: Detailed diagnosis documents
  • Payment Integration: Razorpay/Stripe for premium
  • Voice Messages: Audio diagnosis results
  • Multi-language: Hindi, regional languages
  • Advanced Analytics: Dashboard and insights

πŸ“ž Support

For issues or questions:

πŸ“„ License

MIT License - see LICENSE file for details.


Plant Saathi AI - Empowering farmers with AI-driven plant health solutions 🌱🚜

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors