forked from nfoster1492/ClassMateBot-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
calendar.py
422 lines (397 loc) · 19 KB
/
calendar.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
# Copyright (c) 2023 nfoster1492
from __future__ import print_function
import os.path
import datetime
import discord
import asyncio
from dotenv import load_dotenv
from discord.ext import commands, tasks
from google.auth.transport.requests import Request
from datetime import timedelta, datetime, date
from google.oauth2.credentials import Credentials
from urllib.request import urlopen
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import pdfkit
import pandas as pd
class Calendar(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.checkForEvents.start()
# -----------------------------------------------------------------------------------------------------------------
# Function: credsSetUp(self)
# Description: Sets up the credentials for all calendar actions
# Outputs:
# - The credentials needed to access the google calendar api calls
# -----------------------------------------------------------------------------------------------------------------
def credsSetUp(self):
"""Set up Google Calendar with authentication"""
# If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/calendar"]
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.
if os.path.exists("token.json"):
creds = Credentials.from_authorized_user_file("token.json", 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(
"credentials.json", SCOPES
)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open("token.json", "w", encoding="utf-8") as token:
token.write(creds.to_json())
with open("cogs/token.json", "w", encoding="utf-8") as token:
token.write(creds.to_json())
return creds
# -----------------------------------------------------------------------------------------------------------------
# Function: addCalendarEvent(self, ctx, name, description, eventTime)
# Description: adds an event to the Google Calendar specified in .env configuration
# Inputs:
# - ctx: context of the command
# - name: name of event
# - decription: description of event
# - eventTime: Time of event
# Outputs:
# - Event added to calendar
# -----------------------------------------------------------------------------------------------------------------
@commands.command(
name="addCalendarEvent",
help="Add an event to the course calendar using the format"
": $addCalendarEvent NAME DESCRIPTION DATE/TIME",
)
async def addCalendarEvent(self, ctx, name, description, eventTime):
"""Adds specified event to shared Google Calendar"""
creds = self.credsSetUp()
try:
calendar = os.getenv("CALENDAR_ID")
service = build("calendar", "v3", credentials=creds)
event = {
"summary": name,
"description": description,
"colorId": 4,
"start": {"dateTime": str(eventTime), "timeZone": "UTC"},
"end": {"dateTime": str(eventTime), "timeZone": "UTC"},
}
event = service.events().insert(calendarId=calendar, body=event).execute()
await ctx.send(f"Event {name} added to calendar!")
except HttpError as error:
print(f"An error occurred: {error}")
# -----------------------------------------------------------------------------------------------------------------
# Function: add_office_hours(self, ctx, ta_name, event_time, end_year, end_month, end_day)
# Description: adds a recurring office hour event for a specific TA or instructor to the Google Calendar
# specified in .env configuration
# Inputs:
# - ctx: context of the command
# - ta_name: name of TA or instructor to add office hours for
# - event_time: time of event to recur by
# - end_year: year to stop recurring event
# - end_month: month to stop recurring event
# - end_day: day to stop recurring event
# Outputs:
# - Recurring event added to calendar, confirmation that event is added
# -----------------------------------------------------------------------------------------------------------------
@commands.command(name="add_office_hours")
# pylint: disable=too-many-arguments
async def add_office_hours(
self, ctx, ta_name, event_time, end_year, end_month, end_day
):
creds = self.credsSetUp()
try:
calendar = os.getenv("CALENDAR_ID")
service = build("calendar", "v3", credentials=creds)
event = {
"summary": f"{ta_name}'s office hours",
"colorId": 2,
"start": {"dateTime": str(event_time), "timeZone": "UTC"},
"end": {"dateTime": str(event_time), "timeZone": "UTC"},
"recurrence": [
f"RRULE:FREQ=WEEKLY;UNTIL={end_year}{end_month}{end_day}"
],
}
event = service.events().insert(calendarId=calendar, body=event).execute()
await ctx.send(f"Office hours for {ta_name} added to calendar!")
except HttpError as error:
print(f"An error occurred: {error}")
# -----------------------------------------------------------------------------------------------------------------
# Function: add_lectures(self, ctx, class_name, address, event_time, end_year, end_month, end_day)
# Description: adds a recurring lecture event with a specific address to the Google Calendar specified in .env
# configuration. Assumes lectures will always occur at the same address
# Inputs:
# - ctx: context of the command
# - class_name: name of class to add recurring lectures for
# - address: address of recurring lectures
# - event_time: time of event to recur by
# - end_year: year to stop recurring event
# - end_month: month to stop recurring event
# - end_day: day to stop recurring event
# Outputs:
# - Recurring event added to calendar, confirmation that event is added
# -----------------------------------------------------------------------------------------------------------------
@commands.command(name="add_lectures")
# pylint: disable=too-many-arguments
async def add_lectures(
self, ctx, class_name, address, event_time, end_year, end_month, end_day
):
creds = self.credsSetUp()
try:
calendar = os.getenv("CALENDAR_ID")
service = build("calendar", "v3", credentials=creds)
event = {
"summary": f"{class_name} lecture",
"description": f"Address: {address}",
"colorId": 2,
"start": {"dateTime": str(event_time), "timeZone": "UTC"},
"end": {"dateTime": str(event_time), "timeZone": "UTC"},
"recurrence": [
f"RRULE:FREQ=WEEKLY;UNTIL={end_year}{end_month}{end_day}"
],
}
event = service.events().insert(calendarId=calendar, body=event).execute()
await ctx.send(f"Lecture for {class_name} added to calendar!")
except HttpError as error:
print(f"An error occurred: {error}")
# -----------------------------------------------------------------------------------------------------------------
# Function: clearCalendar(self, ctx)
# Description: clears all events from the google calendar
# Inputs:
# - ctx: context of the command
# Outputs:
# - Whether the command was a success or a failure
# -----------------------------------------------------------------------------------------------------------------
@commands.command(name="clearCalendar", help="Clear all events from calendar")
async def clearCalendar(self, ctx):
"""Clears all events from shared Google Calendar"""
creds = self.credsSetUp()
try:
page_token = None
calendar = os.getenv("CALENDAR_ID")
service = build("calendar", "v3", credentials=creds)
calendar_events = []
while True:
events = (
service.events()
.list(calendarId=calendar, pageToken=page_token)
.execute()
)
for event in events["items"]:
calendar_events.append(event["id"])
page_token = events.get("nextPageToken")
if not page_token:
break
for cid in calendar_events:
service.events().delete(calendarId=calendar, eventId=cid).execute()
await ctx.send("Calendar has been cleared")
except HttpError as error:
print(f"An error occurred: {error}")
# -----------------------------------------------------------------------------------------------------------------
# Function: getiCalDownload(self, ctx)
# Description: sends an ics file of the class calendar to the channel the command was issued in
# Inputs:
# - ctx: context of the command
# Outputs:
# - The ics file of the calendar
# -----------------------------------------------------------------------------------------------------------------
@commands.command(
name="getiCalDownload",
help="Enter the command to receive an ics"
" file of the calendar$getiCalDownload",
)
async def getiCalDownload(self, ctx):
"""Generates an ICAL file of the Google Calendar"""
# Get the calendar in ics format
url = os.getenv("CALENDAR_ICS")
text = urlopen(url).read().decode("iso-8859-1")
# parse the received text to remove all \n characters
newText = ""
for character in text:
if character != "\n":
newText = newText + character
# write to the ics file
f = open(os.getenv("CALENDAR_PATH") + "ical.ics", "w", encoding="utf-8")
f.write(newText)
f.close()
await ctx.send(file=discord.File(os.getenv("CALENDAR_PATH") + "ical.ics"))
# -----------------------------------------------------------------------------------------------------------------
# Function: getPdfDownload(self, ctx)
# Description: sends an pdf file of the class calendar to the channel the command was issued in
# Inputs:
# - ctx: context of the command
# Outputs:
# - The pdf file of the calendar
# -----------------------------------------------------------------------------------------------------------------
@commands.command(
name="getPdfDownload",
help="Enter the command to receive an ics"
" file of the calendar$getiCalDownload",
)
async def getPdfDownload(self, ctx):
"""Sends a pdf file of the class calendar to the Discord Channel"""
creds = self.credsSetUp()
try:
service = build("calendar", "v3", credentials=creds)
# Call the Calendar API
now = datetime.utcnow().isoformat() + "Z" # 'Z' indicates UTC time
calendar = os.getenv("CALENDAR_ID")
events_result = (
service.events()
.list(
calendarId=calendar,
timeMin=now,
maxResults=150,
singleEvents=True,
orderBy="startTime",
)
.execute()
)
events = events_result.get("items", [])
if not events:
await ctx.send("No upcoming events found.")
return
calEvents = []
for event in events:
start = event["start"].get("dateTime", event["start"].get("date"))
end = event["end"].get("dateTime", event["end"].get("date"))
calEvent = {"Summary": event["summary"], "Start": start, "End": end}
calEvents.append(calEvent)
df = pd.DataFrame(calEvents)
htmlCal = df.to_html()
pdfkit.from_string(htmlCal, os.getenv("CALENDAR_PATH") + "calendar.pdf")
await ctx.send(
file=discord.File(os.getenv("CALENDAR_PATH") + "calendar.pdf")
)
except HttpError as error:
print(f"An error occurred: {error}")
# -----------------------------------------------------------------------------------------------------------------
# Function: checkForEvents(self)
# Description: Checks the calendar once per day for any events that are due the same day
# Outputs:
# - Message to the general chat where everyone is pinged of what events are due today
# -----------------------------------------------------------------------------------------------------------------
@tasks.loop(hours=24)
async def checkForEvents(self):
"""Checks calendar daily for the events due that day"""
creds = self.credsSetUp()
try:
service = build("calendar", "v3", credentials=creds)
# Call the Calendar API
now = datetime.utcnow().isoformat() + "Z" # 'Z' indicates UTC time
calendar = os.getenv("CALENDAR_ID")
events_result = (
service.events()
.list(
calendarId=calendar,
timeMin=now,
maxResults=150,
singleEvents=True,
orderBy="startTime",
)
.execute()
)
events = events_result.get("items", [])
summary = ""
for event in events:
dt = datetime.strptime(
(event["start"]["dateTime"])[0:18], "%Y-%m-%dT%H:%M:%S"
)
if dt.day == date.today().day and dt.year == date.today().year:
summary = summary + event["summary"] + ","
if len(summary) != 0:
# If the bot is used in more than one server
for guild in self.bot.guilds:
for channel in guild.text_channels:
# Find the general channel and ping
if channel.name == "general":
await channel.send("@everyone " + summary + "due TODAY!")
break
except HttpError as error:
print(f"An error occurred: {error}")
# -----------------------------------------------------------------------------------------------------------------
# Function: subscribeCalendar(self, ctx, userEmail)
# Description: adds specified user to shared Google Calendar
# Inputs:
# - ctx: context of the command
# - target: calendar to modify
# - userEmail: user to add to target Google Calendar
# Outputs:
# - Confirmation string for successful add, error string for failure.
# -----------------------------------------------------------------------------------------------------------------
@commands.command(
name="subscribeCalendar",
help="Adds user to shared Google Calendar. Ex: subscribeCalendar [email protected]",
)
async def subscribeCalendar(self, ctx, userEmail):
"""Adds user to shared Google Calendar"""
creds = self.credsSetUp()
try:
service = build("calendar", "v3", credentials=creds)
calendar = os.getenv("CALENDAR_ID")
acl_rule = {
"scope": {"type": "user", "value": userEmail},
"role": "reader", # Adjust the role as needed (e.g., reader, owner)
}
acl_rule = (
service.acl().insert(calendarId=calendar, body=acl_rule).execute()
)
await ctx.author.send(f"Added {userEmail} to the calendar.")
except HttpError as e:
print(f"An error occurred: {e}")
await ctx.author.send(
f"Error adding user: {userEmail} is not a valid email."
)
# -----------------------------------------------------------------------------------------------------------------
# Function: removeCalendar(self, ctx, userEmail)
# Description: removes specified user from shared Google Calendar
# Inputs:
# - ctx: context of the command
# - target: calendar to modify
# - userEmail: user to remove from target Google Calendar
# Outputs:
# - Confirmation string for successful removal, error string for failure.
# -----------------------------------------------------------------------------------------------------------------
@commands.has_role("Instructor")
@commands.command(
name="removeCalendar",
help="Removes user from shared Google Calendar. Ex: removeCalendar [email protected]",
)
async def removeCalendar(self, ctx, userEmail):
"""Removes user from shared Google Calendar"""
creds = self.credsSetUp()
try:
service = build("calendar", "v3", credentials=creds)
calendar = os.getenv("CALENDAR_ID")
acl_rule_id = None
# Get the list of ACL rules (permissions) for the calendar.
acl_list = service.acl().list(calendarId=calendar).execute()
for acl_rule in acl_list.get("items", []):
if (
acl_rule["scope"]["type"] == "user"
and acl_rule["scope"]["value"] == userEmail
):
acl_rule_id = acl_rule["id"]
break
if acl_rule_id:
# Delete the ACL rule (permission) to remove the user from the calendar.
service.acl().delete(calendarId=calendar, ruleId=acl_rule_id).execute()
await ctx.author.send(
f"User {userEmail} has been removed from the calendar."
)
else:
await ctx.author.send(
f"User {userEmail} was not found in the calendar's permissions."
)
except HttpError as e:
print(f"An error occurred: {e}")
await ctx.author.send(
f"Error removing user: {userEmail} is not a valid email."
)
async def setup(bot):
"""Adds the file to the bot's cog system"""
n = Calendar(bot)
await bot.add_cog(n)