0

So i am making an assistant in python with the module pyttsx3 and i have this error. Here is the code:

from __future__ import print_function
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os
import pyttsx3
import speech_recognition as sr
from datetime import date
import time
import webbrowser
import random
from google_images_download import google_images_download

invis_RBT = pyttsx3.init()
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')

def SearchImagesInBrowserAssistantOption():
    response = google_images_download.googleimagesdownload()
    run_again = "Y"
    while run_again == "y" or run_again == "Y":
        invis_RBT.say("Please enter the keyword(s) to search for. Please note, multiple keywords should be separated  with a comma : ")
        invis_RBT.runAndWait()
        search = input("Please enter the keyword(s) to search for. Please note, multiple keywords should be separated  with a , : \n")
        absolute_image_paths = response.download({"keywords": "Google Image Search", "limit": 1})
        run_again = input("Perform another search? Y or N:")
        invis_RBT.say("Perform Another serach?  ")
        invis_RBT.runAndWait()
    print("Bye!")


def DriveToSiteAssistantOption():
    try:
        invis_RBT.say("Listening.... (try typing: 'drive me to and the site name. Like in stagram or linked in.') ")
        invis_RBT.runAndWait()
        DriveMeTo = input("Where do you want me to drive you? Please type the site (only name) correct \n with the correct uppercase letters e.t.c:   ")
        invis_RBT.say(f"Redirecting to {DriveMeTo}.....")
        webbrowser.open(f'https://www.{DriveMeTo}.com/')
        invis_RBT.runAndWait()
        time.sleep(1)
        invis_RBT.say("Are we good now?")
        invis_RBT.runAndWait()

    except:
        invis_RBT.say("Error. Could not complete process.")

def SendEmailAssistantOption():
    # If modifying these scopes, delete the file token.pickle .
    # if you run this for the firs
    # t time it will take you to gmail to choose your account
    SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]

    def speak(text):
        engine = pyttsx3.init()
        voices = engine.getProperty('voices')
        engine.setProperty('voice', voices[1].id)
        rate = engine.getProperty('rate')

        engine.setProperty('rate', rate - 20)

        engine.say(text)
        engine.runAndWait()

    speak("Welcome to mail service")

    def get_audio():
        r = sr.Recognizer()
        with sr.Microphone() as source:
            r.pause_threshold = 1
            r.adjust_for_ambient_noise(source, duration=1)
            audio = r.listen(source)
            said = ""

        try:
            said = r.recognize_google(audio)
            print(said)

        except:
            speak("Didn't get that")

        return said.lower()

    def authenticate_gmail():
        """Shows basic usage of the Gmail API.
        Lists the user's Gmail labels.
        """
        creds = None

        # The file token.pickle stores the user's
        # access and refresh tokens, and is
        # created automatically when the authorization
        # flow completes for the first
        # time.
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)

        # If there are no (valid) credentials available,
        # let the user log in.
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'credentials.json', SCOPES)
                creds = flow.run_local_server(port=0)

            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        service = build('gmail', 'v1', credentials=creds)
        return service

    def check_mails(service):

        # fetching emails of today's date
        today = (date.today())

        today_main = today.strftime('%Y/%m/%d')

        # Call the Gmail API
        results = service.users().messages().list(userId='me',
                                                  labelIds=["INBOX", "UNREAD"],
                                                  q="after:{0} and category:Primary".format(today_main)).execute()
        # The above code will get emails from primary
        # inbox which are unread
        messages = results.get('messages', [])

        if not messages:

            # if no new emails
            print('No messages found.')
            speak('No messages found.')
        else:
            m = ""

            # if email found
            speak("{} new emails found".format(len(messages)))

            speak("if you want to read any particular email just type read ")
            speak("and for not reading type leave ")
            for message in messages:

                msg = service.users().messages().get(userId='me',
                                                     id=message['id'], format='metadata').execute()

                for add in msg['payload']['headers']:
                    if add['name'] == "From":

                        # fetching sender's email name
                        a = str(add['value'].split("<")[0])
                        print(a)

                        speak("email from" + a)
                        text = input()

                        if text == "read":

                            print(msg['snippet'])

                            # speak up the mail
                            speak(msg['snippet'])

                        else:
                            speak("email passed")

    SERVICE2 = authenticate_gmail()
    check_mails(SERVICE2)

def PrintCurrentTimeAssistantOption():
    t = time.localtime()
    current_time = time.strftime("%H:%M:%S", t)
    invis_RBT.say("Current time is: " + current_time)
    invis_RBT.runAndWait()
    print("Current time is: " + current_time)
    invis_RBT.runAndWait()

def RockPaperScissorsAssistantOption():
    while True:
        user_action = input("Enter a choice (rock, paper, scissors): ")
        possible_actions = ["rock", "paper", "scissors"]
        computer_action = random.choice(possible_actions)
        print(f"\nYou chose {user_action}, computer chose {computer_action}.\n")

        if user_action == computer_action:
            print(f"Both players selected {user_action}. It's a tie!")
            invis_RBT.say("It's a draw!")
            invis_RBT.runAndWait()
        elif user_action == "rock":
            if computer_action == "scissors":
                print("Rock smashes scissors! You win!")
                invis_RBT.say("You won!")
                invis_RBT.runAndWait()
            else:
                print("Paper covers rock! You lose.")
                invis_RBT.say("You lost.")
                invis_RBT.runAndWait()
        elif user_action == "paper":
            if computer_action == "rock":
                print("Paper covers rock! You win!")
                invis_RBT.say("You win!")
                invis_RBT.runAndWait()
            else:
                print("Scissors cuts paper! You lose.")
                invis_RBT.say("You lost!")
                invis_RBT.runAndWait()
        elif user_action == "scissors":
            if computer_action == "paper":
                print("Scissors cuts paper! You win!")
                invis_RBT.say("You won!")
                invis_RBT.runAndWait()
            else:
                print("Rock smashes scissors! You lose.")
                invis_RBT.say("You lost.")
                invis_RBT.runAndWait()
        invis_RBT.say("Do you wish to play again?")
        invis_RBT.runAndWait()
        play_again = input("Play again? (y/n): ")
        if play_again.lower() != "y":
            invis_RBT.say("Okay, we had fun. See you net time!")
            invis_RBT.runAndWait()
            break


invis_RBT.say("Hello. i am your new personal assistant, Mr invis. Select option: emails, drivetosite, tellthetime, rockpaperscissors, searchanimage")
invis_RBT.runAndWait()
print("Hello. i am your new personal assistant, Mr invis. Select option: emails, drivetosite, tellthetime, rockpaperscissors, searchanimage")
invis_RBT.runAndWait()
SelectOption = input("Type here:   ")
if SelectOption == "drivetosite":
    DriveToSiteAssistantOption()
elif SelectOption == "emails":
    SendEmailAssistantOption()
elif SelectOption == "tellthetime":
    PrintCurrentTimeAssistantOption()
elif SelectOption == "rockpaperscissors":
    RockPaperScissorsAssistantOption()
elif SelectOption == "searchanimage":
    SearchImagesInBrowserAssistantOption()
else:
    print("Sorry, i do not understand your option.")
    invis_RBT.say("Sorry, but i do not understand you option.")

I read that this has to do with Google API. I tried to install some things but it does not work. I installed client_secrets and i also put it in the current directory, it does not work. Do i have to install somehing else? In the google API console i created a new crendetial, I download it and i still have the same error. Thanks for your time, please answer and if you can answer, please tell me with images what to do and what to download -if the error can be fixed-. Thanks!

  • 1
    Well, the classic thing to do (if you're sure the file is where it is supposed to be) is to run a debugger, let it break when the exception is thrown, and then you `import os; print(os.getcwd())` to see the current directory. – Captain Trojan Aug 06 '21 at 12:58
  • TL;DR. Make it concise if possible. AND share the traceback. Well, most likely the comment from @CaptainTrojan will solve your problem. – Abhishek Prajapat Aug 06 '21 at 13:01

1 Answers1

1

Mostly it will be the path error, make sure if have the required file in proper place

vishnun
  • 104
  • 5
  • As said above by Captain Trojan, make sure you have the "credentials.json" file in your working directory. In most cases the "file not found" error is because of the reason that you don't the corresponding file in your working directory. – vishnun Aug 06 '21 at 13:05
  • Yes the path is correct. But you said mostly..... is this kind of a rare situation? – thomas theocharis Aug 06 '21 at 13:05
  • Could be. But can you post the output that you get from this snippet `import os; print(os.getcwd())`. Apart from this check the spelling of your files also once. Because honestly I can't think of any other scenario. – vishnun Aug 06 '21 at 13:09
  • C:\Users\User\PycharmProjects\NewPorject, here is the path that it prints. – thomas theocharis Aug 06 '21 at 13:12
  • Sorry got confused. Can you post this one `print(os.listdir(os.getcwd()))` – vishnun Aug 06 '21 at 13:15
  • It prints this: ['.idea', 'NewFile.py', 'venv'] – thomas theocharis Aug 06 '21 at 13:16
  • Okay, I will tell my inference. As far as I can understand the code that you are executing is NewFile.py and your working directory where you have NewFile.py doesn't have the credentials.json file. If you see, in your authenticate_gmail() function it reads the path as "credentials.json" which is not present here: ['.idea', 'NewFile.py', 'venv']. So I think it's a path error. Your credentials.json is not in the same directory as NewFile.py so maybe check in your virtual environment once. If its there use the proper path while executing the NewFile.py – vishnun Aug 06 '21 at 13:22
  • okay can you show me the path cause i still get the error and it might be in the wrong path – thomas theocharis Aug 06 '21 at 13:30
  • You have to figure out the directory where your credentials.json is present. Then only you use that path. BTW where is "token.pickle" file ? – vishnun Aug 06 '21 at 15:26
  • vishnun i cannot find the location. – thomas theocharis Aug 06 '21 at 20:06