-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
462 lines (431 loc) · 20.3 KB
/
app.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
from os.path import join, exists
from os import listdir, remove
import credentials, globals
import discord
from datetime import datetime, timedelta
from calendar import day_name
from pytz import timezone
import requests, json
from bulletin import Calendar
CAL_FOLDER = './calendars/'
WEATHER_BASE_URL = f'http://api.openweathermap.org/data/2.5/weather?appid={credentials.weather_api_key}&lat=49.26&lon=-123.25'
FORECAST_BASE_URL = f'http://api.openweathermap.org/data/2.5/forecast?appid={credentials.weather_api_key}&lat=49.26&lon=-123.25'
intents = discord.Intents().all()
client = discord.Client(intents=intents)
users = {}
@client.event
async def on_ready():
activity = discord.Activity(type=discord.ActivityType.listening, name="?help")
await client.change_presence(status=discord.Status.online, activity=activity)
print('Logged in as {0.user}'.format(client))
cals = listdir(CAL_FOLDER)
for calfile in cals:
# get user_id from calendar file
filename = join(CAL_FOLDER, calfile)
uid = calfile.split('.')[0]
try:
uid = uid.split('_')[0]
except:
pass
# open file
file = open(filename, 'r')
# create new calendar to save object into
if uid in users.keys():
user_cal = users[uid]
else:
user_cal = Calendar()
users[uid] = user_cal
try:
user_cal.import_calendar(file.read())
except:
pass
file.close()
@client.event
async def on_message(message):
# get information
author = message.author
authid = str(author.id)
content = message.content
chan = message.channel
attachments = message.attachments
guild = chan.guild
print("{} in {}: {}".format(author.name, chan.name, content))
# skip running if it's a bot message
if author == client.user:
return
if content.startswith(globals.prefix) or content.lower().startswith(globals.prefix_who):
now = datetime.now().astimezone()
state = globals.prefix
if content.startswith(globals.prefix):
call = content.split(globals.prefix)[1]
else:
call = content.lower().split(globals.prefix_who)[1]
state = globals.prefix_who
cmd_parameters = get_parameters(call)
if call.startswith(globals.help):
title = "Hey, I'm Bullet! I'm here to help!"
desc = "To get started, download your schedule as a `.ics` file. " \
"For UBC students, do this by accessing your timetable from your SSC and downloading as ical (.ics) file.\n" \
"Next, upload the .ics file and type `?update` to update your schedule. It will be saved to the system.\n\n"
embed = discord.Embed(title=title, description=desc)
embed.add_field(name="?free (hh:mm)", value="Checks who's free right now. Specify a time to see whos free at a given time.")
embed.add_field(name="?events (@[user]) (week)", value="Lists all of the users events. Show future weeks by specifying how many weeks ahead to look")
embed.add_field(name="? @[user] (hh:mm)", value="Lists what event @[user] is currently attending. Specify a time check that time instead.")
embed.add_field(name="?upcoming (hh:mm)", value="Shows what events are happening in the next hour (or at the specified time).")
embed.add_field(name="?toggle", value="Toggles your status (Available / Busy)")
embed.add_field(name="?status (@[user])", value="Shows your current status. If a user is mentioned their status is shown instead")
embed.add_field(name="?update", value="Updates your current calendar. Resets all previously added calendars. (Please attach a valid .ics file)")
embed.add_field(name="?add (link)", value="Adds a concurrent calendar to your schedule. Please attach a valid .ics file or link to a remote .ics")
embed.add_field(name="?weather (upcoming)", value="Shows the weather on UBC campus. Specify \"upcoming\" to see the forecast for the next 4 days.")
embed.add_field(name="Want to add Bullet to your own server?", value="Click [here](https://discord.com/api/oauth2/authorize?client_id=900540913053499472&permissions=8&scope=bot) to add the bot, or contact `inho#7094` for more details!", inline=False)
embed.set_footer(text="Made with ❤️ by InhoStudios")
await chan.send(embed=embed)
return
if call.startswith(globals.status):
user_id = authid
if message.mentions:
user_id = str(message.mentions[0].id)
msg = ""
if user_id in users.keys() and client.get_user(int(uid)) in chan.members:
cal = users[user_id]
if cal.get_status():
msg = "🟡 Busy"
else:
msg = "🟢 Available"
await chan.send(msg)
else:
await chan.send("Unknown user.")
return
if call.startswith(globals.events):
# SET DEFAULT PARAMETERS
id_to_check = authid
weeks = 0
# PARSE PARAMETERS
if message.mentions:
id_to_check = str(message.mentions[0].id)
user = client.get_user(int(id_to_check))
try:
weeks = int(cmd_parameters[-1])
except:
pass
if id_to_check in users.keys():
if user in chan.members:
cal = users[id_to_check]
date_to_check = datetime.now() + timedelta(days=7*weeks)
evt_page = cal.get_week(date_to_check)
sunday = date_to_check - timedelta(days=date_to_check.weekday() + 1)
saturday = sunday + timedelta(days=6)
embed = create_week_embed(evt_page, user, cal.get_status())
embed.set_footer(text="From {} to {}".format(sunday.strftime("%d %B"), saturday.strftime("%d %B")))
await chan.send(embed=embed)
else:
await chan.send("User does not have access to this channel.")
else:
await chan.send("User is not in the system yet. Use ?update")
return
if call.startswith(globals.free):
checked_time = "right now"
check_dt = now
if len(cmd_parameters) > 0:
for param in cmd_parameters:
if param != "at":
check_dt = parse_time(param, now)
checked_time = "at " + check_dt.strftime("%H:%M on %A, %b %d")
print(str(check_dt))
head = ""
freeList = head
upcomingList = head
for member in chan.members:
user_key = str(member.id)
print(user_key)
if user_key in users.keys():
cal = users[user_key]
if cal.is_free(check_dt):
freeList += "<@{}> ".format(user_key)
elif cal.is_free(check_dt + timedelta(hours=1)):
upcomingList += "<@{}> ".format(user_key)
# for user_key in users.keys():
# if guild.get_member(int(user_key)) != None:
# cal = users[user_key]
# if cal.is_free(check_dt):
# freeList += "<@{}> ".format(user_key)
# elif cal.is_free(check_dt + timedelta(hours=1)):
# upcomingList += "<@{}> ".format(user_key)
if freeList == head:
freeList = "Sorry, nobody seems to be free {} :(".format(checked_time)
embed = discord.Embed(title="These people are free {}!".format(checked_time), description=freeList)
if upcomingList != head:
embed.add_field(name="and these people will be free in the hour after", value=upcomingList)
await chan.send(embed=embed)
return
if call.startswith(globals.update):
if len(attachments) == 0:
await chan.send("Please attach the .ics file in the ?update message")
return
for attachment in attachments:
filename = attachment.filename
auth_id = str(author.id)
if filename.endswith(".ics"):
FILE_PATH = CAL_FOLDER + auth_id + ".ics"
save_file = FILE_PATH
# Remove previous calendars
cals = listdir(CAL_FOLDER)
for calfile in cals:
filename = join(CAL_FOLDER, calfile)
uid = calfile.split('.')[0]
try:
uid = uid.split("_")[0]
except:
pass
if uid == auth_id:
remove(filename)
# Save current calendar file
await attachment.save(save_file)
cal = Calendar()
with open(save_file, 'r') as f:
try:
cal.import_calendar(f.read())
except:
pass
users[auth_id] = cal
evt_page = cal.get_week(datetime.now())
embed = create_week_embed(evt_page, author, cal.get_status())
embed.set_footer(text="Events this week")
await chan.send("Thanks, {}! Your calendar has been updated.".format(author.display_name))
await chan.send(embed=embed)
return
if call.startswith(globals.add):
if len(attachments) == 0 and len(cmd_parameters) == 0:
await chan.send("Please attach the .ics file in the ?add message or use a remote ICS link")
return
# generate save file for either situation
FILE_PATH = join(CAL_FOLDER, str(authid) + ".ics")
save_file = FILE_PATH + ""
i = 1
while exists(save_file):
print(save_file)
save_file = join(CAL_FOLDER, str(authid) + "_" + str(i) + ".ics")
i += 1
# get calendar index
try:
cal = users[authid]
except:
cal = Calendar()
users[authid] = cal
# get file and save it
if len(attachments) > 0:
for attachment in attachments:
filename = attachment.filename
if filename.endswith(".ics"):
await attachment.save(save_file)
with open(save_file, 'r') as f:
cal.import_calendar(f.read())
elif len(cmd_parameters) > 0:
await message.delete()
url = cmd_parameters[0]
r = requests.get(url, allow_redirects=True)
open(save_file, "wb").write(r.content)
cal.import_calendar(r.text)
else:
await chan.send("There was an error with your file or link. Please try again.")
return
# finally
evt_page = cal.get_week(datetime.now())
embed = create_week_embed(evt_page, author, cal.get_status())
embed.set_footer(text="Events this week")
await chan.send("Thanks, {}! New events have been added to your calendar.".format(author.display_name))
await chan.send(embed=embed)
return
if call.startswith(globals.toggle):
if authid in users.keys():
cal = users[authid]
cal.toggle_status()
msg = "Gotcha {}! Your status is updated: ".format(author.display_name)
if cal.get_status():
msg += "Busy"
else:
msg += "Free"
await chan.send(msg)
else:
await chan.send("User is not in the system yet. Use ?update")
return
if call.startswith(globals.now):
checkDT = now
if authid in users.keys():
tz = users[authid].timezone
else:
tz = timezone("America/Vancouver")
if len(cmd_parameters) > 0:
time = cmd_parameters[0]
print(time)
try:
checkDT = parse_time(time, now)
print(str(checkDT))
except:
pass
await chan.send("The current time is " + str(checkDT.astimezone(tz).strftime("%H:%M on %A, %b %d")) +
"\nThe timezone is " + str(checkDT.astimezone(tz).tzinfo))
if call.startswith(globals.upcoming):
checked_time = "right now"
check_dt = now + timedelta(hours=1)
has_events = False
if len(cmd_parameters) > 0:
for param in cmd_parameters:
if param != "at":
check_dt = parse_time(param, now)
checked_time = "at " + check_dt.strftime("%H:%M on %A, %b %d")
for user_key in users.keys():
if guild.get_member(int(user_key)) != None:
cal = users[user_key]
if not cal.is_free(check_dt):
has_events = True
user = guild.get_member(int(user_key))
embed = create_events_embed(cal.get_occurring(check_dt), user, cal.get_status(), title="Upcoming events")
await chan.send(embed=embed)
if not has_events:
await chan.send(embed=discord.Embed(title="It seems there are no events upcoming!", description="There are no events happening {}".format(checked_time)))
if call.startswith(" <@"):
uid = str(message.mentions[0].id)
checkDT = now
if len(cmd_parameters) > 1:
time = cmd_parameters[1]
try:
checkDT = parse_time(time, now)
except:
await chan.send("Check a time with `@[user] HH:MM`")
return
if uid in users.keys():
cal = users[uid]
user = client.get_user(int(uid))
if user in chan.members:
await chan.send(embed=create_events_embed(cal.get_occurring(checkDT), user, cal.get_status(), "Current event"))
else:
await chan.send("User does not have access to this channel.")
else:
await chan.send("User is not in the system yet.")
if call.startswith("weather"):
if len(cmd_parameters) > 0:
if cmd_parameters[0] == "upcoming":
weather_embed = get_forecast()
else:
weather_embed = get_current_weather()
else:
weather_embed = get_current_weather()
await chan.send(embed=weather_embed)
def create_week_embed(events, user, status, title="Schedule"):
embed = discord.Embed(title=title)
try:
embed.set_author(name=user.display_name, icon_url=user.avatar)
except:
embed.set_author(name=user.display_name)
weekday_vals = ["", "", "", "", "", "", ""]
timezone = users[str(user.id)].timezone
embed.description = "Timezone: {}".format(timezone)
# add sorting
for event in events:
for interval in event.intervals:
try:
# parse datetime for start times
start_time = interval[0].astimezone(timezone).strftime("%H:%M")
end_time = interval[1].astimezone(timezone).strftime("%H:%M")
weekday_vals[int(interval[0].weekday())] = weekday_vals[int(interval[0].weekday())] + "```\n{}\n{}-{}```".format(event.summary, start_time, end_time)
except AttributeError:
# all day event, no datetime
print(event.summary)
start_time = "All day"
weekday_vals[int(interval[0].weekday())] = weekday_vals[int(interval[0].weekday())] + f"```\n{event.summary}```"
for i in range(len(weekday_vals)):
if (weekday_vals[i] == ""):
weekday_vals[i] = "No events to display."
name = day_name[i]
if (datetime.now().weekday() == i):
name = "[ " + name + " ]"
embed.add_field(name=name, value=weekday_vals[i])
if len(events) == 0:
embed.color = 0x00FF00
embed.description = "This user is free!"
if status:
embed.color = 0xFFAA00
embed.description = "This user is busy"
return embed
def create_events_embed(events, user, status, title="Calendar"):
embed = discord.Embed(title=title)
embed.set_author(name=user.display_name, icon_url=user.avatar)
timezone = users[str(user.id)].timezone
for event in events:
date = event.intervals[0]
try:
date_str = date[0].astimezone(timezone).strftime("%A %d %B, %Y")
start_time = date[0].astimezone(timezone).strftime("%H:%M")
end_time = date[1].astimezone(timezone).strftime("%H:%M")
except AttributeError:
date_str = date[0].strftime("%A %d %B, %Y")
start_time = "All day event"
end_time = "."
location = ""
if event.location != "":
location = "\nLocation: {}".format(event.location)
embed.add_field(name=event.summary, value="```{}\n{}-{}{}```".format(date_str, start_time, end_time, location), inline=False)
if len(events) == 0:
embed.color = 0x00FF00
embed.description = "This user is free!"
if status:
embed.color = 0xFFAA00
embed.description = "This user is busy"
return embed
def get_parameters(msg):
try:
return msg.split(" ")[1:]
except:
return []
# PRE: Time string in the format HH:MM, datetime to be modified
# POST: Returns a datetime with updated hours
def parse_time(time, now):
try:
cur_time = datetime.strptime(time, "%H")
cur_time = cur_time.replace(minute=0)
except:
cur_time = datetime.strptime(time, "%H:%M")
parsed_time = now.replace(hour=cur_time.hour, minute=cur_time.minute)
# check if hour is less than today
if cur_time.hour < 8:
parsed_time = parsed_time + timedelta(hours=12)
if now > parsed_time:
parsed_time = parsed_time + timedelta(days=1)
return parsed_time
def get_current_weather():
response = requests.get(WEATHER_BASE_URL, verify=False)
weather_json = response.json()
print(weather_json)
embed = discord.Embed()
if weather_json["cod"] != "404":
info = weather_json['main']
temp = int(info['temp']) - 273
feels_like = int(info['feels_like']) - 273
weather = weather_json['weather']
desc = weather[0]['description']
icon_url = f"http://openweathermap.org/img/w/{weather[0]['icon']}.png"
embed.set_author(name=desc.capitalize(), icon_url=icon_url)
embed.add_field(name="Temperature", value=f"{temp}°C")
embed.add_field(name="Feels like", value=f"{feels_like}°C")
embed.set_footer(text="Data provided by OpenWeatherMap API for UBC")
else:
embed.description = "Weather info not found. Sorry!"
return embed
def get_forecast():
response = requests.get(FORECAST_BASE_URL, verify=False)
forecast_json = response.json()
embed = discord.Embed(title="Forecast")
if forecast_json["cod"] != "404":
for day in forecast_json['list']:
if day['dt_txt'][11:] == "12:00:00":
date = datetime.fromtimestamp(day['dt'])
date_plaintext = date.strftime("%A %d %B, %Y")
day_info = day['main']
weather = day['weather'][0]
embed.add_field(name=date_plaintext,value=f"Expect {weather['description']} and **{int(day_info['temp'])-273}°C**. There is a **{day['pop']*100}%** chance of precipitation.")
embed.set_footer(text="All forecasts are for 12:00PM each day. Data provided by OpenWeatherMap API for UBC")
else:
embed.description = "Weather info not found. Sorry!"
return embed
client.run(credentials.token)