Context:
Following instructions (here) for setting up GMail push notifications; and (here) for setting up a GMail Watch on a Pub/Sub topic.
(Pub/Sub topic and subscription has already been created; API client access to the app has been granted in Google Apps)
Problem:
Executing the following code results in the following (JSON) error:
{
"error": {
"errors": [{
"domain": "global",
"reason": "failedPrecondition",
"message": "Bad Request"
}],
"code": 400,
"message": "Bad Request"
}
}
Resolutions Attempted:
- Tried including the GMail account as the
sub
parameter, while creating the credentials service. - Recreated Pub/Sub topic & subscription.
- Added domain to Google Developers Console Project.
Code:
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')