-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmake_member.py
More file actions
352 lines (303 loc) · 13.3 KB
/
make_member.py
File metadata and controls
352 lines (303 loc) · 13.3 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
347
348
349
350
351
352
"""Contains cog classes for any make_member interactions."""
import logging
import re
from typing import TYPE_CHECKING, override
import discord
from discord.ui import Modal, View
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, TeXBotApplicationContext, TeXBotBaseCog
from utils.msl import (
fetch_community_group_members_count,
is_id_a_community_group_member,
)
if TYPE_CHECKING:
from collections.abc import Sequence
from logging import Logger
from typing import Final
__all__: "Sequence[str]" = (
"MakeMemberCommandCog",
"MakeMemberModalCommandCog",
"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(" ", "")
)
class MakeMemberCommandCog(TeXBotBaseCog):
"""Cog class that defines the "/make-member" command and its call-back method."""
@discord.slash_command(
name="make-member",
description=(
"Gives you the Member role "
f"when supplied with an appropriate {_GROUP_MEMBER_ID_ARGUMENT_DESCRIPTIVE_NAME}."
),
)
@discord.option(
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="raw_group_member_id",
)
@CommandChecks.check_interaction_user_in_main_guild
async def make_member(
self, ctx: "TeXBotApplicationContext", raw_group_member_id: str
) -> None:
"""
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)
INVALID_GROUP_MEMBER_ID_MESSAGE: Final[str] = (
f"{raw_group_member_id!r} is not a valid {self.bot.group_member_id_type} ID."
)
if not re.fullmatch(r"\A\d{7}\Z", raw_group_member_id):
await self.command_send_error(ctx, message=(INVALID_GROUP_MEMBER_ID_MESSAGE))
return
try:
group_member_id: int = int(raw_group_member_id)
except ValueError:
await self.command_send_error(ctx, message=INVALID_GROUP_MEMBER_ID_MESSAGE)
return
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 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
if not await is_id_a_community_group_member(member_id=group_member_id):
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=f'{ctx.user} used TeX Bot slash-command: "/make-member"'
)
try:
await GroupMadeMember.objects.acreate(group_member_id=raw_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(
'"/make-member" 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=f'{ctx.user} used TeX Bot slash-command: "/make-member"',
)
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=f'{ctx.user} used TeX Bot slash-command: "/make-member"',
)
class MemberCountCommandCog(TeXBotBaseCog):
"""Cog class that defines the "/member-count" command and its call-back method."""
@discord.slash_command(
name="member-count", description="Displays the number of members in the group."
)
async def member_count(self, ctx: "TeXBotApplicationContext") -> None:
"""Definition & callback response of the "member_count" command."""
await ctx.defer(ephemeral=False)
async with ctx.typing():
await ctx.followup.send(
content=(
f"{self.bot.group_full_name} has "
f"{await fetch_community_group_members_count()} members! :tada:"
)
)
class MakeMemberModalActual(Modal):
"""A discord.Modal containing a the input box for make member user interaction."""
@override
def __init__(self) -> None:
super().__init__(title="Make Member Modal")
self.add_item(
discord.ui.InputText(
label="Student ID",
min_length=7,
max_length=7,
required=True,
placeholder="1234567",
)
)
@override
async def callback(self, interaction: discord.Interaction) -> None:
raw_student_id: str | None = self.children[0].value
if not raw_student_id:
await interaction.response.send_message(
content="Invalid Student ID.", ephemeral=True
)
return
try:
student_id: int = int(raw_student_id)
except ValueError:
await interaction.response.send_message(
content="Student ID must be a number.", ephemeral=True
)
return
if await is_id_a_community_group_member(member_id=student_id):
await MakeMemberModalCommandCog.give_member_role(
self=MakeMemberModalCommandCog(bot=interaction.client), # type: ignore[arg-type]
interaction=interaction,
)
await interaction.response.send_message(content="Action complete.")
return
await interaction.response.send_message(
content="Student ID not found.", ephemeral=True
)
class OpenMemberVerifyModalView(View):
"""A discord.View containing a button to open a new member verification modal."""
def __init__(self) -> None:
super().__init__(timeout=None)
@discord.ui.button(
label="Verify", style=discord.ButtonStyle.primary, custom_id="verify_new_member"
)
async def verify_new_member_button_callback( # type: ignore[misc]
self, _: discord.Button, interaction: discord.Interaction
) -> None:
await interaction.response.send_modal(MakeMemberModalActual())
class MakeMemberModalCommandCog(TeXBotBaseCog):
"""Cog class that defines the "/make-member-modal" command and its call-back method."""
@TeXBotBaseCog.listener()
async def on_ready(self) -> None:
"""Add OpenMemberVerifyModalView to the bot's list of permanent views."""
self.bot.add_view(OpenMemberVerifyModalView())
async def give_member_role(self, interaction: discord.Interaction) -> None:
"""Give the member role to the user who interacted with the modal."""
if not isinstance(interaction.user, discord.Member):
await self.command_send_error(
ctx=TeXBotApplicationContext(bot=interaction.client, interaction=interaction), # type: ignore[arg-type]
message="User is not a member.",
)
return
await interaction.user.add_roles(
await self.bot.member_role,
reason=f'{interaction.user} used TeX Bot modal: "Make Member"',
)
async def _open_make_new_member_modal(
self,
button_callback_channel: discord.TextChannel | discord.DMChannel,
) -> None:
await button_callback_channel.send(
content="would you like to open the make member modal",
view=OpenMemberVerifyModalView(),
)
@discord.slash_command(
name="make-member-modal",
description=(
"prints a message with a button that allows users to open the make member modal, "
),
)
@CommandChecks.check_interaction_user_has_committee_role
@CommandChecks.check_interaction_user_in_main_guild
async def make_member_modal(
self,
ctx: "TeXBotApplicationContext",
) -> None:
"""
Definition & callback response of the "make-member-modal" command.
The "make-member-modal" command prints a message with a button that allows users
to open the make member modal
"""
await self._open_make_new_member_modal(
button_callback_channel=ctx.channel,
)
await ctx.respond(
content="The make member modal has been opened in this channel.",
ephemeral=True,
)