Build a Chatbot using Flask in 5 minutes
Tags: machinelearning, flask, python, chatbot
Published: 2019-06-29 06:30:33


Few weeks back I wrote a post  [Build your first ChatBot in 5 minutes.](https://dev.to/sahilrajput/build-your-first-chatbot-in-5-minutes--15e3)

That bot was cool and you can talk through terminal. Today, let’s try to build the same bot with  [Flask](http://flask.pocoo.org/).

So, we will use  [ChatterBot](https://chatterbot.readthedocs.io/en/stable/)  which is a machine learning, conversational dialog engine for creating chat bots.

If you haven’t read my previous post go  [here](https://dev.to/sahilrajput/build-your-first-chatbot-in-5-minutes--15e3)

#### Install ChatterBot

`$ pip install ChatterBot`

#### Install Flask

`$ pip install Flask`

#### Create a file

`app.py`  and open it

```python
#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

```python
app = Flask(__name__)
```
and as we have seen in my  [previous post](https://dev.to/sahilrajput/build-your-first-chatbot-in-5-minutes--15e3)

```python
bot = ChatBot("Candice")
bot.set_trainer(ListTrainer)
bot.set_trainer(ChatterBotCorpusTrainer)
bot.train("chatterbot.corpus.english")
```
and after this
```python
@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 <i>home.html</i> file as a frontend.

Create a folder “templates” and inside that create a file <i>home.html</i>.
```
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>
  ```

![](https://cdn-images-1.medium.com/max/1600/1*kowrn6V77r57CVrZIy8mSw.png)

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 <i>home.html</i>

```
<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 <i>body</i> 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>
```


![](https://cdn-images-1.medium.com/max/1600/1*pdTHnGd_9aZK3nxYn_lNwA.png)


Now, if we type something nothing will happen. So, let’s add some <i>script</i>
```
<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
```

![](https://cdn-images-1.medium.com/max/1600/1*HvzXW2m-BEhLBZvirNegIw.png)

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

![](https://cdn-images-1.medium.com/max/1600/1*HoWut3egxrpXrPlzdl_9yA.png)


You can find the full source code on my [Github](https://github.com/sahil-rajput/Candice-YourPersonalChatBot).