-
Notifications
You must be signed in to change notification settings - Fork 23
/
NotionGCal.py
338 lines (287 loc) · 13.9 KB
/
NotionGCal.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
from datetime import date
from notion_client import Client
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/calendar']
#######################################
CREDENTIALS_FILE = 'credentials.json'
NOTION_TOKEN = "secret_Bg53dmHuIFfzqbYyNZp9VrVFL4EenamUInis5UsQXH4"#The secret code from Notion Integration (it should look like this: NOTION_TOKEN = "secret_XXXXXXXXXXXXX")
database_id = "" #Get the string of numbers before the "?" on your Notion dashboard URL (it should look like this: database_id = "xxxxxxxxxxxxxxxxxxxxxxxxxx")
dateProperty = "Date:" #The name of the 'Date' property for your items in your Notion Database (it should look like this: dateProperty = 'Date')
nameProperty = "Name" #The name of the 'Title' property for your items in your Notion Database (it should look like this: nameProperty = 'Name')
########################################
def get_calendar_service():
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# 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(
CREDENTIALS_FILE, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('calendar', 'v3', credentials=creds)
return service
def list_calendars():
service = get_calendar_service()
# Call the Calendar API
calendars_result = service.calendarList().list().execute()
calendars = calendars_result.get('items', [])
for calendar in calendars:
summary = calendar['summary']
id = calendar['id']
return calendars
os.environ['NOTION_TOKEN'] = NOTION_TOKEN
notion = Client(auth = os.environ["NOTION_TOKEN"])
today = date.today()
print("Today's date:", today)
today = today.strftime('%Y-%m-%d')
print()
if True:
service = get_calendar_service()
calendars = list_calendars()
for calendar in calendars:
print(calendar['summary'],"\n")
while True:
event_items = []
for calendar in calendars:
events = service.events().list(calendarId = calendar['id']).execute()
for single_item in events['items']:
event_items.append(single_item)
GCal_today = []
for event in event_items:
try:
if event['start']['dateTime'][:10] == today :
print(event['summary'])
print()
GCal_today.append(event)
except:
try:
if event['start']['date'][:10] == today :
print(event['summary'])
print()
GCal_today.append(event)
except:
try:
if event['originalStartTime']['dateTime'][:10] == today :
print(event['summary'])
print()
GCal_today.append(event)
except:
if event['originalStartTime']['date'][:10] == today :
print(event['summary'])
print()
GCal_today.append(event)
page_token = events.get('nextPageToken')
if not page_token:
break
print()
#Takes GCal Event and adds it to Notion DB
#Takes all tasks for today from Notion and stores it in Notion_today
Notion_tasks_today = []
Notion_tasks_ID = []
Notion_today = notion.databases.query(
**{
"database_id": database_id,
"filter": {
"and": [
{
"property": dateProperty,
"date": {
"equals": today
}
}
]
}
}
)
id_id = {}
#Takes all Notion tasks and checks if they have anything in the GCal_ID property
for Action_index, Action_Item in enumerate(Notion_today['results']):
Action_Sub = Action_Item['properties']['GCal_ID']['rich_text']
Notion_tasks_ID.append(Action_Sub)
#Takes only the 'plain_text' values
for list_index, list_item in enumerate(Notion_tasks_ID):
if list_item != []:
Notion_tasks_ID[list_index] = list_item[0]['plain_text']
for ID_Guess in Notion_today['results']:
if ID_Guess['properties']['GCal_ID']['rich_text'] != []:
if ID_Guess['properties']['GCal_ID']['rich_text'][0]['plain_text'] == list_item[0]['plain_text']:
id_id[Notion_tasks_ID[list_index]] = ID_Guess['id']
else:
Notion_tasks_ID[list_index] = None
while None in Notion_tasks_ID:
Notion_tasks_ID.remove(None)
#Prints the different daily tasks
for Action_index, Action_Item in enumerate(Notion_today['results']):
Action_Sub = Action_Item['properties'][nameProperty]['title'][0]['text']['content']
Notion_tasks_today.append(Action_Sub)
#Attach GCal_ID to Notion_Page_ID
#Add GCal event to Notion
for GCal_Event in GCal_today:
#Check if the event name is already on Notion_today
if GCal_Event['id'] not in Notion_tasks_ID :
#Add the page
try:
new_page = notion.pages.create(
**{
"parent": {
"database_id": database_id,
},
"properties": {
'GCal_ID': {
'type':'rich_text',
'rich_text': [ {
'id':'_}uo',
'type':'text',
'text': {
'content': str(GCal_Event['id'])
}
} ]
},
nameProperty: {
"type": 'title',
"title": [
{
"type": 'text',
"text": {
"content": GCal_Event['summary'],
},
},
],
},
dateProperty: {
"type": 'date',
'date': {
'start': GCal_Event['start']['dateTime'][:19],
'end': GCal_Event['end']['dateTime'][:19],
}
}
},
},
)
except:
new_page = notion.pages.create(
**{
"parent": {
"database_id": database_id,
},
"properties": {
'GCal_ID': {
'type':'rich_text',
'rich_text': [ {
'id':'_}uo',
'type':'text',
'text': {
'content': str(GCal_Event['id'])
}
} ]
},
nameProperty: {
"type": 'title',
"title": [
{
"type": 'text',
"text": {
"content": GCal_Event['summary'],
},
},
],
},
dateProperty: {
"type": 'date',
'date': {
'start': GCal_Event['start']['date'],
'end': None,
}
}
},
},
)
else:
try:
updated_page = notion.pages.update(
**{
"page_id": id_id[GCal_Event['id']],
"properties": {
'GCal_ID': {
'type':'rich_text',
'rich_text': [ {
'id':'_}uo',
'type':'text',
'text': {
'content': str(GCal_Event['id'])
}
} ]
},
nameProperty: {
"type": 'title',
"title": [
{
"type": 'text',
"text": {
"content": GCal_Event['summary'],
},
},
],
},
dateProperty: {
"type": 'date',
'date': {
'start': GCal_Event['start']['date'],
'end': None,
}
}
}
}
)
except:
updated_page = notion.pages.update(
**{
"page_id": id_id[GCal_Event['id']],
"properties": {
'GCal_ID': {
'type':'rich_text',
'rich_text': [ {
'id':'_}uo',
'type':'text',
'text': {
'content': str(GCal_Event['id'])
}
} ]
},
nameProperty: {
"type": 'title',
"title": [
{
"type": 'text',
"text": {
"content": GCal_Event['summary'],
},
},
],
},
dateProperty: {
"type": 'date',
'date': {
'start': GCal_Event['start']['dateTime'][:19],
'end': GCal_Event['end']['dateTime'][:19],
}
}
}
}
)
print('Sync done.')