Skip to content

vaishnavi2810-code/whatsapp-dcd

Repository files navigation

WhatsApp Daily Chat Digest

Backend API for generating daily WhatsApp message summaries using AI.

Features

  • Automatically fetches messages from all WhatsApp chats
  • Generates concise summaries using Anthropic Claude
  • RESTful API built with FastAPI
  • Integrates with WhatsApp via MCP (Model Context Protocol) server
  • Docker-ready for easy deployment
  • Optimized for Railway deployment

Architecture

  • FastAPI - Modern Python web framework for the API
  • WhatsApp MCP Server - Go-based subprocess for WhatsApp integration
  • Anthropic Claude Sonnet 4.5 - AI model for generating summaries
  • Docker - Multi-stage build for Go + Python

Prerequisites

  • Docker (for containerized deployment)
  • Anthropic API key (get one at https://console.anthropic.com)
  • Custom WhatsApp MCP server code - Place your modified whatsapp-mcp in the whatsapp-mcp/ directory
  • For local development:
    • Python 3.11+
    • Go 1.21+

Quick Start

1. Clone the repository

git clone https://github.com/your-username/whatsapp-dcd.git
cd whatsapp-dcd

2. Add your custom WhatsApp MCP server

Place your custom whatsapp-mcp code in the whatsapp-mcp/ directory:

# Copy your custom whatsapp-mcp code here
cp -r /path/to/your/custom/whatsapp-mcp/* ./whatsapp-mcp/

The directory should contain your whatsapp-bridge/ subdirectory with main.go.

3. Set up environment variables

cp .env.template .env

Edit .env and add your Anthropic API key:

ANTHROPIC_API_KEY=your_actual_api_key_here

4. Run with Docker

Option A: Using Docker Compose (Recommended)

docker-compose up -d

To view logs:

docker-compose logs -f

To stop:

docker-compose down

Option B: Using Docker directly

docker build -t whatsapp-dcd .
docker run -p 8033:8033 --env-file .env whatsapp-dcd

5. Test the API

Option A: Automated login with QR code image (requires jq and qrencode)

./login_qr.sh

This will:

  1. Request a QR code from the backend
  2. Generate a PNG image (whatsapp_qr.png)
  3. Automatically open it (if possible)
  4. Monitor authentication status until successful

Option B: Use the test script (requires jq)

./test_api.sh

Option C: Test individual endpoints

# Health check
curl http://localhost:8033/health

# Check authentication status
curl http://localhost:8033/auth/status

# Start authentication (get QR code)
curl -X POST http://localhost:8033/auth/start

# Generate summaries (after authentication)
curl -X POST http://localhost:8033/generate_summaries \
  -H "Content-Type: application/json" \
  -d '{"date": "yesterday"}'

# Send a query to Claude
curl -X POST http://localhost:8033/query \
  -H "Content-Type: application/json" \
  -d '{"query": "Tell me a fun fact about space"}'

# Logout from WhatsApp
curl -X POST http://localhost:8033/auth/logout

Installing dependencies for scripts:

sudo apt-get install jq qrencode  # For Ubuntu/Debian

API Documentation

GET /

Health check endpoint.

Response:

{
  "service": "WhatsApp Daily Chat Digest",
  "status": "running",
  "version": "0.1.0"
}

GET /health

Detailed health check including MCP server status.

Response:

{
  "status": "healthy",
  "mcp_server": "connected"
}

GET /auth/status

Check WhatsApp authentication status.

Response:

{
  "status": "connected",
  "message": "Connected and authenticated.",
  "is_connected": true,
  "is_authenticated": true
}

Status values:

  • not_authenticated - Not authenticated, need to start auth
  • authenticating - QR code shown, waiting for scan
  • connected - Successfully authenticated
  • logged_out - Previously authenticated but logged out
  • auth_timeout - Authentication session expired
  • error - Authentication error occurred

POST /auth/start

Start WhatsApp authentication process and get QR code.

Response:

{
  "success": true,
  "message": "Authentication started. Session expires in 3 minutes.",
  "qr_code": "2@A1B2C3D4...",
  "instructions": "Step-by-step instructions for scanning..."
}

Usage:

curl -X POST http://localhost:8033/auth/start

GET /auth/qr

Get current QR code during active authentication session.

Response:

{
  "success": true,
  "message": "Current QR code",
  "qr_code": "2@A1B2C3D4...",
  "instructions": "Scan this with WhatsApp..."
}

Note: Only works when authentication is in progress (status = "authenticating")

POST /auth/logout

Logout from WhatsApp. This allows you to log in with a different account or re-authenticate without restarting the server.

Response:

{
  "success": true,
  "message": "Successfully logged out. You can authenticate again with /api/auth/start."
}

Usage:

curl -X POST http://localhost:8033/auth/logout

Note: After logging out, you can use /auth/start to authenticate again without restarting the backend

POST /generate_summaries

Generate summaries for all WhatsApp chats from a specific date.

Request Body:

{
  "date": "yesterday"  // Options: "yesterday", "today", or "YYYY-MM-DD"
}

Response:

{
  "summaries": [
    {
      "chat_name": "Family Group",
      "chat_id": "123456789@g.us",
      "summary": "- Discussed weekend plans...\n- Made dinner reservations...",
      "message_count": 45
    }
  ],
  "date_range": "2024-01-10T00:00:00 to 2024-01-10T23:59:59",
  "total_chats": 1
}

POST /query

Send a query to Claude (Haiku 4.5) with WhatsApp MCP tools enabled.

Claude can automatically use WhatsApp tools to search contacts, list messages, send messages, and more.

Request Body:

{
  "query": "What is the capital of France?",
  "context": "Optional context to help Claude answer better"
}

Response:

{
  "response": "The capital of France is Paris.",
  "model": "claude-haiku-4-5-20251001"
}

Example - Simple query:

curl -X POST http://localhost:8033/query \
  -H "Content-Type: application/json" \
  -d '{"query": "Explain quantum computing in simple terms"}'

Example - Query with context:

curl -X POST http://localhost:8033/query \
  -H "Content-Type: application/json" \
  -d '{
    "query": "What are the main topics discussed?",
    "context": "Yesterday we talked about project deadlines, team assignments, and budget constraints."
  }'

Example - Using WhatsApp tools (requires authentication):

# Search for a contact
curl -X POST http://localhost:8033/query \
  -H "Content-Type: application/json" \
  -d '{"query": "Search for contacts named John"}'

# List recent chats
curl -X POST http://localhost:8033/query \
  -H "Content-Type: application/json" \
  -d '{"query": "List my 5 most recent WhatsApp chats"}'

# Get messages from a specific chat
curl -X POST http://localhost:8033/query \
  -H "Content-Type: application/json" \
  -d '{"query": "Show me the last 10 messages from Mom"}'

Note: Claude will automatically decide when to use WhatsApp tools based on your query. The tool execution happens transparently in the background.

Railway Deployment

1. Push to GitHub

git add .
git commit -m "Initial commit"
git push origin main

2. Deploy to Railway

  1. Go to Railway
  2. Click "New Project" → "Deploy from GitHub repo"
  3. Select your repository
  4. Railway will automatically detect the Dockerfile

3. Set Environment Variables

In your Railway project settings, add:

  • ANTHROPIC_API_KEY - Your Anthropic API key
  • Railway automatically provides PORT

4. Deploy

Railway will automatically build and deploy your application. Once deployed, you'll get a URL like: https://your-app.railway.app

WhatsApp Authentication

The backend provides API endpoints for WhatsApp authentication via QR code.

Quick Login

Use the automated login script (recommended):

./login_qr.sh

This automatically:

  • Requests a QR code
  • Generates a PNG image
  • Opens the image for scanning
  • Monitors authentication status

See LOGIN_README.md for detailed authentication documentation.

Manual Authentication Flow

  1. Check authentication status:

    curl http://localhost:8033/auth/status
  2. Start authentication (if not authenticated):

    curl -X POST http://localhost:8033/auth/start

    This returns a QR code string that needs to be displayed to the user.

  3. Scan the QR code with WhatsApp on your phone:

    • Open WhatsApp
    • Go to Settings > Linked Devices
    • Tap "Link a Device"
    • Scan the QR code
  4. Verify authentication:

    curl http://localhost:8033/auth/status

    Status should change to "connected" after successful scan.

Important Notes

  • QR codes expire after 3 minutes
  • Authentication session persists across restarts once successfully authenticated
  • You can restart authentication by calling /auth/start again
  • Use /auth/qr to get a refreshed QR code during active authentication

Docker Compose Features

When using Docker Compose, the following features are available:

  • Persistent WhatsApp Sessions: A Docker volume (whatsapp-store) automatically stores WhatsApp authentication data, so you don't need to re-authenticate after container restarts
  • Auto-restart: Container automatically restarts if it crashes (unless manually stopped)
  • Easy Management: Simple commands to start, stop, and view logs

To remove the volume and start fresh:

docker-compose down -v

Development

Local Setup (without Docker)

  1. Install Python dependencies:
pip install -r requirements.txt
  1. Place your custom WhatsApp MCP server:
# Make sure your custom whatsapp-mcp code is in ./whatsapp-mcp/
# It should contain whatsapp-bridge/ subdirectory with main.go
  1. Set environment variables:
export ANTHROPIC_API_KEY=your_key_here
export MCP_SERVER_PATH=./whatsapp-mcp/whatsapp-bridge
  1. Run the application:
uvicorn app.main:app --reload

Project Structure

whatsapp-dcd/
├── app/
│   ├── __init__.py
│   ├── main.py              # FastAPI application
│   ├── config.py            # Configuration management
│   ├── mcp_client.py        # MCP subprocess client
│   └── services/
│       └── summarizer.py    # Anthropic integration
├── Dockerfile               # Multi-stage Docker build
├── requirements.txt         # Python dependencies
├── .env.template           # Environment variables template
└── README.md

Troubleshooting

MCP Server Connection Issues

  • Check that the WhatsApp MCP server is running: Look for startup messages in logs
  • Verify the MCP_SERVER_PATH environment variable points to the correct directory

Anthropic API Errors

  • Verify your API key is correct in the .env file
  • Check your Anthropic account has sufficient credits
  • Review rate limits if you're processing many chats

Docker Build Issues

  • Ensure you have enough disk space for the multi-stage build
  • Try clearing Docker cache: docker system prune -a

Future Enhancements

  • WebSocket endpoint for real-time QR code delivery to frontend
  • Session persistence across container restarts
  • Caching layer for message fetching
  • Authentication and rate limiting
  • Scheduled daily summaries
  • Email/notification delivery of summaries

License

See LICENSE file for details

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages