-
Notifications
You must be signed in to change notification settings - Fork 1
/
get_next_events.py
89 lines (65 loc) · 2.82 KB
/
get_next_events.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from __future__ import print_function
import time
import json
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from datetime import datetime, date, timedelta
from settings import CALENDAR_LIST
from funcs import echoMsg, echoError
calendarService = None
def getNextEvents():
global calendarService
creds = None
try:
if os.path.exists('config/token.pickle'):
with open('config/token.pickle', 'rb') as token:
creds = pickle.load(token)
else:
raise Exception('config/token.pickle not found. Run "pyhton3 connect_google_calendar.py"')
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
raise Exception('config/token.pickle expired and cannot refresh. Run "pyhton3 connect_google_calendar.py"')
calendarService = build('calendar', 'v3', credentials=creds)
timeMin = (date.today()-timedelta(days=30)).isoformat() + 'T00:00:00.0000Z' # 'Z' indicates UTC time
timeMax = (date.today()+timedelta(days=60)).isoformat() + 'T00:00:00.0000Z' # 'Z' indicates UTC time
# Retrieve the calendars from CALENDAR_LIST
events = []
for calendarId in CALENDAR_LIST.keys():
events += getEvents(calendarId, timeMin, timeMax)
# Sort the events by start time
events = sorted(events, key=lambda k: k['start'])
# Save the events to a JSON
with open('data/events.json', 'w') as fout:
json.dump(events , fout)
return True
except:
e = sys.exc_info()[1]
echoError(str(e))
return False
def getEvents(calendarId, timeMin, timeMax):
global calendarService
ret = []
# Call the Calendar API
events_result = calendarService.events().list(calendarId=calendarId,
timeMin=timeMin,
timeMax=timeMax,
maxResults=100,
singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
if not events:
return ret
for event in events:
evt = {}
evt['owner'] = calendarId
evt['start'] = event['start'].get('dateTime', event['start'].get('date'))
evt['summary'] = event['summary'] if "summary" in event else "-- Privat"
ret.append(evt)
return ret
if __name__ == '__main__':
getNextEvents()