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.
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
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
- Create a folder named
basicchatbot
basicchatbot
. - Open the folder in your favorite code editor or IDE.
- Create a file named
basicchatbot.py
basicchatbot.py
. - Copy the code given code and paste it in your
basicchatbot.py
basicchatbot.py
file.
Write the code
- Copy and paste the following code in your
basicchatbot.py
basicchatbot.py
file.
⚙️ 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
# 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")
- Save the file.
- Open the terminal in your code editor or IDE and navigate to the folder
basicchatbot
basicchatbot
.
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
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
- Import the required modules.
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
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
- Initialize the pyttsx3 module.
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
- Define a function
speak()
speak()
that will takeaudio
audio
as an argument and will speak theaudio
audio
that is passed to it.
def speak(audio):
engine.say(audio)
engine.runAndWait()
def speak(audio):
engine.say(audio)
engine.runAndWait()
- Define a function
wishMe()
wishMe()
that will wish you according to the time.
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 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")
- Define a function
takeCommand()
takeCommand()
that will take microphone input from the user and returns string output.
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 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
- Define a function
sendEmail()
sendEmail()
that will send an email to the person you want to send an email to.
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()
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()
- Define the main function
main()
main()
that will call all the functions.
if __name__ == "__main__":
wishMe()
while True:
if __name__ == "__main__":
wishMe()
while True:
- Call the
takeCommand()
takeCommand()
function and store the returned value in the variablequery
query
.
if __name__ == "__main__":
wishMe()
while True:
# if 1:
query = takeCommand().lower()
if __name__ == "__main__":
wishMe()
while True:
# if 1:
query = takeCommand().lower()
- Check if the word
wikipedia
wikipedia
is in thequery
query
variable. If it is in thequery
query
variable then call thespeak()
speak()
function and speak the following lines.
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)
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)
- Check if the word
open youtube
open youtube
is in thequery
query
variable. If it is in thequery
query
variable then call thewebbrowser.open()
webbrowser.open()
function and open youtube.
elif 'open youtube' in query:
webbrowser.open("youtube.com")
elif 'open youtube' in query:
webbrowser.open("youtube.com")
- Check if the word
open google
open google
is in thequery
query
variable. If it is in thequery
query
variable then call thewebbrowser.open()
webbrowser.open()
function and open google.
elif 'open google' in query:
webbrowser.open("google.com")
elif 'open google' in query:
webbrowser.open("google.com")
- Check if the word
open stackoverflow
open stackoverflow
is in thequery
query
variable. If it is in thequery
query
variable then call thewebbrowser.open()
webbrowser.open()
function and open stackoverflow.
elif 'open stackoverflow' in query:
webbrowser.open("stackoverflow.com")
elif 'open stackoverflow' in query:
webbrowser.open("stackoverflow.com")
- Check if the word
play music
play music
is in thequery
query
variable. If it is in thequery
query
variable then call theos.listdir()
os.listdir()
function and list all the files in the music directory. Then call theos.startfile()
os.startfile()
function and play the first song in the music directory.
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 '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]))
- Check if the word
the time
the time
is in thequery
query
variable. If it is in thequery
query
variable then call thedatetime.datetime.now()
datetime.datetime.now()
function and get the current time. Then call thespeak()
speak()
function and speak the current time.
elif 'the time' in query:
strTime = datetime.datetime.now().strftime("%H:%M:%S")
speak(f"Sir, the time is {strTime}")
elif 'the time' in query:
strTime = datetime.datetime.now().strftime("%H:%M:%S")
speak(f"Sir, the time is {strTime}")
- Check if the word
open code
open code
is in thequery
query
variable. If it is in thequery
query
variable then call theos.startfile()
os.startfile()
function and open the code.
elif 'open code' in query:
codePath = "C:\\Users\\Ravi\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
os.startfile(codePath)
elif 'open code' in query:
codePath = "C:\\Users\\Ravi\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
os.startfile(codePath)
- Check if the word
email to ravi
email to ravi
is in thequery
query
variable. If it is in thequery
query
variable then call thespeak()
speak()
function and speak the following lines. Then call thetakeCommand()
takeCommand()
function and store the returned value in the variablecontent
content
. Then call thesendEmail()
sendEmail()
function and send the email to the person you want to send the email to.
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")
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
- Open the terminal in your code editor or IDE and navigate to the folder
basicchatbot
basicchatbot
.
C:\Users\Your Name\basicchatbot> python basicchatbot.py
C:\Users\Your Name\basicchatbot> python basicchatbot.py
- Run the
basicchatbot.py
basicchatbot.py
file.
C:\Users\Your Name\basicchatbot> python basicchatbot.py
C:\Users\Your Name\basicchatbot> python basicchatbot.py
- 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
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
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:
- You can 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.
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