Created
May 3, 2021 06:02
-
-
Save danielk333/95e689984c61ebe20c80e14be2655256 to your computer and use it in GitHub Desktop.
Simple script to get google calendar events using the Google API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import datetime | |
import pathlib | |
ROOT = pathlib.Path(__file__).resolve().parent | |
#List of calendar names to get events from | |
#if empty, just take all calendars | |
GOOGLE_CALENDARS = [ | |
] | |
from googleapiclient.discovery import build | |
from google_auth_oauthlib.flow import InstalledAppFlow | |
from google.auth.transport.requests import Request | |
from google.oauth2.credentials import Credentials | |
# If modifying these scopes, delete the file token.json. | |
GOOGLE_SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] | |
def get_calendar_data(date): | |
"""Basic usage of the Google Calendar API, get events of the date from either all calendars or the ones listed in `GOOGLE_CALENDARS`. | |
""" | |
creds = None | |
# The file token.json stores the user's access and refresh tokens, and is | |
# created automatically when the authorization flow completes for the first | |
# time. | |
token_file = ROOT / 'token.json' | |
credential_file = ROOT / 'credentials.json' | |
if token_file.is_file(): | |
creds = Credentials.from_authorized_user_file(str(token_file.resolve()), GOOGLE_SCOPES) | |
# If there are no (valid) credentials available, let the user log in. | |
if not creds or not creds.valid: | |
if creds and creds.expired and creds.refresh_token: | |
creds.refresh(Request()) | |
else: | |
flow = InstalledAppFlow.from_client_secrets_file( | |
str(credential_file.resolve()), GOOGLE_SCOPES) | |
creds = flow.run_local_server(port=0) | |
# Save the credentials for the next run | |
with open(str(token_file.resolve()), 'w') as token: | |
token.write(creds.to_json()) | |
service = build('calendar', 'v3', credentials=creds) | |
# Call the Calendar API | |
# 'Z' indicates UTC time | |
start_dt = datetime.datetime(date.year, date.month, date.day, 0, 0, 0) | |
start = start_dt.isoformat() + 'Z' | |
stop = (start_dt + datetime.timedelta(days=1)).isoformat() + 'Z' | |
calendars = [] | |
# Get all the calendar id's and names the user has access too | |
page_token = None | |
while True: | |
calendar_list = service.calendarList().list(pageToken=page_token).execute() | |
for calendar_list_entry in calendar_list['items']: | |
calendars.append((calendar_list_entry['id'], calendar_list_entry['summary'])) | |
page_token = calendar_list.get('nextPageToken') | |
if not page_token: | |
break | |
#Use the `events` service on each calendar to get the events. | |
events = [] | |
for calendar, summary in calendars: | |
if summary not in GOOGLE_CALENDARS and len(GOOGLE_CALENDARS) > 0: | |
continue | |
events_result = service.events().list( | |
calendarId=calendar, | |
timeMin=start, | |
timeMax=stop, | |
maxResults=None, | |
singleEvents=True, | |
orderBy='startTime', | |
).execute() | |
cal_events = events_result.get('items', []) | |
for x in cal_events: | |
x['calendar_summary'] = summary | |
events += cal_events | |
#do some sorting | |
for ev in events: | |
start = ev['start'].get('dateTime', ev['start'].get('date')) | |
start_dt = datetime.datetime.fromisoformat(start) | |
start_dt = start_dt.replace(tzinfo=datetime.datetime.now().astimezone().tzinfo) | |
ev['_sort_date'] = start_dt | |
events.sort(key=lambda ev: ev['_sort_date']) | |
return events | |
if __name__=='__main__': | |
events = get_calendar_data(datetime.datetime.today()) | |
for event in events: | |
print(event["summary"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment