I was searching the internet on "How to build a Chatbot?" and I discovered ChatterBot which is a machine learning, conversational dialog engine for creating chat bots
In this article we will see how to build a chatbot with ChatterBot in just 5 minutes.
First Install ChatterBot
pip install ChatterBot
Create a file
#import ChatBot from chatterbot import ChatBot
Create a new chat bot with the name of your choice(I am using "Candice").
bot = ChatBot('Candice')
Your bot is created but at this point your bot has no knowledge, for that you have to train it on some data.
Also, by default the ChatterBot library will create a sqlite database to build up statements of the chats.
#import ListTrainer from chatterbot.trainers import ListTrainer bot.set_trainer(ListTrainer) # Training bot.train(['What is your name?', 'My name is Candice']) bot.train(['Who are you?', 'I am a bot, created by you' ])
Your bot is now trained on 2 statements. When you ask your bot "what is your name", it will reply back with "My name is Candice".
You can also trained it on multiple statements like
bot.train(['Do you know me?', 'Yes, you created me', 'No', 'Sahil?', 'No idea'])
As you can see it is difficult to train the bot on every single statements. So, we will use
ChatterBotCorpusTrainer to train our bot on the large dataset.
from chatterbot.trainers import ChatterBotCorpusTrainer # Create a new trainer for the chatbot trainer = ChatterBotCorpusTrainer(bot) # Train the chatbot based on the english corpus trainer.train("chatterbot.corpus.english") # Get a response to an input statement chatbot.get_response("Hello, how are you today?")
or you can download the dataset of your language and train your bot in your language.
I downloaded the english language dataset and we can train our bot like this
for files in os.listdir('./english/'): data=open('./english/'+files,'r').readlines() bot.train(data)
NOTE: Make sure the dataset and the program file is on same folder, otherwise edit the path.
# To exit say "Bye" while True: # Input from user message=input('\t\t\tYou:') #if message is not "Bye" if message.strip()!='Bye': reply=bot.get_response(message) print('Candice:',reply) # if message is "Bye" if message.strip()=='Bye': print('Candice: Bye') break
To run it, Go to terminal
It will train your bot first and then you can start chatting.
#import libraries from chatterbot import ChatBot from chatterbot.trainers import ListTrainer import os #Create a chatbot bot=ChatBot('Candice') bot.set_trainer(ListTrainer) #training on english dataset for files in os.listdir('./english/'): data=open('./english/'+files,'r').readlines() bot.train(data) #chat feature while True: message=input('\t\t\tYou:') if message.strip()!='Bye': reply=bot.get_response(message) print('Candice:',reply) if message.strip()=='Bye': print('Candice: Bye') break