Google Drive Api и Rasa проблема - PullRequest
0 голосов
/ 06 марта 2020

Я столкнулся со странной проблемой, выполняя это действие, уже опубликованное здесь: https://forum.rasa.com/t/rasa-google-drive-api/25743.

Я решил эту проблему с помощью следующего кода:

class ActionQuestion(Action):
    #
    def name(self) -> Text:
        return "action_question"

    def run(self, dispatcher: CollectingDispatcher,

            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        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 logging

        logging.getLogger('googleapicliet.discovery_cache').setLevel(logging.ERROR)
        # If modifying these scopes, delete the file token.pickle.
        SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']

        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('drive', 'v3', credentials=creds)
            # Call the Drive v3 API

        page_token = None
        while True:
            response = service.files().list(q="name='Getting Started'",
                                            spaces='drive',
                                            fields='nextPageToken, files(id, name)',
                                            pageToken=page_token).execute()
            for file in response.get('files', []):
                # Process change
                dispatcher.utter_message('Found file: %s please visit the link https://drive.google.com/open?id=%s' % (file.get('name'), file.get('id')))
                dispatcher.utter_message(type(question))
            page_token = response.get('nextPageToken', None)
            if page_token is None:
                break
        return []

Моя проблема в том, что вместо прямой передачи имени файла в этих строках:

            response = service.files().list(q="name='Getting Started'",
                                            spaces='drive',
                                            fields='nextPageToken, files(id, name)',
                                            pageToken=page_token).execute()

я использую метод tracker.get_slot для передачи имени файла следующим образом:

        question = tracker.get_slot("document")
        response = service.files().list(q="name=question",
                                            spaces='drive',
                                            fields='nextPageToken, files(id, name)',
                                            pageToken=page_token).execute()

я получаю следующую ошибку http:

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/drive/v3/files?**q=name+%3D+question**&spaces=drive&fields=nextPageToken%2C+files%28id%2C+name%29&alt=json returned "Invalid Value">

При выполнении прямых значений я получаю следующий запрос http и возвращаю правильное значение:

googleapiclient.discovery  - URL being requested: GET https://www.googleapis.com/drive/v3/files?**q=name+%3D+%27getting+started%27**&spaces=drive&fields=nextPageToken%2C+files%28id%2C+name%29&alt=json

Как передать этот слот в URL запроса правильно? URL выделил текст запроса, чтобы отобразить запрошенный URL.

1 Ответ

0 голосов
/ 06 марта 2020

Решено


        response = service.files().list(q='(name contains \'{0}\')'.format(a),
                                          spaces='drive',
                                          fields='nextPageToken, files(id, name)',
                                          pageToken=page_token).execute()
...