前提・実現したいこと
Google Cloud Functions でメールの自動返信BOTを作ろうと思い以下のコードを実行しましたが、Oauth認証でbad request error が返って来ます。
クライアントIDによる認証(run_flowでcodeを手入力しました)は出来たのですが サービスアカウントキーを使用する認証ができませんでした。
*当質問はG suiteサービス未利用でもGmail API にサービスキーでアクセスができるだろうという、私の誤解が前提で書かれています。ご回答いただきまして、前提自体が誤りであることがわかりました
環境
- WindowsのAtomで実行(Scriptパッケージで実行してます…)
- 下記コードのエラー結果は上記ローカル環境によるものです
- クラウドサービスの動作テストは全てGoogle Cloud Platform の同一プロジェクト内で行っています
- Gsuiteサービスは利用しておりません。 個人利用アカウントで実行しています
ファイル構成
-main.py
-requirements.txt
-project.json
試したこと
- クライアントID認証コードでcloud Functions にデプロイして途中まで動作したことを確認しました
(jasonトークンを上書き出来ませんと言われました)
-
サービスアカウントキーをcloud storage に保存するプログラムをcloud Functionsデプロイしてサービスアカウントキーが保存できることを確認しました
-
キー発行アカウントにAPI管理者とAPI閲覧者の権限を付けました
(同一アカウントにストレージ管理者の権限も与えcloud storage の認証も受けています)
コード
main.py
python
1os.environ["GOOGLE_APPLICATION_CREDENTIALS"]='project.json' 2 3from google.oauth2 import service_account 4import googleapiclient.discovery 5 6 7def run_m(): 8 SCOPES = ['https://www.googleapis.com/auth/gmail.readonly', 9 'https://www.googleapis.com/auth/gmail.compose', 10 'https://www.googleapis.com/auth/gmail.labels'] 11 json_file = 'project.json' 12 credentials = service_account.Credentials.from_service_account_file(json_file, scopes=SCOPES) 13 delegated_credentials = credentials.with_subject('"****t@******.com"') 14 service = googleapiclient.discovery.build('gmail', 'v1', credentials=credentials) 15 request = {'labelIds': ['Label_4501394728387839841'], 16 #'labelFilterAction' : "include", 17 'topicName': 'mytopic'} 18 res = service.users().watch(userId='me', body=request).execute()
project.json
project.json
1{ 2 "type": "service_account", 3 "project_id": "project", 4 "private_key_id": "******************", 5 "private_key": "-----BEGIN PRIVATE KEY-----********\n-----END PRIVATE KEY-----\n", 6 "client_email": "****t@******.com", 7 "client_id": "***********", 8 "auth_uri": "https://accounts.google.com/o/oauth2/auth", 9 "token_uri": "https://oauth2.googleapis.com/token", 10 "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", 11 "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/account%40project.iam.gserviceaccount.com" 12} 13
エラー
Traceback (most recent call last):
File "C:\Users\user\deploy\main.py", line 38, in <module>
run_m()
File "C:\Users\user\deploy\main.py", line 31, in run_m
res = service.users().watch(userId='me', body=request).execute()
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\googleapiclient_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\googleapiclient\http.py", line 851, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/watch?alt=json returned "Bad Request">
[Finished in 5.113s]
回答1件
あなたの回答
tips
プレビュー