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
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
bot_logic.py
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
🚀 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