Skip to main content

Python chatbot sample


Prerequisites:

    1. Install python 3.11.4

    2. Install Flask by pip install Flask

How to Install:

    1. Open command prompt.

    2. Change the directory (CD) to where the app.py file is presenting.

    3. After navigating to the folder type python. It will automatically trigger  to install the latest python package. Example -   

          C:\Users\PythonProjectFolder>python

    4. Install the Flask.
       
      C:\Users\PythonProjectFolder>pip install Flask

How to run the website:

          C:\Users\PythonProjectFolder>python app.py

Steps to creating the files:

1. Create one main folder and sub folder structure like below. We are going to using the note pad as the code editor.



2. The app.py is the start up file and routing to the sub pages. app.py code is below.

from flask import Flask, render_template, request
from contact import contacts_bp
from chatbot import chatbot_bp
app = Flask(__name__)
app.register_blueprint(contacts_bp)
app.register_blueprint(chatbot_bp)
# Route for the home page
@app.route('/')
def home():
    return render_template('index.html')
# Route for the about page
@app.route('/about')
def about():
    return render_template('about.html')
# Route for the helpdesk page
@app.route('/helpdesk')
def helpdesk():
    return render_template('helpdesk.html')
if __name__ == '__main__':
    app.run(debug=True)

3. I am using master page to serve the unique styles to entire website, name is base.html code is below.

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}Sample Website{% endblock %}</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <header>
        <h1>Welcome to the Sample Website</h1>
        <nav>
            <a href="/">Home</a>
            <a href="/helpdesk">Help Desk</a>
            <a href="/contact">Contact Us</a>
        </nav>
    </header>
    <main>
        {% block content %}{% endblock %}
    </main>
    <footer>
        <p>&copy; 2023 Sample Website</p>
    </footer>
</body>
</html>

4. The base.html file referring the style.css.

body {
    font-family: Arial, sans-serif;
    margin: 20px;
}

h1 {
    color: #333;
}

a {
    color: #007BFF;
    text-decoration: none;
}

5. index.html code is below.

{% extends "base.html" %}

{% block title %}Home Page{% endblock %}

{% block content %}
    <p>This is a simple sample website built using Python and Flask.</p>
{% endblock %}

6. about.html code 

{% extends "base.html" %}

{% block title %}About Page{% endblock %}

{% block content %}
    <h1>About Us</h1>
    <p>This is the about page content.</p>
    <a href="/">Home</a>
    <a href="/contact">Contact</a>
{% endblock %}

7. helpdesk.html

{%extends "base.html"%}
{%block title%}Help Desk{%endblock%}
{%block content%}
   <h2>Chat with our Chatbot:</h2>
    <div id="chat-box"></div>
    <form id="chat-form">
        <input type="text" id="user-message" placeholder="Type your message..." autocomplete="off" required>
        <button type="submit">Send</button>
    </form>

    <a href="/">Back to Home</a>
<script src="{{ url_for('static', filename='chatbot.js') }}"></script>
{%endblock%}

8. contact.html

{%extends "base.html"%}
{%block title%}Contact Us{%endblock%}
{%block content%}
<h2>Sample Contacts</h2>
<ul>
{%for contact in contacts%}
<li>{{contact.name}}-{{contact.email}}</li>
{%endfor%}
</ul>
<p>Total Contacts: {{ total_contacts }}</p>
    <form method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required><br>

        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required><br>

        <label for="message">Message:</label><br>
        <textarea id="message" name="message" rows="4" required></textarea><br>

        <input type="submit" value="Submit">
    </form>
    <a href="/">Back to Home</a>
<script src="{{ url_for('static', filename='chatbot.js') }}"></script>
{%endblock%}

9. chatbot.js

document.addEventListener('DOMContentLoaded', () => {
  const chatForm = document.getElementById('chat-form');
  const chatBox = document.getElementById('chat-box');

  chatForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const userMessage = e.target.elements['user-message'].value;
    const botResponse = await sendMessage(userMessage);
    displayMessage('user', userMessage);
    displayMessage('bot', botResponse.bot_response);
    e.target.elements['user-message'].value = '';
  });

  async function sendMessage(message) {
    const response = await fetch('/chatbot', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ message }),
    });
    return response.json();
  }

  function displayMessage(sender, message) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `${sender}-message`;
    messageDiv.textContent = `${sender === 'user' ? 'You' : 'Bot'}: ${message}`;
    chatBox.appendChild(messageDiv);
    chatBox.scrollTop = chatBox.scrollHeight;
  }
});

10. contact.py

from flask import render_template, Blueprint, request

class Contact:
    def __init__(self):
        # Sample model data
        self.contacts = [
            {'name': 'John Doe', 'email': 'john@example.com'},
            {'name': 'Jane Smith', 'email': 'jane@example.com'},
            {'name': 'Alice Johnson', 'email': 'alice@example.com'}
        ]

    def contact_page(self):
        if request.method == 'POST':
            name = request.form['name']
            email = request.form['email']
            message = request.form['message']
            # Process the form data or save it to a database
            # For this example, we'll just print the data
            print(f"Name: {name}, Email: {email}, Message: {message}")
        return render_template('contact.html', contacts=self.contacts)

    def contact_page_get(self):
        return render_template('contact.html', contacts=self.contacts)

    @property
    def total_contacts(self):
        return len(self.contacts)

# Create a Blueprint object for the contact-related routes
contacts_bp = Blueprint('contact', __name__)
contact = Contact()

# Route for the contact page with a simple form and model data (GET method)
contacts_bp.add_url_rule('/contact', 'contact_page', contact.contact_page_get, methods=['GET'])

# Route for the contact page form submission (POST method)
contacts_bp.add_url_rule('/contact', 'contact_post', contact.contact_page, methods=['POST'])

11. chatbot.py

import json
import random
from flask import Blueprint, request

class Chatbot:
    def __init__(self):
    with open('data/data.json') as f:
    self.responses = json.load(f)

    def get_sample_contacts(self):
        # Sample model data
        return [
            {'name': 'John Doe', 'email': 'john@example.com'},
            {'name': 'Jane Smith', 'email': 'jane@example.com'},
            {'name': 'Alice Johnson', 'email': 'alice@example.com'}
        ]

    def get_response(self, message):
        response = self.responses.get(message.lower(), self.responses['default'])
        return random.choice(response)

    def chatbot_response(self, user_message):
        return {'bot_response': self.get_response(user_message)}

# Create a Blueprint object for the chatbot-related routes
chatbot_bp = Blueprint('chatbot', __name__)
chatbot = Chatbot()  # Create an instance of the Chatbot class

# Route for chatbot API
@chatbot_bp.route('/chatbot', methods=['POST'])
def chatbot_response_route():
    if request.method == 'POST':
        user_message = request.json['message']
        return chatbot.chatbot_response(user_message)


12. data.json

{
    "greeting": [
        "Hello!", 
        "Hi there!", 
        "Hey! How can I help you?"
    ],
    "name": [
        "My name is ChatBot. Nice to meet you!",
        "You can call me ChatBot.",
        "I'm ChatBot, at your service."
    ],
    "bye": [
        "Goodbye! Have a great day!",
        "Farewell! Come back anytime.",
        "See you later!"
    ],
    "default": [
        "I'm sorry, but I don't understand. Please try again.",
        "I'm not sure what you mean. Could you rephrase that?",
        "I'm still learning. Can you provide more context?"
    ]
}

output:



Comments

Popular posts from this blog

Data transfer from dataverse to Azure SQL using Microsoft Data Fabric

Transfer the data from dataverse to Azure SQL using Microsoft Data Fabric 1. Open  Microsoft Fabric 2. Select Data Engineering . 3. Go to your workspace. 4. Select the  Dataflow Gen2 . 4. Click the hyper link ' Get data from another source ' 5. Popup will open, Search by Dataverse and select. 6. Select your environment domain and click Next. 7. We can select our entities and click Create . 8. We have the option to Choose the specific columns. 9. I have selected accountid and name column from account entity. 10. Select the data destination from the drop down. I have selected Azure SQL Database. 11. Popup will open there we can fill the azure sql database server details. then Click Next. 12. Select the Database and choose Replace option then Click Save Settings. 13. Click Publish. 14. Dataflow is created and loading the data to Azure SQL. 15. Now the selected entity and corresponding data has been populated in the Azure SQL database. 16. We can set the timer to schedule the data...