Skip to content

Instantly share code, notes, and snippets.

@dansayo
Last active October 17, 2019 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dansayo/ee83dda02f6b869989f91135d8516c3b to your computer and use it in GitHub Desktop.
Save dansayo/ee83dda02f6b869989f91135d8516c3b to your computer and use it in GitHub Desktop.
Setting up a subscriber to changes in a Google folder
# python 3.7.4
import os
import json
import datetime # for the expiration property: a date string to epoch millisec
import uuid # for the id property
from apiclient import discovery
from google.oauth2 import service_account
try:
ep = (
lambda yr, mo, dd, hh, mm: int(
datetime.datetime(yr, mo, dd, hh, mm).timestamp()
)
* 1000
)
API = "drive"
API_VERSION = "v3"
scopes = [
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.file",
]
with open("client_servacc.json", "r") as read_file:
serv_acct_info = json.load(read_file)
# this needs to change to get credentials from a string object instead of a file
# i.e. json.loads of a string from AWS SSM
# https://google-auth.readthedocs.io/en/latest/reference/google.oauth2.service_account.html
credentials = service_account.Credentials.from_service_account_info(
serv_acct_info, scopes=scopes
)
drive_service = discovery.build(API, API_VERSION, credentials=credentials)
# more to put in SSM
url_webhook = os.environ.get('GDRIVE_WEBHOOK_URL')
gfolder_id = os.environ.get('GDRIVE_FOLDER_ID')
if url_webhook and gfolder_id:
pass
else:
raise KeyError
# request body; note expiration ep is based on local time
data = {
"id": str(uuid.uuid4()),
"expiration": ep(2019, 10, 17, 8, 53),
"address": url_webhook,
"type": "web_hook"
}
response = drive_service.files().watch(fileId=gfolder_id, body=data).execute()
print(response)
# sample successful request response
# https://developers.google.com/drive/api/v3/reference/files/watch?authuser=0#response_1
except OSError as e:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment