Program to Create Simple Chatbot in Python

write a program to Build a simple chatbot in python that can communicate with users in a natural language and help them with tasks, such as scheduling appointments or answering questions

Building an AI chatbot that can communicate with users in a natural language and help them with tasks, such as scheduling appointments or answering questions, is a challenging but rewarding project. There are many ways to approach this problem, but one of the most popular and easy-to-use libraries for building chatbots in Python is ChatterBot.

ChatterBot is a library that uses machine learning to learn from conversations and generate responses based on similarity and logicIt also provides various features such as language detection, sentiment analysis, spell checking, voice recognition and synthesisChatterBot can be trained with different types of data sources, such as plain text files, JSON files or corpora of predefined conversations.

Here are the steps to build a chatbot in Python using ChatterBot:

Step 1: Prepare the Dependencies

The first step to create chatbot in Python with the ChatterBot library. To install the library in your system. You can use pip command:

pip install chatterbot

You need to install some additional dependencies depending your operating system and language preferences. For example if you want to use voice recognition & synthesis you need to install PyAudio & SpeechRecognition:

pip install pyaudio
pip install speechrecognition

You can find more information about the installation process and requirements on the official documentation.

Step 2: Import Classes

Importing classes is second step in the Python chatbot creation process. You will need to import some classes from the ChatterBot module such as ChatBot and ListTrainer. You will also need to import some other modules for voice recognition and synthesis such as speech_recognition and pyttsx3:

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import speech_recognition as sr
import pyttsx3

Step 3: Create and Train the Chatbot

The next step is to create instance of the ChatBot class and give it a name. You can also customize some parameters of your chatbot such as its logic adapters (which determine how it responds), its storage adapter (which determines how it stores data), its filters (which determine what messages it ignores) and its preprocessors (which determine how it processes input). For example:

chatbot = ChatBot(
    "MyChatBot",
    logic_adapters=[
        {
            "import_path": "chatterbot.logic.BestMatch",
            "default_response": "I'm sorry, I don't understand.",
            "maximum_similarity_threshold": 0.9
        }
    ],
    storage_adapter="chatterbot.storage.SQLStorageAdapter",
    database_uri="sqlite:///database.sqlite3",
    filters=["chatterbot.filters.RepetitiveResponseFilter"],
    preprocessors=["chatterbot.preprocessors.clean_whitespace"]
)

After creating your chatbot instance you need to train it with data. You can use any type of data source that ChatterBot supports but for simplicity we will use a list of strings that represent a sample conversation:

conversation = [
    "Hello",
    "Hi there!",
    "How are you doing?",
    "I'm doing great.",
    "That's good to hear.",
    "Thank you.",
    "You're welcome."
]

trainer = ListTrainer(chatbot)
trainer.train(conversation)

This will train your chatbot with given list of strings using a ListTrainer object. You can train your chatbot with multiple lists or other types of data sources by calling the train method multiple times.

Step 4: Communicate with the Python Chatbot

The final step is to communicate with your chatbot using either text or voice input. You can use any method you prefer for getting user input, such as input() or tkinter. For voice input, you will need to use speech_recognition’s Recognizer class which allows you to capture audio from a microphone and convert it into text.

For example:

recognizer = sr.Recognizer()

with sr.Microphone() as source:
    print("Say something:")
    audio = recognizer.listen(source)

try:
    message = recognizer.recognize_google(audio)
except sr.UnknownValueError:
    message = ""
except sr.RequestError:
    message = ""

print("You said:", message)

This will print what you said after capturing audio from your microphone using Google’s speech recognition service. To get response from your chatbot based on your input you need to use the get_response method of your chatbot instance and pass your input as an argument. For example:

response = chatbot.get_response(message)
print("Chatbot said:", response)

This will print what your chatbot said based on your input using the logic adapters and data sources you specified.

To make the communication more natural, you can also use pyttsx3’s init function which allows you to initialize a text-to-speech engine and speak the response aloud. For example:

engine = pyttsx3.init()

engine.say(response)

engine.runAndWait()

This will speak response using the default voice and settings of your system.

Step 5: Complete Code for Chatbot in Python

Here is complete code for building a simple AI chatbot in Python using ChatterBot:

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import speech_recognition as sr
import pyttsx3

# Create and train the chatbot
chatbot = ChatBot(
    "MyChatBot",
    logic_adapters=[
        {
            "import_path": "chatterbot.logic.BestMatch",
            "default_response": "I'm sorry, I don't understand.",
            "maximum_similarity_threshold": 0.9
        }
    ],
    storage_adapter="chatterbot.storage.SQLStorageAdapter",
    database_uri="sqlite:///database.sqlite3",
    filters=["chatterbot.filters.RepetitiveResponseFilter"],
    preprocessors=["chatterbot.preprocessors.clean_whitespace"]
)

conversation = [
    "Hello",
    "Hi there!",
    "How are you doing?",
    "I'm doing great.",
    "That's good to hear.",
    "Thank you.",
    "You're welcome."
]

trainer = ListTrainer(chatbot)

trainer.train(conversation)

# Initialize speech recognition and synthesis
recognizer = sr.Recognizer()
engine = pyttsx3.init()

# Communicate with the chatbot
while True:
    
    # Get user input by voice
    with sr.Microphone() as source:
        print("Say something:")
        audio = recognizer.listen(source)

    try:
        message = recognizer.recognize_google(audio)
        print("You said:", message)
        
        # Break the loop if user says bye
        if message.lower() == "bye":
            break
        
        # Get chatbot response by text
        response = chatbot.get_response(message)
        print("Chatbot said:", response)
        
        # Speak chatbot response by voice
        engine.say(response)
        engine.runAndWait()
        
    except sr.UnknownValueError:
        print("Sorry, I could not understand what you said.")
        
    except sr.RequestError:
        print("Sorry, there was a problem with the service.")

You may also read:

Recipe Recommender in Python – Python Project

Automatic Email Sender in Python – Python Code to Send Email

Create a News Feed Application in Python | Python Project