help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
whatsapp-chatbot
/
__pycache__
RSK World
whatsapp-chatbot
WhatsApp Chatbot - Python Flask + Twilio + Admin Dashboard + Multilingual Support + Sentiment Analysis + Booking Management
__pycache__
  • app.cpython-313.pyc1.5 KB
  • bot_logic.cpython-313.pyc11.4 KB
test_analysis.pyanalytics.py.gitignoredemo-readme.mdapp.pyrun.pyREADME.md
.gitignore
Raw Download
Find: Go to:
venv/
__pycache__/
*.pyc
.env
.DS_Store
bookings.json
analytics.json
8 lines•76 B
text
app.py
Raw Download
Find: Go to:
# Project: WhatsApp Chatbot
# Author: RSK World
# Email: info@rskworld.com, support@rskworld.com
# Website: https://rskworld.in
# Phone: +91 93305 39277
# Year: 2026
# Description: WhatsApp-integrated chatbot for business messaging and customer engagement.

from flask import Flask, request, render_template, jsonify, send_file
from twilio.twiml.messaging_response import MessagingResponse
from bot_logic import process_message, load_bookings, get_analytics_data
import os
import csv
import io
from datetime import datetime

app = Flask(__name__)

@app.route("/")
def home():
    """Renders the landing page for the WhatsApp Chatbot demo."""
    return render_template("index.html")

@app.route("/admin")
def admin():
    """Renders the Admin Dashboard."""
    bookings = load_bookings()
    return render_template("admin.html", bookings=bookings)

@app.route("/api/analytics")
def analytics():
    """API endpoint for dashboard charts."""
    return jsonify(get_analytics_data())

@app.route("/api/export_bookings")
def export_bookings():
    """Exports bookings to CSV."""
    bookings = load_bookings()
    
    # Create CSV in memory
    si = io.StringIO()
    cw = csv.writer(si)
    cw.writerow(["Timestamp", "Name", "Phone", "Preferred Date", "Topic"])
    
    for b in bookings:
        cw.writerow([b.get("timestamp"), b.get("name"), b.get("phone"), b.get("date"), b.get("topic")])
        
    output = io.BytesIO()
    output.write(si.getvalue().encode('utf-8'))
    output.seek(0)
    
    filename = f"bookings_{datetime.now().strftime('%Y%m%d')}.csv"
    return send_file(output, mimetype="text/csv", as_attachment=True, download_name=filename)

@app.route("/api/broadcast", methods=["POST"])
def broadcast():
    """Simulates sending a broadcast message."""
    data = request.json
    message = data.get("message", "")
    # In a real app, you would iterate over a User DB and call Twilio API here.
    return jsonify({"status": "success", "count": 142}) # Simulated count

@app.route("/webhook", methods=["POST"])
def webhook():
    """Receives incoming WhatsApp messages from Twilio."""
    incoming_msg = request.values.get('Body', '').lower()
    sender = request.values.get('From', '')

    response = MessagingResponse()
    msg = response.message()
    
    # Process the message and get the reply text
    reply_text = process_message(incoming_msg, sender)
    msg.body(reply_text)

    return str(response)

if __name__ == "__main__":
    app.run(debug=True, port=5000)
80 lines•2.5 KB
python
README.md
Raw Download

README.md

# WhatsApp Chatbot (Ultimate Edition v3.0)

**Project ID:** 8
**Category:** Custom Chatbots
**Difficulty:** Advanced
**Author:** RSK World
**Website:** [rskworld.in](https://rskworld.in)
**Contact:** info@rskworld.com | +91 93305 39277

## Description
A feature-rich **WhatsApp-integrated chatbot solution**. Version 3.0 introduces **Multilingual support**, **Broadcasting capabilities**, and a full-fledged **Admin Dashboard**. This project is designed for real-world usage with essential business features, including sentiment analysis, urgency detection, and appointment management.

## 🚀 Key Features

### 🤖 Intelligent Chat Bot
* **Multilingual Support**: Instant toggle between **Hindi** and **English** languages (`hindi`/`english`).
* **Fuzzy Matching**: Smartly handles typos (e.g., "boking" -> "booking").
* **Contextual Memory**: Remembers user state for multi-step conversations.
* **Sentiment Analysis**: Analyzes user mood (Positive/Negative/Neutral).
* **Urgency Detection**: Automatically flags messages with keywords like "urgent".
* **Interactive Menu**: Structured menu navigation for services and support.
* **Joke Engine**: Adds personality with random joke generation.
* **Fallback Handling**: Graceful responses for unrecognized inputs.
* **Session Management**: Robust in-memory user session tracking.
* **State Machine**: Guided flows for complex tasks like booking.
* **Knowledge Base**: Fuzzy search over predefined service descriptions.
* **Greeting Recognition**: Natural greeting handling in multiple languages.
* **Conversation Reset**: `reset` command to clear user session context.
* **Admin Escalation**: Intelligent routing for negative sentiment queries.

### 📊 Powerful Admin Dashboard
* **Live Analytics**: Real-time sentiment charts validation.
* **Booking Watchtower**: Centralized view of all customer appointments.
* **Broadcast System**: Send mass marketing messages to all users.
* **CSV Export**: One-click download of all booking data for Excel.
* **User Management**: View details of interacting users and histories.
* **Status Tracking**: Monitor booking implementation statuses visually.
* **Sentiment Trends**: Visual distribution of user satisfaction levels.
* **Recent Activity**: Live feed of user intents and interactions.
* **Secure Access**: Admin route protection logic.
* **Responsive Design**: Mobile-friendly Bootstrap 5 dashboard interface.
* **Data Visualization**: Interactive charts using Chart.js.
* **Total Interaction Count**: Track overall system usage metrics.
* **Broadcast Simulation**: Safe testing mode for broadcast features.

### 🌟 Key Capabilities
* **Appointment Booking**: Multi-step conversational booking flow.
* **Emergency Detection**: Prioritizes urgent messages automatically.
* **Broadcasting**: Marketing/Announcement capability via API.
* **Bilingual**: Hindi and English support out of the box.
* **Cross-Platform**: Works on WhatsApp Mobile, Web, and Desktop.
* **Zero-Database Setup**: No SQL setup required to get started.
* **Cloud Ready**: Configured for immediate cloud deployment.
* **User-Centric Design**: Focus on natural conversational flow.
* **Rapid Prototyping**: Ideal base for MVP development.

## 💻 Technologies
* **Python 3.10+**: Leveraging modern language features.
* **Flask Framework**: Lightweight, flexible, and powerful backend.
* **Twilio API**: Industry-standard WhatsApp integration.
* **Bootstrap 5**: Modern, responsive UI framework for dashboard.
* **Chart.js**: Beautiful, reactive data visualization libraries.
* **TextBlob**: Advanced Natural Language Processing (NLP).
* **TheFuzz**: High-performance string matching and deduplication.
* **JSON Storage**: Lightweight, serverless flat-file database.
* **REST API**: Clean API architecture for frontend communication.
* **Jinja2 Templating**: Dynamic HTML rendering for admin pages.

## 📂 Project Structure
* `app.py`: Main Flask application entry point and route handlers.
* `bot_logic.py`: Core AI logic, state management, and NLP processing.
* `templates/`: Jinja2 HTML templates for Admin Dashboard.
* `static/`: CSS, JavaScript, and Image assets directory.
* `bookings.json`: Portable JSON database for appointment data.
* `analytics.json`: Storage for sentiment and interaction logs.
* `requirements.txt`: Complete dependency list for easy installation.
* `Procfile`: Deployment configuration for Heroku/Cloud platforms.
* `runtime.txt`: Python version specification for environments.

## Setup & Running

1. **Install dependencies:**
```bash
pip install -r requirements.txt
```

2. **Download NLTK Corpora (if needed):**
```bash
python -m textblob.download_corpora
```

3. **Run the application:**
```bash
python app.py
```

4. **Access:**
- **App**: `http://localhost:5000/`
- **Dashboard**: `http://localhost:5000/admin`

## 🙏 Credits & Acknowledgments
* [Flask](https://flask.palletsprojects.com/) - Web Framework
* [Twilio](https://www.twilio.com/) - WhatsApp API
* [Bootstrap 5](https://getbootstrap.com/) - UI Framework
* [TextBlob](https://textblob.readthedocs.io/) - NLP Library
* [TheFuzz](https://github.com/seatgeek/thefuzz) - Fuzzy String Matching
* [RSK World](https://rskworld.in) - Project Creator

© 2026 RSK World. All rights reserved.
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer