Kalebu Jordan

Become a Pro Python Developer

Hi guys, In this tutorial, you will learn how to build your own knowledge-based chatbot in python, which is able to answer you most of the general question you can ask.

what is chatbot?

chatbot is an artificial intelligence (AI) software that can simulate a conversation (or a chat) with a user in natural language, In this tutorial, you’re going to learn how to build your own simple chatbot using Python.

Requirements

If you’re in window you don’t need to install anything because every module we are going to use comes automatically with Python Standard Library

However, if you’re a Linux user you might need to Install Tkinter Libary on your own

Installation

$ pip install python-tk 

Also you need to have Dictionary json on your local folder which will act as our Knowledge base for our chatbot .

Download the Below Json Dictionary and put it on your project Directory

Project Directory

Your project directory should look as shown below

.
├── app.py
└── knowledge.json

0 directories, 2 files

Building Our Chatbot

Now after you have set everything clear let’s start building our application, throughout the project we are going to use the following Python standard modules

Importing Modules

Now import all necessary modules ready to start crafting our chatbot

import json
from difflib import get_close_matches
from tkinter import Tk, Label, Entry, Button, Text, Scrollbar,Frame

giving our chatbot app exoskeleton

We now required to create the exoskeleton of our application by designing our user Interface for our chatbot using Tkinter Library.

Our chatbot UI will need to have the following features

  • Entry box to allow as to type a message
  • A button to submit the message
  • Message part for showing the conversation with a chatbot
  • Scroll bar to help us scroll throughout the conversation

Using knowledge of Tkinter I have crafted the above features into Python code shown below.

app.py

import json
from difflib import get_close_matches
from tkinter import Tk, Label, Entry, Button, Text, Scrollbar,Frame

class Chatbot:
    def __init__(self, window):
        window.title('Iris bot')
        window.geometry('400x400')
        window.resizable(0,0)
        self.message_session = Text(window, bd=3, relief="flat", font=("Times", 10), undo=True, wrap="word")
        self.message_session.config(width=45, height=15,bg="#596", fg="white", state='disabled')
        self.overscroll = Scrollbar(window, command=self.message_session.yview)
        self.overscroll.config(width=20)
        self.message_session["yscrollcommand"] = self.overscroll.set
        self.message_position = 1.5
        self.send_button = Button(window, text='send', fg='white', bg='blue',width=9,font=('Times', 12), relief ='flat')
        self.Message_Entry = Entry(window, width=40, font=('Times', 12))
        self.message_session.place(x=20, y=20)
        self.overscroll.place(x=370, y=50)
        self.send_button.place(x=0, y=360)
        self.Message_Entry.place(x=135, y=365)
        self.Brain = json.load(open('knowledge.json'))

root = Tk()
Chatbot(root)
root.mainloop()

on the above code I have also loaded by knowledge base dictionary into the application ready to be used in the conversations

Output :
When you run the above UI code it will produce the following output

Tutorial on building a simple chatbot application in python

building logic blocks for our chatbot

Flow chart indicating logic flow our chatbot app

As we have in the above flow chart, you first enter your text on the entry box, you will then press the Enter key or send button to send our message to our program logic which will process the details as shown above.

Below complete code just to do that able to chat with you on thousands of domain of knowledge, so now you try copying it and run it to begin chatting with it

app.py

import json
from difflib import get_close_matches
from tkinter import Tk, Label, Entry, Button, Text, Scrollbar,Frame

class Chatbot:
    def __init__(self, window):
        window.title('Iris Assitant')
        window.geometry('400x400')
        window.resizable(0,0)
        self.message_session = Text(window, bd=3, relief="flat", font=("Times", 10), undo=True, wrap="word")
        self.message_session.config(width=45, height=15,bg="#596", fg="white", state='disabled')
        self.overscroll = Scrollbar(window, command=self.message_session.yview)
        self.overscroll.config(width=20)
        self.message_session["yscrollcommand"] = self.overscroll.set
        self.message_position = 1.5
        self.send_button = Button(window, text='send', fg='white', bg='blue',width=9,font=('Times', 12), relief ='flat', command = self.reply_to_you)
        self.Message_Entry = Entry(window, width=40, font=('Times', 12))
        self.Message_Entry.bind('<Return>', self.reply_to_you)
        self.message_session.place(x=20, y=20)
        self.overscroll.place(x=370, y=50)
        self.send_button.place(x=0, y=360)
        self.Message_Entry.place(x=135, y=365)
        self.Brain = json.load(open('knowledge.json'))

    def add_chat(self, message):
        self.message_position+=1.5
        print(self.message_position)
        self.Message_Entry.delete(0, 'end')
        self.message_session.config(state='normal')
        self.message_session.insert(self.message_position, message)
        self.message_session.see('end')
        self.message_session.config(state='disabled')
        
    def reply_to_you(self, event=None):
        message = self.Message_Entry.get().lower()
        message = 'you: '+ message+'\n'
        close_match = get_close_matches(message, self.Brain.keys())
        if close_match:   
            reply = 'Iris: '+ self.Brain[close_match[0]][0] + '\n'
        else:
            reply = 'Iris: ' + 'Can\'t find it it in my knowledge base\n'
        self.add_chat(message)
        self.add_chat(reply)

root = Tk()
Chatbot(root)
root.mainloop()

Output :

When you run the above code it will produce the following results

🎉🎉🎉 Congratulations you have just made your own How to build your own knowledge based chatbot in Python, Tweet now to share these good news with your fellow developers.

I also recommend you checking

In case of any suggestion or comment, drop it in the comment box and I will get back to you ASAP.

Full code for this article is available on My Github

5 thoughts on “Make your own knowledge-based chatbot in Python

Leave a Reply

error

Enjoy this blog? Please spread the word :)

%d bloggers like this: