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
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
whatsapp-chatbot
RSK World
whatsapp-chatbot
WhatsApp Chatbot - Python Flask + Twilio + Admin Dashboard + Multilingual Support + Sentiment Analysis + Booking Management
whatsapp-chatbot
  • __pycache__
  • static
  • templates
  • tests
  • .env418 B
  • .gitignore76 B
  • LICENSE1.5 KB
  • Procfile23 B
  • README.md5.4 KB
  • analytics.json10 B
  • app.py2.5 KB
  • bookings.json10 B
  • bot_logic.py10.9 KB
  • requirements.txt104 B
  • runtime.txt16 B
  • whatsapp-chatbot.png624.8 KB
README.mdbot_logic.py
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.
bot_logic.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.

import json
import os
from datetime import datetime
from textblob import TextBlob
from thefuzz import process
import random

# File paths
BOOKINGS_FILE = "bookings.json"
ANALYTICS_FILE = "analytics.json"

# In-memory session storage
sessions = {}

# Predefined Knowledge Base
SERVICES = {
    "web": "We build modern, responsive, and SEO-friendly websites using the latest technologies.",
    "chatbot": "Our AI-powered chatbots work 24/7 on WhatsApp, Telegram, and Web to engage your customers.",
    "ai": "We offer custom AI solutions including predictive analytics, NLP, and computer vision.",
    "marketing": "Boost your business with our data-driven digital marketing strategies.",
    "seo": "Rank higher on search engines with our 2026 advanced SEO tactics."
}

HINDI_STRINGS = {
    "greeting": "👋 *नमस्ते!* RSK World के एडवांस AI असिस्टेंट (2026) में आपका स्वागत है।\n",
    "menu": ("🤖 *मुख्य मेनू* 🤖\n\n"
             "1. 🌐 *हमारी सेवाएँ*\n"
             "2. 📅 *परामर्श बुक करें* (इंटरैक्टिव)\n"
             "3. 📞 *समर्थन से संपर्क करें*\n"
             "4. ℹ️ *हमारे बारे में*\n"
             "5. 😄 *मुझे एक चुटकुला सुनाओ*\n\n"
             "_पुनः आरंभ करने के लिए 'reset' टाइप करें।_"),
    "services": "🚀 *हमारी सेवाएँ:*\n- 🌐 वेब विकास\n- 🤖 कस्टम चैटबॉट्स\n- 🧠 AI समाधान\n- 📈 डिजिटल मार्केटिंग",
    "contact": "📞 *संपर्क करें*\nइमेल: info@rskworld.com\nफ़ोन: +91 93305 39277",
    "fallback": "🤔 मुझे वह समझ नहीं आया। मेनू देखने के लिए 'hi' कहें।"
}

JOKES = [
    "Why did the AI go to school? To improve its learning rate!",
    "I'd tell you a UDP joke, but you might not get it.",
    "Why do programmers prefer dark mode? Because light attracts bugs!"
]

MENU_TEXT = (
    "🤖 *Main Menu* 🤖\n\n"
    "1. 🌐 *Our Services*\n"
    "2. 📅 *Book Consultation* (Interactive)\n"
    "3. 📞 *Contact Support*\n"
    "4. ℹ️ *About Us*\n"
    "5. 😄 *Tell me a joke*\n\n"
    "_Type 'reset' anytime to restart._"
)

def save_analytics(sentiment_score, sentiment_label, intent):
    """Logs data for the admin dashboard."""
    entry = {
        "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "sentiment_score": sentiment_score,
        "sentiment_label": sentiment_label,
        "intent": intent
    }
    
    data = []
    if os.path.exists(ANALYTICS_FILE):
        try:
            with open(ANALYTICS_FILE, 'r') as f:
                data = json.load(f)
        except:
            data = []
            
    data.append(entry)
    # Keep last 100 entries only for demo
    if len(data) > 100:
        data = data[-100:]
        
    with open(ANALYTICS_FILE, 'w') as f:
        json.dump(data, f, indent=4)

def save_booking(name, date, topic, phone):
    """Saves booking to JSON."""
    entry = {
        "name": name,
        "date": date,
        "topic": topic,
        "phone": phone,
        "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }
    
    data = []
    if os.path.exists(BOOKINGS_FILE):
        try:
            with open(BOOKINGS_FILE, 'r') as f:
                data = json.load(f)
        except:
            data = []
            
    data.append(entry)
    with open(BOOKINGS_FILE, 'w') as f:
        json.dump(data, f, indent=4)

def load_bookings():
    if os.path.exists(BOOKINGS_FILE):
        try:
            with open(BOOKINGS_FILE, 'r') as f:
                return json.load(f)
        except:
            pass
    return []

def get_analytics_data():
    if os.path.exists(ANALYTICS_FILE):
        try:
            with open(ANALYTICS_FILE, 'r') as f:
                data = json.load(f)
            
            # Process for charts
            positive = len([x for x in data if x['sentiment_label'] == 'positive'])
            neutral = len([x for x in data if x['sentiment_label'] == 'neutral'])
            negative = len([x for x in data if x['sentiment_label'] == 'negative'])
            
            return {
                "sentiment_counts": [positive, neutral, negative],
                "total_interactions": len(data),
                "recent_intents": [x['intent'] for x in data[-10:]]
            }
        except:
            pass
    return {"sentiment_counts": [0,0,0], "total_interactions": 0, "recent_intents": []}

def get_sentiment(text):
    blob = TextBlob(text)
    polarity = blob.sentiment.polarity
    if polarity > 0.1:
        return polarity, 'positive'
    elif polarity < -0.1:
        return polarity, 'negative'
    return polarity, 'neutral'

def fuzzy_match_command(text, options):
    match, score = process.extractOne(text, options)
    return match if score > 70 else None

def process_message(message, sender):
    message = message.strip().lower()
    
    # Initialize session
    if sender not in sessions:
        sessions[sender] = {"state": "NORMAL", "data": {}, "lang": "en"}
    
    user_session = sessions[sender]
    current_state = user_session["state"]
    current_lang = user_session.get("lang", "en")
    
    # Analyze Sentiment first for tracking
    score, sentiment_label = get_sentiment(message)
    intent = "unknown" # Will update below

    # Urgency Detection
    urgent_keywords = ["urgent", "emergency", "asap", "immediate", "broken"]
    is_urgent = any(k in message for k in urgent_keywords)

    if message == "reset":
        user_session["state"] = "NORMAL"
        return "🔄 Conversation reset. " + MENU_TEXT
        
    if "hindi" in message:
        user_session["lang"] = "hi"
        return "🇮🇳 भाषा को हिंदी में बदल दिया गया।\n" + HINDI_STRINGS["menu"]
        
    if "english" in message:
        user_session["lang"] = "en"
        return "🇺🇸 Language set to English.\n" + MENU_TEXT

    reply = ""

    # STATE: NORMAL
    if current_state == "NORMAL":
        if is_urgent:
            intent = "urgency"
            reply = "🚨 **Urgency Detected**\nWe have flagged this conversation for immediate supervisor attention. Please hold."
        
        elif sentiment_label == 'negative' and ("help" in message or "support" in message):
            intent = "negative_support"
            reply = "😟 It seems like you're having a tough time. I'm prioritizing your query for a human agent."

        elif any(x in message for x in ["hi", "hello", "hey", "start", "नमस्ते"]):
            intent = "greeting"
            if current_lang == "hi":
                reply = HINDI_STRINGS["greeting"] + HINDI_STRINGS["menu"]
            else:
                reply = "👋 *Hello!* Welcome to RSK World's Advanced AI Assistant (2026).\n" + MENU_TEXT

        else:
            cmd = fuzzy_match_command(message, ["services", "consultation", "booking", "contact", "about", "help", "joke", "funny"])
            
            if message == "1" or cmd == "services":
                intent = "services"
                if current_lang == "hi":
                    reply = HINDI_STRINGS["services"]
                else:
                    reply = ("🚀 *Our Services:*\n\n"
                            "- 🌐 Web Development\n"
                            "- 🤖 Custom Chatbots\n"
                            "- 🧠 AI Solutions\n"
                            "- 📈 Digital Marketing\n\n"
                            "Reply with a topic (e.g., 'seo') to learn more.")
            
            elif message == "2" or cmd in ["consultation", "booking"]:
                intent = "booking_start"
                user_session["state"] = "BOOKING_NAME"
                reply = "📅 *Book a Free Consultation*\n\nFirst, what is your **Full Name**?"
            
            elif message == "3" or cmd == "contact":
                intent = "contact"
                if current_lang == "hi":
                    reply = HINDI_STRINGS["contact"]
                else:
                    reply = "📞 *Contact Us*\nEmail: info@rskworld.com\nPhone: +91 93305 39277"
            
            elif message == "4" or cmd == "about":
                intent = "about"
                reply = "ℹ️ RSK World (2026) specializes in AI-driven automation."
                
            elif message == "5" or cmd in ["joke", "funny"]:
                intent = "joke"
                reply = f"😄 {random.choice(JOKES)}\n\n_Haha! Type 'menu' for more options._"

            else:
                # Local KB Search
                kb_match = fuzzy_match_command(message, list(SERVICES.keys()))
                if kb_match:
                    intent = "kb_query"
                    reply = f"💡 *{kb_match.title()} Service:*\n{SERVICES[kb_match]}"
                else:
                    if current_lang == "hi":
                        reply = HINDI_STRINGS["fallback"]
                    else:
                        reply = "🤔 I didn't quite catch that. Try saying 'hi' to see the menu."

    # STATE: BOOKING FLOW (English only for now for simplicity)
    elif current_state == "BOOKING_NAME":
        intent = "booking_name"
        user_session["data"]["name"] = message
        user_session["state"] = "BOOKING_DATE"
        reply = f"Nice to meet you, {message.title()}! 👋\nWhen would you like to schedule? (e.g., 'Tomorrow')"

    elif current_state == "BOOKING_DATE":
        intent = "booking_date"
        user_session["data"]["date"] = message
        user_session["state"] = "BOOKING_TOPIC"
        reply = "✍️ Got it. What is the topic? (e.g., 'New Website')"

    elif current_state == "BOOKING_TOPIC":
        intent = "booking_finish"
        user_session["data"]["topic"] = message
        
        save_booking(user_session["data"]["name"], 
                    user_session["data"]["date"], 
                    user_session["data"]["topic"], 
                    sender)

        user_session["state"] = "NORMAL"
        user_session["data"] = {}
        
        reply = "✅ *Booking Confirmed!* We'll be in touch."

    # Save analytics before returning
    save_analytics(score, sentiment_label, intent)
    
    return reply
279 lines•10.9 KB
python

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