Skip to content

Basic Chatbot

Abstract

This is a basic chatbot that can answer some basic questions. You have some predefined commands that you can ask the chatbot and it will answer you accordingly. In this chatbot, you can ask the chatbot to open youtube, google, stackoverflow, play music, tell you the time, open code, and send an email to someone. This is inspire by Jarvis Project From CodeWithHarry.

Prerequisites

  • Python 3.6 or above
  • A code editor or IDE
  • pyttsx3 module
  • speech_recognition module
  • wikipedia module
  • webbrowser module

Before you Start

Before starting making this project, you must have python installed on your computer. If you don’t have python installed you can download it from here. You must have a code editor or IDE installed on your computer. If you don’t have any code editor or IDE installed you can download Visual Studio Code from here. You must have the request module and BeautifulSoup module installed on your computer. If you don’t have these modules installed you can install them by using the following commands in your terminal.

command
C:\Users\Your Name>pip install pyttsx3
C:\Users\Your Name>pip install speechRecognition
C:\Users\Your Name>pip install wikipedia
C:\Users\Your Name>pip install webbrowser
C:\Users\Your Name>pip install pyaudio
C:\Users\Your Name>pip install smtplib
C:\Users\Your Name>pip install setuptools
command
C:\Users\Your Name>pip install pyttsx3
C:\Users\Your Name>pip install speechRecognition
C:\Users\Your Name>pip install wikipedia
C:\Users\Your Name>pip install webbrowser
C:\Users\Your Name>pip install pyaudio
C:\Users\Your Name>pip install smtplib
C:\Users\Your Name>pip install setuptools

Getting Started

Create a Project

  1. Create a folder named basicchatbotbasicchatbot.
  2. Open the folder in your favorite code editor or IDE.
  3. Create a file named basicchatbot.pybasicchatbot.py.
  4. Copy the code given code and paste it in your basicchatbot.pybasicchatbot.py file.

Write the code

  1. Copy and paste the following code in your basicchatbot.pybasicchatbot.py file.
⚙️ Basic Chat Bot
Basic Chat Bot
# Basic Chat Bot
# Credits: https://www.youtube.com/watch?v=Lp9Ftuq2sVI&t=3008s
# Author: Code With Harry
 
import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install speechRecognition
import datetime
import wikipedia #pip install wikipedia
import webbrowser
import os
import smtplib
 
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
 
 
def speak(audio):
    engine.say(audio)
    engine.runAndWait()
 
 
def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning!")
 
    elif hour>=12 and hour<18:
        speak("Good Afternoon!")   
 
    else:
        speak("Good Evening!")  
 
    speak("I am Jarvis Sir. Please tell me how may I help you")       
 
def takeCommand():
    #It takes microphone input from the user and returns string output
 
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)
 
    try:
        print("Recognizing...")    
        query = r.recognize_google(audio, language='en-in')
        print(f"User said: {query}\n")
 
    except Exception as e:
        # print(e)    
        print("Say that again please...")  
        return "None"
    return query
 
def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login('youremail@gmail.com', 'your-password') # Enter your email and password at youremail@gmail.com and your-password
    server.sendmail('youremail@gmail.com', to, content) # Enter your email at youremail@gmail
    server.close()
 
if __name__ == "__main__":
    wishMe()
    while True:
    # if 1:
        query = takeCommand().lower()
 
        # Logic for executing tasks based on query
        if 'wikipedia' in query:
            speak('Searching Wikipedia...')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=2)
            speak("According to Wikipedia")
            print(results)
            speak(results)
 
        elif 'open youtube' in query:
            webbrowser.open("youtube.com")
 
        elif 'open google' in query:
            webbrowser.open("google.com")
 
        elif 'open stackoverflow' in query:
            webbrowser.open("stackoverflow.com")   
 
 
        elif 'play music' in query:
            music_dir = 'Your Music Directory' # Enter your music directory here like C:\\Users\\Ravi\\Music
            songs = os.listdir(music_dir)
            print(songs)    
            os.startfile(os.path.join(music_dir, songs[0]))
 
        elif 'the time' in query:
            strTime = datetime.datetime.now().strftime("%H:%M:%S")    
            speak(f"Sir, the time is {strTime}")
 
        elif 'open code' in query:
            codePath = "C:\\Users\\Ravi\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
            os.startfile(codePath)
 
        elif 'email to ravi' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                to = "ravi@gmail.com"    
                sendEmail(to, content)
                speak("Email has been sent!")
            except Exception as e:
                print(e)
                speak("Sorry. I am not able to send this email")  
Basic Chat Bot
# Basic Chat Bot
# Credits: https://www.youtube.com/watch?v=Lp9Ftuq2sVI&t=3008s
# Author: Code With Harry
 
import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install speechRecognition
import datetime
import wikipedia #pip install wikipedia
import webbrowser
import os
import smtplib
 
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
 
 
def speak(audio):
    engine.say(audio)
    engine.runAndWait()
 
 
def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning!")
 
    elif hour>=12 and hour<18:
        speak("Good Afternoon!")   
 
    else:
        speak("Good Evening!")  
 
    speak("I am Jarvis Sir. Please tell me how may I help you")       
 
def takeCommand():
    #It takes microphone input from the user and returns string output
 
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)
 
    try:
        print("Recognizing...")    
        query = r.recognize_google(audio, language='en-in')
        print(f"User said: {query}\n")
 
    except Exception as e:
        # print(e)    
        print("Say that again please...")  
        return "None"
    return query
 
def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login('youremail@gmail.com', 'your-password') # Enter your email and password at youremail@gmail.com and your-password
    server.sendmail('youremail@gmail.com', to, content) # Enter your email at youremail@gmail
    server.close()
 
if __name__ == "__main__":
    wishMe()
    while True:
    # if 1:
        query = takeCommand().lower()
 
        # Logic for executing tasks based on query
        if 'wikipedia' in query:
            speak('Searching Wikipedia...')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=2)
            speak("According to Wikipedia")
            print(results)
            speak(results)
 
        elif 'open youtube' in query:
            webbrowser.open("youtube.com")
 
        elif 'open google' in query:
            webbrowser.open("google.com")
 
        elif 'open stackoverflow' in query:
            webbrowser.open("stackoverflow.com")   
 
 
        elif 'play music' in query:
            music_dir = 'Your Music Directory' # Enter your music directory here like C:\\Users\\Ravi\\Music
            songs = os.listdir(music_dir)
            print(songs)    
            os.startfile(os.path.join(music_dir, songs[0]))
 
        elif 'the time' in query:
            strTime = datetime.datetime.now().strftime("%H:%M:%S")    
            speak(f"Sir, the time is {strTime}")
 
        elif 'open code' in query:
            codePath = "C:\\Users\\Ravi\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
            os.startfile(codePath)
 
        elif 'email to ravi' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                to = "ravi@gmail.com"    
                sendEmail(to, content)
                speak("Email has been sent!")
            except Exception as e:
                print(e)
                speak("Sorry. I am not able to send this email")  
  1. Save the file.
  2. Open the terminal in your code editor or IDE and navigate to the folder basicchatbotbasicchatbot.
command
C:\Users\Your Name\basicchatbot> python basicchatbot.py
Listening...
Recognizing...
User said: Silicon Valley Wikipedia
 
Silicon Valley is a region in Northern California that is a global center for high technology and innovation. Located in the southern part of the San Francisco Bay Area, it corresponds roughly to the geographical area of the Santa Clara Valley.
Listening...
Recognizing...
User said: open YouTube
 
Listening...
Recognizing...
User said: open Google
 
Listening...
Recognizing...
User said: open stack overflow
 
Listening...
Recognizing...
Say that again please...
Listening...
Recognizing...
User said: tell me the time
 
Listening...
Recognizing...
User said: open code
command
C:\Users\Your Name\basicchatbot> python basicchatbot.py
Listening...
Recognizing...
User said: Silicon Valley Wikipedia
 
Silicon Valley is a region in Northern California that is a global center for high technology and innovation. Located in the southern part of the San Francisco Bay Area, it corresponds roughly to the geographical area of the Santa Clara Valley.
Listening...
Recognizing...
User said: open YouTube
 
Listening...
Recognizing...
User said: open Google
 
Listening...
Recognizing...
User said: open stack overflow
 
Listening...
Recognizing...
Say that again please...
Listening...
Recognizing...
User said: tell me the time
 
Listening...
Recognizing...
User said: open code

Explanation

  1. Import the required modules.
basicchatbot.py
import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install speechRecognition
import datetime
import wikipedia #pip install wikipedia
import webbrowser
import os
import smtplib
basicchatbot.py
import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install speechRecognition
import datetime
import wikipedia #pip install wikipedia
import webbrowser
import os
import smtplib
  1. Initialize the pyttsx3 module.
basicchatbot.py
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
basicchatbot.py
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
  1. Define a function speak()speak() that will take audioaudio as an argument and will speak the audioaudio that is passed to it.
basicchatbot.py
def speak(audio):
    engine.say(audio)
    engine.runAndWait()
basicchatbot.py
def speak(audio):
    engine.say(audio)
    engine.runAndWait()
  1. Define a function wishMe()wishMe() that will wish you according to the time.
basicchatbot.py
def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning!")
 
    elif hour>=12 and hour<18:
        speak("Good Afternoon!")   
 
    else:
        speak("Good Evening!")  
 
    speak("I am Jarvis Sir. Please tell me how may I help you")       
basicchatbot.py
def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning!")
 
    elif hour>=12 and hour<18:
        speak("Good Afternoon!")   
 
    else:
        speak("Good Evening!")  
 
    speak("I am Jarvis Sir. Please tell me how may I help you")       
  1. Define a function takeCommand()takeCommand() that will take microphone input from the user and returns string output.
basicchatbot.py
def takeCommand():
    #It takes microphone input from the user and returns string output
 
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)
 
    try:
        print("Recognizing...")    
        query = r.recognize_google(audio, language='en-in')
        print(f"User said: {query}\n")
 
    except Exception as e:
        # print(e)    
        print("Say that again please...")  
        return "None"
    return query
basicchatbot.py
def takeCommand():
    #It takes microphone input from the user and returns string output
 
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)
 
    try:
        print("Recognizing...")    
        query = r.recognize_google(audio, language='en-in')
        print(f"User said: {query}\n")
 
    except Exception as e:
        # print(e)    
        print("Say that again please...")  
        return "None"
    return query
  1. Define a function sendEmail()sendEmail() that will send an email to the person you want to send an email to.
basicchatbot.py
def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login('youremail@gmail.com', 'your-password') # Enter your email and password at
    server.sendmail('youremail@gmail.com', to, content) # Enter your email at youremail@gmail
    server.close()
basicchatbot.py
def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login('youremail@gmail.com', 'your-password') # Enter your email and password at
    server.sendmail('youremail@gmail.com', to, content) # Enter your email at youremail@gmail
    server.close()
  1. Define the main function main()main() that will call all the functions.
basicchatbot.py
if __name__ == "__main__":
    wishMe()
    while True:
basicchatbot.py
if __name__ == "__main__":
    wishMe()
    while True:
  1. Call the takeCommand()takeCommand() function and store the returned value in the variable queryquery.
basicchatbot.py
if __name__ == "__main__":
    wishMe()
    while True:
    # if 1:
        query = takeCommand().lower()
basicchatbot.py
if __name__ == "__main__":
    wishMe()
    while True:
    # if 1:
        query = takeCommand().lower()
  1. Check if the word wikipediawikipedia is in the queryquery variable. If it is in the queryquery variable then call the speak()speak() function and speak the following lines.
basicchatbot.py
if 'wikipedia' in query:
    speak('Searching Wikipedia...')
    query = query.replace("wikipedia", "")
    results = wikipedia.summary(query, sentences=2)
    speak("According to Wikipedia")
    print(results)
    speak(results)
basicchatbot.py
if 'wikipedia' in query:
    speak('Searching Wikipedia...')
    query = query.replace("wikipedia", "")
    results = wikipedia.summary(query, sentences=2)
    speak("According to Wikipedia")
    print(results)
    speak(results)
  1. Check if the word open youtubeopen youtube is in the queryquery variable. If it is in the queryquery variable then call the webbrowser.open()webbrowser.open() function and open youtube.
basicchatbot.py
elif 'open youtube' in query:
    webbrowser.open("youtube.com")
basicchatbot.py
elif 'open youtube' in query:
    webbrowser.open("youtube.com")
  1. Check if the word open googleopen google is in the queryquery variable. If it is in the queryquery variable then call the webbrowser.open()webbrowser.open() function and open google.
basicchatbot.py
elif 'open google' in query:
    webbrowser.open("google.com")
basicchatbot.py
elif 'open google' in query:
    webbrowser.open("google.com")
  1. Check if the word open stackoverflowopen stackoverflow is in the queryquery variable. If it is in the queryquery variable then call the webbrowser.open()webbrowser.open() function and open stackoverflow.
basicchatbot.py
elif 'open stackoverflow' in query:
    webbrowser.open("stackoverflow.com")   
basicchatbot.py
elif 'open stackoverflow' in query:
    webbrowser.open("stackoverflow.com")   
  1. Check if the word play musicplay music is in the queryquery variable. If it is in the queryquery variable then call the os.listdir()os.listdir() function and list all the files in the music directory. Then call the os.startfile()os.startfile() function and play the first song in the music directory.
basicchatbot.py
elif 'play music' in query:
    music_dir = 'Your Music Directory' # Enter your music directory here like C:\\Users\\Ravi\\Music
    songs = os.listdir(music_dir)
    print(songs)    
    os.startfile(os.path.join(music_dir, songs[0]))
basicchatbot.py
elif 'play music' in query:
    music_dir = 'Your Music Directory' # Enter your music directory here like C:\\Users\\Ravi\\Music
    songs = os.listdir(music_dir)
    print(songs)    
    os.startfile(os.path.join(music_dir, songs[0]))
  1. Check if the word the timethe time is in the queryquery variable. If it is in the queryquery variable then call the datetime.datetime.now()datetime.datetime.now() function and get the current time. Then call the speak()speak() function and speak the current time.
basicchatbot.py
elif 'the time' in query:
    strTime = datetime.datetime.now().strftime("%H:%M:%S")    
    speak(f"Sir, the time is {strTime}")
basicchatbot.py
elif 'the time' in query:
    strTime = datetime.datetime.now().strftime("%H:%M:%S")    
    speak(f"Sir, the time is {strTime}")
  1. Check if the word open codeopen code is in the queryquery variable. If it is in the queryquery variable then call the os.startfile()os.startfile() function and open the code.
basicchatbot.py
elif 'open code' in query:
    codePath = "C:\\Users\\Ravi\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
    os.startfile(codePath)
basicchatbot.py
elif 'open code' in query:
    codePath = "C:\\Users\\Ravi\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
    os.startfile(codePath)
  1. Check if the word email to raviemail to ravi is in the queryquery variable. If it is in the queryquery variable then call the speak()speak() function and speak the following lines. Then call the takeCommand()takeCommand() function and store the returned value in the variable contentcontent. Then call the sendEmail()sendEmail() function and send the email to the person you want to send the email to.
basicchatbot.py
elif 'email to ravi' in query:
    try:
        speak("What should I say?")
        content = takeCommand()
        to = "ravi@gmail.com"
        sendEmail(to, content)
        speak("Email has been sent!")
    except Exception as e:
        print(e)
        speak("Sorry. I am not able to send this email")
basicchatbot.py
elif 'email to ravi' in query:
    try:
        speak("What should I say?")
        content = takeCommand()
        to = "ravi@gmail.com"
        sendEmail(to, content)
        speak("Email has been sent!")
    except Exception as e:
        print(e)
        speak("Sorry. I am not able to send this email")

Usage

  1. Open the terminal in your code editor or IDE and navigate to the folder basicchatbotbasicchatbot.
command
C:\Users\Your Name\basicchatbot> python basicchatbot.py
command
C:\Users\Your Name\basicchatbot> python basicchatbot.py
  1. Run the basicchatbot.pybasicchatbot.py file.
command
C:\Users\Your Name\basicchatbot> python basicchatbot.py
command
C:\Users\Your Name\basicchatbot> python basicchatbot.py
  1. Now you can ask the chatbot to open youtube, google, stackoverflow, play music, tell you the time, open code, and send an email to someone.

Output

command
C:\Users\Your Name\basicchatbot> python basicchatbot.py
Listening...
Recognizing...
User said: Silicon Valley Wikipedia
 
Silicon Valley is a region in Northern California that is a global center for high technology and innovation. Located in the southern part of the San Francisco Bay Area, it corresponds roughly to the geographical area of the Santa Clara Valley.
Listening...
Recognizing...
User said: open YouTube
 
Listening...
Recognizing...
User said: open Google
 
Listening...
Recognizing...
User said: open stack overflow
 
Listening...
Recognizing...
Say that again please...
Listening...
Recognizing...
User said: tell me the time
 
Listening...
Recognizing...
User said: open code
command
C:\Users\Your Name\basicchatbot> python basicchatbot.py
Listening...
Recognizing...
User said: Silicon Valley Wikipedia
 
Silicon Valley is a region in Northern California that is a global center for high technology and innovation. Located in the southern part of the San Francisco Bay Area, it corresponds roughly to the geographical area of the Santa Clara Valley.
Listening...
Recognizing...
User said: open YouTube
 
Listening...
Recognizing...
User said: open Google
 
Listening...
Recognizing...
User said: open stack overflow
 
Listening...
Recognizing...
Say that again please...
Listening...
Recognizing...
User said: tell me the time
 
Listening...
Recognizing...
User said: open code

Next Steps

Congratulations 🎉 you have successfully created a basic chatbot that can answer some basic questions. You have some predefined commands that you can ask the chatbot and it will answer you accordingly. Now you can ask the chatbot to open youtube, google, stackoverflow, play music, tell you the time, open code, and send an email to someone. You can also add more commands to the chatbot.

Here are some ideas:

  1. You can add more commands to the chatbot.
  2. You can add more features to the chatbot.
  3. Add more voices to the chatbot.
  4. You can use more intelligent algorithms to make the chatbot more intelligent.
  5. Use open-source libraries to make the chatbot more intelligent.

Conclusion

Now you have a good understanding of how to create a basic chatbot that can answer some basic questions. You have some predefined commands that you can ask the chatbot and it will answer you accordingly. In this chatbot, you can ask the chatbot to open youtube, google, stackoverflow, play music, tell you the time, open code, and send an email to someone. This is inspire by Jarvis Project From CodeWithHarry. You can also add more commands to the chatbot. You can add more features to the chatbot. Add more voices to the chatbot. You can use more intelligent algorithms to make the chatbot more intelligent. Use open-source libraries to make the chatbot more intelligent.

Was this page helpful?

Let us know how we did