diff --git a/cogs/__init__.py b/cogs/__init__.py index 98be47a5a..c4aadb7b5 100644 --- a/cogs/__init__.py +++ b/cogs/__init__.py @@ -31,6 +31,7 @@ "ManualModerationCog", "MemberCountCommandCog", "PingCommandCog", + "SelectColourRoleCommandCog", "SendGetRolesRemindersTaskCog", "SendIntroductionRemindersTaskCog", "SourceCommandCog", @@ -76,6 +77,7 @@ from .make_applicant import MakeApplicantContextCommandsCog, MakeApplicantSlashCommandCog from .make_member import MakeMemberCommandCog, MemberCountCommandCog from .ping import PingCommandCog +from .select_colour_role import SelectColourRoleCommandCog from .send_get_roles_reminders import SendGetRolesRemindersTaskCog from .send_introduction_reminders import SendIntroductionRemindersTaskCog from .source import SourceCommandCog @@ -112,6 +114,7 @@ def setup(bot: TeXBot) -> None: ManualModerationCog, MemberCountCommandCog, PingCommandCog, + SelectColourRoleCommandCog, SendGetRolesRemindersTaskCog, SendIntroductionRemindersTaskCog, SourceCommandCog, diff --git a/cogs/add_users_to_threads_and_channels.py b/cogs/add_users_to_threads_and_channels.py index 25b0a29f6..1f1bb3ed1 100644 --- a/cogs/add_users_to_threads_and_channels.py +++ b/cogs/add_users_to_threads_and_channels.py @@ -13,7 +13,11 @@ from utils import CommandChecks, TeXBotBaseCog from utils.error_capture_decorators import capture_guild_does_not_exist_error lazy from config import settings -lazy from exceptions import GuestRoleDoesNotExistError, GuildDoesNotExistError +lazy from exceptions import ( + GuestRoleDoesNotExistError, + GuildDoesNotExistError, + RoleNotFoundInMainGuildError, +) lazy from utils import TeXBotApplicationContext, TeXBotAutocompleteContext logger: Final[Logger] = logging.getLogger("TeX-Bot") @@ -268,20 +272,25 @@ async def add_role_to_channel( await ctx.defer(ephemeral=True) - main_guild: discord.Guild = ctx.bot.main_guild - try: - role_id: int = int(role_id_str) - except ValueError: - logger.debug("Role ID: %s is not a valid ID.", role_id_str) - await ctx.respond(content=f"The role: {role_id_str} is not valid.") + role_to_add: discord.Role = await self.bot.get_role_from_str_id(role_id_str) + except RoleNotFoundInMainGuildError: + await self.command_send_error( + ctx, + message=( + "The specified role could not be found " + f"in the {self.bot.group_short_name} Discord server. " + "Please use the autocomplete." + ), + ) return - - role_to_add: discord.Role | None = discord.utils.get(main_guild.roles, id=role_id) - - if role_to_add is None: + except ValueError: await self.command_send_error( - ctx, message=f"The role: <@{role_id}> is not valid or couldn't be found." + ctx, + message=( + "The specified role ID is not a valid role ID. " + "Please use the autocomplete." + ), ) return diff --git a/cogs/command_error.py b/cogs/command_error.py index 8ebb0b776..5b41d70ba 100644 --- a/cogs/command_error.py +++ b/cogs/command_error.py @@ -12,6 +12,7 @@ lazy from discord.ext.commands.errors import CheckAnyFailure from utils import TeXBotBaseCog +lazy from config import settings lazy from exceptions import GuildDoesNotExistError lazy from exceptions.base import BaseErrorWithErrorCode lazy from utils import CommandChecks, TeXBotApplicationContext @@ -57,6 +58,18 @@ async def on_application_command_error( "members can run this command." ) + elif CommandChecks.is_interaction_user_has_member_role_failure(error.checks[0]): # type: ignore[arg-type] + message = ( + "You must have the " + f"{await self.bot.get_mention_string(self.bot.member_role)} role " + 'to run this command. Buy membership or run the "/make-member" command.' + f"{ + f'\n{settings["PURCHASE_MEMBERSHIP_URL"]}' + if settings['PURCHASE_MEMBERSHIP_URL'] + else '' + }" + ) + else: logging_message = error diff --git a/cogs/select_colour_role.py b/cogs/select_colour_role.py new file mode 100644 index 000000000..13c22ccc2 --- /dev/null +++ b/cogs/select_colour_role.py @@ -0,0 +1,167 @@ +"""Contains cog classes for any select_colour_role interactions.""" + +__all__: Sequence[str] = ("SelectColourRoleCommandCog",) + +import logging +lazy from collections.abc import Collection, Sequence +lazy from collections.abc import Set as AbstractSet +lazy from logging import Logger +lazy from typing import Final + +import discord + +from utils import CommandChecks, TeXBotBaseCog +lazy from exceptions import GuildDoesNotExistError, RoleNotFoundInMainGuildError +lazy from utils import TeXBotApplicationContext, TeXBotAutocompleteContext + +logger: Final[Logger] = logging.getLogger("TeX-Bot") + +# TODO: Make this a config option in the future # noqa: FIX002 +COLOUR_ROLE_NAMES: Final[AbstractSet[str]] = { + "og-green", + "pink", + "orange", + "purple", + "new-green", + "yellow", + "red", +} + + +class SelectColourRoleCommandCog(TeXBotBaseCog): + """Cog class that defines the "/select-colour-role" command and its call-back method.""" + + @staticmethod + async def autocomplete_get_colour_roles( + ctx: TeXBotAutocompleteContext, + ) -> AbstractSet[discord.OptionChoice] | AbstractSet[str]: + """Autocomplete callable that generates the set of selectable colour roles.""" + try: + main_guild: discord.Guild = ctx.bot.main_guild + except GuildDoesNotExistError: + return set() + + roles: set[discord.Role] = { + role for role in main_guild.roles if role.name.lower() in COLOUR_ROLE_NAMES + } + + if not ctx.value or ctx.value.startswith("@"): + return { + discord.OptionChoice(name=f"@{role.name}", value=str(role.id)) + for role in roles + } + + return {discord.OptionChoice(name=role.name, value=str(role.id)) for role in roles} + + @discord.slash_command( + name="select-colour-role", description="Select a colour role for yourself." + ) + @discord.option( + name="colour-role", + description="The colour role you want to select.", + autocomplete=discord.utils.basic_autocomplete(autocomplete_get_colour_roles), + input_type=str, + required=True, + parameter_name="str_role_id", + ) + @CommandChecks.check_interaction_user_in_main_guild + @CommandChecks.check_interaction_user_has_member_role + async def select_colour_role( + self, ctx: TeXBotApplicationContext, str_role_id: str + ) -> None: + """ + Definition & callback response of the "select_colour_role" command. + + The "select_colour_role" command assigns a colour role to the member that used + the command to allow them to change their display colour. + """ + await ctx.defer(ephemeral=True) + + async with ctx.typing(): + missing_colour_role_names: AbstractSet[str] = COLOUR_ROLE_NAMES - { + role.name.lower() for role in self.bot.main_guild.roles + } + if missing_colour_role_names: + logger.warning( + "Colour roles %s could not be found.", + ", ".join(sorted(missing_colour_role_names)), + ) + + try: + role_to_add: discord.Role = await self.bot.get_role_from_str_id(str_role_id) + except RoleNotFoundInMainGuildError: + await self.command_send_error( + ctx, + message=( + "The specified role could not be found " + f"in the {self.bot.group_short_name} Discord server. " + "Please use the autocomplete." + ), + ) + return + except ValueError: + await self.command_send_error( + ctx, + message=( + "The specified role ID is not a valid role ID. " + "Please use the autocomplete." + ), + ) + return + + if role_to_add.name.lower() not in COLOUR_ROLE_NAMES: + await ctx.followup.send( + content=( + ":information_source: No changes made. " + f"{role_to_add.name} is not a valid colour role. " + ":information_source:" + ), + ephemeral=True, + ) + return + + interaction_member: discord.Member = await self.bot.get_main_guild_member(ctx.user) + + roles_to_remove: Collection[discord.Role] = [ + role + for role in interaction_member.roles + if role.name.lower() in COLOUR_ROLE_NAMES and role != role_to_add + ] + + member_already_has_role_to_add: bool = role_to_add in interaction_member.roles + + if member_already_has_role_to_add and not roles_to_remove: + await ctx.followup.send( + content=( + ":information_source: No changes made. " + f"You already have the {role_to_add.name} colour role. " + ":information_source:" + ), + ephemeral=True, + ) + return + + SELECT_COLOUR_ROLE_AUDIT_MESSAGE: Final[str] = ( + f'{interaction_member} used TeX-Bot slash-command "/select-colour-role".' + ) + + if not member_already_has_role_to_add: + await interaction_member.add_roles( + role_to_add, reason=SELECT_COLOUR_ROLE_AUDIT_MESSAGE + ) + + await interaction_member.remove_roles( + *roles_to_remove, reason=SELECT_COLOUR_ROLE_AUDIT_MESSAGE + ) + + await ctx.followup.send( + content=( + ( + f"You already have the {role_to_add.name} colour role, " + "so your other colour roles have been removed." + ) + if member_already_has_role_to_add + else f"Successfully gave you the {role_to_add.name} colour role!" + ), + ephemeral=True, + ) diff --git a/exceptions/__init__.py b/exceptions/__init__.py index fedc9a8a0..a20f8c9ca 100644 --- a/exceptions/__init__.py +++ b/exceptions/__init__.py @@ -22,6 +22,7 @@ "NoAuditLogsStrikeTrackingError", "RestartRequiredDueToConfigChange", "RoleDoesNotExistError", + "RoleNotFoundInMainGuildError", "RolesChannelDoesNotExistError", "RulesChannelDoesNotExistError", "StrikeTrackingError", @@ -45,7 +46,11 @@ RolesChannelDoesNotExistError, RulesChannelDoesNotExistError, ) -from .guild import DiscordMemberNotInMainGuildError, EveryoneRoleCouldNotBeRetrievedError +from .guild import ( + DiscordMemberNotInMainGuildError, + EveryoneRoleCouldNotBeRetrievedError, + RoleNotFoundInMainGuildError, +) from .messages import ( InvalidMessagesJSONFileError, MessagesJSONFileMissingKeyError, diff --git a/exceptions/does_not_exist.py b/exceptions/does_not_exist.py index 44ce7ae41..e1e11f63c 100644 --- a/exceptions/does_not_exist.py +++ b/exceptions/does_not_exist.py @@ -187,7 +187,14 @@ def ERROR_CODE(cls) -> str: @classproperty @override def DEPENDENT_COMMANDS(cls) -> frozenset[str]: - return frozenset({"make-member", "ensure-members-inducted", "annual-roles-reset"}) + return frozenset( + { + "make-member", + "ensure-members-inducted", + "annual-roles-reset", + "select-colour-role", + } + ) @classproperty @override diff --git a/exceptions/guild.py b/exceptions/guild.py index 02e3cc2b3..c2eee4d87 100644 --- a/exceptions/guild.py +++ b/exceptions/guild.py @@ -3,6 +3,7 @@ __all__: Sequence[str] = ( "DiscordMemberNotInMainGuildError", "EveryoneRoleCouldNotBeRetrievedError", + "RoleNotFoundInMainGuildError", ) from typing import override @@ -29,6 +30,22 @@ def __init__(self, message: str | None = None, user_id: int | None = None) -> No super().__init__(message) +class RoleNotFoundInMainGuildError(BaseTeXBotError, ValueError): + """Exception class for when no roles of your Discord guild have the given role ID.""" + + @classproperty + @override + def DEFAULT_MESSAGE(cls) -> str: + return "Given role ID does not represent any role of your group's Discord guild." + + @override + def __init__(self, message: str | None = None, role_id: int | None = None) -> None: + """Initialise a ValueError exception for a non-existent role ID.""" + self.role_id: int | None = role_id + + super().__init__(message) + + class EveryoneRoleCouldNotBeRetrievedError(BaseErrorWithErrorCode, ValueError): """Exception class for when the "@everyone" role could not be retrieved.""" diff --git a/utils/command_checks.py b/utils/command_checks.py index 3f0307658..8a274669c 100644 --- a/utils/command_checks.py +++ b/utils/command_checks.py @@ -65,6 +65,29 @@ async def check_interaction_user_has_committee_role( ) )(func) + @staticmethod + def check_interaction_user_has_member_role[T: TeXBotBaseCog, **P]( + func: Callable[Concatenate[T, P], Awaitable[None]], + ) -> Callable[Concatenate[T, P], Awaitable[None]]: + """ + Command check decorator to ensure the interaction user has the "Member" role. + + If this check does not pass, the decorated command will not be executed. + Instead, an error message will be sent to the user. + """ + + # NOTE: The check function shares this decorator's name, so that `is_interaction_user_has_member_role_failure()` can identify it within a `CheckAnyFailure` + async def check_interaction_user_has_member_role( + ctx: TeXBotApplicationContext, + ) -> bool: + return await ctx.bot.check_user_has_member_role(ctx.user) + + return commands.check_any( + commands.check( + check_interaction_user_has_member_role # type: ignore[arg-type] + ) + )(func) + @classmethod def is_interaction_user_in_main_guild_failure(cls, check: CheckFailure) -> bool: """Whether the check failed due to the user not being in your Discord guild.""" @@ -72,5 +95,10 @@ def is_interaction_user_in_main_guild_failure(cls, check: CheckFailure) -> bool: @classmethod def is_interaction_user_has_committee_role_failure(cls, check: CheckFailure) -> bool: - """Whether the check failed due to the user not having the committee role.""" + """Whether the check failed due to the user not having the "Committee" role.""" return bool(check.__name__ == cls.check_interaction_user_has_committee_role.__name__) # type: ignore[attr-defined] + + @classmethod + def is_interaction_user_has_member_role_failure(cls, check: CheckFailure) -> bool: + """Whether the check failed due to the user not having the "Member" role.""" + return bool(check.__name__ == cls.check_interaction_user_has_member_role.__name__) # type: ignore[attr-defined] diff --git a/utils/tex_bot.py b/utils/tex_bot.py index 58327c153..5933c86b2 100644 --- a/utils/tex_bot.py +++ b/utils/tex_bot.py @@ -27,6 +27,7 @@ GuildDoesNotExistError, MemberRoleDoesNotExistError, RoleDoesNotExistError, + RoleNotFoundInMainGuildError, RolesChannelDoesNotExistError, RulesChannelDoesNotExistError, ) @@ -430,6 +431,10 @@ async def check_user_has_committee_role(self, user: discord.Member | discord.Use """Util method to validate whether the given user has the "Committee" role.""" return await self.committee_role in (await self.get_main_guild_member(user)).roles + async def check_user_has_member_role(self, user: discord.Member | discord.User) -> bool: + """Util method to validate whether the given user has the "Member" role.""" + return await self.member_role in (await self.get_main_guild_member(user)).roles + def set_main_guild(self, main_guild: discord.Guild) -> None: """ Set the main_guild value that TeX-Bot will reference in the future. @@ -488,6 +493,32 @@ async def get_member_from_str_id(self, str_member_id: str) -> discord.Member: return member + async def get_role_from_str_id(self, str_role_id: str) -> discord.Role: + """ + Retrieve a role of your group's Discord guild by its ID. + + Raises `ValueError` if the provided ID does not represent any role + of your group's Discord guild. + """ + str_role_id = re.sub(r"\A\s*(<@&)(.*)(?(1)>|)\s*\Z", r"\2", str_role_id) + + if not re.fullmatch(r"\A\d{17,20}\Z", str_role_id): + INVALID_ROLE_ID_MESSAGE: Final[str] = f"'{str_role_id}' is not a valid role ID." + raise ValueError(INVALID_ROLE_ID_MESSAGE) + + role: discord.Role | None = await self.main_guild.get_or_fetch( + discord.Role, int(str_role_id) + ) + if role is None: + ROLE_NOT_FOUND_MESSAGE: Final[str] = ( + f"Role with ID '{str_role_id}' could not be found in the main guild." + ) + raise RoleNotFoundInMainGuildError( + message=ROLE_NOT_FOUND_MESSAGE, role_id=int(str_role_id) + ) + + return role + async def fetch_log_channel(self) -> discord.TextChannel: """ Retrieve the Discord log channel.