Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
1a4f883
Implement member colour change command
MattyTheHacker Aug 23, 2026
b27aff8
Fix errors
MattyTheHacker Aug 23, 2026
9523733
Add util function
MattyTheHacker Aug 23, 2026
8f14666
Drop in real role names
MattyTheHacker Aug 23, 2026
23ddee8
Fixes
MattyTheHacker Aug 23, 2026
fba38c6
Improvements
MattyTheHacker Aug 23, 2026
fa8f7e5
Fixes
MattyTheHacker Aug 23, 2026
38053a9
More fixes
MattyTheHacker Aug 23, 2026
5c4dd46
Merge main into colour-command
automatic-pr-updater[bot] Sep 1, 2026
439ca33
Merge main into colour-command
automatic-pr-updater[bot] Sep 15, 2026
6dc3138
Merge main into colour-command
automatic-pr-updater[bot] Sep 15, 2026
360b065
Merge main into colour-command
automatic-pr-updater[bot] Sep 15, 2026
9c4bef6
Merge main into colour-command
automatic-pr-updater[bot] Sep 15, 2026
a815f16
Merge main into colour-command
automatic-pr-updater[bot] Sep 15, 2026
0656dde
Run ruff format
MattyTheHacker Sep 15, 2026
161c037
[autofix.ci] apply automated fixes
autofix-ci[bot] Sep 15, 2026
c9104a3
Merge main into colour-command
automatic-pr-updater[bot] Sep 16, 2026
476fd0e
Merge main into colour-command
automatic-pr-updater[bot] Sep 16, 2026
1b456e4
Refactor role fetching
MattyTheHacker Sep 29, 2026
ec53b4a
Other fixes
MattyTheHacker Sep 29, 2026
abca8e5
Formatting
MattyTheHacker Sep 29, 2026
4b8c11a
Fix
MattyTheHacker Sep 29, 2026
62adb7e
More fixes
MattyTheHacker Sep 29, 2026
144b333
Reformat
MattyTheHacker Sep 29, 2026
5c41c77
Move TODO comment
MattyTheHacker Sep 29, 2026
5a6c87a
Improve removing logic
MattyTheHacker Sep 29, 2026
53f05d2
Merge remote-tracking branch 'origin/main' into colour-command
MattyTheHacker Nov 20, 2026
2826f27
Use lazy imports in colour selector cog
MattyTheHacker Nov 20, 2026
6f0a827
Merge main into colour-command
automatic-pr-updater[bot] Nov 21, 2026
f3b4dcc
Merge main into colour-command
automatic-pr-updater[bot] Nov 24, 2026
ba4c9a4
Minor fixes
MattyTheHacker Nov 25, 2026
712b051
Fixes
MattyTheHacker Nov 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions cogs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"ManualModerationCog",
"MemberCountCommandCog",
"PingCommandCog",
"SelectColourRoleCommandCog",
"SendGetRolesRemindersTaskCog",
"SendIntroductionRemindersTaskCog",
"SourceCommandCog",
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -112,6 +114,7 @@ def setup(bot: TeXBot) -> None:
ManualModerationCog,
MemberCountCommandCog,
PingCommandCog,
SelectColourRoleCommandCog,
SendGetRolesRemindersTaskCog,
SendIntroductionRemindersTaskCog,
SourceCommandCog,
Expand Down
33 changes: 21 additions & 12 deletions cogs/add_users_to_threads_and_channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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

Expand Down
13 changes: 13 additions & 0 deletions cogs/command_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
167 changes: 167 additions & 0 deletions cogs/select_colour_role.py
Original file line number Diff line number Diff line change
@@ -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():
Comment thread
MattyTheHacker marked this conversation as resolved.
Resolved
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
Comment thread
MattyTheHacker marked this conversation as resolved.
Resolved

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,
)
7 changes: 6 additions & 1 deletion exceptions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"NoAuditLogsStrikeTrackingError",
"RestartRequiredDueToConfigChange",
"RoleDoesNotExistError",
"RoleNotFoundInMainGuildError",
"RolesChannelDoesNotExistError",
"RulesChannelDoesNotExistError",
"StrikeTrackingError",
Expand All @@ -45,7 +46,11 @@
RolesChannelDoesNotExistError,
RulesChannelDoesNotExistError,
)
from .guild import DiscordMemberNotInMainGuildError, EveryoneRoleCouldNotBeRetrievedError
from .guild import (
DiscordMemberNotInMainGuildError,
EveryoneRoleCouldNotBeRetrievedError,
RoleNotFoundInMainGuildError,
)
from .messages import (
InvalidMessagesJSONFileError,
MessagesJSONFileMissingKeyError,
Expand Down
9 changes: 8 additions & 1 deletion exceptions/does_not_exist.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions exceptions/guild.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
__all__: Sequence[str] = (
"DiscordMemberNotInMainGuildError",
"EveryoneRoleCouldNotBeRetrievedError",
"RoleNotFoundInMainGuildError",
)

from typing import override
Expand All @@ -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."""

Expand Down
30 changes: 29 additions & 1 deletion utils/command_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,40 @@ 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."""
return bool(check.__name__ == cls.check_interaction_user_in_main_guild.__name__) # type: ignore[attr-defined]

@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]
Loading