-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
86 lines (69 loc) · 2.75 KB
/
main.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
import os
import asyncio
import requests
import logging as log
from dotenv import load_dotenv
from datetime import datetime, timezone
from edspy import edspy
from static import *
# webhook url that can be loaded from .env with same name (see .env.example)
COURSE_IDS = {
12345: 'CS_XYZ_WEBHOOK',
12346: 'DATA_XYZ_WEBHOOK',
12347: 'INFO_XYZ_WEBHOOK',
}
class EventHandler:
def __init__(self, client: edspy.EdClient, webhooks: dict) -> None:
self.client = client
self.webhooks = webhooks
self.courses = None
async def update_courses(self):
# update user courses cache every hour
while True:
self.courses = await self.client.get_courses()
await asyncio.sleep(3600)
@edspy.listener(edspy.ThreadNewEvent)
async def on_new_thread(self, event: edspy.ThreadNewEvent):
thread: edspy.Thread = event.thread
if not self.courses:
await self.update_courses()
course = next(filter(lambda x: x.id == thread.course_id, self.courses), None)
# send payload to Discord
requests.post(
url=self.webhooks.get(course.id),
json={
'username': 'Ed',
'avatar_url': ED_ICON,
'embeds': self.build_embed(thread, course)
})
@staticmethod
def build_embed(thread: edspy.Thread, course: edspy.Course):
return [{
'title': '#{} **{}**'.format(thread.number, thread.title),
'description': thread.document,
'url': BASE_URL + '/courses/{}/discussion/{}'.format(thread.course_id, thread.id),
'color': EMBED_COLORS.get(thread.type, UKNOWN_COLOR),
'author': {
'name': '{} • {}'.format(course.code, thread.category),
'url': BASE_URL + '/courses/{}/discussion'.format(thread.course_id)},
'footer': {
'text': 'Anonymous User' if thread.is_anonymous else '{} ({})'.format(
thread.user.name, thread.user.course_role.capitalize()),
'icon_url': AVATAR_URL + thread.user.avatar if not thread.is_anonymous and
thread.user.avatar else USER_ICON
},
'timestamp': f'{datetime.now(timezone.utc).isoformat()[:-9]}Z'
}]
async def main():
load_dotenv()
webhook_urls = {course_id: os.getenv(webhook) for
course_id, webhook in COURSE_IDS.items()}
client = edspy.EdClient()
handler = EventHandler(client=client, webhooks=webhook_urls)
client.add_event_hooks(handler)
await asyncio.gather(
handler.update_courses(),
client.subscribe(list(webhook_urls.keys())))
if __name__ == '__main__':
log.basicConfig(level=log.INFO)
asyncio.run(main())