diff --git a/discord/guild.py b/discord/guild.py index 7dd87cb11..e1f4b80b7 100644 --- a/discord/guild.py +++ b/discord/guild.py @@ -3934,6 +3934,33 @@ class Guild(Hashable): return roles + async def role_member_counts(self) -> Dict[Role, int]: + """|coro| + + Retrieves the number of members in each role the guild has. + + .. versionadded:: 2.1 + + Raises + ------- + Forbidden + You do not have permissions to get the member counts. + HTTPException + Getting the member counts failed. + + Returns + -------- + Dict[:class:`Role`, :class:`int`] + A mapping of the role to the number of members in that role. + """ + data = await self._state.http.get_role_member_counts(self.id) + ret: Dict[Role, int] = {} + for k, v in data.items(): + role = self.get_role(int(k)) + if role is not None: + ret[role] = v + return ret + async def kick(self, user: Snowflake, *, reason: Optional[str] = None) -> None: """|coro| diff --git a/discord/http.py b/discord/http.py index aa00ef9be..604a87432 100644 --- a/discord/http.py +++ b/discord/http.py @@ -2431,6 +2431,9 @@ class HTTPClient: reason=reason, ) + def get_role_member_counts(self, guild_id: Snowflake) -> Response[Dict[Snowflake, int]]: + return self.request(Route('GET', '/guilds/{guild_id}/roles/member-counts', guild_id=guild_id)) + def edit_channel_permissions( self, channel_id: Snowflake, diff --git a/discord/role.py b/discord/role.py index 7f83f9108..d690833b3 100644 --- a/discord/role.py +++ b/discord/role.py @@ -678,5 +678,29 @@ class Role(Hashable): HTTPException Deleting the role failed. """ - await self._state.http.delete_role(self.guild.id, self.id, reason=reason) + + async def member_count(self) -> int: + """|coro| + + Retrieves the number of members that have this role. + + .. versionadded:: 2.1 + + Raises + ------- + Forbidden + You do not have permissions to get the member count. + HTTPException + Retrieving the member count failed. + + Returns + -------- + :class:`int` + The number of members with this role. + """ + if self.is_default(): + return self.guild.member_count or self.guild.approximate_member_count or 0 + + data = await self._state.http.get_role_member_counts(self.guild.id) + return data.get(str(self.id), 0)