aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar D0rs4n <[email protected]>2021-07-30 03:25:25 +0200
committerGravatar D0rs4n <[email protected]>2021-07-30 03:34:03 +0200
commit43240643642fae3fe92413189e99d772fdebf562 (patch)
tree10a985ad1167de61006dab8004accdde88bda1ad
parentModify error handling in join_role_stats and move it to the Information Cog (diff)
Update join_role_stats, add new custom error
- Add new custom error to handle non-existent roles in the Information cog - Update join_role_stats to use built in generics for typing
-rw-r--r--bot/errors.py12
-rw-r--r--bot/exts/info/information.py24
2 files changed, 25 insertions, 11 deletions
diff --git a/bot/errors.py b/bot/errors.py
index 46efb6d4f..ce2371f56 100644
--- a/bot/errors.py
+++ b/bot/errors.py
@@ -41,3 +41,15 @@ class BrandingMisconfiguration(RuntimeError):
"""Raised by the Branding cog when a misconfigured event is encountered."""
pass
+
+
+class NonExistentRoleError(ValueError):
+ """
+ Raised by the Information Cog when encountering a role that does not exist.
+
+ Attributes:
+ `role_id` -- the ID of the role that does not exist
+ """
+
+ def __init__(self, role_id: int):
+ super().__init__(f"Could not fetch data for role {role_id}")
diff --git a/bot/exts/info/information.py b/bot/exts/info/information.py
index 54616a1c6..78a9b2122 100644
--- a/bot/exts/info/information.py
+++ b/bot/exts/info/information.py
@@ -3,7 +3,7 @@ import logging
import pprint
import textwrap
from collections import defaultdict
-from typing import Any, DefaultDict, Dict, List, Mapping, Optional, Tuple, Union
+from typing import Any, DefaultDict, Mapping, Optional, Tuple, Union
import rapidfuzz
from discord import AllowedMentions, Colour, Embed, Guild, Message, Role
@@ -14,12 +14,12 @@ from bot.api import ResponseCodeError
from bot.bot import Bot
from bot.converters import FetchedMember
from bot.decorators import in_whitelist
+from bot.errors import NonExistentRoleError
from bot.pagination import LinePaginator
from bot.utils.channel import is_mod_channel, is_staff_channel
from bot.utils.checks import cooldown_with_role_bypass, has_no_roles_check, in_whitelist_check
from bot.utils.time import TimestampFormats, discord_timestamp, humanize_delta
-
log = logging.getLogger(__name__)
@@ -43,25 +43,27 @@ class Information(Cog):
return channel_counter
@staticmethod
- def join_role_stats(role_ids: List[int], name: str, guild: Guild) -> Dict[str, int]:
+ def join_role_stats(role_ids: list[int], name: str, guild: Guild) -> dict[str, int]:
"""Return a dictionary with the number of `members` of each role given, and the `name` for this joined group."""
members = []
for role_id in role_ids:
if (role := guild.get_role(role_id)) is None:
- raise ValueError(f"Could not fetch data for role {role} for server embed.")
+ raise NonExistentRoleError(role_id)
else:
members += role.members
return {name: len(set(members))}
@staticmethod
- def get_member_counts(guild: Guild) -> Dict[str, int]:
+ def get_member_counts(guild: Guild) -> dict[str, int]:
"""Return the total number of members for certain roles in `guild`."""
- roles = (
- guild.get_role(role_id) for role_id in (
- constants.Roles.helpers, constants.Roles.mod_team, constants.Roles.admins,
- constants.Roles.owners, constants.Roles.contributors,
- )
- )
+ role_ids = [constants.Roles.helpers, constants.Roles.mod_team, constants.Roles.admins,
+ constants.Roles.owners, constants.Roles.contributors]
+ roles = []
+ for role_id in role_ids:
+ if (role := guild.get_role(role_id)) is None:
+ raise NonExistentRoleError(role_id)
+ else:
+ roles.append(role)
role_stats = {role.name.title(): len(role.members) for role in roles}
role_stats.update(
**Information.join_role_stats([constants.Roles.project_leads, constants.Roles.domain_leads], "Leads", guild)