Make Your Tasks Automated With Your Voice πŸ”₯

Using Python!

Β·

6 min read

Make Your Tasks Automated With Your Voice πŸ”₯

Hello, buddies! Developers, it means us, always do is click, click and click and type, type, type. But from today, you are not going to click everything and open them! We're the developers, we can save one second of clicking using Python(or any other languageπŸ˜‰) So today we are going to automate our computer functions like Opening folders, Opening websites, Sending emails, and many things using your voice, with Python!!

P.S. This may look like Jarvis that we made before, but this can do many more things than himπŸ˜‰.

wow.gif your face now...

Setting Up

Before adding tasks, let's import modules and set up the script. Here, we need only 6 modules.

import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install speech_recognition
import webbrowser 
import os
import smtplib
import socket #IP Adress

The first and foremost thing for an A.I. assistant is that it should be able to speak. To make our Assistant talk, we will make a function called speak(). This function will take audio as an argument, and then it will pronounce it.

def speak(audio):
       pass      #For now, we will write the conditions later.

Now, the next thing we need is audio. We must supply audio so that we can pronounce it using the speak() function we made. We are going to install a module called pyttsx3. To install pyttsx3 you can open the terminal and type

pip install pyttsx

After that, pyttsx is imported(Code in Prerequisites)!

import pyttsx3

engine = pyttsx3.init('sapi5')

voices= engine.getProperty('voices') #getting details of current voice

engine.setProperty('voice', voice[0].id)
  • voice[0].id = Male voice
  • voice[1].id = Female voice

main() Function

We will create a main() function, and inside this main() Function, we will call our speak function.

if __name__=="__main__" :

speak("Unity Buddy Will Help You!")

takeCommand() Function

The next most important thing for our assistant is that it should take command with the help of the microphone of the user's system. So, now we will make a takeCommand() function. With the help of the takeCommand() function, our assistant will return a string output by taking microphone input from the user.

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') ##Using google for voice recognition.
        print(f"User said: {query}\n") #User query will be printed.

    except Exception as e:
        # print(e)
        speak("Say that again please...") #Say that again will be printed in case of improper voice
        return "None"   #None string will be returned(rarely)
    return query

Congrats! We have set up our assistant. Now it's time to add Tasks!

Commands and Tasks

Most interesting and an important part! Go ahead!😎

Browser Functions

Open Youtube

if __name__ == "__main__":
    wishMe()
    while True:
    # if 1:
        query = takeCommand().lower() #Converting user query into lower case

 if 'open youtube' in query:
            webbrowser.open("youtube.com")

Open Google

elif 'open google' in query:
            webbrowser.open("google.com")

Open Stackoverflow

        elif 'open stackoverflow' in query:
            webbrowser.open("stackoverflow.com")

You can open any other website using the same lines of code.

Your Computer Functions

Open Downloads

 elif 'open downloads' in query:
            downloadsPath = "C:\\Users\\Admin\\Downloads"

Open A Application/Game

        elif 'open Among Us' in query:
            amongUs = "C:\\Users\\Admin\\AmongUs.exe"

Open Code

        elif 'open code' in query:
            codePath = "C:\\Users\\chenuli\\AppData\\Local\\Programs\\Microsoft VS Code\\levelmenu.exe"
            os.startfile(codePath)

It's super easy, you have only to include the path of the file/folder

Display Hostname and IP address

        elif 'display hostname' in query:
            hostname = socket.gethostname()
            ip_address = socket.gethostbyname(hostname)
            print(f"Hostname: {hostname}")
            print(f"IP Address: {ip_address}")

Reference - Display Hostname and IP address using Python by Nishant Gour

Play Music

 elif 'play music' in query:
            music_dir = 'D:\MyPlayList'
            songs = os.listdir(music_dir)
            print(songs)
            os.startfile(os.path.join(music_dir, songs[0]))

Hashnode Functions 😎😎

Open Hashnode

        elif 'open hashnode'in query:
             webbrowser.open("hashnode.com")

Open Hashnode Notifications

        elif 'open notifications' in query:
            webbrowser.open("hashnode.com/notifications")

Write New Article

 elif 'write new article' in query:
            webbrowser.open("hn.new")

And almost anything in Hashnode!

Send E-mails

This is somewhat different from other tasks. We will create a sendEmail() function, which will help us send emails to one or more than one recipient. πŸ“§

def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login('boobagames123@gmail.com', 'hacker123')
    server.sendmail('boobagames123@gmail.com', to, content)
    server.close()
  1. The sender: Email address of the sender.
  2. The receiver: Email of the receiver.
  3. The message: A string message which needs to be sent to one or more than one recipient.

Call sendEmail() function inside the main() function:

 elif 'email to Victoria' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                to = "chenuliilz@gmail.com.com"
                sendEmail(to, content)
                speak("Email has been sent!")
            except Exception as e:
                print(e)
                speak("Sorry my friend Unity buddy. I am not able to send this email") # If your email and password is incorrect.

You are done!

Wohoo! You have made your assistant and now, just give the command. He will do it for you. Here's the full code that you were looking for! P.S. Sorry for missing full code. Here you are!

import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install speechRecognition
import datetime
import webbrowser
import os
import smtplib
import socket

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
# print(voices[1].id)
engine.setProperty('voice', voices[0].id)


def speak(audio):
    engine.say(audio)
    engine.runAndWait()



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)
        speak("Say that again please.. I didn't get it.")
        return "None"
    return query

def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login('boobagames123@gmail.com', 'Chenuli14836')
    server.sendmail('boobagames123@gmail.com', to, content)
    server.close()

if __name__ == "__main__":

    while True:
    # if 1:
        query = takeCommand().lower()
# ____________________________Browser_______________________________________________________
        if '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 = 'D:\MyPlayList'
            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}")
 # ____________________________your computer_______________________________________________________
        elif 'open code' in query:
            codePath = "C:\\Users\\chenuli\\AppData\\Local\\Programs\\Microsoft VS Code\\levelmenu.exe"
            os.startfile(codePath)
        elif 'open downloads' in query:
            downloadsPath = "C:\\Users\\Admin\\Downloads"
        elif 'open Among Us' in query:
            amongUs = "C:\\Users\\Admin\\AmongUs.exe"
        elif 'display hostname' in query:
            hostname = socket.gethostname()
            ip_address = socket.gethostbyname(hostname)
            print(f"Hostname: {hostname}")
            print(f"IP Address: {ip_address}")


    #____________________________Hashnode_______________________________________________________
        elif 'open hashnode'in query:
             webbrowser.open("hashnode.com")

        elif 'open notifications' in query:
            webbrowser.open("hashnode.com/notifications")
        elif 'write new article' in query:
            webbrowser.open("hn.new")
#________________________________________________________________________________________

        elif 'email to Victoria' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                to = "chenuliilz@gmail.com.com"
                sendEmail(to, content)
                speak("Email has been sent!")
            except Exception as e:
                print(e)
                speak("Sorry my buddy. I am not able to send this email")

And that's it! Thanks for reading this long article and now you can let your mouse rest. Happy Coding!

Β