DEV Community

Cover image for Learn how to build a simple chatbot app in Python
Jordan Kalebu
Jordan Kalebu

Posted on • Edited on

Learn how to build a simple chatbot app in Python

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

$ pip install python-tk 

Enter fullscreen mode Exit fullscreen mode

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

Project Directory

Your project directory should look as shown below

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

0 directories, 2 files
Enter fullscreen mode Exit fullscreen mode

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

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
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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

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

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.

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()
Enter fullscreen mode Exit fullscreen mode

Output :

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

Hope you find this post interesting, share now with your fellow peers by pressing tweet this to show that you have made it.

The Original Article can be found on kalebujordan.dev

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

GitHub logo Kalebu / Desktop-chatbot-app

A python knowledge-based chatbot application built with Tkinter

This a cross-platform desktop app built with [tkinter] which simply acts like a dictionary chatbot, you can send it a message and it will return a response on what it thinks the message is by fetching it in a very large dictionary.

Getting started

To get started with this app, you might have to clone or download the repository first;

git clone https://github.com/Kalebu/Desktop-chatbot-app
cd Desktop-chatbot-app
Desktop-chatbot-app->
Enter fullscreen mode Exit fullscreen mode

Dependencies

For Window user, there is no extra dependencies to be installed however for those in Linux or Mac sometimes Python does not come with Tkinter installed so you might have to install it manually;

sudo apt-get install python3-tk
Enter fullscreen mode Exit fullscreen mode

launching

Now once installed launch it by running as you would run a normal python script and the gui for chatbot will pop up;

python app.py
Enter fullscreen mode Exit fullscreen mode

launched interface

Your interface for the chatbot app will probably look like shown below;

chatbot application

Issues

Top comments (0)