如何解决gcloud gmail-api watch 400(错误请求)?

时间:2016-01-19 15:42:00

标签: gmail-api google-cloud-pubsub google-managed-vm

上下文

按照说明(here)设置GMail推送通知;和(here)用于在Pub / Sub主题上设置GMail Watch。

(已创建发布/订阅主题和订阅;已在Google Apps中授予对该应用的API客户端访问权限)

问题:

执行以下代码会导致以下(JSON)错误:

{
    "error": {
        "errors": [{
            "domain": "global",
            "reason": "failedPrecondition",
            "message": "Bad Request"
        }],
        "code": 400,
        "message": "Bad Request"
    }
}

尝试的决议:

  1. 在创建凭据服务时尝试将GMail帐户作为sub参数。
  2. 重新制作的Pub / Sub主题&订阅。
  3. 将域添加到Google Developers Console Project。
  4. 代码:

    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')
    

0 个答案:

没有答案