-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
197 lines (157 loc) · 5.12 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
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
import requests
import re
import discord
import os
import zoneinfo
import traceback
from datetime import datetime, timedelta
from html import unescape
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("BOT_TOKEN", "")
CHANNEL = int(os.getenv("CHANNEL", ""))
MANADA_USER = os.getenv("MANADA_USER", "")
MANADA_PWD = os.getenv("MANADA_PWD", "")
AUTH_URL = os.getenv("AUTH_URL", "")
MANADA_URL = os.getenv("MANADA_URL", "")
if not all(
[e for e in (TOKEN, CHANNEL, MANADA_USER, MANADA_PWD, AUTH_URL, MANADA_URL)]
):
print("Not all variables are set")
exit(1)
HIGH_PRI = 0xFF0000
MEDIUM_PRI = 0xF58216
LOW_PRI = 0x86DC3D
NO_TASK = 0x33C7FF
DUE_FORMAT = "%Y-%m-%d %H:%M"
COLOR_LIST = [0x000000, HIGH_PRI, MEDIUM_PRI, LOW_PRI]
UA = "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/116.0"
def get_shib() -> dict[str, str]:
s = requests.session()
headers = {
"User-Agent": UA,
}
r = s.get(f"{MANADA_URL}/ct/home", headers=headers)
headers = {
"User-Agent": UA,
"Content-Type": "application/x-www-form-urlencoded",
}
data = {
"shib_idp_ls_exception.shib_idp_session_ss": "",
"shib_idp_ls_success.shib_idp_session_ss": "true",
"shib_idp_ls_value.shib_idp_session_ss": "",
"shib_idp_ls_exception.shib_idp_persistent_ss": "",
"shib_idp_ls_success.shib_idp_persistent_ss": "true",
"shib_idp_ls_value.shib_idp_persistent_ss": "",
"shib_idp_ls_supported": "true",
"_eventId_proceed": "",
}
r = s.post(
f"{AUTH_URL}?execution=e1s1",
headers=headers,
data=data,
)
######
data = {
"j_username": MANADA_USER,
"j_password": MANADA_PWD,
"_eventId_proceed": "",
}
r = s.post(
f"{AUTH_URL}?execution=e1s2",
headers=headers,
data=data,
)
######
data = {
"shib_idp_ls_exception.shib_idp_session_ss": "",
"shib_idp_ls_success.shib_idp_session_ss": "true",
"_eventId_proceed": "",
}
r = s.post(
f"{AUTH_URL}?execution=e1s3",
headers=headers,
data=data,
)
relay_state, saml = map(lambda x: x[7:-3], re.findall(r'value=".*"/>', r.text)[:2])
######
data = {"RelayState": unescape(relay_state), "SAMLResponse": saml}
r = s.post(
f"{MANADA_URL}/Shibboleth.sso/SAML2/POST",
headers=headers,
data=data,
)
shib_key = [
k for k in s.cookies.get_dict().keys() if k.startswith("_shibsession_")
][0]
return {f"{shib_key}": s.cookies.get_dict()[shib_key]}
def get_messages() -> list[discord.Embed]:
headers = {"User-Agent": UA}
cookies = get_shib()
r = requests.get(
f"{MANADA_URL}/ct/home_library_query",
cookies=cookies,
headers=headers,
)
res = []
for e in r.text.split("myassignments-title")[1:]:
due = re.findall(r'td-period">(.*)</td>', e)
priority = 0
if not (due and len(due) >= 2 and due[1].startswith("202")):
continue
due = datetime.strptime(f"{due[1].strip()} +09:00", f"{DUE_FORMAT} %z")
due_remain = due - datetime.now(tz=zoneinfo.ZoneInfo("Asia/Tokyo"))
# overdue check
if due_remain < timedelta(days=0):
continue
if due_remain < timedelta(days=1):
priority = 1
elif due_remain < timedelta(days=2):
priority = 2
elif due_remain < timedelta(days=3):
priority = 3
else:
continue
url_name = re.search(r'<a href="(.+)">(.+?)</a>', e)
course = re.search(r'class="mycourse-title"><.*>(.*)</a>', e)
if not url_name or not course:
continue
url = f"{MANADA_URL}/ct/" + url_name.group(1)
name = url_name.group(2).replace("amp;", "")
color = COLOR_LIST[priority]
embed = discord.Embed(title=name, url=url, color=color)
embed.add_field(
name="コース", value=course.group(1).replace("amp;", ""), inline=False
)
embed.add_field(name="締切", value=due.strftime(DUE_FORMAT), inline=True)
embed.add_field(
name="残り時間",
value=f"{due_remain.days}d {due_remain.seconds // (60 * 60)}h {due_remain.seconds // 60 % 60}m",
inline=True,
)
res.append(embed)
if not res:
embed = discord.Embed(title="直近の課題なし", color=NO_TASK)
res.append(embed)
return res
def send_msg(msgs: list[discord.Embed]):
client = discord.Client(intents=discord.Intents.default())
@client.event
async def on_ready():
for msg in msgs:
await client.get_channel(CHANNEL).send(embed=msg)
await client.close()
client.run(TOKEN)
def send_err(msg: str):
client = discord.Client(intents=discord.Intents.default())
@client.event
async def on_ready():
await client.get_channel(CHANNEL).send(f"```{msg}```")
await client.close()
client.run(TOKEN)
if __name__ == "__main__":
try:
msg = get_messages()
send_msg(msg)
except Exception:
send_err(traceback.format_exc())