Search code examples
pythonpython-3.xartificial-intelligencespeech-recognitionspeech-to-text

How do i fix AttributeError: 'NoneType' object has no attribute 'lower'?


Every time I run the code my code aimed at building a weak Ai platform I receive a AttributeError: 'NoneType' object has no attribute 'lower', and I have totally no clue why as it works fine in a tutorial i am following.can someone please walk me through fixing this as I am fairly new to python. Thanks

import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import smtplib
import pythoncom

print("Initializing Bot")

MASTER = "Bob"

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

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


def wishMe():
    hour = int(datetime.datetime.now().hour)

    if hour>=0 and hour <12:
        speak("Good Morning" + MASTER)

    elif hour>=12 and hour<18:
        speak("Good Afternoon" + MASTER)
    else:
        speak("Good Evening" + MASTER)


    speak("How may I assist you?")

def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        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("Sorry i didn't catch that...")

speak("Initializing bot...")
wishMe()
    query = takeCommand()

#Logic

if 'wikipedia' in query.lower():
    speak('Searching wikipedia...')
    query = query.replace("wikipedia", "")
    results = wikipedia.summary(query, sentences =2)
    print(results)
    speak(results)


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

Alternatively the microphone also does not pick up an input, any ideas on why this is also the case?


Solution

  • The error is because the variable query is sometimes None. And you are applying .lower() function on it which only works on str type objects.

    You can control this by putting your code inside a if loop which runs only when there's a string in query variable. Like this maybe:

    wishMe()
    query = takeCommand()
    
    #Logic
    
    if query:
        if 'wikipedia' in query.lower():
            speak('Searching wikipedia...')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences =2)
            print(results)
            speak(results)
    
    
        if 'open youtube' in query.lower():
            webbrowser.open("youtube.com")