ChatterBot is a machine-learning based conversational dialogue engine build in Python which makes it possible to generate responses based on collections of known conversations. The language-independent design of ChatterBot allows it to be trained to speak any language. Initially, it has no knowledge, then based on training and communication it tries to respond to the user's query accurately. It matches the closest matching response by searching a statement that matches the input and how frequently the response is used. These things are highly customizable with logic adapters, training processes, preprocessors, filters, and other custom behaviour.
We'll install a
chatterbot package with pip. So first, open your terminal and type the following command with the appropriate Python version. Here I'm using v3.7.10 specifically.
pip install chatterbot
Check if the installation is successful, run the below command:
pip show chatterbot
Once done with installation let's start with a basic example.
Create a Bot
First, create a file named greet_bot.py. import ChatBot class from chatterbot library.
from chatterbot import ChatBot
Create a new chatbot named "GreetBot", you can give any name you want.
chatbot = ChatBot("GreetBot")
Training your Bot
Import ListTrainer from sets of available trainers to train bot with greet data so it can respond to our inputs.
from chatterbot.trainers import ListTrainer
Create trainer instance of ListTrainer with chatbot parameter, and train with list of sample greeting data.
trainer = ListTrainer(chatbot) train_data = [ "Hello", "Hi", "Hi, how are you?", "I'm doing great.", "Greetings!", "How do you do?", "Great, thanks for asking!", "What's up" ] trainer.train(train_data)
Retrieve response from Bot
To retrieve a response from trained bot use get_response method of bot object with input parameter.
response = chatbot.get_response('hi') print(response)
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer chatbot = ChatBot('GreetBot') trainer = ListTrainer(chatbot) train_data = [ "Hello", "Hi", "Hi, how are you?", "I'm doing great.", "Greetings!", "How do you do?", "Great, thanks for asking!", "What's up" ] trainer.train(train_data) response = chatbot.get_response('Hi') print(response)
To run a bot, run the script greet_bot.py
Thank You for reading this article. I hope this helps in some ways and get a basic idea of how to get started with bot building with Python and the Chatterbot library. This was a very basic explanation and demo. Share, Like, Subscribe and stay tuned for the same and other bot-building tutorials.