Building a Chatbot using Chatterbot in Python

Do you find waiting in long queues for customer service frustrating? Do you dislike reading through FAQ pages? If so, you are in the right place. Have you ever chatted with a customer service agent regarding a wrong item being delivered to you, only to find out it was a bot responding to you? This blog post will answer questions such as: What are bots? How are they built? What code sources are required?

Artificial intelligence, specifically designed to improve human−computer interactions, utilises machine learning and Natural Language Processing (NLP) to create chatbots. Chatbots are present in various industries, such as banking, pizza stores, and e−commerce shopping stores, providing real−time customer service assistance related to their respective domains. Chatbots converse with humans in a natural, human−like manner by adapting to natural human language.

Chatbots have become increasingly popular in recent years due to their ability to improve customer engagement and reduce workload for customer service representatives. In fact, studies show that 80% of businesses are already using or planning to use chatbots by 2022.

In simpler terms, chatbots are an evolution of question−answer systems that utilise natural language processing. According to recent data, the global chatbot market size is projected to reach $16.5 billion by 2024, with an annual growth rate of 29.7%. With the growing trend of customer self−service, chatbots provide a convenient and efficient way for customers to find answers to their queries without having to wait for human assistance.

Overall, chatbots have revolutionised the way businesses interact with their customers, providing a cost−effective solution for customer support while enhancing the overall customer experience.

What is a chatbot?

In 1994, Michael Mauldin created his first chatbot named "Julia", leading to the birth of the term "chatterbot". According to the Oxford Dictionary, a chatbot is defined as a computer program that simulates conversation with human users, primarily over the internet. Chatbots act as virtual assistants, communicating with users via text messages and helping businesses establish closer connections with their customers. Essentially, chatbots are designed to replicate the way humans communicate with each other, whether through a chat interface or voice call. Developers strive to create chatbots that are difficult for users to differentiate between a human and a robot.

Below are the points where we will discuss why and where chatbots are useful in today's world.

Why are chatbots useful?

  • 24/7 availability: Chatbots can provide customer service support round the clock without requiring breaks or time off, making them ideal for businesses that operate in different time zones.

  • Cost−effective: Chatbots can help businesses reduce their operational costs, as they can handle multiple customer queries simultaneously without needing additional staff.

  • Personalization: Chatbots can be programmed to provide personalised responses to customers based on their preferences, purchase history, and other data.

  • Improved customer engagement: Chatbots can enhance customer engagement by providing a conversational experience that is more interactive and user−friendly than traditional customer service methods.

Where are chatbots useful?

  • E−commerce: Chatbots can help customers find products, provide product recommendations, and answer common queries related to orders and delivery.

  • Healthcare: Chatbots can help patients find information about their health conditions, schedule appointments, and get reminders about medication schedules.

  • Finance: Chatbots can assist customers with account management, provide investment advice, and help with financial planning.

  • Travel: Chatbots can help customers find and book flights, hotels, and rental cars, as well as provide information on travel destinations.

  • Customer service: Chatbots can provide quick and efficient customer service support, answering frequently asked questions and resolving simple issues.

How does a chatbot work?

Chatbots use a combination of technologies such as machine learning, natural language processing (NLP), and artificial intelligence (AI) to simulate conversations with humans. Here's a detailed explanation of how chatbots work:

  • Input from the user: The conversation between the user and the chatbot starts with an input from the user. This can be a text message or a voice command.

  • Natural language processing (NLP): The chatbot uses NLP to analyze the input from the user and understand the intent behind it. This involves breaking down the input into individual words and identifying the key phrases, keywords, and context.

  • Retrieve information: Once the chatbot understands the user's intent, it retrieves the relevant information from its knowledge base or database. This information can be stored in a structured format like a database or unstructured format like a website or social media page.

  • Generate response: Based on the information retrieved, the chatbot generates a response that is relevant to the user's input. This response can be in the form of text, voice, or both.

  • Machine learning: As the chatbot interacts with more users, it learns from the conversations and improves its responses. This is done using machine learning algorithms that analyse the conversations and identify patterns.

  • Integration with other systems: Chatbots can be integrated with other systems such as customer relationship management (CRM) software, marketing automation tools, and e−commerce platforms to provide a seamless user experience.

  • Continuous improvement: Chatbots are continuously improved and updated to provide better responses, handle more complex queries, and integrate with new systems.

Overall, chatbots use a combination of advanced technologies to provide a conversational experience that is personalised, efficient, and user−friendly. With the ability to handle multiple queries simultaneously and provide 24/7 customer support, chatbots are becoming an essential tool for businesses of all sizes.

Now that we are familiar with what are chatbots, and where they are used and how beneficial they are, let's talk a little about chatterbot.


Chatterbot is a Python library that allows developers to create chatbots using natural language processing (NLP) and machine learning algorithms. It is a popular choice for building conversational interfaces and is used by businesses and developers worldwide.

Here are some of the features of Chatterbot:

  • Support for multiple languages: Chatterbot supports multiple languages including English, Spanish, French, and German, making it a versatile choice for developers working with international clients.

  • Pre−trained models: Chatterbot comes with pre−trained models that can be used out of the box to build chatbots quickly. These models are trained on large datasets and can provide accurate responses to common queries.

  • Custom training: Developers can also train Chatterbot on their own datasets to create a custom chatbot that can respond to specific queries and use cases.

  • Integration with other platforms: Chatterbot can be integrated with other platforms such as Facebook Messenger, Slack, and Twitter, allowing businesses to provide 24/7 customer support and improve customer engagement.

  • Support for different conversational formats: Chatterbot can be used to create chatbots that support different conversational formats such as text, voice, and video.

  • Open−source: Chatterbot is an open−source library, which means that developers can modify and customise it to suit their specific needs.

Now let's make use of chatterbot to write a few examples of simple chatbots in Python.

Example 1

The first step for us is to be able to install the chatbot library and for that we need to run the commands shown below.


pip install chatterbot

After the above command, we need to run the below command as well.


pip install chatterbot_corpus

Once these two commands run successfully on your machine, the next step is to create a new file named, and write the following code inside it.


from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

import logging
logger = logging.getLogger()

# Create a new chatbot instance
chatbot = ChatBot('MyChatBot')

# Create a new trainer for the chatbot
trainer = ListTrainer(chatbot)

# Train the chatbot on a dataset of conversations
	'How are you?',
	'I am doing well, thank you.',
	'That is good to hear.',
	'What is your name?',
	'My name is MyChatBot.',
	'Nice to meet you, MyChatBot.',

# Get a response to user input
response = chatbot.get_response('Hello')

# Print the response


This Python code demonstrates how to create and train a basic chatbot using the ChatterBot library:

  • Import the necessary libraries:

    • ChatBot class from chatterbot library to create the chatbot instance

    • ListTrainer class from chatterbot.trainers library to train the chatbot on a dataset of conversations

    • logging library to set the logger level to CRITICAL (optional)

  • Create a logger and set its level to CRITICAL (optional). This is done to suppress any logging messages from the chatbot.

  • Create a new chatbot instance using ChatBot('MyChatBot') constructor, where 'MyChatBot' is the name given to the chatbot.

  • Create a new trainer for the chatbot using ListTrainer(chatbot) constructor.

  • Train the chatbot using trainer.train() method with a list of conversation pairs as its argument. Each pair consists of a question and its corresponding answer.

  • Get a response from the chatbot for a given user input using chatbot.get_response() method. The user input is passed as an argument to this method.

  • Print the response obtained from the chatbot using print(response) statement.

To run the above code, we need to run the command shown below.



Once we run the above command, we should expect an output similar to the one shown below.


[nltk_data] Downloading package averaged_perceptron_tagger to
[nltk_data] 	/Users/mlatiya/nltk_data...
[nltk_data]   Package averaged_perceptron_tagger is already up-to-
[nltk_data]   	date!
[nltk_data] Downloading package punkt to /Users/mlatiya/nltk_data...
[nltk_data]   Package punkt is already up-to-date!
[nltk_data] Downloading package stopwords to
[nltk_data] 	/Users/mlatiya/nltk_data...
[nltk_data]   Package stopwords is already up-to-date!
List Trainer: [####################] 100%
Nice to meet you, MyChatBot.

Let's explore one more example of chatterbot.

Consider the code shown below.


from chatterbot import ChatBot

# Uncomment the following lines to enable verbose logging
import logging

# Create a new instance of a ChatBot
bot = ChatBot(

print('Welcome! Type something to begin, or enter "bye" to end the conversation.')

# The following loop will execute each time the user enters input
while True:
    	user_input = input()

    	if user_input.lower() == 'bye':

    	bot_response = bot.get_response(user_input)


	# Press ctrl-c or ctrl-d on the keyboard to exit
	except (KeyboardInterrupt, EOFError, SystemExit):


This code creates a command−line chatbot that responds to user input using a pre−trained model. The chatbot is created using the ChatBot class from the chatterbot library.

The ChatBot object is created with a name "Terminal" and some other parameters, such as the storage adapter to be used, which is set to a SQL storage adapter, and the logic adapters to be used. The logic adapters define how the chatbot will generate responses to user input. In this case, the chatbot will use a combination of a mathematical evaluation adapter, a time logic adapter, and a best match adapter.

The database_uri parameter sets the location of the database that the chatbot will use for storage. In this example, a SQLite database is used with the filename database.db.

Once the chatbot has been created, the code enters a loop that continuously prompts the user for input and prints the chatbot's response. The input() function is used to get user input from the command line, and the bot.get_response() method is used to get the chatbot's response to the user's input. The chatbot's response is then printed to the console using the print() function.

The loop will continue to execute until the user presses ctrl−c or ctrl−d on the keyboard, which will raise an exception and cause the loop to exit.

To run the above code, we need to run the command shown below.



Once we run the above command, we should expect an output similar to the one shown below.


[nltk_data] Downloading package averaged_perceptron_tagger to
[nltk_data] 	/Users/mlatiya/nltk_data...
[nltk_data]   Package averaged_perceptron_tagger is already up-to-
[nltk_data]   	date!
[nltk_data] Downloading package punkt to /Users/mlatiya/nltk_data...
[nltk_data]   Package punkt is already up-to-date!
[nltk_data] Downloading package stopwords to
[nltk_data] 	/Users/mlatiya/nltk_data...
[nltk_data]   Package stopwords is already up-to-date!
Welcome! Type something to begin, or enter "bye" to end the conversation.


In conclusion, the development of chatbots has revolutionised the way businesses interact with their customers. By using ChatterBot, a Python library for building chatbots, developers can easily create intelligent and responsive chatbots that can assist with various tasks. ChatterBot comes with several built−in adapters for common chatbot functions such as mathematical evaluation, time logic, and the ability to find the best match to a user's input.

Additionally, ChatterBot provides a simple interface for training the chatbot on custom datasets, allowing developers to tailor the chatbot to their specific needs. Overall, ChatterBot is a powerful tool for creating chatbots that can provide value to businesses and enhance the customer experience.

Updated on: 02-Aug-2023


Kickstart Your Career

Get certified by completing the course

Get Started