-
Notifications
You must be signed in to change notification settings - Fork 51
/
Notion-GCal-2WaySync-Public.py
1573 lines (1358 loc) · 63.2 KB
/
Notion-GCal-2WaySync-Public.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
from notion_client import Client
from datetime import datetime, timedelta, date
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
import pickle
###########################################################################
##### The Set-Up Section. Please follow the comments to understand the code.
###########################################################################
NOTION_TOKEN = "" #the secret_something from Notion Integration
database_id = "" #get the mess of numbers before the "?" on your dashboard URL (no need to split into dashes)
urlRoot = 'https://www.notion.so/akarri/2583098dfd32472ab6ca1ff2a8b2866d?v=3a1adf60f15748f08ed925a2eca88421&p=' #open up a task and then copy the URL root up to the "p="
runScript = "python3 GCalToken.py" #This is the command you will be feeding into the command prompt to run the GCalToken program
#GCal Set Up Part
credentialsLocation = "token.pkl" #This is where you keep the pickle file that has the Google Calendar Credentials
DEFAULT_EVENT_LENGTH = 60 #This is how many minutes the default event length is. Feel free to change it as you please
timezone = 'America/New_York' #Choose your respective time zone: http://www.timezoneconverter.com/cgi-bin/zonehelp.tzc
def notion_time():
return datetime.now().strftime("%Y-%m-%dT%H:%M:%S-04:00") #Change the last 5 characters to be representative of your timezone
#^^ has to be adjusted for when daylight savings is different if your area observes it
def DateTimeIntoNotionFormat(dateTimeValue):
return dateTimeValue.strftime("%Y-%m-%dT%H:%M:%S-04:00") #Change the last 5 characters to be representative of your timezone
#^^ has to be adjusted for when daylight savings is different if your area observes it
def googleQuery():
return datetime.now().strftime("%Y-%m-%dT%H:%M:%S")+"-04:00" #Change the last 5 characters to be representative of your timezone
#^^ has to be adjusted for when daylight savings is different if your area observes it
DEFAULT_EVENT_START = 8 #8 would be 8 am. 16 would be 4 pm. Only whole numbers
AllDayEventOption = 0 #0 if you want dates on your Notion dashboard to be treated as an all-day event
#^^ 1 if you want dates on your Notion dashboard to be created at whatever hour you defined in the DEFAULT_EVENT_START variable
### MULTIPLE CALENDAR PART:
# - VERY IMPORTANT: For each 'key' of the dictionary, make sure that you make that EXACT thing in the Notion database first before running the code. You WILL have an error and your dashboard/calendar will be messed up
DEFAULT_CALENDAR_ID = '[email protected]' #The GCal calendar id. The format is something like "[email protected]"
DEFAULT_CALENDAR_NAME = 'Test'
#leave the first entry as is
#the structure should be as follows: WHAT_THE_OPTION_IN_NOTION_IS_CALLED : GCAL_CALENDAR_ID
calendarDictionary = {
DEFAULT_CALENDAR_NAME : DEFAULT_CALENDAR_ID,
'Test' : '[email protected]', #just typed some random ids but put the one for your calendars here
'New Test' : '[email protected]'
}
## doesn't delete the Notion task (yet), I'm waiting for the Python API to be updated to allow deleting tasks
DELETE_OPTION = 0
#set at 0 if you want the delete column being checked off to mean that the gCal event and the Notion Event will be checked off.
#set at 1 if you want nothing deleted
##### DATABASE SPECIFIC EDITS
# There needs to be a few properties on the Notion Database for this to work. Replace the values of each variable with the string of what the variable is called on your Notion dashboard
# The Last Edited Time column is a property of the notion pages themselves, you just have to make it a column
# The NeedGCalUpdate column is a formula column that works as such "if(prop("Last Edited Time") > prop("Last Updated Time"), true, false)"
#Please refer to the Template if you are confused: https://www.notion.so/akarri/2583098dfd32472ab6ca1ff2a8b2866d?v=3a1adf60f15748f08ed925a2eca88421
Task_Notion_Name = 'Task Name'
Date_Notion_Name = 'Date'
Initiative_Notion_Name = 'Initiative'
ExtraInfo_Notion_Name = 'Extra Info'
On_GCal_Notion_Name = 'On GCal?'
NeedGCalUpdate_Notion_Name = 'NeedGCalUpdate'
GCalEventId_Notion_Name = 'GCal Event Id'
LastUpdatedTime_Notion_Name = 'Last Updated Time'
Calendar_Notion_Name = 'Calendar'
Current_Calendar_Id_Notion_Name = 'Current Calendar Id'
Delete_Notion_Name = 'Done?'
#######################################################################################
### No additional user editing beyond this point is needed ###
#######################################################################################
#SET UP THE GOOGLE CALENDAR API INTERFACE
credentials = pickle.load(open(credentialsLocation, "rb"))
service = build("calendar", "v3", credentials=credentials)
#There could be a hiccup if the Google Calendar API token expires.
#If the token expires, the other python script GCalToken.py creates a new token for the program to use
#This is placed here because it can take a few seconds to start working and I want the most heavy tasks to occur first
try:
calendar = service.calendars().get(calendarId=DEFAULT_CALENDAR_ID).execute()
except:
#refresh the token
import os
os.system(runScript)
#SET UP THE GOOGLE CALENDAR API INTERFACE
credentials = pickle.load(open(credentialsLocation, "rb"))
service = build("calendar", "v3", credentials=credentials)
# result = service.calendarList().list().execute()
# print(result['items'][:])
calendar = service.calendars().get(calendarId=calendarID).execute()
##This is where we set up the connection with the Notion API
os.environ['NOTION_TOKEN'] = NOTION_TOKEN
notion = Client(auth=os.environ["NOTION_TOKEN"])
###########################################################################
##### The Methods that we will use in this scipt are below
###########################################################################
######################################################################
#METHOD TO MAKE A CALENDAR EVENT DESCRIPTION
#This method can be edited as wanted. Whatever is returned from this method will be in the GCal event description
#Whatever you change up, be sure to return a string
def makeEventDescription(initiative, info):
if initiative == '' and info == '':
return ''
elif info == "":
return initiative
elif initiative == '':
return info
else:
return f'Initiative: {initiative} \n{info}'
######################################################################
#METHOD TO MAKE A TASK'S URL
#To make a url for the notion task, we have to take the id of the task and take away the hyphens from the string
def makeTaskURL(ending, urlRoot):
# urlId = ending[0:8] + ending[9:13] + ending[14:18] + ending[19:23] + ending[24:] #<--- super inefficient way to do things lol
urlId = ending.replace('-', '')
return urlRoot + urlId
######################################################################
#METHOD TO MAKE A CALENDAR EVENT
def makeCalEvent(eventName, eventDescription, eventStartTime, sourceURL, eventEndTime, calId):
if eventStartTime.hour == 0 and eventStartTime.minute == 0 and eventEndTime == eventStartTime: #only startTime is given from the Notion Dashboard
if AllDayEventOption == 1:
eventStartTime = datetime.combine(eventStartTime, datetime.min.time()) + timedelta(hours=DEFAULT_EVENT_START) ##make the events pop up at 8 am instead of 12 am
eventEndTime = eventStartTime + timedelta(minutes= DEFAULT_EVENT_LENGTH)
event = {
'summary': eventName,
'description': eventDescription,
'start': {
'dateTime': eventStartTime.strftime("%Y-%m-%dT%H:%M:%S"),
'timeZone': timezone,
},
'end': {
'dateTime': eventEndTime.strftime("%Y-%m-%dT%H:%M:%S"),
'timeZone': timezone,
},
'source': {
'title': 'Notion Link',
'url': sourceURL,
}
}
else:
eventEndTime = eventEndTime + timedelta(days=1) #gotta make it to 12AM the day after
event = {
'summary': eventName,
'description': eventDescription,
'start': {
'date': eventStartTime.strftime("%Y-%m-%d"),
'timeZone': timezone,
},
'end': {
'date': eventEndTime.strftime("%Y-%m-%d"),
'timeZone': timezone,
},
'source': {
'title': 'Notion Link',
'url': sourceURL,
}
}
elif eventStartTime.hour == 0 and eventStartTime.minute == 0 and eventEndTime.hour == 0 and eventEndTime.minute == 0 and eventStartTime != eventEndTime:
eventEndTime = eventEndTime + timedelta(days=1) #gotta make it to 12AM the day after
event = {
'summary': eventName,
'description': eventDescription,
'start': {
'date': eventStartTime.strftime("%Y-%m-%d"),
'timeZone': timezone,
},
'end': {
'date': eventEndTime.strftime("%Y-%m-%d"),
'timeZone': timezone,
},
'source': {
'title': 'Notion Link',
'url': sourceURL,
}
}
else: #just 2 datetimes passed in from the method call that are not at 12 AM
if eventStartTime.hour == 0 and eventStartTime.minute == 0 and eventEndTime != eventStartTime: #Start on Notion is 12 am and end is also given on Notion
eventStartTime = eventStartTime #start will be 12 am
eventEndTime = eventEndTime #end will be whenever specified
elif eventStartTime.hour == 0 and eventStartTime.minute == 0: #if the datetime fed into this is only a date or is at 12 AM, then the event will fall under here
eventStartTime = datetime.combine(eventStartTime, datetime.min.time()) + timedelta(hours=DEFAULT_EVENT_START) ##make the events pop up at 8 am instead of 12 am
eventEndTime = eventStartTime + timedelta(minutes= DEFAULT_EVENT_LENGTH)
elif eventEndTime == eventStartTime: #this would meant that only 1 datetime was actually on the notion dashboard
eventStartTime = eventStartTime
eventEndTime = eventStartTime + timedelta(minutes= DEFAULT_EVENT_LENGTH)
else: #if you give a specific start time to the event
eventStartTime = eventStartTime
eventEndTime = eventEndTime
event = {
'summary': eventName,
'description': eventDescription,
'start': {
'dateTime': eventStartTime.strftime("%Y-%m-%dT%H:%M:%S"),
'timeZone': timezone,
},
'end': {
'dateTime': eventEndTime.strftime("%Y-%m-%dT%H:%M:%S"),
'timeZone': timezone,
},
'source': {
'title': 'Notion Link',
'url': sourceURL,
}
}
print('Adding this event to calendar: ', eventName)
print(event)
x = service.events().insert(calendarId=calId, body=event).execute()
return x['id']
######################################################################
#METHOD TO UPDATE A CALENDAR EVENT
def upDateCalEvent(eventName, eventDescription, eventStartTime, sourceURL, eventId, eventEndTime, currentCalId, CalId):
if eventStartTime.hour == 0 and eventStartTime.minute == 0 and eventEndTime == eventStartTime: #you're given a single date
if AllDayEventOption == 1:
eventStartTime = datetime.combine(eventStartTime, datetime.min.time()) + timedelta(hours=DEFAULT_EVENT_START) ##make the events pop up at 8 am instead of 12 am
eventEndTime = eventStartTime + timedelta(minutes= DEFAULT_EVENT_LENGTH)
event = {
'summary': eventName,
'description': eventDescription,
'start': {
'dateTime': eventStartTime.strftime("%Y-%m-%dT%H:%M:%S"),
'timeZone': timezone,
},
'end': {
'dateTime': eventEndTime.strftime("%Y-%m-%dT%H:%M:%S"),
'timeZone': timezone,
},
'source': {
'title': 'Notion Link',
'url': sourceURL,
}
}
else:
eventEndTime = eventEndTime + timedelta(days=1) #gotta make it to 12AM the day after
event = {
'summary': eventName,
'description': eventDescription,
'start': {
'date': eventStartTime.strftime("%Y-%m-%d"),
'timeZone': timezone,
},
'end': {
'date': eventEndTime.strftime("%Y-%m-%d"),
'timeZone': timezone,
},
'source': {
'title': 'Notion Link',
'url': sourceURL,
}
}
elif eventStartTime.hour == 0 and eventStartTime.minute == 0 and eventEndTime.hour == 0 and eventEndTime.minute == 0 and eventStartTime != eventEndTime: #it's a multiple day event
eventEndTime = eventEndTime + timedelta(days=1) #gotta make it to 12AM the day after
event = {
'summary': eventName,
'description': eventDescription,
'start': {
'date': eventStartTime.strftime("%Y-%m-%d"),
'timeZone': timezone,
},
'end': {
'date': eventEndTime.strftime("%Y-%m-%d"),
'timeZone': timezone,
},
'source': {
'title': 'Notion Link',
'url': sourceURL,
}
}
else: #just 2 datetimes passed in
if eventStartTime.hour == 0 and eventStartTime.minute == 0 and eventEndTime != eventStartTime: #Start on Notion is 12 am and end is also given on Notion
eventStartTime = eventStartTime #start will be 12 am
eventEndTime = eventEndTime #end will be whenever specified
elif eventStartTime.hour == 0 and eventStartTime.minute == 0: #if the datetime fed into this is only a date or is at 12 AM, then the event will fall under here
eventStartTime = datetime.combine(eventStartTime, datetime.min.time()) + timedelta(hours=DEFAULT_EVENT_START) ##make the events pop up at 8 am instead of 12 am
eventEndTime = eventStartTime + timedelta(minutes= DEFAULT_EVENT_LENGTH)
elif eventEndTime == eventStartTime: #this would meant that only 1 datetime was actually on the notion dashboard
eventStartTime = eventStartTime
eventEndTime = eventStartTime + timedelta(minutes= DEFAULT_EVENT_LENGTH)
else: #if you give a specific start time to the event
eventStartTime = eventStartTime
eventEndTime = eventEndTime
event = {
'summary': eventName,
'description': eventDescription,
'start': {
'dateTime': eventStartTime.strftime("%Y-%m-%dT%H:%M:%S"),
'timeZone': timezone,
},
'end': {
'dateTime': eventEndTime.strftime("%Y-%m-%dT%H:%M:%S"),
'timeZone': timezone,
},
'source': {
'title': 'Notion Link',
'url': sourceURL,
}
}
print('Updating this event to calendar: ', eventName)
if currentCalId == CalId:
x = service.events().update(calendarId=CalId, eventId = eventId, body=event).execute()
else: #When we have to move the event to a new calendar. We must move the event over to the new calendar and then update the information on the event
print('Event ' + eventId)
print('CurrentCal ' + currentCalId)
print('NewCal ' + CalId)
x= service.events().move(calendarId= currentCalId , eventId= eventId, destination=CalId).execute()
print('New event id: ' + x['id'])
x = service.events().update(calendarId=CalId, eventId = eventId, body=event).execute()
return x['id']
###########################################################################
##### Part 1: Take Notion Events not on GCal and move them over to GCal
###########################################################################
## Note that we are only querying for events that are today or in the next week so the code can be efficient.
## If you just want all Notion events to be on GCal, then you'll have to edit the query so it is only checking the 'On GCal?' property
todayDate = datetime.today().strftime("%Y-%m-%d")
my_page = notion.databases.query( #this query will return a dictionary that we will parse for information that we want
**{
"database_id": database_id,
"filter": {
"and": [
{
"property": On_GCal_Notion_Name,
"checkbox": {
"equals": False
}
},
{
"or": [
{
"property": Date_Notion_Name,
"date": {
"equals": todayDate
}
},
{
"property": Date_Notion_Name,
"date": {
"next_week": {}
}
}
]
},
{
"property": Delete_Notion_Name,
"checkbox": {
"equals": False
}
}
]
},
}
)
resultList = my_page['results']
# print(len(resultList))
try:
print(resultList[0])
except:
print('')
TaskNames = []
start_Dates = []
end_Times = []
Initiatives = []
ExtraInfo = []
URL_list = []
calEventIdList = []
CalendarList = []
if len(resultList) > 0:
for i, el in enumerate(resultList):
print('\n')
print(el)
print('\n')
TaskNames.append(el['properties'][Task_Notion_Name]['title'][0]['text']['content'])
start_Dates.append(el['properties'][Date_Notion_Name]['date']['start'])
if el['properties'][Date_Notion_Name]['date']['end'] != None:
end_Times.append(el['properties'][Date_Notion_Name]['date']['end'])
else:
end_Times.append(el['properties'][Date_Notion_Name]['date']['start'])
try:
Initiatives.append(el['properties'][Initiative_Notion_Name]['select']['name'])
except:
Initiatives.append("")
try:
ExtraInfo.append(el['properties'][ExtraInfo_Notion_Name]['rich_text'][0]['text']['content'])
except:
ExtraInfo.append("")
URL_list.append(makeTaskURL(el['id'], urlRoot))
try:
CalendarList.append(calendarDictionary[el['properties'][Calendar_Notion_Name]['select']['name']])
except: #keyerror occurs when there's nothing put into the calendar in the first place
CalendarList.append(calendarDictionary[DEFAULT_CALENDAR_NAME])
pageId = el['id']
my_page = notion.pages.update( ##### This checks off that the event has been put on Google Calendar
**{
"page_id": pageId,
"properties": {
On_GCal_Notion_Name: {
"checkbox": True
},
LastUpdatedTime_Notion_Name: {
"date":{
'start': notion_time(),
'end': None,
}
},
},
},
)
print(CalendarList)
# 2 Cases: Start and End are both either date or date+time #Have restriction that the calendar events don't cross days
try:
#start and end are both dates
calEventId = makeCalEvent(TaskNames[i], makeEventDescription(Initiatives[i], ExtraInfo[i]), datetime.strptime(start_Dates[i], '%Y-%m-%d'), URL_list[i], datetime.strptime(end_Times[i], '%Y-%m-%d'), CalendarList[i] )
except:
try:
#start and end are both date+time
calEventId = makeCalEvent(TaskNames[i], makeEventDescription(Initiatives[i], ExtraInfo[i]), datetime.strptime(start_Dates[i][:-6], "%Y-%m-%dT%H:%M:%S.000"), URL_list[i], datetime.strptime(end_Times[i][:-6], "%Y-%m-%dT%H:%M:%S.000"), CalendarList[i])
except:
calEventId = makeCalEvent(TaskNames[i], makeEventDescription(Initiatives[i], ExtraInfo[i]), datetime.strptime(start_Dates[i][:-6], "%Y-%m-%dT%H:%M:%S.%f"), URL_list[i], datetime.strptime(end_Times[i][:-6], "%Y-%m-%dT%H:%M:%S.%f"), CalendarList[i])
calEventIdList.append(calEventId)
if CalendarList[i] == calendarDictionary[DEFAULT_CALENDAR_NAME]: #this means that there is no calendar assigned on Notion
my_page = notion.pages.update( ##### This puts the the GCal Id into the Notion Dashboard
**{
"page_id": pageId,
"properties": {
GCalEventId_Notion_Name: {
"rich_text": [{
'text': {
'content': calEventIdList[i]
}
}]
},
Current_Calendar_Id_Notion_Name: {
"rich_text": [{
'text': {
'content': CalendarList[i]
}
}]
},
Calendar_Notion_Name: {
'select': {
"name": DEFAULT_CALENDAR_NAME
},
},
},
},
)
else: #just a regular update
my_page = notion.pages.update(
**{
"page_id": pageId,
"properties": {
GCalEventId_Notion_Name: {
"rich_text": [{
'text': {
'content': calEventIdList[i]
}
}]
},
Current_Calendar_Id_Notion_Name: {
"rich_text": [{
'text': {
'content': CalendarList[i]
}
}]
}
},
},
)
else:
print("Nothing new added to GCal")
###########################################################################
##### Part 2: Updating GCal Events that Need To Be Updated (Changed on Notion but need to be changed on GCal)
###########################################################################
#Just gotta put a fail-safe in here in case people deleted the Calendar Variable
#this queries items in the next week where the Calendar select thing is empty
my_page = notion.databases.query(
**{
"database_id": database_id,
"filter": {
"and": [
{
"property": Calendar_Notion_Name,
"select": {
"is_empty": True
}
},
{
"or": [
{
"property": Date_Notion_Name,
"date": {
"equals": todayDate
}
},
{
"property": Date_Notion_Name,
"date": {
"next_week": {}
}
}
]
},
{
"property": Delete_Notion_Name,
"checkbox": {
"equals": False
}
}
]
},
}
)
resultList = my_page['results']
if len(resultList) > 0:
for i, el in enumerate(resultList):
pageId = el['id']
my_page = notion.pages.update( ##### This checks off that the event has been put on Google Calendar
**{
"page_id": pageId,
"properties": {
Calendar_Notion_Name: {
'select': {
"name": DEFAULT_CALENDAR_NAME
},
},
LastUpdatedTime_Notion_Name: {
"date":{
'start': notion_time(),
'end': None,
}
},
},
},
)
## Filter events that have been updated since the GCal event has been made
#this query will return a dictionary that we will parse for information that we want
#look for events that are today or in the next week
my_page = notion.databases.query(
**{
"database_id": database_id,
"filter": {
"and": [
{
"property": NeedGCalUpdate_Notion_Name,
"checkbox": {
"equals": True
}
},
{
"property": On_GCal_Notion_Name,
"checkbox": {
"equals": True
}
},
{
"or": [
{
"property": Date_Notion_Name,
"date": {
"equals": todayDate
}
},
{
"property": Date_Notion_Name,
"date": {
"next_week": {}
}
}
]
},
{
"property": Delete_Notion_Name,
"checkbox": {
"equals": False
}
}
]
},
}
)
resultList = my_page['results']
updatingNotionPageIds = []
updatingCalEventIds = []
for result in resultList:
print(result)
print('\n')
pageId = result['id']
updatingNotionPageIds.append(pageId)
print('\n')
print(result)
print('\n')
try:
calId = result['properties'][GCalEventId_Notion_Name]['rich_text'][0]['text']['content']
except:
calId = DEFAULT_CALENDAR_ID
print(calId)
updatingCalEventIds.append(calId)
TaskNames = []
start_Dates = []
end_Times = []
Initiatives = []
ExtraInfo = []
URL_list = []
CalendarList = []
CurrentCalList = []
if len(resultList) > 0:
for i, el in enumerate(resultList):
print('\n')
print(el)
print('\n')
TaskNames.append(el['properties'][Task_Notion_Name]['title'][0]['text']['content'])
start_Dates.append(el['properties'][Date_Notion_Name]['date']['start'])
if el['properties'][Date_Notion_Name]['date']['end'] != None:
end_Times.append(el['properties'][Date_Notion_Name]['date']['end'])
else:
end_Times.append(el['properties'][Date_Notion_Name]['date']['start'])
try:
Initiatives.append(el['properties'][Initiative_Notion_Name]['select']['name'])
except:
Initiatives.append("")
try:
ExtraInfo.append(el['properties'][ExtraInfo_Notion_Name]['rich_text'][0]['text']['content'])
except:
ExtraInfo.append("")
URL_list.append(makeTaskURL(el['id'], urlRoot))
print(el)
# CalendarList.append(calendarDictionary[el['properties'][Calendar_Notion_Name]['select']['name']])
try:
CalendarList.append(calendarDictionary[el['properties'][Calendar_Notion_Name]['select']['name']])
except: #keyerror occurs when there's nothing put into the calendar in the first place
CalendarList.append(calendarDictionary[DEFAULT_CALENDAR_NAME])
CurrentCalList.append(el['properties'][Current_Calendar_Id_Notion_Name]['rich_text'][0]['text']['content'])
pageId = el['id']
##depending on the format of the dates, we'll update the gCal event as necessary
try:
calEventId = upDateCalEvent(TaskNames[i], makeEventDescription(Initiatives[i], ExtraInfo[i]), datetime.strptime(start_Dates[i], '%Y-%m-%d'), URL_list[i], updatingCalEventIds[i], datetime.strptime(end_Times[i], '%Y-%m-%d'), CurrentCalList[i], CalendarList[i])
except:
try:
calEventId = upDateCalEvent(TaskNames[i], makeEventDescription(Initiatives[i], ExtraInfo[i]), datetime.strptime(start_Dates[i][:-6], "%Y-%m-%dT%H:%M:%S.000"), URL_list[i], updatingCalEventIds[i], datetime.strptime(end_Times[i][:-6], "%Y-%m-%dT%H:%M:%S.000"), CurrentCalList[i], CalendarList[i])
except:
calEventId = upDateCalEvent(TaskNames[i], makeEventDescription(Initiatives[i], ExtraInfo[i]), datetime.strptime(start_Dates[i][:-6], "%Y-%m-%dT%H:%M:%S.%f"), URL_list[i], updatingCalEventIds[i], datetime.strptime(end_Times[i][:-6], "%Y-%m-%dT%H:%M:%S.%f"), CurrentCalList[i], CalendarList[i])
my_page = notion.pages.update( ##### This updates the last time that the page in Notion was updated by the code
**{
"page_id": pageId,
"properties": {
LastUpdatedTime_Notion_Name: {
"date":{
'start': notion_time(), #has to be adjusted for when daylight savings is different
'end': None,
}
},
Current_Calendar_Id_Notion_Name: {
"rich_text": [{
'text': {
'content': CalendarList[i]
}
}]
},
},
},
)
else:
print("Nothing new updated to GCal")
todayDate = datetime.today().strftime("%Y-%m-%d")
###########################################################################
##### Part 3: Sync GCal event updates for events already in Notion back to Notion!
###########################################################################
##Query notion tasks already in Gcal, don't have to be updated, and are today or in the next week
my_page = notion.databases.query(
**{
"database_id": database_id,
"filter": {
"and": [
{
"property": NeedGCalUpdate_Notion_Name,
"formula":{
"checkbox": {
"equals": False
}
}
},
{
"property": On_GCal_Notion_Name,
"checkbox": {
"equals": True
}
},
{
"or": [
{
"property": Date_Notion_Name,
"date": {
"equals": todayDate
}
},
{
"property": Date_Notion_Name,
"date": {
"next_week": {}
}
}
]
},
{
"property": Delete_Notion_Name,
"checkbox": {
"equals": False
}
}
]
},
}
)
resultList = my_page['results']
#Comparison section:
# We need to see what times between GCal and Notion are not the same, so we are going to convert all of the notion date/times into
## datetime values and then compare that against the datetime value of the GCal event. If they are not the same, then we change the Notion
### event as appropriate
notion_IDs_List = []
notion_start_datetimes = []
notion_end_datetimes = []
notion_gCal_IDs = [] #we will be comparing this against the gCal_datetimes
gCal_start_datetimes = []
gCal_end_datetimes = []
notion_gCal_CalIds = [] #going to fill this in from the select option, not the text option.
notion_gCal_CalNames = []
gCal_CalIds = []
for result in resultList:
notion_IDs_List.append(result['id'])
notion_start_datetimes.append(result['properties'][Date_Notion_Name]['date']['start'])
notion_end_datetimes.append(result['properties'][Date_Notion_Name]['date']['end'])
notion_gCal_IDs.append(result['properties'][GCalEventId_Notion_Name]['rich_text'][0]['text']['content'])
try:
notion_gCal_CalIds.append(calendarDictionary[result['properties'][Calendar_Notion_Name]['select']['name']])
notion_gCal_CalNames.append(result['properties'][Calendar_Notion_Name]['select']['name'])
except: #keyerror occurs when there's nothing put into the calendar in the first place
notion_gCal_CalIds.append(calendarDictionary[DEFAULT_CALENDAR_NAME])
notion_gCal_CalNames.append(result['properties'][Calendar_Notion_Name]['select']['name'])
#the reason we take off the last 6 characters is so we can focus in on just the date and time instead of any extra info
for i in range(len(notion_start_datetimes)):
try:
notion_start_datetimes[i] = datetime.strptime(notion_start_datetimes[i], "%Y-%m-%d")
except:
try:
notion_start_datetimes[i] = datetime.strptime(notion_start_datetimes[i][:-6], "%Y-%m-%dT%H:%M:%S.000")
except:
notion_start_datetimes[i] = datetime.strptime(notion_start_datetimes[i][:-6], "%Y-%m-%dT%H:%M:%S.%f")
for i in range(len(notion_end_datetimes)):
if notion_end_datetimes[i] != None:
try:
notion_end_datetimes[i] = datetime.strptime(notion_end_datetimes[i], "%Y-%m-%d")
except:
try:
notion_end_datetimes[i] = datetime.strptime(notion_end_datetimes[i][:-6], "%Y-%m-%dT%H:%M:%S.000")
except:
notion_end_datetimes[i] = datetime.strptime(notion_end_datetimes[i][:-6], "%Y-%m-%dT%H:%M:%S.%f")
else:
notion_end_datetimes[i] = notion_start_datetimes[i] #the reason we're doing this weird ass thing is because when we put the end time into the update or make GCal event, it'll be representative of the date
##We use the gCalId from the Notion dashboard to get retrieve the start Time from the gCal event
value =''
exitVar = ''
for gCalId in notion_gCal_IDs:
for calendarID in calendarDictionary.keys(): #just check all of the calendars of interest for info about the event
print('Trying ' + calendarID + ' for ' + gCalId)
try:
x = service.events().get(calendarId=calendarDictionary[calendarID], eventId = gCalId).execute()
except:
print('Event not found')
x = {'status': 'unconfirmed'}
if x['status'] == 'confirmed':
gCal_CalIds.append(calendarID)
value = x
else:
continue
print(value)
print('\n')
try:
gCal_start_datetimes.append(datetime.strptime(value['start']['dateTime'][:-6], "%Y-%m-%dT%H:%M:%S"))
except:
date = datetime.strptime(value['start']['date'], "%Y-%m-%d")
x = datetime(date.year, date.month, date.day, 0, 0, 0)
# gCal_start_datetimes.append(datetime.strptime(x, "%Y-%m-%dT%H:%M:%S"))
gCal_start_datetimes.append(x)
try:
gCal_end_datetimes.append(datetime.strptime(value['end']['dateTime'][:-6], "%Y-%m-%dT%H:%M:%S"))
except:
date = datetime.strptime(value['end']['date'], "%Y-%m-%d")
x = datetime(date.year, date.month, date.day, 0, 0, 0) - timedelta(days=1)
# gCal_end_datetimes.append(datetime.strptime(value['end']['date'][:-6], "%Y-%m-%dT%H:%M:%S"))
gCal_end_datetimes.append(x)
#Now we iterate and compare the time on the Notion Dashboard and the start time of the GCal event
#If the datetimes don't match up, then the Notion Dashboard must be updated
new_notion_start_datetimes = ['']*len(notion_start_datetimes)
new_notion_end_datetimes = ['']*len(notion_end_datetimes)
for i in range(len(new_notion_start_datetimes)):
if notion_start_datetimes[i] != gCal_start_datetimes[i]:
new_notion_start_datetimes[i] = gCal_start_datetimes[i]
if notion_end_datetimes[i] != gCal_end_datetimes[i]: #this means that there is no end time in notion
new_notion_end_datetimes[i] = gCal_end_datetimes[i]
print('test')
print(new_notion_start_datetimes)
print(new_notion_end_datetimes)
print('\n')
for i in range(len(notion_gCal_IDs)):
print(notion_start_datetimes[i], gCal_start_datetimes[i], notion_gCal_IDs[i])
for i in range(len(new_notion_start_datetimes)):
if new_notion_start_datetimes[i] != '' and new_notion_end_datetimes[i] != '': #both start and end time need to be updated
start = new_notion_start_datetimes[i]
end = new_notion_end_datetimes[i]
if start.hour == 0 and start.minute == 0 and start == end: #you're given 12 am dateTimes so you want to enter them as dates (not datetimes) into Notion
my_page = notion.pages.update( #update the notion dashboard with the new datetime and update the last updated time
**{
"page_id": notion_IDs_List[i],
"properties": {
Date_Notion_Name: {
"date":{
'start': start.strftime("%Y-%m-%d"),
'end': None,
}
},
LastUpdatedTime_Notion_Name: {
"date":{
'start': notion_time(), #has to be adjsuted for when daylight savings is different
'end': None,
}
}
},
},
)
elif start.hour == 0 and start.minute == 0 and end.hour == 0 and end.minute == 0: #you're given 12 am dateTimes so you want to enter them as dates (not datetimes) into Notion
my_page = notion.pages.update( #update the notion dashboard with the new datetime and update the last updated time
**{
"page_id": notion_IDs_List[i],
"properties": {
Date_Notion_Name: {
"date":{
'start': start.strftime("%Y-%m-%d"),
'end': end.strftime("%Y-%m-%d"),
}
},
LastUpdatedTime_Notion_Name: {
"date":{
'start': notion_time(), #has to be adjsuted for when daylight savings is different
'end': None,