FileNotFoundError:[Errno 2]没有这样的文件或目录:“credentials.json”

2024-05-29 08:03:16 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我在python中使用模块pyttsx3制作了一个助手,出现了这个错误。代码如下:

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.")

我读到这与谷歌API有关。我试图安装一些东西,但它不工作。 我安装了client_secrets,并将其放在当前目录中,它不起作用。我必须安装其他东西吗?在GoogleAPI控制台中,我创建了一个新的crendetial,我下载了它,但仍然有相同的错误。谢谢你的时间,请回答,如果你能回答,请用图片告诉我该做什么和下载什么-如果错误可以修复-。谢谢


Tags: thetoimporttokenyouiftimeaction

热门问题