Create ChatBot Project Using Python
A chatbot is a computer program simulates a conversation between a user and computer through the auditory or textual method, it works as a real conversational partner and eases your work.
Now let’s take the real-world example of this, I would be sure that you all know about Siri, Alexa, OkGoogle, Cortana, or even Natasha from the hike. They all are complicated chatbots which are made with the power of Deep Learning (Neural Network). Which actually makes them smart, quick to respond, and accurate.
You
would be surprised that the chatbot is not new to us the first of it’s kind
was developed in 1966 called ELIZA.
![]() |
ELIZA |
This chatbot was developed by Sir Joseph Weizenbaum.
If
you want to want to know more about the history of this, you can check out this
link History Of Chatbots.
![]() |
Sir Joseph Weizenbaum |
Now
talking about the evolution of chatbots it took a very drastic turn during this
decades and the future of the chatbots looks very promising as well, chatbots
are expected to complete around 80% of all the works in the coming decade.
The task that is completed by the chatbots includes simply giving out the
information or booking tickets etc.
Whenever
we are making chatbot we have to consider a few things such as we should know our
target audience and we must understand the natural language of communication as
well.
What
we are going to create?
The
chatbot which we are going to create can be used by any organization or community,
but for example, we are going to create a chatbot specifically for the Computer
Science Departement of college where parents will be able to know all the
details about the CS department with the help of a chatbot.
We
are going to create a chatbot application using:
- Python:
Programming Language (Version: 3.6).
- Chatterbot:
* Library
in python which generates the responses to the user input.
* It
uses a number of machine learning algorithms to produce a variety of responses.
* It
is easy to use and implement.
* With
the help of chatterbot library we can train our chatbot in multiple languages it
supports languages such a Hindi, English, Spanish, etc.
* It
easily get trained.
If
you want to know more about ChatterBot
Click
Here: ChatterBot
- Tkinter:
Python GUI ( Graphical User Interface ) Library.
- Notepad:
To save our questions and user queries.
- Pycharm:
IDE ( Integrated Development Environment ).
Let’s
start to create a chatbot from scratch steps:
[ THE WHOLE PROJECT WILL BE CREATED IN WINDOWS & ALL THE STEPS WILL BE RESPECT TO
WINDOWS USERS ]
* Install
PyCharm in your system:
* Go
to start Enter “cmd” a Type “ pip
install chatterbot ” after installation à Type “ pip install chatterbot_corpus ”
[ WHILE
INSTALLING “chatterbot & chatterbot_corpus” PLEASE SELECT THE
SAME PYTHON VERSION WHICH YOU ARE GOING TO USE ]
*Now
open your PyCharm :
-Create
a new python file
-Now
click on file a setting a Project: your_proj_name a Project Interpreter a click on “ + ” at the right side of the
window a Now search and
install the libraries:
*chatterbot
*chatterbot-corpus
*PyAudio
*NumPy
*pypiwin32
*pyttsx3
*pywin32
*PyYAML
All
the required file will be available here :
After
all the steps you had done if you still get errors like these here are it’s
solutions:
Error_1:
modulenotfounderror: no module named 'chatterbot_corpus'
Solution:
(i) Go to: https://github.com/gunthercox/chatterbot-corpus
(ii) Click on download or clone a file
(iii) Download Zip
(iv) Save it at a certain location > unzip it
(v) Copy chatterbot_corpus folder from the unzipped file
(vi) Go to My_project(your_project_location) > venv > Lib > site-packages ; Now paste that chatterbot_corpus
problem
solved.
Error_2:
import pythoncom
ModuleNotFoundError : No module name 'pythoncom'
Solution:
(i) Open Pycharm
(ii) Go to file > settings > Project:(Project_name) > Project
Interpreter > Click on the (+) which is near scrollbar.
(iii)search (pypiwin32) > install it
(iv) close all tab & import this into your project > import win32com.client
problem
solved.
Error_3:
I think the set_trainer was removed. You have to use the training method
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
chatbot = ChatBot('Ron Obvious')
# Create a new trainer for the chatbot
trainer = ChatterBotCorpusTrainer(chatbot)
# 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?")
problem
solved.
Now
let’s start to create our chatbot:
Create a file where you would save all the files and go to your PyCharm and paste this code:
Create a file where you would save all the files and go to your PyCharm and paste this code:
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.logic import logic_adapter
from tkinter import *
from tkinter import font
from tkinter import messagebox
import speech_recognition as s
import threading
import pyaudio
import pyttsx3 as pp
import win32com.client
import os
main=Tk()
frame = Frame(main)
ment=StringVar()
main.geometry("500x700")
main.title("CS Department")
img=PhotoImage(file='unnamed.png')
photo=Label(main,image=img)
photo.place(x=1,y=440)
eng=pp.init()
voices = eng.getProperty('voices')
print(voices)
i=IntVar()
def speak(word):
if i.get()==1:
eng.setProperty('voice', voices[0].id)
eng.say(word)
eng.runAndWait()
elif i.get()==2:
eng.setProperty('voice', voices[1].id)
eng.say(word)
eng.runAndWait()
else:
eng.runAndWait()
lbl=Label(main,text="Select Gender of voice :",font=40).place(x=100,y=50)
r1=Radiobutton(main,text="Male Voice",value=1,variable=i,command=speak,font=35).place(x=100,y=100)
r2=Radiobutton(main,text="Female Voice",value=2,variable=i,command=speak,font=35).place(x=100,y=150)
r3=Radiobutton(main,text="Sound ON/OF",value=3,variable=i,command=speak,font=35).place(x=100,y=200)
#import conversation
chatbot=ChatBot('Bot')
for _file in os.listdir('files'):
chats=open('files/' + _file,'r').readlines()
trainer = ListTrainer(chatbot)
trainer.train(chats)
sy=Scrollbar(main)
fnt = font.Font(size=10)
lbl2=Label(main,text="List of Questions you may ask :",font=35).place(x=1150,y=15)
txt=Listbox(main,width=55,height=44,font=fnt,yscrollcommand=sy.set, bd=5)
txt.insert(1," ADMISSION INFORMATION: "+"\n")
txt.insert(2,"\n")
txt.insert(3," what is the registration process"+"\n")
txt.insert(4," what document will be required"+"\n")
txt.insert(5," what are the timing for admission"+"\n")
txt.insert(6," Form where do we have to collect forms"+"\n")
txt.insert(7," How to fill form"+"\n")
txt.insert(8," can we cancel admission"+"\n")
txt.insert(9," Refund"+"\n")
txt.insert(10,"\n")
txt.insert(11,"\n")
txt.insert(12," FEES INFORMATION: "+"\n")
txt.insert(13,"\n")
txt.insert(14," What is the Fees for computer science"+"\n")
txt.insert(15," what document will be required"+"\n")
txt.insert(16," Fees for open categories"+"\n")
txt.insert(17," What is Fees for NT cast"+"\n")
txt.insert(18," Whats is Fees for Other Backward Class"+"\n")
txt.insert(19," What is the Fees for extracurricular activities"+"\n")
txt.insert(20,"\n")
txt.insert(21,"\n")
txt.insert(22," EXTRACURRICULAR INFORMATION: "+"\n")
txt.insert(23,"\n")
txt.insert(24," extracurricular activities are there in you college"+"\n")
txt.insert(25," what document will be required"+"\n")
txt.insert(26," what link of extracurricular activities will be provided"+"\n")
txt.insert(27," how will extracurricular activities will help to my child"+"\n")
txt.insert(28,"\n")
txt.insert(29,"\n")
txt.insert(30," CONCESSION INFORMATION: "+"\n")
txt.insert(31,"\n")
txt.insert(32," what kind of concession will be provided"+"\n")
txt.insert(32," Any specific concession for girls"+"\n")
txt.insert(33,"\n")
txt.insert(34,"\n")
txt.insert(35," PAYMENT INFORMATION: "+"\n")
txt.insert(36,"\n")
txt.insert(37," What are the Payment procedure"+"\n")
txt.insert(38," Can payment be done in installment"+"\n")
txt.insert(39," Do you support UPI"+"\n")
txt.insert(40," Any cash back is available for specific bank"+"\n")
txt.insert(41,"\n")
txt.insert(42,"\n")
txt.insert(43," STAFF INFORMATION: "+"\n")
txt.insert(44,"\n")
txt.insert(45," how is your teaching staff"+"\n")
txt.insert(46," how teachers will inform us about our childs progress"+"\n")
txt.insert(47," how technically advance are you laboratory"+"\n")
txt.insert(48," what placement opportunity will be provided to over child"+"\n")
txt.insert(49,"\n")
txt.insert(50,"\n")
txt.insert(51," CONTACT INFORMATION: "+"\n")
txt.insert(52,"\n")
txt.insert(53," I need a help"+"\n")
txt.insert(54," what is your contact number"+"\n")
txt.insert(55," Help"+"\n")
txt.insert(56," How can I contact you"+"\n")
txt.insert(57," how can I get further information"+"\n")
txt.insert(58," I do not get you"+"\n")
txt.insert(59," calling which number might help me"+"\n")
txt.config()
sy.pack(side=RIGHT,fill=Y)
txt.place(x=1125,y=45)
#I do not get you
lbl3=Label(main,text="Help us to Advance, Enter your unanswered Query :",font=35).place(x=525,y=585)
# txt1=Entry(main,bd=5,width=20)
# txt1.place(x=515,y=580)
txt1 = Entry(main,font=10, bd=5)
txt1.place(width=500,height=50,x=515,y=650)
def Unsolved():
q = txt1.get()
if len(q) < 5 :
messagebox.showinfo("Error","Please Enter Your Unsolved Query")
else:
f=open('Unsolved_Query.txt','a')
f.write(q+"\n")
f.close()
messagebox.showinfo("Congratulations", "Your Query is Accepted Successfully")
txt1.delete(0, END)
btn1=Button(main, text="Enter Query", font=("Times", 16),command=Unsolved).place(x=710,y=710)
sc=Scrollbar(frame)
scx=Scrollbar(frame,orient=HORIZONTAL)
msg=Listbox(frame,width=100,height=25,yscrollcommand=sc.set,xscrollcommand=scx.set, bd=5)
scx.pack(side=BOTTOM,fill=X)
scx.config(command=msg.xview)
msg.config()
msg.pack(side=LEFT,fill=BOTH,pady=10)
sc.pack(side=RIGHT,fill=Y)
frame.pack()
def take_query():
sr=s.Recognizer()
sr.pause_threshold=1
print("Your Bot is listening try to speak")
with s.Microphone() as m:
try:
audio = sr.listen(m)
question = sr.recognize_google(audio, language='eng-in')
print(question)
text.delete(0, END)
text.insert(0, question)
Ask_from_Bot()
except Exception as e:
print(e)
print("Not recognized")
def Ask_from_Bot():
question = text.get()
if question == 'Bye' or question == 'bye':
print("ChatBot:Bye")
main.destroy()
else:
ans = chatbot.get_response(question)
msg.insert(END, "You : " + question + '\n')
print(type(ans))
msg.insert(END, "Bot : " + str(ans))
speak(ans)
text.delete(0, END)
msg.xview()
msg.yview(END)
# Creating a text field
text = Entry(main, bd=5,font=("Times", 15))
text.place(x=650,y=450,width=220,height=35)
btn = Button(main, text="Ask From Bot", font=("Times", 16), command=Ask_from_Bot)
btn.place(x=695,y=510)
# Press Enter & get Output
def Enter_fun(event):
btn.invoke()
# going to bind the main window with entering key
main.bind('', Enter_fun)
def repeatL():
while True:
take_query()
t=threading.Thread(target=repeatL)
t.start()
main.mainloop()
from chatterbot.trainers import ListTrainer
from chatterbot.logic import logic_adapter
from tkinter import *
from tkinter import font
from tkinter import messagebox
import speech_recognition as s
import threading
import pyaudio
import pyttsx3 as pp
import win32com.client
import os
main=Tk()
frame = Frame(main)
ment=StringVar()
main.geometry("500x700")
main.title("CS Department")
img=PhotoImage(file='unnamed.png')
photo=Label(main,image=img)
photo.place(x=1,y=440)
eng=pp.init()
voices = eng.getProperty('voices')
print(voices)
i=IntVar()
def speak(word):
if i.get()==1:
eng.setProperty('voice', voices[0].id)
eng.say(word)
eng.runAndWait()
elif i.get()==2:
eng.setProperty('voice', voices[1].id)
eng.say(word)
eng.runAndWait()
else:
eng.runAndWait()
lbl=Label(main,text="Select Gender of voice :",font=40).place(x=100,y=50)
r1=Radiobutton(main,text="Male Voice",value=1,variable=i,command=speak,font=35).place(x=100,y=100)
r2=Radiobutton(main,text="Female Voice",value=2,variable=i,command=speak,font=35).place(x=100,y=150)
r3=Radiobutton(main,text="Sound ON/OF",value=3,variable=i,command=speak,font=35).place(x=100,y=200)
#import conversation
chatbot=ChatBot('Bot')
for _file in os.listdir('files'):
chats=open('files/' + _file,'r').readlines()
trainer = ListTrainer(chatbot)
trainer.train(chats)
sy=Scrollbar(main)
fnt = font.Font(size=10)
lbl2=Label(main,text="List of Questions you may ask :",font=35).place(x=1150,y=15)
txt=Listbox(main,width=55,height=44,font=fnt,yscrollcommand=sy.set, bd=5)
txt.insert(1," ADMISSION INFORMATION: "+"\n")
txt.insert(2,"\n")
txt.insert(3," what is the registration process"+"\n")
txt.insert(4," what document will be required"+"\n")
txt.insert(5," what are the timing for admission"+"\n")
txt.insert(6," Form where do we have to collect forms"+"\n")
txt.insert(7," How to fill form"+"\n")
txt.insert(8," can we cancel admission"+"\n")
txt.insert(9," Refund"+"\n")
txt.insert(10,"\n")
txt.insert(11,"\n")
txt.insert(12," FEES INFORMATION: "+"\n")
txt.insert(13,"\n")
txt.insert(14," What is the Fees for computer science"+"\n")
txt.insert(15," what document will be required"+"\n")
txt.insert(16," Fees for open categories"+"\n")
txt.insert(17," What is Fees for NT cast"+"\n")
txt.insert(18," Whats is Fees for Other Backward Class"+"\n")
txt.insert(19," What is the Fees for extracurricular activities"+"\n")
txt.insert(20,"\n")
txt.insert(21,"\n")
txt.insert(22," EXTRACURRICULAR INFORMATION: "+"\n")
txt.insert(23,"\n")
txt.insert(24," extracurricular activities are there in you college"+"\n")
txt.insert(25," what document will be required"+"\n")
txt.insert(26," what link of extracurricular activities will be provided"+"\n")
txt.insert(27," how will extracurricular activities will help to my child"+"\n")
txt.insert(28,"\n")
txt.insert(29,"\n")
txt.insert(30," CONCESSION INFORMATION: "+"\n")
txt.insert(31,"\n")
txt.insert(32," what kind of concession will be provided"+"\n")
txt.insert(32," Any specific concession for girls"+"\n")
txt.insert(33,"\n")
txt.insert(34,"\n")
txt.insert(35," PAYMENT INFORMATION: "+"\n")
txt.insert(36,"\n")
txt.insert(37," What are the Payment procedure"+"\n")
txt.insert(38," Can payment be done in installment"+"\n")
txt.insert(39," Do you support UPI"+"\n")
txt.insert(40," Any cash back is available for specific bank"+"\n")
txt.insert(41,"\n")
txt.insert(42,"\n")
txt.insert(43," STAFF INFORMATION: "+"\n")
txt.insert(44,"\n")
txt.insert(45," how is your teaching staff"+"\n")
txt.insert(46," how teachers will inform us about our childs progress"+"\n")
txt.insert(47," how technically advance are you laboratory"+"\n")
txt.insert(48," what placement opportunity will be provided to over child"+"\n")
txt.insert(49,"\n")
txt.insert(50,"\n")
txt.insert(51," CONTACT INFORMATION: "+"\n")
txt.insert(52,"\n")
txt.insert(53," I need a help"+"\n")
txt.insert(54," what is your contact number"+"\n")
txt.insert(55," Help"+"\n")
txt.insert(56," How can I contact you"+"\n")
txt.insert(57," how can I get further information"+"\n")
txt.insert(58," I do not get you"+"\n")
txt.insert(59," calling which number might help me"+"\n")
txt.config()
sy.pack(side=RIGHT,fill=Y)
txt.place(x=1125,y=45)
#I do not get you
lbl3=Label(main,text="Help us to Advance, Enter your unanswered Query :",font=35).place(x=525,y=585)
# txt1=Entry(main,bd=5,width=20)
# txt1.place(x=515,y=580)
txt1 = Entry(main,font=10, bd=5)
txt1.place(width=500,height=50,x=515,y=650)
def Unsolved():
q = txt1.get()
if len(q) < 5 :
messagebox.showinfo("Error","Please Enter Your Unsolved Query")
else:
f=open('Unsolved_Query.txt','a')
f.write(q+"\n")
f.close()
messagebox.showinfo("Congratulations", "Your Query is Accepted Successfully")
txt1.delete(0, END)
btn1=Button(main, text="Enter Query", font=("Times", 16),command=Unsolved).place(x=710,y=710)
sc=Scrollbar(frame)
scx=Scrollbar(frame,orient=HORIZONTAL)
msg=Listbox(frame,width=100,height=25,yscrollcommand=sc.set,xscrollcommand=scx.set, bd=5)
scx.pack(side=BOTTOM,fill=X)
scx.config(command=msg.xview)
msg.config()
msg.pack(side=LEFT,fill=BOTH,pady=10)
sc.pack(side=RIGHT,fill=Y)
frame.pack()
def take_query():
sr=s.Recognizer()
sr.pause_threshold=1
print("Your Bot is listening try to speak")
with s.Microphone() as m:
try:
audio = sr.listen(m)
question = sr.recognize_google(audio, language='eng-in')
print(question)
text.delete(0, END)
text.insert(0, question)
Ask_from_Bot()
except Exception as e:
print(e)
print("Not recognized")
def Ask_from_Bot():
question = text.get()
if question == 'Bye' or question == 'bye':
print("ChatBot:Bye")
main.destroy()
else:
ans = chatbot.get_response(question)
msg.insert(END, "You : " + question + '\n')
print(type(ans))
msg.insert(END, "Bot : " + str(ans))
speak(ans)
text.delete(0, END)
msg.xview()
msg.yview(END)
# Creating a text field
text = Entry(main, bd=5,font=("Times", 15))
text.place(x=650,y=450,width=220,height=35)
btn = Button(main, text="Ask From Bot", font=("Times", 16), command=Ask_from_Bot)
btn.place(x=695,y=510)
# Press Enter & get Output
def Enter_fun(event):
btn.invoke()
# going to bind the main window with entering key
main.bind('
def repeatL():
while True:
take_query()
t=threading.Thread(target=repeatL)
main.mainloop()
- admission.txt
- consession.txt
- contact.txt
- extracurricularactivities.txt
- fees.txt
- greeting.txt
- payment.txt
- teachingstaff.txt
[ ALL THE FILES WHICH ARE MENTIONED, ARE ALREADY IN THE LINK ABOVE IN THE "chatbotdata" LINK. ]
Now let's discuss all the steps :
[ CODE EXPLANATION ]
In the initial step, we imported all the important libraries let's discuss all the libraries one by one.
→ from chatterbot import ChatBot
ChatterBot is a python library that makes it easy to generate automated responses to a user's input. Before we do anything else, ChatterBot needs to be imported. The import for ChatterBot should look like as mentioned above.
→ from chatterbot.trainers import ListTrainer
If you want to create a list of conversation in your code directly like this;
[
'How are you?',
'I am good.',
'That is good to hear.',
'Thank you',
'You are welcome.',
]
you can use this but in our project, we had created a Folder named as a file in which we had we had created multiple .txt files that hold your conversation.→ from chatterbot.logic import logic_adapter
Logic adapters determine the logic for how ChatterBot selects a response to a given input statement. But in our project, we didn't implement this because it's a simply enquire chatbot not a chatbot for reasoning. So this import is optional in our project.
→ from tkinter import *
Tkinter to create a graphical user interface for the end-user.
→ from tkinter import font
This import is for font various fonts.
→ from tkinter import messagebox
Tkinter to create a graphical user interface for the end-user. This import is used to create a messagebox where our conversation will be placed.
→ import speech_recognition as s
This import is used for speech recognition before using this import you have to install it.
pip install SpeechRecognition
→ import threading
Python threading allows you to have different parts of the program run concurrently and can simplify your design.
→ import pyaudio
With PyAudio, you can easily use Python to play and record audio on a variety of platforms such as Linux, Mac, and Windows. Before using this import you have to install it.
pip install PyAudio
→ import pyttsx3 as pp
pyttsx3 is a text-to-speech conversation library in python. Unlike alternative libraries, it works offline and is compatible with both Python 2 and 3. Before using this import you have to install it.
pip install pyttsx3
→ import win32com.client
It is an essential library which is used to avoid a certain error in our program.
→ import os
→ import os
The os module is used to read and write file directly.
After importing all the libraries we will create a object of chatbot and we named that object as chatbot and named your bot as Bot. Now we will create a list trainer object which we named as trainer but as we are going to have our conversation in .txt format we would read our folder named as files which contains all our .txt files, which will help you chatbot to learn.
We would also a function named as speak in which will help us to get the audio output both in male voice or female voice, for that we had created a radio button by clicking which the output will be get as male voice or female voice.
For end users we would also create a Listbox where we will show them what kind of conversations that they can do with our bot.
If any user didn't get appropriate out put or have any query they can post them in the textbox, where all the queries which are enteried by the end user will be saved in the Unsolved_Query.txt than when the developer want to update the chatbot they can add the unsolved or unanswered queries which are constantly asked by the end user.
With the help of the microphone user can even use speech in english to have a nice conversation with our chatbot this speech feature is availabe in the take_query() function.
And if end user type bye at the end of the conversation the chatbot will automatically get closed.
So we hope that you enjoyed this project. If you did then please share it with your friends and shpread this knowledge.
Follow us at :
Instagram : https://www.instagram.com/infinitycode_x/ Facebook : https://www.facebook.com/InfinitycodeX/ Twitter : https://twitter.com/InfinityCodeX1
chatbot for business I have read all the comments and suggestions posted by the visitors for this article are very fine,We will wait for your next article so only.Thanks!
ReplyDeletethanks for your support
DeleteThank you for sharing such a useful article. It will be useful to those who are looking for knowledge. Continue to share your knowledge with others through posts like these, and keep posting on
ReplyDeleteBig Data Solutions
Advanced Data Analytics Services
Data Modernization Solutions
AI & ML Service Provider
thank you
Deletethank you
ReplyDeleteThe blog is really interesting and informative content. Your blog helps for me to know more updated information's. Keep sharing more informative content like this.
ReplyDeleteProduct Engineering Services
Mobile App Development Services
Low Code Development Services
Mendix Development Services
Software Testing Services
Digital Assurance Services
Cloud Engineering Services
Cloud Migration Services
The blog is really interesting and informative content. Your blog helps for me to know more updated information's. Keep sharing more informative content like this.
ReplyDeleteProduct Engineering Services
Mobile App Development Services
Low Code Development Services
Mendix Development Services
Software Testing Services
Digital Assurance Services
Cloud Engineering Services
Cloud Migration Services
The blog has really interesting and informative content. Your blog helps me to know more updated information. Keep sharing more informative content like this.
ReplyDeleteTest Automation Services
Data Modernization Services