Join our Telegram Community Join Us Join Now!

How To Make A Chatbot In Python

How To Make A Chatbot In Python
Please wait 0 seconds...
Scroll Down and click on link or Go to Link for destination
Congrats! Link is Generated

Chatbots now complete nearly 30 percent of all tasks. Chatbots are used by businesses to provide services such as customer support, information generation, and so on. With examples such as Siri and Alexa, it is clear how a chatbot can help us in our daily lives. In this article, we'll look at how to create a chatbot in Python with the ChatterBot library, which uses various machine-learning algorithms to generate responses.

What Is A Chatbot?

A chatbot, also known as a chatterbot, bot, artificial agent, and so on, is a software program powered by artificial intelligence that allows the user to communicate with it via text or speech. Famous examples include Siri, Alexa, etc.

These chatbots are programmed to perform a specific task for the user. Chatbots frequently perform tasks such as transaction processing, hotel booking, form submissions, and so on. With technological advancements in the field of artificial intelligence, the possibilities for a chatbot are limitless.

Chatbots perform nearly 30% of all tasks in any organization. Chatbots are used by businesses to provide services such as customer support, information delivery, and so on. Despite how far chatbots have progressed, the journey began with very basic performance. Let's take a look at how chatbots have evolved over the last few decades.

Evolution Of Chatbots

It all started in 1966 when Joseph Weizenbaum created a natural language conversational program with a dialogue between a user and a computer program. With this great breakthrough came the new age of chatbot technology which has taken an enormous leap throughout the decades.

Traditional BotsCurrent BotsFuture Bots
System DrivenDriven by back-and-forth communicationCommunication at multiple-levels
Automation basedThe automation is at the task levelAutomation at the service level
Minimal FunctionalityMaintains system contextAbility to maintain task, system and people context
Maintained only system contextMaintains task context as well

Introduction to master bots and eventually a bot OS as well.


Limitations With A Chatbot

With increasing advancements, there comes a point where working with chatbots becomes somewhat difficult. The following are some of the limitations of 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 having 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 classify chatbots into two categories. Here are the two chatbot categories:

  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 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 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. Currently, 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('PrepsNG')
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.

How To Make A Chatbot In Python

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:

How To Make A Chatbot In Python

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

How To Make A Chatbot In Python

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.

Share This Post: If you believe this post will be useful to others, please share it using the buttons below!

2 comments

  1. So Nice, I gained a lot through this.
  2. I actually took my time to study this and it's just best to say the author of this content knows exactly what he was doing while he was writing the article

Advertisement

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.