How To Make A Chatbot In Python?

Aayushi Johari
Edureka
Published in
7 min readAug 6, 2019
How To Make A Chatbot In Python? — Edureka

Nowadays almost 30 percent of the tasks are fulfilled by chatbots. Companies use chatbots to provide services like customer support, generating information, etc. With examples like Siri, Alexa it becomes clear how a chatbot can make a difference in our daily lives. In this article, we will learn how to make a chatbot in python using the ChatterBot library which implements various machine learning algorithms to generate responses. Following are the topics discussed in this article:

  • What Is A Chatbot?
  1. Evolution Of Chatbots
  2. Limitations With A Chatbot
  3. How Does It Work?
  • Chatterbot Library In Python
  1. How Does It work?
  • Trainer For Chatbot
  • Use Case — Flask Chatbot

What Is A Chatbot?

A chatbot also known as a chatterbot, bot, artificial agent, etc is basically a software program driven by artificial intelligence which serves the purpose of making a conversation with the user by texts or by speech. Famous examples include Siri, Alexa, etc.

These chatbots are inclined towards performing a specific task for the user. Chatbots often perform tasks like making a transaction, booking a hotel, form submissions, etc. The possibilities with a chatbot are endless with the technological advancements in the domain of artificial intelligence.

Almost 30 percent of the tasks are performed by the chatbots in any company. Companies employ these chatbots for services like customer support, to deliver information, etc. Although the chatbots have come so far down the line, the journey started from a very basic performance. Let’s take a look at the evolution of chatbots over the last few decades.

Evolution Of Chatbots

It started in 1966 when Joseph Weizenbaum made a natural language conversational program that featured a dialog between a user and a computer program. With this great breakthrough came the new age chatbot technology that has taken an enormous leap throughout the decades.

Limitations With A Chatbot

With increasing advancements, there also comes a point where it becomes fairly difficult to work with the chatbots. Following are a few limitations we face with the chatbots.

  • Domain Knowledge — Since true artificial intelligence is still out of reach, it becomes difficult for any chatbot to completely fathom the conversational boundaries when it comes to conversing with a human.
  • Personality — Not being able to respond correctly and fairly poor comprehension skills has been more than frequent errors of any chatbot, adding a personality to a chatbot is still a benchmark that seems far far away. But we are more than hopeful with the existing innovations and progress-driven approaches.

How Does It Work?

We can define the chatbots into two categories, the following are the two categories of chatbots:

  1. Rule-Based Approach — In this approach, a bot is trained according to rules. Based on this a bot can answer simple queries but sometimes fails to answer complex queries.
  2. Self-Learning Approach — These bots follow the machine learning approach which is rather more efficient and is further divided into two more categories.
  • Retrieval-Based Models — In this approach, the bot retrieves the best response from a list of responses according to the user input.
  • Generative Models — These models often come up with answers than searching from a set of answers which makes them intelligent bots as well.

Let us try to make a chatbot from scratch using the chatterbot library in python.

ChatterBot Library In Python

ChatterBot is a library in python which generates responses to user input. It uses a number of machine learning algorithms to produce a variety of responses. It becomes easier for the users to make chatbots using the ChatterBot library with more accurate responses.

Language Independence

The design of ChatterBot is such that it allows the bot to be trained in multiple languages. On top of this, the machine learning algorithms make it easier for the bot to improve on its own using the user’s input.

How Does It work?

ChatterBot makes it easy to create software that engages in conversation. Every time a chatbot gets the input from the user, it saves the input and the response which helps the chatbot with no initial knowledge to evolve using the collected responses.

With increased responses, the accuracy of the chatbot also increases. The program selects the closest matching response from the closest matching statement that matches the input, it then chooses the response from the known selection of statements for that response.

How To Install ChatterBot In Python?

Run the following command in the terminal or in the command prompt to install ChatterBot in python.

pip install chatterbot

Trainer For Chatbot

Chatterbot comes with a data utility module that can be used to train the chatbots. At the moment there is training data for more than a dozen languages in this module. Take a look at the data files here.

Following is a simple example to get started with ChatterBot in python.

from chatterbot import chatbot
from chatterbot.trainers import ListTrainer

#creating a new chatbot
chatbot = Chatbot('Edureka')
trainer = ListTrainer(chatbot)
trainer.train([ 'hi, can I help you find a course', 'sure I'd love to find you a course', 'your course have been selected'])

#getting a response from the chatbot
response = chatbot.get_response("I want a course")
print(response)

In this example, we get a response from the chatbot according to the input that we have given. Let us try to build a rather complex flask-chatbot using the chatterbot-corpus to generate a response in a flask application.

Use Case — Flask ChatterBot

After we are done setting up the flask app, we need to add two more directories static and templates for HTML and CSS files. Following is the code for the flask ChatterBot app.

App.py

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

app = Flask(__name__)

english_bot = ChatBot("Chatterbot", storage_adapter="chatterbot.storage.SQLStorageAdapter")
trainer = ChatterBotCorpusTrainer(english_bot)
trainer.train("chatterbot.corpus.english")

@app.route("/")
def home():
return render_template("index.html")

@app.route("/get")
def get_bot_response():
userText = request.args.get('msg')
return str(english_bot.get_response(userText))


if __name__ == "__main__":
app.run()

index.html

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/static/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<h1>Flask Chatterbot Example</h1>
<div>
<div id="chatbox">
<p class="botText"><span>Hi! I'm Chatterbot.</span></p>
</div>
<div id="userInput">
<input id="textInput" type="text" name="msg" placeholder="Message">
<input id="buttonInput" type="submit" value="Send">
</div>
<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();
}
});
$("#buttonInput").click(function() {
getBotResponse();
})
</script>
</div>
</body>
</html>

index.html file will have the template of the app and style.css will contain the style sheet with the CSS code. After we execute the above program we will get the output like the image shown below.

Style.css

body
{
font-family: Garamond;
background-color: black;
}
h1
{
color: black;
margin-bottom: 0;
margin-top: 0;
text-align: center;
font-size: 40px;
}
h3
{
color: black;
font-size: 20px;
margin-top: 3px;
text-align: center;
}
#chatbox
{
background-color: black;
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: 87%;
border: none;
border-bottom: 3px solid #009688;
font-family: monospace;
font-size: 17px;
}
#buttonInput {
padding: 3px;
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: #009688;
padding: 10px;
border-radius: 2px;
}
.botText {
color: white;
font-family: monospace;
font-size: 17px;
text-align: left;
line-height: 30px;
}
.botText span {
background-color: #EF5350;
padding: 10px;
border-radius: 2px;
}
#tidbit {
position:absolute;
bottom:0;
right:0;
width: 300px;
}

Output:

Go to the address shown in the output, and you will get the app with the chatbot in the browser.

The chatbot will look something like this, which will have a textbox where we can give the user input, and the bot will generate a response for that statement.

In this article, we have learned how to make a chatbot in python using the ChatterBot library using the flask framework. With new-age technological advancements in the artificial intelligence and machine learning domain, we are only so far away from creating the best version of the chatbot available to mankind.

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Python and Data Science.

1. Machine Learning Classifier in Python

2. Python Scikit-Learn Cheat Sheet

3. Machine Learning Tools

4. Python Libraries For Data Science And Machine Learning

5. Python Interview Questions

6. Python Collections

7. Python Modules

8. Python developer Skills

9. OOPs Interview Questions and Answers

10. Resume For A Python Developer

11. Exploratory Data Analysis In Python

12. Snake Game With Python’s Turtle Module

13. Python Developer Salary

14. Principal Component Analysis

15. Python vs C++

16. Scrapy Tutorial

17. Python SciPy

18. Least Squares Regression Method

19. Jupyter Notebook Cheat Sheet

20. Python Basics

21. Python Pattern Programs

22. Generators in Python

23. Python Decorator

24. Python Spyder IDE

25. Mobile Applications Using Kivy In Python

26. Top 10 Best Books To Learn & Practice Python

27. Robot Framework With Python

28. Snake Game in Python using PyGame

29. Django Interview Questions and Answers

30. Top 10 Python Applications

31. Hash Tables and Hashmaps in Python

32. Python 3.8

33. Support Vector Machine

34. Python Tutorial

Originally published at https://www.edureka.co on August 6, 2019.

--

--

Aayushi Johari
Edureka

A technology enthusiast who likes writing about different technologies including Python, Data Science, Java, etc. and spreading knowledge.