Creating a chatterbot in python
Tags: python, programming
Published: 2021-08-30 17:03:00

I'm fairly new to the world of Python and apart from watching course material on the subject, I thought I would challenge myself. I spent a few hours this morning contacting a company to move my broadband to my new address and came across an automated chatbot which did after a few questions get the job done, but some of those questions were irrelevant and time-consuming so I thought I'd have a go with my new skillset to build my own!

This post is firstly a breakdown of the code and also a way for me to understand exactly what I did and hopefully help you also.

The one point I will make is that Python has a HUGE library of packages! More than I thought to be honest and if you think about making something then I'm sure out there in the wild is a package already exists to help you in your quest.

So let's crack on! Create a new folder and call it whatever you choose. I have gone for /chatterbot

Open the folder with whatever text editor you use and create a new python file, do not name it chatterbot.py for reasons you will see in a second.

Once we have that file lets install our packages and get started, if you run in your terminal:

```
pip3 install chatterbot
pip3 install chatterbot_corpus
pip3 install pytz
```
Now Im assuming you are using a Mac with macOS and Python 3, if you are not please install the above the same way you would install any other pip packages.

Ok so now we need to import the packages into our project and write our little bot.

```python
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
```
Had we named our file chatterbot.py Python would now being trying to import from there, hence my comment above!

So we have our imports, lets use the first one

```python
bot = ChatBot("bot")
```

All we are doing here is creating an instance of the chatterbot package and giving our bot a name, and in this moment she is simply called bot. Now it would be quite boring if our little bot couldn't learn anything, so we are going to ping a SQL database in there so we can save some chats and have the bot learn from it (This blew my mind!). So let's add some extra code.

```python
bot = ChatBot(
    "bot",
    storage_adapter='chatterbot.storage.SQLStorageAdapter',
    database_uri='sqlite:///db.sqlite3',
    logic_adapters=[
        'chatterbot.logic.BestMatch',
        'chatterbot.logic.TimeLogicAdapter'
    ]
    )
```
Ok, so what are we doing here? Well, firstly we are creating an SQLite DB if one doesn't exist, and then we are using it to store data that is feed in so our bot can use it to determine any responses it wants to give. Chatterbot also allows us to use many logical Adapters. When more than one logical adapter is in use, the chatbot will work out the confidence level! The response with the highest calculated confidence will be returned and here we have used two logical adapters, the BestMatch and TimeLogicAdapter.

Maybe it's time we teach our bot a thing or two! So we now need to train our bot a little and by using the following code the bot will have some phrases and such to use to deal with a user asking it questions

```python
# Creates an instance of the trainer    
lessons = ListTrainer(bot)

# Simple statements to teach the bot
lessons.train([
    'Hi',
    'Hello',
    'Good Morning',
    'Good Morning',
    'I need to ask a question about my order',
    'Please, Can i have your order id',
    'Ok I can see your order has been shipped',
    "That's great",
    'Is there anything else I can help you with',
    'No thank you',
    'Ok great, have a great day!',
    'Thanks',
    'Goodbye',
    'Bye'
])
```

So we have trained our bot, we have given it a brand new DB to work with and we have given it a name! So now its time to get a response and check its all working! So let's do that now!

```python
response = bot.get_response('I need to make a complaint')
print('Bot Response:', response)
```

So if we now run our script we should get a printed response back from our bot to the question "I need to make a complaint". Just so you know at this point on my first attempt I ran into an issue with nltk and some packages that are required, if like me, you have the same please do the following:

Open python3 in the terminal
```
import nltk
nltk download()
```

This will pull in the nltk packages and get you going! If you get a SSL error again which I did, then you can open Python3 in the terminal and run 

```python
import nltk
import ssl

try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    pass
else:
    ssl._create_default_https_context = _create_unverified_https_context

nltk.download()
```
This got me going and my app working. 

So now we should see a response and all we need to do now is create a full chat experience, so we can ask questions and hopefully get some responses back. 

```python
# Grab Users name
name=input("Hello, I'm Bot! Please tell me your name? ")

#Start Questions
print("What is it I can help you with today " + name +" ?")

while True:
    request=input(name+': ')
    if request.lower() == 'bye':
        print('Bot: Bye')
        break
    else: 
        response=bot.get_response(request)
        print('Bot: ', response) 
```

What is happening here is while everything is true we will run over this code, if we type 'Bye' at any point the bot will send its well wishes and close, else we type a question into the input and the bot will reply with the closet answer that matches! 

Should you require any further information on Chatterbot you can read the full docs here https://chatterbot.readthedocs.io/en/stable/

So to wrap things up you should have a final file that looks like this:
```python
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

bot = ChatBot("bot")

bot = ChatBot(
    "bot",
    storage_adapter='chatterbot.storage.SQLStorageAdapter',
    database_uri='sqlite:///db.sqlite3',
    logic_adapters=[
        'chatterbot.logic.BestMatch',
        'chatterbot.logic.TimeLogicAdapter'
    ]
    )

# Creates an instance of the trainer    
lessons = ListTrainer(bot)

# Simple statements to teach the bot
lessons.train([
    'Hi',
    'Hello',
    'Good Morning',
    'Good Morning',
    'I need to ask a question about my order',
    'Please, Can i have your order id',
    'Ok I can see your order has been shipped',
    "That's great",
    'Is there anything else I can help you with',
    'No thank you',
    'Ok great, have a great day!',
    'Thanks',
    'Goodbye',
    'Bye'
])

# Grab Users name
name=input("Hello, I'm Bot! Please tell me your name? ")

#Start Questions
print("What is it I can help you with today " + name +" ?")

while True:
    request=input(name+': ')
    if request.lower() == 'bye':
        print('Bot: Bye')
        break
    else: 
        response=bot.get_response(request)
        print('Bot: ', response) 
```

So using your favourite Python editor get building and see if you can create this bot and have a good old chin wag with it! 


Any issues with this tutorial please leave them down in the comments below and i'll do my best to help. 

First Published at: https://www.leighton.com/blog/python-chatterbot

[![Buy me a coffee or pizza](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2cl4e9xe8hwf891he4kc.png)](https://www.buymeacoffee.com/grahammorbydev)