-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmake_applicant.py
More file actions
246 lines (204 loc) · 10.1 KB
/
make_applicant.py
File metadata and controls
246 lines (204 loc) · 10.1 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
"""Contains cog classes for making a user into an applicant."""
import logging
from typing import TYPE_CHECKING
import discord
from exceptions.does_not_exist import ApplicantRoleDoesNotExistError, GuildDoesNotExistError
from utils import CommandChecks, TeXBotBaseCog
if TYPE_CHECKING:
from collections.abc import Sequence
from logging import Logger
from typing import Final
from utils import TeXBotApplicationContext, TeXBotAutocompleteContext
__all__: "Sequence[str]" = (
"BaseMakeApplicantCog",
"MakeApplicantContextCommandsCog",
"MakeApplicantSlashCommandCog",
)
logger: "Final[Logger]" = logging.getLogger("TeX-Bot")
class BaseMakeApplicantCog(TeXBotBaseCog):
"""
Base making-applicant cog container class.
Defines the methods for making users into group-applicants that are called by
child cog container classes.
"""
async def _perform_make_applicant(
self, ctx: "TeXBotApplicationContext", applicant_member_id: int
) -> None:
"""Perform the actual process of making the user into a group-applicant."""
# 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 = ctx.bot.main_guild
applicant_role: discord.Role = await ctx.bot.applicant_role
guest_role: discord.Role = await ctx.bot.guest_role
applicant_member: discord.Member | None = main_guild.get_member(applicant_member_id)
if not applicant_member:
await ctx.respond(
content=(
":information_source: "
"No changes made. User cannot be made into an applicant "
"because they have left the server :information_source:"
),
ephemeral=True,
)
return
if applicant_role in applicant_member.roles:
await ctx.respond("User is already an applicant! Command aborted.")
return
if applicant_member.bot:
await self.command_send_error(ctx, message="Cannot make a bot user an applicant!")
return
await ctx.defer(ephemeral=True)
async with ctx.typing():
AUDIT_MESSAGE: Final[str] = (
f'{ctx.user} used TeX-Bot Command "Make User Applicant"'
)
if guest_role in applicant_member.roles:
await applicant_member.remove_roles(guest_role, reason=AUDIT_MESSAGE)
logger.debug("Removed Guest role from user %s", applicant_member)
await applicant_member.add_roles(applicant_role, reason=AUDIT_MESSAGE)
logger.debug("Applicant role given to user %s", applicant_member)
tex_emoji: discord.Emoji | None = self.bot.get_emoji(743218410409820213)
if not tex_emoji:
tex_emoji = discord.utils.get(main_guild.emojis, name="TeX")
intro_channel: discord.TextChannel | None = discord.utils.get(
main_guild.text_channels, name="introductions"
)
if intro_channel:
recent_message: discord.Message
for recent_message in await intro_channel.history(limit=30).flatten():
if recent_message.author.id == applicant_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
try:
await applicant_member.send(
content=(
f"Congratulations {applicant_member.mention}, you've "
"now been given applicant access to the CSS Discord server! "
"As you are not yet a student at the University, "
"you only have limited access to participate in certain channels.\n\n"
"If you are already a student and your induction as an applicant was"
" a mistake, please contact a committee member.\n\n"
"If you have already purchased a membership, you can run the "
"`/make-member` command, and you will be given full access by "
f"{self.bot.user.display_name if self.bot.user else 'TeX-Bot'}.\n\n"
"Some things to do to get started:\n"
"1. Check out our rules in "
f"{await self.bot.get_mention_string(self.bot.rules_channel)}\n"
"2. Head to "
f"{await self.bot.get_mention_string(self.bot.roles_channel)}"
" and click on the icons to get optional roles like "
"pronouns and year group\n"
"3. Change your nickname to whatever "
"you wish others to refer to you as"
)
)
except discord.Forbidden:
logger.warning(
"Failed to send applicant induction DM to user %s", applicant_member
)
news_role: discord.Role | None = discord.utils.get(main_guild.roles, name="News")
if news_role and news_role not in applicant_member.roles:
await applicant_member.add_roles(news_role, reason=AUDIT_MESSAGE)
await ctx.followup.send(
content=":white_check_mark: User is now an applicant.", ephemeral=True
)
class MakeApplicantSlashCommandCog(BaseMakeApplicantCog):
"""Cog class that defines the "/make-applicant" slash-command."""
@staticmethod
async def autocomplete_get_members(
ctx: "TeXBotAutocompleteContext",
) -> set[discord.OptionChoice]:
"""
Autocomplete callable that generates the set of available selectable members.
This list of selectable members is used in any of the "make_applicant" slash-command
options that have a member input-type.
"""
try:
main_guild: discord.Guild = ctx.bot.main_guild
applicant_role: discord.Role = await ctx.bot.applicant_role
except (GuildDoesNotExistError, ApplicantRoleDoesNotExistError):
return set()
members: set[discord.Member] = {
member
for member in main_guild.members
if not member.bot and applicant_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(
name="make-applicant",
description="Gives the user @Applicant role and removes the @Guest role if present.",
)
@discord.option(
name="user",
description="The user to make an Applicant.",
input_type=str,
autocomplete=discord.utils.basic_autocomplete(autocomplete_get_members),
required=True,
parameter_name="str_applicant_member_id",
)
@CommandChecks.check_interaction_user_has_committee_role
@CommandChecks.check_interaction_user_in_main_guild
async def make_applicant(
self, ctx: "TeXBotApplicationContext", str_applicant_member_id: str
) -> None:
"""
Definition & callback response of the "make_applicant" command.
The "make_applicant" command gives the specified user the "Applicant" role and
removes the "Guest" role if they have it.
"""
member_id_not_integer_error: ValueError
try:
applicant_member: discord.Member = await self.bot.get_member_from_str_id(
str_applicant_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_make_applicant(ctx, applicant_member.id)
class MakeApplicantContextCommandsCog(BaseMakeApplicantCog):
"""Cog class that defines the context menu make-applicant commands."""
@discord.user_command(name="Make Applicant")
@CommandChecks.check_interaction_user_has_committee_role
@CommandChecks.check_interaction_user_in_main_guild
async def user_make_applicant(
self, ctx: "TeXBotApplicationContext", member: discord.Member | discord.User
) -> None:
"""
Definition and callback response of the "make_applicant" user-context-command.
The "make_applicant" user-context-command executes the same process as
the "make_applicant" slash-command and thus gives the specified user the
"Applicant" role and removes the "Guest" role if they have it.
"""
await self._perform_make_applicant(ctx, member.id)
@discord.message_command(name="Make Message Author Applicant")
@CommandChecks.check_interaction_user_has_committee_role
@CommandChecks.check_interaction_user_in_main_guild
async def message_make_applicant(
self, ctx: "TeXBotApplicationContext", message: discord.Message
) -> None:
"""
Definition of the "message_make_applicant" message-context-command.
The "make_applicant" message-context-command executes the same process as
the "make_applicant" slash-command and thus gives the specified user the
"Applicant" role and removes the "Guest" role if they have it.
"""
await self._perform_make_applicant(ctx, message.author.id)