-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathcalender.py
222 lines (178 loc) · 6.87 KB
/
calender.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
from __future__ import print_function
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
import pytz
import pyttsx3
import speech_recognition as sr
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
MONTHS = ["january", "febraury", "march", "april", "may", "june", "july", "august", "september"
, "october", "november", "december"]
DAYS = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]
DAY_EXTENTIONS = ["st", "nd", "th", "rd"]
MONTH_DAYS = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30,
7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
def speak(text):
speaker = pyttsx3.init()
speaker.say(text)
speaker.runAndWait()
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
print(said)
except Exception as e:
print("Exception: " + str(e))
return said
def get_date(text):
today = datetime.date.today()
text = text.lower()
if text.count("today") > 0:
return today
if text.count("tomorrow") > 0:
day = today.day + 1
if day > MONTH_DAYS.get(today.month):
day -= MONTH_DAYS.get(today.month)
month = today.month
year = today.year
if month > 11:
month -= 11
year += 1
return datetime.date(month=month, day=day, year=year)
day = -1
day_of_week = -1
month = -1
year = today.year
for word in text.split():
if word in MONTHS:
month = MONTHS.index(word) + 1
elif word in DAYS:
day_of_week = DAYS.index(word)
elif word.isdigit():
day = int(word)
else:
for ext in DAY_EXTENTIONS:
found = word.find(ext)
if found > 0:
try:
day = int(word[:found])
except:
pass
if month < today.month and month != -1:
year = year + 1
if month == -1 and day != -1:
if day < today.day:
month = today.month + 1
else:
month = today.month
if month == -1 and day == -1 and day_of_week != -1:
current_day_of_week = today.weekday()
dif = day_of_week - current_day_of_week
if dif < 0:
dif += 7
if text.count("next") >= 1:
dif += 7
return today + datetime.timedelta(dif)
if day != -1:
return datetime.date(month=month, day=day, year=year)
def authenticate():
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
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.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('calendar', 'v3', credentials=creds)
return service
# Call the Calendar API
def get_all_events(service, msg_list, tk):
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
events_result = service.events().list(calendarId='primary', timeMin=now,
maxResults=20, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
if not events:
print('No upcoming events found.')
msg_list.insert(tk.END, "Boss: No upcoming events found!")
speak(f"You have {len(events)} events.")
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
# print(start, event['summary'])
msg_list.insert(tk.END, "Boss: " + str(start) + str(event['summary']))
start_time = str(start.split("T")[1].split("-")[0])
if int(start_time.split(":")[0]) < 12:
start_time = start_time + "am"
else:
start_time = str(int(start_time.split(":")[0]) - 12) + start_time.split(":")[1]
start_time = start_time + "pm"
speak(event["summary"] + " at " + start_time)
def get_selected_events(service, day, msg_list, tk):
date = datetime.datetime.combine(day, datetime.datetime.min.time())
end_date = datetime.datetime.combine(day, datetime.datetime.max.time())
utc = pytz.UTC
date = date.astimezone(utc)
end_date = end_date.astimezone(utc)
events_result = service.events().list(calendarId='primary', timeMin=date.isoformat(), timeMax=end_date.isoformat(),
singleEvents=True, orderBy='startTime').execute()
events = events_result.get('items', [])
if not events:
speak('No events found!')
msg_list.insert(tk.END, "Boss: No events found!")
else:
speak(f"You have {len(events)} events on this day.")
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
# print(start, event['summary'])
msg_list.insert(tk.END, "Boss: " + str(start) + str(event['summary']))
start_time = str(start.split("T")[1].split("-")[0])
if int(start_time.split(":")[0]) < 12:
start_time = start_time + "am"
else:
start_time = str(int(start_time.split(":")[0]) - 12)
start_time = start_time + "pm"
speak(event["summary"] + " at " + start_time)
def get_date_for_day(text):
text = text.lower()
today = datetime.date.today()
if text.count("today") > 0:
return today
if text.count("tomorrow") > 0:
day = today.day + 1
month = today.month
year = today.year
if day > MONTH_DAYS.get(today.month):
day -= MONTH_DAYS.get(today.month)
month += 1
if month > 11:
month -= 11
year += 1
return datetime.date(month=month, day=day, year=year)
for word in text.split():
if word in DAYS:
# TODO just get the date
required_day = DAYS.index(word)
diff = required_day - today.day + 1
if diff < 0:
diff += 7
if text.count("next") >= 1:
diff += 7
curr_month = today.month
day = today.day + diff
if day > MONTH_DAYS.get(curr_month):
day -= MONTH_DAYS.get(curr_month)
curr_month = today.month - 1
year = today.year
return datetime.date(month=curr_month, day=day, year=year)