-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmake_member.py
More file actions
346 lines (304 loc) · 13.4 KB
/
make_member.py
File metadata and controls
346 lines (304 loc) · 13.4 KB
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
"""Contains cog classes for any make_member interactions."""
import logging
import re
from typing import TYPE_CHECKING
import aiohttp
import bs4
import discord
from bs4 import BeautifulSoup
from django.core.exceptions import ValidationError
from config import settings
from db.core.models import GroupMadeMember
from exceptions import ApplicantRoleDoesNotExistError, GuestRoleDoesNotExistError
from utils import CommandChecks, TeXBotBaseCog
if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
from logging import Logger
from typing import Final
from utils import TeXBotApplicationContext
__all__: "Sequence[str]" = ("MakeMemberCommandCog", "MemberCountCommandCog")
logger: "Final[Logger]" = logging.getLogger("TeX-Bot")
_GROUP_MEMBER_ID_ARGUMENT_DESCRIPTIVE_NAME: "Final[str]" = f"""{
"Student"
if (
settings["_GROUP_FULL_NAME"]
and (
"computer science society" in settings["_GROUP_FULL_NAME"].lower()
or "css" in settings["_GROUP_FULL_NAME"].lower()
or "uob" in settings["_GROUP_FULL_NAME"].lower()
or "university of birmingham" in settings["_GROUP_FULL_NAME"].lower()
or "uob" in settings["_GROUP_FULL_NAME"].lower()
or (
"bham" in settings["_GROUP_FULL_NAME"].lower()
and "uni" in settings["_GROUP_FULL_NAME"].lower()
)
)
)
else "Member"
} ID"""
_GROUP_MEMBER_ID_ARGUMENT_NAME: "Final[str]" = (
_GROUP_MEMBER_ID_ARGUMENT_DESCRIPTIVE_NAME.lower().replace(
" ",
"",
)
)
REQUEST_HEADERS: "Final[Mapping[str, str]]" = {
"Cache-Control": "no-cache",
"Pragma": "no-cache",
"Expires": "0",
}
REQUEST_COOKIES: "Final[Mapping[str, str]]" = {
".ASPXAUTH": settings["MEMBERS_LIST_AUTH_SESSION_COOKIE"],
}
ORGANISATION_ID: "Final[str]" = settings["ORGANISATION_ID"]
GROUP_NAME: "Final[str]" = settings["_GROUP_FULL_NAME"]
GROUPED_MEMBRS_URL: "Final[str]" = (
f"https://guildofstudents.com/organisation/memberlist/{ORGANISATION_ID}/?sort=groups"
)
BASE_MEMBERS_URL: "Final[str]" = (
f"https://guildofstudents.com/organisation/memberlist/{ORGANISATION_ID}"
)
class MakeMemberCommandCog(TeXBotBaseCog):
"""Cog class that defines the "/makemember" command and its call-back method."""
@discord.slash_command( # type: ignore[no-untyped-call, misc]
name="makemember",
description=(
"Gives you the Member role "
f"when supplied with an appropriate {_GROUP_MEMBER_ID_ARGUMENT_DESCRIPTIVE_NAME}."
),
)
@discord.option( # type: ignore[no-untyped-call, misc]
name=_GROUP_MEMBER_ID_ARGUMENT_NAME,
description=(
f"""Your UoB Student {
"UoB Student"
if (
settings["_GROUP_FULL_NAME"]
and (
"computer science society" in settings["_GROUP_FULL_NAME"].lower()
or "css" in settings["_GROUP_FULL_NAME"].lower()
or "uob" in settings["_GROUP_FULL_NAME"].lower()
or "university of birmingham" in settings["_GROUP_FULL_NAME"].lower()
or "uob" in settings["_GROUP_FULL_NAME"].lower()
or (
"bham" in settings["_GROUP_FULL_NAME"].lower()
and "uni" in settings["_GROUP_FULL_NAME"].lower()
)
)
)
else "Member"
} ID"""
),
input_type=str,
required=True,
max_length=7,
min_length=7,
parameter_name="group_member_id",
)
@CommandChecks.check_interaction_user_in_main_guild
async def make_member(self, ctx: "TeXBotApplicationContext", group_member_id: str) -> None: # type: ignore[misc]
"""
Definition & callback response of the "make_member" command.
The "make_member" command validates that the given member
has purchased a valid membership to your community group,
then gives the member the "Member" role.
"""
# NOTE: Shortcut accessors are placed at the top of the function, so that the exceptions they raise are displayed before any further errors may be sent
member_role: discord.Role = await self.bot.member_role
interaction_member: discord.Member = await ctx.bot.get_main_guild_member(ctx.user)
await ctx.defer(ephemeral=True)
async with ctx.typing():
if member_role in interaction_member.roles:
await ctx.followup.send(
content=(
":information_source: No changes made. You're already a member "
"- why are you trying this again? :information_source:"
),
ephemeral=True,
)
return
if not re.fullmatch(r"\A\d{7}\Z", group_member_id):
await self.command_send_error(
ctx,
message=(
f"{group_member_id!r} is not a valid "
f"{self.bot.group_member_id_type} ID."
),
)
return
if await GroupMadeMember.objects.filter(
hashed_group_member_id=GroupMadeMember.hash_group_member_id(
group_member_id, self.bot.group_member_id_type
)
).aexists():
await ctx.followup.send(
content=(
":information_source: No changes made. This student ID has already "
f"been used. Please contact a {
await self.bot.get_mention_string(self.bot.committee_role)
} member if this is an error. :information_source:"
),
ephemeral=True,
)
return
guild_member_ids: set[str] = set()
http_session: aiohttp.ClientSession = aiohttp.ClientSession(
headers=REQUEST_HEADERS,
cookies=REQUEST_COOKIES,
)
async with http_session, http_session.get(GROUPED_MEMBRS_URL) as http_response:
response_html: str = await http_response.text()
MEMBER_HTML_TABLE_IDS: Final[frozenset[str]] = frozenset(
{
"ctl00_Main_rptGroups_ctl05_gvMemberships",
"ctl00_Main_rptGroups_ctl03_gvMemberships",
"ctl00_ctl00_Main_AdminPageContent_rptGroups_ctl03_gvMemberships",
"ctl00_ctl00_Main_AdminPageContent_rptGroups_ctl05_gvMemberships",
},
)
table_id: str
for table_id in MEMBER_HTML_TABLE_IDS:
parsed_html: bs4.Tag | bs4.NavigableString | None = BeautifulSoup(
response_html,
"html.parser",
).find(
"table",
{"id": table_id},
)
if parsed_html is None or isinstance(parsed_html, bs4.NavigableString):
continue
guild_member_ids.update(
row.contents[2].text
for row in parsed_html.find_all(
"tr",
{"class": ["msl_row", "msl_altrow"]},
)
)
guild_member_ids.discard("")
guild_member_ids.discard("\n")
guild_member_ids.discard(" ")
if not guild_member_ids:
await self.command_send_error(
ctx,
error_code="E1041",
logging_message=OSError(
"The guild member IDs could not be retrieved from "
"the MEMBERS_LIST_URL.",
),
)
return
if group_member_id not in guild_member_ids:
await self.command_send_error(
ctx,
message=(
f"You must be a member of {self.bot.group_full_name} "
"to use this command.\n"
f"The provided {_GROUP_MEMBER_ID_ARGUMENT_NAME} must match "
f"the {self.bot.group_member_id_type} ID "
f"that you purchased your {self.bot.group_short_name} membership with."
),
)
return
# NOTE: The "Member" role must be added to the user **before** the "Guest" role to ensure that the welcome message does not include the suggestion to purchase membership
await interaction_member.add_roles(
member_role,
reason='TeX Bot slash-command: "/makemember"',
)
try:
await GroupMadeMember.objects.acreate(group_member_id=group_member_id) # type: ignore[misc]
except ValidationError as create_group_made_member_error:
error_is_already_exists: bool = (
"hashed_group_member_id" in create_group_made_member_error.message_dict
and any(
"already exists" in error
for error in create_group_made_member_error.message_dict[
"hashed_group_member_id"
]
)
)
if not error_is_already_exists:
raise
await ctx.followup.send(content="Successfully made you a member!", ephemeral=True)
try:
guest_role: discord.Role = await self.bot.guest_role
except GuestRoleDoesNotExistError:
logger.warning(
'"/makemember" command used but the "Guest" role does not exist. '
'Some user\'s may now have the "Member" role without the "Guest" role. '
'Use the "/ensure-members-inducted" command to fix this issue.',
)
else:
if guest_role not in interaction_member.roles:
await interaction_member.add_roles(
guest_role,
reason='TeX Bot slash-command: "/makemember"',
)
applicant_role: discord.Role | None
try:
applicant_role = await ctx.bot.applicant_role
except ApplicantRoleDoesNotExistError:
applicant_role = None
if applicant_role and applicant_role in interaction_member.roles:
await interaction_member.remove_roles(
applicant_role,
reason='TeX Bot slash-command: "/makemember"',
)
class MemberCountCommandCog(TeXBotBaseCog):
"""Cog class that defines the "/membercount" command and its call-back method."""
@discord.slash_command( # type: ignore[no-untyped-call, misc]
name="membercount",
description="Displays the number of members in the group.",
)
async def member_count(self, ctx: "TeXBotApplicationContext") -> None: # type: ignore[misc]
"""Definition & callback response of the "member_count" command."""
await ctx.defer(ephemeral=False)
async with ctx.typing():
http_session: aiohttp.ClientSession = aiohttp.ClientSession(
headers=REQUEST_HEADERS,
cookies=REQUEST_COOKIES,
)
async with http_session, http_session.get(BASE_MEMBERS_URL) as http_response:
response_html: str = await http_response.text()
member_list_div: bs4.Tag | bs4.NavigableString | None = BeautifulSoup(
response_html,
"html.parser",
).find(
"div",
{"class": "memberlistcol"},
)
if member_list_div is None or isinstance(member_list_div, bs4.NavigableString):
await self.command_send_error(
ctx=ctx,
error_code="E1041",
logging_message=OSError(
"The member count could not be retrieved from the MEMBERS_LIST_URL.",
),
)
return
if "showing 100 of" in member_list_div.text.lower():
member_count: str = member_list_div.text.split(" ")[3]
await ctx.followup.send(
content=f"{GROUP_NAME} has {member_count} members! :tada:",
)
return
member_table: bs4.Tag | bs4.NavigableString | None = BeautifulSoup(
response_html,
"html.parser",
).find(
"table",
{"id": "ctl00_ctl00_Main_AdminPageContent_gvMembers"},
)
if member_table is None or isinstance(member_table, bs4.NavigableString):
await self.command_send_error(
ctx=ctx,
error_code="E1041",
logging_message=OSError(
"The member count could not be retrieved from the MEMBERS_LIST_URL."
),
)
return
await ctx.followup.send(
content=f"{GROUP_NAME} has {
len(member_table.find_all('tr', {'class': ['msl_row', 'msl_altrow']}))
} members! :tada:"
)