Learn how to build a simple chatbot app in Python
Tags: python, machinelearning, datascience, computerscience
Published: 2020-10-10 08:03:19

## Build a simple chatbot app in Python

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

### what is a chatbot?
A chatbot is **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

```bash
$ pip install python-tk 

```


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

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

[knowledge](https://kalebujordan.com/wp-content/uploads/2020/05/knowledge.json)

### Project Directory

Your project directory should look as shown below

```bash
.
├── 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 modules**

- [json](https://docs.python.org/3/library/json.html)
- [difflib](https://docs.python.org/3/library/difflib.html)
- [tkinter](https://docs.python.org/3/library/tkinter.html)

### importing Modules
Now import all necessary modules ready to start crafting our chatbot


```python
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**

```python
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 JSON** into the application ready to be used in the conversations

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hy4ecxenbtck12c18102.png)

### building logic blocks for our chatbot

we will a function to get the **message** from the **entry box** and then searching for relevant keywords in the dictionary **knowledge base** If it finds any it will return to the user.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1h1c6limqgnfvdexbom7.png)

I have added two simple methods just to do that, together with linking the send button with the methods we just made.

 
Now Our Complete chatbot code should look as shown below.

```python
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: ' + 'Cant 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

<iframe width="560" height="315" src="https://www.youtube.com/embed/oM00lyfWF5c" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

Hope you find this post interesting, share now with your fellow peers by pressing [tweet this](https://twitter.com/intent/tweet?text=hello guys I have successfully completed the tutorial on making your own chatbot in python by @j_kalebu check it out at https://kalebujordan.dev/building-a-chat-app-using-sockets-in-python/) to show that you have made it.

The [Original Article](https://kalebujordan.dev/building-a-chat-app-using-sockets-in-python/) can be found on [kalebujordan.dev](https://kalebujordan.dev/building-a-chat-app-using-sockets-in-python/)

In case of any suggestion or comment, drop it on the comment box and I will reply to you immediately.

{% github https://github.com/Kalebu/Desktop-chatbot-app %}