A Flask application that handles WhatsApp messages via Twilio webhooks and stores them in MongoDB Atlas.
- WhatsApp Webhook: Receives messages from Twilio
- MongoDB Storage: Stores chats and messages in ServiceDeckDB
- Chat Management: Automatic chat creation and tracking
- Duplicate Prevention: Handles Twilio retries gracefully
- REST API: Retrieve chat history and manage conversations
- Unique Index:
{ channel: 1, userPhone: 1 } - Performance Index:
{ lastUserTs: -1 } - Fields: channel, userPhone, createdAt, updatedAt, lastUserTs
- Compound Index:
{ chatId: 1, createdAt: 1 } - Unique Sparse Index:
{ providerMsgId: 1 } - Fields: chatId, direction, role, body, providerMsgId, from, to, createdAt, meta
Create a .env file with:
# MongoDB Atlas Connection
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/ServiceDeckDB?retryWrites=true&w=majority
# Twilio Configuration
TWILIO_ACCOUNT_SID=your_twilio_account_sid_here
TWILIO_AUTH_TOKEN=your_twilio_auth_token_here
TWILIO_WHATSAPP_NUMBER=whatsapp:+1234567890- Install dependencies:
pip install -r requirements.txt- Set up environment variables
- Run the application:
python app.py- Purpose: Twilio webhook for incoming WhatsApp messages
- Handles: Message storage, chat creation, duplicate prevention
- Response: JSON with status and chat_id
- Purpose: Retrieve chat history for a specific phone number
- Format: E.164 phone number (e.g.,
/chat/+1234567890) - Response: Chat messages sorted by creation time
- Purpose: List all chats with basic information
- Response: Summary of all chats with message counts
- Purpose: Health check endpoint
- Response: MongoDB connection status
- Webhook Reception: Twilio sends WhatsApp message to
/webhook - Chat Management: System ensures chat document exists for user
- Message Storage: Inbound message stored with Twilio MessageSid
- Duplicate Handling: Prevents duplicate messages from retries
- Canned Reply: Optional outbound message stored (not sent)