语境:
按照说明(此处)设置 GMail 推送通知;和(此处)用于在 Pub/Sub 主题上设置 GMail Watch。
(已创建 Pub/Sub 主题和订阅;已在 Google Apps 中授予 API 客户端访问应用程序的权限)
问题:
执行以下代码会导致以下 (JSON) 错误:
{
"error": {
"errors": [{
"domain": "global",
"reason": "failedPrecondition",
"message": "Bad Request"
}],
"code": 400,
"message": "Bad Request"
}
}
尝试的解决方案:
sub
在创建凭证服务时尝试将 GMail 帐户作为参数。- 重新创建了 Pub/Sub 主题和订阅。
- 将域添加到 Google Developers Console 项目。
代码:
import logging
import httplib2
import json
from apiclient import errors
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
# Read in service credentials form file
with open('secrets.json') as data_file:
data = json.load(data_file)
client_email = data["client_email"]
private_key = data["private_key"]
credentials = SignedJwtAssertionCredentials(client_email,
private_key,
'https://mail.google.com/')
def build_gmail_service(credentials):
# Build a authorized, Gmail service object.
http = httplib2.Http()
http = credentials.authorize(http)
return build('gmail', 'v1', http=http)
def watch_gmail(service, user_id='me'):
request = {
'topicName': 'projects/app/topics/gmail',
'labelIds': ['INBOX'],
'labelFilterAction': "include"
}
try:
# Make the request.
response = service.users().watch(userId=user_id,
body=request).execute()
# Print the results of the request
if 'error' in response:
# The API executed, but the script returned an error.
error = response['error']['details'][0]
print "Script error! Message: {0}".format(error['errorMessage'])
else:
# response successful
return response
except errors.HttpError as e:
# The API encountered a problem before the script started executing.
logging.error('An error occurred: %s', e.content)
service = build_gmail_service(credentials)
watch_gmail(service, 'user@google_apps_domain.com')