Python Forum
Adding a Wake word to my Script
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Adding a Wake word to my Script
#3
(Jan-12-2022, 06:51 PM)SheeppOSU Wrote: I think you may need to restructure your code a bit. I would first separate each command into its own function to get rid of clutter in the main function. Also, it would be better to put a while loop in the main function rather than looping the main function itself. As for the problem, I would use the listen function in a while loop, and put an if statement to check if baxter has been said. If not, return to the top of the loop with continue. Otherwise, listen again, this time for the command that's being specified, if any.

So I changed the main function to a while loop, and now I'm wondering how to change the listenCommand(): function to a while loop.

Would it be like this?
#def listenCommand():
while True():
    command=0
    hear = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = hear.listen(source)  
    #---------------------------
    # Uses google API to listen
    try:
        print("Recognizing...")
        command = hear.recognize_google(audio, language='en-in')
        print(f'{Commander} : {command}\n')
    #--------------------------------
    if ('baxter' not in command):
        continue
 
Thanks.


Full Working Code (as of now):
#!/usr/bin/env python3

import json
import random
import datetime
import operator
import os
import time
import sys
import requests
from bs4 import BeautifulSoup
from Weather import *
import wikipedia
import wolframalpha
import pyttsx3
import espeakng
import speech_recognition as sr 

#-------------------------------------------------------------------------------------
                            #Commander Name (You) and A.I Name
#-------------------------------------------------------------------------------------
Commander = "Commander"
AI_Name = 'baxter'
#-------------------------------------------------------------------------------------

print ("Initializing B.A.X.T.E.R...")

def speak(text):
    mySpeaker = espeakng.Speaker()
    #mySpeaker.say('Initializing Baxter')
    

def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning" + Commander)
        print("Good Morning " + Commander)
    elif hour>=12 and hour<18:
        speak("Good Afternoon" + Commander)
        print("Good Afternoon " + Commander)   
    else:
        speak("Good Evening" + Commander) 
        print("Good Evening " + Commander) 
        speak("How may I be of service?")
        print("How may I be of service?")   

def listenCommand():
    command=0
    hear = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = hear.listen(source)  
    #---------------------------
    # Uses google API to listen
    try:
        print("Recognizing...")
        command = hear.recognize_google(audio, language='en-in')
        print(f'{Commander} : {command}\n')
    #--------------------------------

    except:
            pass

    return command 

speak("Initializing Baxter..........")
wishMe()

while True():
    command = listenCommand()
    command=str(command).lower()

    #-------------------------------------------------------------------------------------
                            #Search Wikipedia (General Info)
    #-------------------------------------------------------------------------------------
    if ('weather' not in command):
        if ('who is' in command) or ('what is the' in command) or ('what is a' in command):
            if ('time' not in command):
                speak('Searching Wikipedia...')
                command = command.replace("who is","")
                command = command.replace("what is the","")
                command = command.replace("what is a","")
                results = wikipedia.summary(command, sentences = 2)
                #----------------------
                #Auto typing animation:
                print("Baxter: ", end="")
                for i in results:
                    sys.stdout.write(i)
                    sys.stdout.flush()
                    time.sleep(0.05)
                print("\n")
                #----------------------
                speak(results) 
    #-------------------------------------------------------------------------------------
                    #Search Wolfram Alpha (Math/Conversions, Definitions)
    #-------------------------------------------------------------------------------------
    if ('calculate' in command) or ('what is' in command) or ('define' in command):
        speak('Searching Wolfram Alpha...')
        command = command.replace("calculate","")
        command = command.replace("what is","")
        command = command.replace("define","")
        # Wolframalpha App Id
        appId = 'JH9XHR-W9J76L7H5A'
        # Wolfram Instance
        client = wolframalpha.Client(appId)
        res = client.query(''.join(command))
        results = next(res.results).text
        #print("Baxter:",results)
        #----------------------
        #Auto typing animation:
        print("Baxter: ", end="")
        for i in results:
            sys.stdout.write(i)
            sys.stdout.flush()
            time.sleep(0.05)
        print("\n")
        #----------------------
        speak(results) 
    #-------------------------------------------------------------------------------------
                                    #Search News
    #-------------------------------------------------------------------------------------
    if ('news' in command):
        speak('Searching news networks...')
        command = command.replace("news","")
        #Gets the news headlines from this url:
        url='https://www.google.com/search?q=windsor+news&client=firefox-b-d&source=lnms&tbm=nws&sa=X&ved=2ahUKEwjFr5SwoJb1AhXELs0KHdabBAEQ_AUoAXoECAEQAw&biw=1024&bih=486'
        results = requests.get(url)
        soup = BeautifulSoup(results.text, 'html.parser')
        headlines = soup.find('body').find_all('h3')
        for x in headlines:
            print("Baxter:",x.text.strip())
        speak(results) 
    #-------------------------------------------------------------------------------------
                                        #Search Weather
    #-------------------------------------------------------------------------------------
    if ('weather' in command):
        if ('week' in command):
            speak('Searching weather networks...')
            command = command.replace("weather for the week","")
            #Call weather data for the week:
            displayWeeksWeatherData()
        else:
            speak('Searching weather networks...')
            command = command.replace("weather","")
        #Call weather data for today:
        displayWeatherData()
    #-------------------------------------------------------------------------------------
                                        #Tell Time
    #-------------------------------------------------------------------------------------
    elif ('time' in command):
        speak('Scanning local clock networks...')
        command = command.replace("time","")
        strTime = datetime.datetime.now().strftime("%I:%M%P")
        speak("The time is {strTime}")
        print("Baxter: The time is ", strTime)
    #-------------------------------------------------------------------------------------
                                #Enter the Matrix (Easter Egg)
    #-------------------------------------------------------------------------------------
    elif ('matrix' in command):
        speak('Entering the matrix...')
        command = command.replace("matrix","")
        response = "Taking the red pill..."
        #----------------------
        #Auto typing animation:
        print("Baxter: ", end="")
        for i in response:
            sys.stdout.write(i)
            sys.stdout.flush()
            time.sleep(0.2)
        print("\n")
        #----------------------
        time.sleep(2)
        os.system("cmatrix")
    #-------------------------------------------------------------------------------------

    #-------------------------------------------------------------------------------------
                                #Stop Program/Script Command
    #-------------------------------------------------------------------------------------
    elif ('stop' in command) or ('shutdown' in command) or ('quit' in command):
        speak("Shutting Down...")
        response = "Terminating program..."
        #----------------------
        #Auto typing animation:
        print("Baxter: ", end="")
        for i in response:
            sys.stdout.write(i)
            sys.stdout.flush()
            time.sleep(0.2)
        print("\n")
        #----------------------
        exit()
    #-------------------------------------------------------------------------------------
Reply


Messages In This Thread
Adding a Wake word to my Script - by Extra - Jan-12-2022, 04:34 PM
RE: Adding a Wake word to my Script - by SheeppOSU - Jan-12-2022, 06:51 PM
RE: Adding a Wake word to my Script - by Extra - Jan-13-2022, 01:55 PM
RE: Adding a Wake word to my Script - by SheeppOSU - Jan-13-2022, 07:48 PM
RE: Adding a Wake word to my Script - by Extra - Jan-13-2022, 09:10 PM
RE: Adding a Wake word to my Script - by SheeppOSU - Jan-13-2022, 11:53 PM
RE: Adding a Wake word to my Script - by Extra - Jan-14-2022, 06:52 PM
RE: Adding a Wake word to my Script - by SheeppOSU - Jan-14-2022, 07:50 PM
RE: Adding a Wake word to my Script - by Extra - Jan-14-2022, 09:17 PM
RE: Adding a Wake word to my Script - by SheeppOSU - Jan-16-2022, 10:46 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 3,757 Aug-12-2021, 04:25 PM
Last Post: palladium
  Adding a list to Python Emailing Script Cknutson575 4 3,577 Feb-18-2021, 09:13 AM
Last Post: buran
Question Word, adding a hyperlink from a bookmark using Python mart79 1 3,305 Jan-14-2021, 08:41 PM
Last Post: Larz60+
  Python Speech recognition, word by word AceScottie 6 18,809 Apr-12-2020, 09:50 AM
Last Post: vinayakdhage
  print a word after specific word search evilcode1 8 6,642 Oct-22-2019, 08:08 AM
Last Post: newbieAuggie2019
  Adding markers to Folium map only adding last element. tantony 0 2,944 Oct-16-2019, 03:28 PM
Last Post: tantony
  difference between word: and word[:] in for loop zowhair 2 4,685 Mar-03-2018, 07:24 AM
Last Post: zowhair
  Adding a parameter/argument to a script jehoshua 11 12,872 Jan-29-2018, 09:45 AM
Last Post: jehoshua
  How to make a script to find a certain word in text files in a whole directory ? RandoomDude 2 7,128 Apr-27-2017, 10:27 AM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020