Building a Chatbot using Chatterbot in Python

In this tutorial, you’ll learn how to build a chatbot using chatterbot in Python.

Are you tired of waiting in long queues for your call to be connected to the customer service executive? Does reading FAQ’s make you feel lethargic? Then you are on the right page. Can you remember the last time you communicated to a customer service agent via chat for the wrong item being delivered to you? There is a high probability that you were being communicated to by a bot rather than a customer service representative. So what exactly are bots? How do we build one? What source of code does it require? These are some of the questions which will be answered in this blog post!

Artificial intelligence, which brings into play machine learning and Natural language Processing (NLP) for building a bot or chatbot, is specifically designed to unravel the smooth interaction between humans and computers. Chatbots are everywhere, be it a banking website, pizza store, to e-commerce shopping stores, you will find chatbots left, right, and center. Chatbots provide real-time customer service assistance on a range of pre-defined questions related to the domain it is built on. It adapts natural human language and converses with humans in a human-like manner.

To simplify the chatbot’s definition, we can say chatbots are the evolution of Question Answer systems employing natural language processing. As per sources by the year 2024, the global conversation market’s size will grow to $15.7 billion, with 30.2% being the annual growth rate. For instance, amidst the CoronaVirus Pandemic, we have witnessed thousands of hoaxes circulating on WhatsApp, such as what can be used to treat COVID or what can be beneficial in increasing immunity, or whether the virus was developed in a lab. Putting an end to such hoaxes, Facebook launched a chatbot that works as a fact-checker.

In this tutorial, we’ll learn Chatbot building in detail, including:

  • Introduction
  • What is Chatbot?
  • How Does Chatbot Work?
  • Comparison of Chatbot platforms
  • Chatterbot Library
  • Building a Chatbot using Chatterbot
  • Chatbot Testing
  • Conclusion

Originally published on

What is a chatbot?

Chatbots helps any business/organization in accomplishing the following goals:

  • Increases operational efficiency.
  • Automating customer request fulfillment.
  • Handling basic queries, which in turn free employees to work for complex & higher value inquiries.
  • Offers Multi-language support.
  • Saves time & effort by automating customer support.
  • Improves the response rate as well as customer engagement.
  • Personalization of communication
Image for post
Image for post


How Does a Chatbot Work?

  • Rule-Based Chatbot: This is the basic chatbot made, the user interacts with this kind of bot by using predefined options. To get answers from these bots, users need to click on certain options. These kinds of bots collect the user’s request, analyze it, and then offer results in the form of buttons. These bots are commonly used to replace frequently asked questions when it comes to complex queries; they aren’t always the best solution.
  • Independent(Keyword) Chatbots: These are machine learning bots, unlike rule-based chatbots, they analyze what the user wants and respond appropriately. These chatbots use customizable keywords and machine learning to determine how to respond to users’ requests effectively and efficiently.
  • NLP (Contextual) Chatbots: These are so far the most advanced chatbots. They are a combination of best from rule-based and keyword chatbots. These chatbots use NLP to understand the context and intent in users’ requests and thus act accordingly. These chatbots can handle multiple requests from the same user at ease.

Comparisons of Chatbot Platform

Listing down the AI chatbot building platform in 2020:

  • Azure Bot Service: Azure bot service offers to build a chatbot from scratch, i.e., you can build, connect, test, and deploy. It allows developers to use the open-source SDK and tools. It also enables developers to create advanced bots such as virtual assistants to handle complex queries.
  • Botsify: This tool’s uniqueness is that it enables non-technical users to build a chatbot with its intuitive interface. Bots are represented here as stories, i.e., you can create multiple stories or multiple chatbots and deploy them as per the requirement. Another great feature is the ability to save users’ responses to a form that can be easily exported to a CSV.
  • Amazon Lex: Amazon lex allows developers to build conversational interfaces using text and voice. It comes up with advanced deep learning functionalities and NLP for understanding the context of the text. It provides an easy to use the console for building chatbot in minutes.
  • Mobile Monkey: Mobile monkey offers developers to build chatbots specifically for marketing purposes. It allows developers to make Facebook ad bots, SMS bots, and native web chatbots all in a single platform. They also offer ready-made chatbot templates for every business possible, which can be directly embedded on a website.
  • ChatterOn: It claims to handle different types of rich content responses from the Bot as it allows developers to connect different APIs at each interaction with the user. ChatterOn offers more than 20 pre-built bolts that can be put to use in a single click. It doesn’t require much coding, which makes it easier for non-technical users to build chatbots.
  • TARS: It offers you to build a conversational landing page, which enables you to create an automated chatbot to greet you, customers, give them relevant information about their queries regarding your products, and ask for their contact simultaneously. Tars offers many pre-defined chatbot templates, which are classified into two parts — by industry and by use-case.

By now, you must be curious to build a chatbot of your own. And what’s better than a customizable NLP chatbot? Let’s get started on building our very own chatbot in Python using library chatterbot.


Image for post
Image for post

As the name suggests, chatterbot is a python library specifically designed to generate chatbots. This algorithm uses a selection of machine learning algorithms to fabricate varying responses to users as per their requests.

Chatterbot makes it easier to develop chatbots that can engage in conversations. It starts by creating an untrained chatterbot that has no prior experience or knowledge regarding how to communicate. As the users enter statements, the library saves the request made by the user as well as it also saves the responses that are sent back to the users. As the number of instances increases in chatterbot, the accuracy of the responses made by chatterbot also increases.

Chatterbot is trained to search the closest analogous response by finding the closest analogous request made by users that is equivalent to the new request made. Then it selects a response from the already existing responses. The USP of chatterbot is that it enables developers to create their own dataset and structures at ease.

Building a Chatbot using Chatterbot

Installation commands for terminal:

pip install chatterbotpip install chatterbot_corpus

Installation commands for Jupyter Notebook:

!pip install chatterbot!pip install chatterbot_corpus

Let’s first import the Chatbot class of the chatterbot module.

# Importing chatterbot
from chatterbot import ChatBot

Create Chatbot Instance

# Create object of ChatBot class
bot = ChatBot('Buddy')
[nltk_data] Downloading package averaged_perceptron_tagger to
[nltk_data] /root/nltk_data...
[nltk_data] Unzipping taggers/
[nltk_data] Downloading package stopwords to /root/nltk_data...
[nltk_data] Unzipping corpora/
[nltk_data] Downloading package wordnet to /root/nltk_data...
[nltk_data] Unzipping corpora/

You can position the storage adapter with the chatbot object. Storage Adapters allow you to connect to a particular storage unit or network. For using a storage adapter, we need to specify it. We will position the storage adapter by assigning it to the import path of the storage we want to use. Here we are using SQL Storage Adapter, which permits chatbot to connect to databases in SQL. By using the database parameter, we will create a new SQLite Database. Please follow the code below, for creating a new database for chatbot.

# Create object of ChatBot class with Storage Adapter
bot = ChatBot(

You can also position the logical adapter with a chatbot object. As the name implies, Logical Adapter regulates the logic behind the chatterbot, i.e., it picks responses for any input provided to it. This parameter contains a list of logical operators. Chatterbot allows us to use a number of logical Adapters. When more than one logical adapter is put to use, the chatbot will calculate the confidence level, and the response with the highest calculated confidence will be returned as output. Here we have used two logical adapters: BestMatch and TimeLogicAdapter.

# Create object of ChatBot class with Logic Adapter
bot = ChatBot(

Training the chatbot

# Inport ListTrainer
from chatterbot.trainers import ListTrainer
trainer = ListTrainer(bot)trainer.train([
'I need your assistance regarding my order',
'Please, Provide me with your order id',
'I have a complaint.',
'Please elaborate, your concern',
'How long it will take to receive an order ?',
'An order takes 3-5 Business days to get delivered.',
'Okay Thanks',
'No Problem! Have a Good Day!'
List Trainer: [####################] 100%

Chatbot Testing

# Get a response to the input text 'I would like to book a flight.'
response = bot.get_response('I have a complaint.')
print("Bot Response:", response)Bot Response: Please elaborate, your concern

We will create a while loop for our chatbot to run in. When statements are passed in the loop, we will get an appropriate response for it, as we have already entered data into our database. If we get “Bye” or “bye” statement from the user, we can put an end to the loop and stop the program.

name=input("Enter Your Name: ")
print("Welcome to the Bot Service! Let me know how can I help you?")
while True:
if request=='Bye' or request =='bye':
print('Bot: Bye')
Enter Your Name: Avinash
Welcome to the Bot Service! Let me know how can I help you?
Avinash:I need your assistance regarding my order
Bot: Please, Provide me with your order id
Bot: No Problem! Have a Good Day!
Bot: Bye


This article was based on learning how to make a chatbot in Python using the ChatterBot library. Building a chatbot with ChatterBot was not only simple but also, the results were accurate. With Artificial Intelligence and Machine Learning, in advancement, everything and anything is possible to achieve whether it is creating bots with conversational skills like humans or be it anything else.

Originally published on

Do you want to learn data science, check out on DataCamp.

For more such article, you can visit my blog Machine Learning Geek

Image for post
Image for post

Sr Data Scientist| Analytics Consulting | Data Science Communicator | Helping Clients to Improve Products & Services with Data

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store