How to build a chatbot in Python


Tutorial to build a python chat box

Hi Dev mates, Welcome to The Codezine again, & Dark Soulz is back with another python #DIY tutorial. Today, I will gonna bring out one of the important & cool python projects that you are gonna like & love to do it yourself. So, Today we are going to make a python GUI Chatbot/python chat box[graphical user interface]. Exciting right? But, what is it actually?

What is Chat Bot?

chatbot is a computer program that imitates human conversation through voice commands or text chats or both. It is built with AI tools like as Natural Language Processing (NLP) etc.

Advantages of Chatbot?

Some of the few advantages of Chatbot are as follow:

  • Cost Savings as it reduces human resource costs.
  • 24/7 Customer support which helps in better customer engagement.
  • Lesser Human Errors as its fully based on AI
  • Larger Client Management capability.

But how to make a Chatbot/Python Chat box?

So, lets move forward & straight on how to make a chatbot easily.

Requirements

  • A laptop or Pc where Python latest version can be installed.
  • A good & fast Code Editor or Ide like Visual Studio Code or Atom.
  • A notebook where you can write important points.
  • Lastly, your focus.

Python Packages/Library Needed:

  1. pip install nltk —> A python package for natural language processing. It’s the core & vital package for making a chat box.
  2. pip3 install ChatterBot —> It’s a machine learning, conversational dialog engine.
  3. pip install pyttsx3 —> It is a python library for converting text to speech.
  4. pip install SpeechRecognition —> A python library for recognizing speech.
  5. Tkinter —> It’s a standard GUI library for Python

Note: Some errors may arise while installing pip install ChatterBot packages which may disrupt your project work. For Example “error: Microsoft Visual C++ 14.0 is required.”

How to fix “error: Microsoft Visual C++ 14.0 is required.”

For fixing it you can follow the following steps.

Method No. 1

  1. First, of all download the Microsoft C++ Build Tools after downloading Visual Studio. [You can also download from Offline Installer]
  2. Secondly, follow the pattern,

Select: Workloads → Desktop development with C++, then for Individual Components, select only:

  • Windows 10 SDK
  • C++ x64/x86 build tools

3. Lastly, Download all C++ tools provided including that are not selected & restart your PC & that’s it.

Alternative Method:

Also, If the first method doesn’t work you can try to install with pip3 install ChatterBot instead of pip install ChatterBot command. But, I hope the first method will work. 😀

How to make it?

  • The first step is to make a folder name chatbot & drag it to your code editor for opening it.
  • Second step is to make a file called main.py[Your chatbot codes] & chat.txt[For storing your chatbot command which you will imply to your chatbot]
  • After that, go to your terminal & install your pip extension/package as per list provided below.

  1. pip install nltk
  2. pip3 install ChatterBot
  3. pip install pyttsx3
  4. pip install SpeechRecognition
  • Fourthly, Copy the codes after reading the quotation given in the codes accordingly. I have given it in the downsides & lastly paste it.
  • Lastly, run it by tapping python main.py & your chatbot is created.

Note: After you run your py code you can see the db.sqlite3 file. It’s the database file where your data/commands are in place.

Code

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from tkinter import *
import pyttsx3 as pp
import speech_recognition as s
import threading engine = pp.init() voices = engine.getProperty('voices')
print(voices) engine.setProperty('voice', voices[0].id) def speak(words): engine.say(words) engine.runAndWait() # pyttsx3
[ The Code allows chatbot to read commands from chat.txt] bot = ChatBot("T.Codezine Bot") convo = open('chat.txt', 'r').readlines() trainer = ListTrainer(bot) # now training the bot with the help of trainer trainer.train(convo) # Tkinter Dimension
main = Tk() main.geometry("500x650") main.title("T.Codezine bot") img = PhotoImage(file="bot.png") photoL = Label(main, image=img) photoL.pack(pady=5) # takey query : This code takes audio as input from user and convert it to string def takeQuery(): 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) query = sr.recognize_google(audio, language='eng-in') print(query) textF.delete(0, END) textF.insert(0, query) ask_from_bot() except Exception as e: print(e) print("not recognized") def ask_from_bot(): query = textF.get() answer_from_bot = bot.get_response(query) msgs.insert(END, "you : " + query) print(type(answer_from_bot)) msgs.insert(END, "c.z bot : " + str(answer_from_bot)) speak(answer_from_bot) textF.delete(0, END) msgs.yview(END) frame = Frame(main) sc = Scrollbar(frame)
msgs = Listbox(frame, width=80, height=20, yscrollcommand=sc.set) sc.pack(side=RIGHT, fill=Y) msgs.pack(side=LEFT, fill=BOTH, pady=10) frame.pack() # creating text field textF = Entry(main, font=("Courier", 10))
textF.pack(fill=X, pady=10) btn = Button(main, text="Ask T.Codezine bot", font=( "Courier", 10),bg='red', command=ask_from_bot)
btn.pack() # creating a function
def enter_function(event): btn.invoke() # going to bind main window with enter key... main.bind('<Return>', enter_function) def repeatL(): while True: takeQuery() t = threading.Thread(target=repeatL) t.start() main.mainloop()

hello
hi Buddy !
what is your name ?
My name is C.z Bot & I am created by Dark Soulz
how are you ?
I am doing great these days ?
thank you
In which city you live ?
I live in agartala
In which language you talk?
I mostly talk in english, kokborok
I love You
I love you too dear

Conclusion:

For making your chatbot to talk back or text back according to your command/word, you can edit into chat.txt. But, make sure to delete db.sqlite3 first after updating the chat.txt file. Finally, make sure you follow all the steps carefully & share this piece of content if you find it useful & amazing. Thank You!

Source: https://thecodezine.com/how-to-build-a-chatbot-in-python/



You might also like this video