-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathinduct.py
482 lines (407 loc) · 19 KB
/
induct.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
"""Contains cog classes for any induction interactions."""
import contextlib
import logging
import random
from typing import TYPE_CHECKING
import discord
from config import settings
from db.core.models import IntroductionReminderOptOutMember
from exceptions import (
ApplicantRoleDoesNotExistError,
CommitteeRoleDoesNotExistError,
GuestRoleDoesNotExistError,
GuildDoesNotExistError,
MemberRoleDoesNotExistError,
RolesChannelDoesNotExistError,
RulesChannelDoesNotExistError,
)
from utils import (
CommandChecks,
TeXBotBaseCog,
)
from utils.error_capture_decorators import capture_guild_does_not_exist_error
if TYPE_CHECKING:
from collections.abc import Sequence
from collections.abc import Set as AbstractSet
from logging import Logger
from typing import Final, Literal
from utils import (
TeXBotApplicationContext,
TeXBotAutocompleteContext,
)
__all__: "Sequence[str]" = (
"BaseInductCog",
"EnsureMembersInductedCommandCog",
"InductContextCommandsCog",
"InductSendMessageCog",
"InductSlashCommandCog",
)
logger: "Final[Logger]" = logging.getLogger("TeX-Bot")
class InductSendMessageCog(TeXBotBaseCog):
"""Cog class that defines the "/induct" command and its call-back method."""
@TeXBotBaseCog.listener()
@capture_guild_does_not_exist_error
async def on_member_update(self, before: discord.Member, after: discord.Member) -> None:
"""
Send a welcome message to this member's DMs & remove introduction reminder flags.
These post-induction actions are only applied to users that have just been inducted as
a guest into your group's Discord guild.
"""
# 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
main_guild: discord.Guild = self.bot.main_guild
if before.guild != main_guild or after.guild != main_guild or before.bot or after.bot:
return
try:
guest_role: discord.Role = await self.bot.guest_role
except GuestRoleDoesNotExistError:
return
if guest_role in before.roles or guest_role not in after.roles:
return
with contextlib.suppress(IntroductionReminderOptOutMember.DoesNotExist):
await (
await IntroductionReminderOptOutMember.objects.aget(discord_id=before.id)
).adelete()
async for message in after.history():
MESSAGE_IS_INTRODUCTION_REMINDER: bool = bool(
("joined the " in message.content)
and (" Discord guild but have not yet introduced" in message.content)
and message.author.bot
)
if MESSAGE_IS_INTRODUCTION_REMINDER:
await message.delete(
reason="Delete introduction reminders after member is inducted.",
)
# noinspection PyUnusedLocal
rules_channel_mention: str = "**`#welcome`**"
with contextlib.suppress(RulesChannelDoesNotExistError):
rules_channel_mention = (await self.bot.rules_channel).mention
# noinspection PyUnusedLocal
roles_channel_mention: str = "**`#roles`**"
with contextlib.suppress(RolesChannelDoesNotExistError):
roles_channel_mention = (await self.bot.roles_channel).mention
user_type: Literal["guest", "member"] = "guest"
with contextlib.suppress(MemberRoleDoesNotExistError):
if await self.bot.member_role in after.roles:
user_type = "member"
try:
await after.send(
f"**Congrats on joining the {self.bot.group_short_name} Discord server "
f"as a {user_type}!** "
"You now have access to communicate in all the public channels.\n\n"
"Some things to do to get started:\n"
f"1. Check out our rules in {rules_channel_mention}\n"
f"2. Head to {roles_channel_mention} and click on the icons to get "
"optional roles like pronouns and year groups\n"
"3. Change your nickname to whatever you wish others to refer to you as "
"(You can do this by right-clicking your name in the members-list "
'to the right & selecting "Edit Server Profile").',
)
if user_type != "member":
await after.send(
f"You can also get yourself an annual membership "
f"to {self.bot.group_full_name} for only £5! "
f"Just head to {settings['PURCHASE_MEMBERSHIP_URL']}. "
"You'll get awesome perks like a free T-shirt:shirt:, "
"access to member only events:calendar_spiral: and a cool green name on "
f"the {self.bot.group_short_name} Discord server:green_square:! "
f"Checkout all the perks at {settings['MEMBERSHIP_PERKS_URL']}",
)
except discord.Forbidden:
logger.info(
"Failed to open DM channel to user %s so no welcome message was sent.",
after,
)
class BaseInductCog(TeXBotBaseCog):
"""
Base user-induction cog container class.
Defines the methods for inducting users that are called by
child user-induction cog container classes.
"""
async def get_random_welcome_message(
self, induction_member: discord.User | discord.Member | None = None
) -> str:
"""Get & format a random welcome message."""
random_welcome_message: str = random.choice(tuple(settings["WELCOME_MESSAGES"])) # noqa: S311
if "<User>" in random_welcome_message:
if not induction_member:
return await self.get_random_welcome_message(induction_member)
random_welcome_message = random_welcome_message.replace(
"<User>",
induction_member.mention,
)
if "<Committee>" in random_welcome_message:
try:
committee_role_mention: str = (await self.bot.committee_role).mention
except CommitteeRoleDoesNotExistError:
return await self.get_random_welcome_message(induction_member)
else:
random_welcome_message = random_welcome_message.replace(
"<Committee>",
committee_role_mention,
)
if "<Purchase_Membership_URL>" in random_welcome_message:
if not settings["PURCHASE_MEMBERSHIP_URL"]:
return await self.get_random_welcome_message(induction_member)
random_welcome_message = random_welcome_message.replace(
"<Purchase_Membership_URL>",
settings["PURCHASE_MEMBERSHIP_URL"],
)
if "<Group_Name>" in random_welcome_message:
random_welcome_message = random_welcome_message.replace(
"<Group_Name>",
self.bot.group_short_name,
)
return random_welcome_message.strip()
async def _perform_induction(
self,
ctx: "TeXBotApplicationContext",
induction_member: discord.Member,
*,
silent: bool,
) -> None:
"""Perform the actual process of inducting a member by giving them the Guest 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
main_guild: discord.Guild = self.bot.main_guild
guest_role: discord.Role = await self.bot.guest_role
await ctx.defer(ephemeral=True)
async with ctx.typing():
logger.debug("Inducting member %s, silent=%s", induction_member, silent)
INDUCT_AUDIT_MESSAGE: Final[str] = (
f'{ctx.user} used TeX Bot slash-command: "/induct"'
)
intro_channel: discord.TextChannel | None = discord.utils.get(
main_guild.text_channels,
name="introductions",
)
if induction_member.bot:
await self.command_send_error(
ctx,
message="Member cannot be inducted because they are a bot.",
)
return
if guest_role in induction_member.roles:
await ctx.respond(
content=(
":information_source: No changes made. "
"User has already been inducted. :information_source:"
),
ephemeral=True,
)
return
if not silent:
general_channel: discord.TextChannel = await self.bot.general_channel
# noinspection PyUnusedLocal
roles_channel_mention: str = "**`#roles`**"
with contextlib.suppress(RolesChannelDoesNotExistError):
roles_channel_mention = (await self.bot.roles_channel).mention
await general_channel.send(
f"{await self.get_random_welcome_message(induction_member)} :tada:\n"
f"Remember to grab your roles in {roles_channel_mention} "
"and say hello to everyone here! :wave:",
)
await induction_member.add_roles(
guest_role,
reason=INDUCT_AUDIT_MESSAGE,
)
# noinspection PyUnusedLocal
applicant_role: discord.Role | None = None
with contextlib.suppress(ApplicantRoleDoesNotExistError):
applicant_role = await ctx.bot.applicant_role
if applicant_role and applicant_role in induction_member.roles:
await induction_member.remove_roles(
applicant_role,
reason=INDUCT_AUDIT_MESSAGE,
)
tex_emoji: discord.Emoji | None = self.bot.get_emoji(743218410409820213)
if not tex_emoji:
tex_emoji = discord.utils.get(main_guild.emojis, name="TeX")
if intro_channel:
recent_message: discord.Message
for recent_message in await intro_channel.history(limit=30).flatten():
if recent_message.author.id == induction_member.id:
try:
if tex_emoji:
await recent_message.add_reaction(tex_emoji)
await recent_message.add_reaction("👋")
except discord.Forbidden as e:
if "90001" not in str(e):
raise e from e
logger.info(
"Failed to add reactions because the user, %s, "
"has blocked TeX-Bot.",
recent_message.author,
)
break
await ctx.followup.send(
content=":white_check_mark: User inducted successfully.",
ephemeral=True,
)
class InductSlashCommandCog(BaseInductCog):
"""Cog class that defines the "/induct" command and its call-back method."""
@staticmethod
async def autocomplete_get_members(
ctx: "TeXBotAutocompleteContext",
) -> "AbstractSet[discord.OptionChoice] | AbstractSet[str]":
"""
Autocomplete callable that generates the set of available selectable members.
This list of selectable members is used in any of the "induct" slash-command options
that have a member input-type.
"""
try:
main_guild: discord.Guild = ctx.bot.main_guild
guest_role: discord.Role = await ctx.bot.guest_role
except (GuildDoesNotExistError, GuestRoleDoesNotExistError):
return set()
members: set[discord.Member] = {
member
for member in main_guild.members
if not member.bot and guest_role not in member.roles
}
if not ctx.value or ctx.value.startswith("@"):
return {
discord.OptionChoice(name=f"@{member.name}", value=str(member.id))
for member in members
}
return {
discord.OptionChoice(name=member.name, value=str(member.id)) for member in members
}
@discord.slash_command( # type: ignore[no-untyped-call, misc]
name="induct",
description=(
"Gives a user the @Guest role, then sends a message in #general saying hello."
),
)
@discord.option( # type: ignore[no-untyped-call, misc]
name="user",
description="The user to induct.",
input_type=str,
autocomplete=discord.utils.basic_autocomplete(autocomplete_get_members), # type: ignore[arg-type]
required=True,
parameter_name="str_induct_member_id",
)
@discord.option( # type: ignore[no-untyped-call, misc]
name="silent",
description="Triggers whether a message is sent or not.",
input_type=bool,
default=False,
required=False,
)
@CommandChecks.check_interaction_user_has_committee_role
@CommandChecks.check_interaction_user_in_main_guild
async def induct( # type: ignore[misc]
self, ctx: "TeXBotApplicationContext", str_induct_member_id: str, *, silent: bool
) -> None:
"""
Definition & callback response of the "induct" command.
The "induct" command inducts a given member into your group's Discord guild
by giving them the "Guest" role.
"""
member_id_not_integer_error: ValueError
try:
induct_member: discord.Member = await self.bot.get_member_from_str_id(
str_induct_member_id,
)
except ValueError as member_id_not_integer_error:
await self.command_send_error(ctx, message=member_id_not_integer_error.args[0])
return
await self._perform_induction(ctx, induct_member, silent=silent)
class InductContextCommandsCog(BaseInductCog):
"""Cog class that defines the context-menu induction commands & their call-back methods."""
@discord.user_command(name="Induct User") # type: ignore[no-untyped-call, misc]
@CommandChecks.check_interaction_user_has_committee_role
@CommandChecks.check_interaction_user_in_main_guild
async def non_silent_user_induct( # type: ignore[misc]
self, ctx: "TeXBotApplicationContext", member: discord.Member
) -> None:
"""
Definition & callback response of the "non_silent_induct" user-context-command.
The "non_silent_induct" command executes the same process
as the "induct" slash-command, using the user-context-menu.
Therefore, it will induct a given member into your group's Discord guild
by giving them the "Guest" role.
"""
await self._perform_induction(ctx, member, silent=False)
@discord.user_command(name="Silently Induct User") # type: ignore[no-untyped-call, misc]
@CommandChecks.check_interaction_user_has_committee_role
@CommandChecks.check_interaction_user_in_main_guild
async def silent_user_induct( # type: ignore[misc]
self, ctx: "TeXBotApplicationContext", member: discord.Member
) -> None:
"""
Definition & callback response of the "silent_induct" user-context-command.
The "silent_induct" command executes the same process as the "induct" slash-command,
using the user-context-menu.
Therefore, it will induct a given member into your group's Discord guild
by giving them the "Guest" role, only without broadcasting a welcome message.
"""
await self._perform_induction(ctx, member, silent=True)
@discord.message_command(name="Induct Message Author") # type: ignore[no-untyped-call, misc]
@CommandChecks.check_interaction_user_has_committee_role
@CommandChecks.check_interaction_user_in_main_guild
async def non_silent_message_induct( # type: ignore[misc]
self, ctx: "TeXBotApplicationContext", message: discord.Message
) -> None:
"""
Definition and callback response of the "non_silent_induct" message-context-command.
The "non_silent_induct" command executes the same process
as the "induct" slash-command, using the message-context-menu.
Therefore, it will induct a given member into your group's Discord guild
by giving them the "Guest" role.
"""
try:
member: discord.Member = await self.bot.get_member_from_str_id(
str(message.author.id),
)
except ValueError:
await ctx.respond(
(
":information_source: No changes made. User cannot be inducted "
"because they have left the server "
":information_source:"
),
ephemeral=True,
)
return
await self._perform_induction(ctx, member, silent=False)
class EnsureMembersInductedCommandCog(TeXBotBaseCog):
"""Cog class that defines the "/ensure-members-inducted" command and call-back method."""
# noinspection SpellCheckingInspection
@discord.slash_command( # type: ignore[no-untyped-call, misc]
name="ensure-members-inducted",
description="Ensures all users with the @Member role also have the @Guest role.",
)
@CommandChecks.check_interaction_user_has_committee_role
@CommandChecks.check_interaction_user_in_main_guild
async def ensure_members_inducted(self, ctx: "TeXBotApplicationContext") -> None: # type: ignore[misc]
"""
Definition & callback response of the "ensure_members_inducted" command.
The "ensure_members_inducted" command ensures that users
within your group's Discord guild that have the "Member" role
have also been given the "Guest" 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
main_guild: discord.Guild = self.bot.main_guild
member_role: discord.Role = await self.bot.member_role
guest_role: discord.Role = await self.bot.guest_role
await ctx.defer(ephemeral=True)
changes_made: bool = False
member: discord.Member
for member in main_guild.members:
if guest_role in member.roles:
continue
if member_role in member.roles and guest_role not in member.roles:
changes_made = True
await member.add_roles(
guest_role,
reason=(
f'{ctx.user} used TeX Bot slash-command: "/ensure-members-inducted"'
),
)
await ctx.respond(
(
"All members successfully inducted"
if changes_made
else "No members required inducting"
),
ephemeral=True,
)