loading...
Cover image for Build a Chatbot using Flask in 5 minutes

Build a Chatbot using Flask in 5 minutes

sahilrajput profile image Sahil Rajput Originally published at dev.to ・3 min read

Few weeks back I wrote a post Build your first ChatBot in 5 minutes.

That bot was cool and you can talk through terminal. Today, let’s try to build the same bot with Flask.

So, we will use ChatterBot which is a machine learning, conversational dialog engine for creating chat bots.

If you haven’t read my previous post go here

Install ChatterBot

$ pip install ChatterBot

Install Flask

$ pip install Flask

Create a file

app.py and open it

#import files
from flask import Flask, render_template, request
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
from chatterbot.trainers import ListTrainer

Create a flask app

app = Flask(__name__)

and as we have seen in my previous post

bot = ChatBot("Candice")
bot.set_trainer(ListTrainer)
bot.set_trainer(ChatterBotCorpusTrainer)
bot.train("chatterbot.corpus.english")

and after this

@app.route("/")
def home():    
    return render_template("home.html") 
@app.route("/get")
def get_bot_response():    
    userText = request.args.get('msg')    
    return str(bot.get_response(userText)) 
if __name__ == "__main__":    
    app.run()

So, as we can see we need to create a home.html file as a frontend.

Create a folder “templates” and inside that create a file home.html.

templates/home.html

Open home.html

  <!DOCTYPE html>
<html>
  <title>Candice</title>
  <body>
    <center>
      <h1>
        Your Personal ChatBot
      </h1>
    </center>
      <div>
       <p>
          <center><span>Hi! I'm Candice your personal ChatBot</span></center>
          </p>
       </div>
       <div id="userInput">
          <input id="textInput" type="text" name="msg" placeholder="Message" />
       </div>
  </body>
</html>

So, this is just a basic structure let’s add some css to it. We are not creating another file for css, we are just adding style into home.html

<head>
    <link
      rel="shortcut icon"
      type="image/x-icon"
      href="https://user-images.githubusercontent.com/20112458/49326597-773b7280-f57a-11e8-853d-20ed61d18b0d.png"
    />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <style>
      body {
        font-family: monospace;
      }
      h1 {
        background-color: yellow;
        display: inline-block;
        font-size: 3em;
        margin: 0;
        padding: 14px;
      }
      h3 {
        color: black;
        font-size: 20px;
        margin-top: 3px;
        text-align: center;
      }
      #chatbox {
        margin-left: auto;
        margin-right: auto;
        width: 40%;
        margin-top: 60px;
      }
      #userInput {
        margin-left: auto;
        margin-right: auto;
        width: 40%;
        margin-top: 60px;
      }
      #textInput {
        width: 90%;
        border: none;
        border-bottom: 3px solid black;
        font-family: monospace;
        font-size: 17px;
      }
      .userText {
        color: white;
        font-family: monospace;
        font-size: 17px;
        text-align: right;
        line-height: 30px;
      }
      .userText span {
        background-color: #808080;
        padding: 10px;
        border-radius: 2px;
      }
      .botText {
        color: white;
        font-family: monospace;
        font-size: 17px;
        text-align: left;
        line-height: 30px;
      }
      .botText span {
        background-color: #4169e1;
        padding: 10px;
        border-radius: 2px;
      }
      #tidbit {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 300px;
      }
      .boxed {
        margin-left: auto;
        margin-right: auto;
        width: 78%;
        margin-top: 60px;
        border: 1px solid green;
      }
      .box {
        border: 2px solid black;
      }
    </style>
</head>

Now, after that let’s change body structure.

<body>
    <center>
      <h1>
        <img
          src="https://user-images.githubusercontent.com/20112458/49326597-773b7280-f57a-11e8-853d-20ed61d18b0d.png"
          alt="CANDICE"
          style="width:40px;height:40px;"
        />Your Personal ChatBot
      </h1>
    </center>
<div class="box"></div>
    <div class="boxed">
      <div>
        <div id="chatbox">
          <img
            src="https://user-images.githubusercontent.com/20112458/49326597-773b7280-f57a-11e8-853d-20ed61d18b0d.png"
            alt="CANDICE"
            style="width:40px;height:40px;"
          />
          <p class="botText">
            <span>Hi! I'm Candice your personal ChatBot</span>
          </p>
        </div>
        <div id="userInput">
          <input id="textInput" type="text" name="msg" placeholder="Message" />
        </div>
      </div>
    </div>
  </body>

Now, if we type something nothing will happen. So, let’s add some script

<script>
        function getBotResponse() {
          var rawText = $("#textInput").val();
          var userHtml = '<p class="userText"><span>' + rawText + "</span></p>";
          $("#textInput").val("");
          $("#chatbox").append(userHtml);
          document
            .getElementById("userInput")
            .scrollIntoView({ block: "start", behavior: "smooth" });
          $.get("/get", { msg: rawText }).done(function(data) {
            var botHtml = '<p class="botText"><span>' + data + "</span></p>";
            $("#chatbox").append(botHtml);
            document
              .getElementById("userInput")
              .scrollIntoView({ block: "start", behavior: "smooth" });
          });
        }
        $("#textInput").keypress(function(e) {
          if (e.which == 13) {
            getBotResponse();
          }
        });
</script>

Now, you will see whatever you write will be shown on the ChatBox but your chatbot will not give any reply.

So, to do that let’s run your app.py

$ python app.py

So, go to the link and chat with your personal ChatBot

You can find the full source code on my Github.

Posted on Nov 1 '18 by:

Discussion

markdown guide
 

You might enjoy Stream's react components: getstream.io/chat/react-chat/tutor...

We have a lot of AI related tutorials coming up btw. Message me if you're interested in doing some freelance writing.

 
 
  • Running on 127.0.0.1:5000/ (Press CTRL+C to quit) [2019-09-18 21:05:34,441] ERROR in app: Exception on / [GET] Traceback (most recent call last): File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise raise value File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request return self.view_functionsrule.endpoint File "/home/muzibur/PycharmProjects/corpus/venv/app.py", line 13, in home return render_template("index.html") File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/templating.py", line 134, in render_template return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list), File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/jinja2/environment.py", line 869, in get_or_select_template return self.get_template(template_name_or_list, parent, globals) File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/jinja2/environment.py", line 830, in get_template return self._load_template(name, self.make_globals(globals)) File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/jinja2/environment.py", line 804, in _load_template template = self.loader.load(self, name, globals) File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/jinja2/loaders.py", line 113, in load source, filename, uptodate = self.get_source(environment, name) File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/templating.py", line 58, in get_source return self._get_source_fast(environment, template) File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/templating.py", line 86, in _get_source_fast raise TemplateNotFound(template) jinja2.exceptions.TemplateNotFound: index.html 127.0.0.1 - - [18/Sep/2019 21:05:35] "GET / HTTP/1.1" 500 - 127.0.0.1 - - [18/Sep/2019 21:05:39] "GET /favicon.ico HTTP/1.1" 404 - [2019-09-18 21:17:03,880] ERROR in app: Exception on / [GET] Traceback (most recent call last): File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise raise value File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request return self.view_functionsrule.endpoint File "/home/muzibur/PycharmProjects/corpus/venv/app.py", line 13, in home return render_template("index.html") File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/templating.py", line 134, in render_template return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list), File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/jinja2/environment.py", line 869, in get_or_select_template return self.get_template(template_name_or_list, parent, globals) File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/jinja2/environment.py", line 830, in get_template return self._load_template(name, self.make_globals(globals)) File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/jinja2/environment.py", line 804, in _load_template template = self.loader.load(self, name, globals) File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/jinja2/loaders.py", line 113, in load source, filename, uptodate = self.get_source(environment, name) File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/templating.py", line 58, in get_source return self._get_source_fast(environment, template) File "/home/muzibur/anaconda3/envs/Chatbot/lib/python3.7/site-packages/flask/templating.py", line 86, in _get_source_fast raise TemplateNotFound(template) jinja2.exceptions.TemplateNotFound: index.html 127.0.0.1 - - [18/Sep/2019 21:17:03] "GET / HTTP/1.1" 500 -

This error showen here Please help me!

 
bot = ChatBot("Candice")

File "C:\Users\sangv\AppData\Local\Programs\Python\Python38\lib\site-packages\chatterbot\chatterbot.py", line 35, in init
self.storage = utils.initialize_class(storage_adapter, **kwargs)
File "C:\Users\sangv\AppData\Local\Programs\Python\Python38\lib\site-packages\chatterbot\utils.py", line 54, in initialize_class
return Class(*args, **kwargs)
File "C:\Users\sangv\AppData\Local\Programs\Python\Python38\lib\site-packages\chatterbot\storage\sql_storage.py", line 22, in init
from sqlalchemy import create_engine
File "C:\Users\sangv\AppData\Local\Programs\Python\Python38\lib\site-packages\sqlalchemy_init.py", line 8, in
from . import util as _util # noqa
File "C:\Users\sangv\AppData\Local\Programs\Python\Python38\lib\site-packages\sqlalchemy\util__init
_.py", line 14, in
from ._collections import coerce_generator_arg # noqa
File "C:\Users\sangv\AppData\Local\Programs\Python\Python38\lib\site-packages\sqlalchemy\util_collections.py", line 16, in
from .compat import binary_types
File "C:\Users\sangv\AppData\Local\Programs\Python\Python38\lib\site-packages\sqlalchemy\util\compat.py", line 264, in
time_func = time.clock
AttributeError: module 'time' has no attribute 'clock'

C:\Users\sangv\Desktop>python app.py
Traceback (most recent call last):
File "app.py", line 5, in
from time import clock
ImportError: cannot import name 'clock' from 'time' (unknown location)

C:\Users\sangv\Desktop>python
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.


THIS ERROR IS OCCURING WHILE RUNNING
PLEASE TELL ME WHAT SHOULD I DO?

 

Can you please explain the code written inside the

 

which versions you have used ?

i am getting error while installing chatterbot.
please reply soon.

thank you

 

stop your antivirus, and start installing the module again

 

Can you please explain the script???

 

I am having the below error.

Traceback (most recent call last):
File "app.py", line 9, in
bot.set_trainer(ListTrainer)
AttributeError: 'ChatBot' object has no attribute 'set_trainer'

 

Use
trainer = ChatterBotCorpusTrainer(bot)
trainer.train('chatterbot.corpus.english')

 

That's good but one suggestion is when the user clicks the link please provide open in a new tab mode so that the users will read your entire post.