Skip to content

About

A chat agent that can create service requests, provide customer service and integrate with WhatsApp or messenger through their developer Api.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

32 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Service Chat Agent - WhatsApp + MongoDB Integration

A Flask application that handles WhatsApp messages via Twilio webhooks and stores them in MongoDB Atlas.

Features

  • 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

Database Design

Collections

chats

  • Unique Index: { channel: 1, userPhone: 1 }
  • Performance Index: { lastUserTs: -1 }
  • Fields: channel, userPhone, createdAt, updatedAt, lastUserTs

messages

  • Compound Index: { chatId: 1, createdAt: 1 }
  • Unique Sparse Index: { providerMsgId: 1 }
  • Fields: chatId, direction, role, body, providerMsgId, from, to, createdAt, meta

Environment Variables

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

Installation

  1. Install dependencies:
pip install -r requirements.txt
  1. Set up environment variables
  2. Run the application:
python app.py

API Endpoints

POST /webhook

  • Purpose: Twilio webhook for incoming WhatsApp messages
  • Handles: Message storage, chat creation, duplicate prevention
  • Response: JSON with status and chat_id

GET /chat/<phone_number>

  • 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

GET /chats

  • Purpose: List all chats with basic information
  • Response: Summary of all chats with message counts

GET /health

  • Purpose: Health check endpoint
  • Response: MongoDB connection status

How It Works

  1. Webhook Reception: Twilio sends WhatsApp message to /webhook
  2. Chat Management: System ensures chat document exists for user
  3. Message Storage: Inbound message stored with Twilio MessageSid
  4. Duplicate Handling: Prevents duplicate messages from retries
  5. Canned Reply: Optional outbound message stored (not sent)

About

A chat agent that can create service requests, provide customer service and integrate with WhatsApp or messenger through their developer Api.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages