Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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: 2 additions & 1 deletion bot/exts/backend/sync/_syncers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import bot
from bot.api import ResponseCodeError
from bot.utils.members import get_or_fetch_member

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -156,7 +157,7 @@ def maybe_update(db_field: str, guild_value: t.Union[str, int]) -> None:
if db_user[db_field] != guild_value:
updated_fields[db_field] = guild_value

if guild_user := guild.get_member(db_user["id"]):
if guild_user := await get_or_fetch_member(guild, db_user["id"]):
seen_guild_users.add(guild_user.id)

maybe_update("name", guild_user.name)
Expand Down
7 changes: 4 additions & 3 deletions bot/exts/events/code_jams/_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from bot.bot import Bot
from bot.constants import Emojis, Roles
from bot.exts.events.code_jams import _channels
from bot.utils.members import get_or_fetch_member
from bot.utils.services import send_to_paste_service

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -59,7 +60,7 @@ async def create(self, ctx: commands.Context, csv_file: t.Optional[str] = None)
reader = csv.DictReader(csv_file.splitlines())

for row in reader:
member = ctx.guild.get_member(int(row["Team Member Discord ID"]))
member = await get_or_fetch_member(ctx.guild, int(row["Team Member Discord ID"]))

if member is None:
log.trace(f"Got an invalid member ID: {row['Team Member Discord ID']}")
Expand All @@ -69,8 +70,8 @@ async def create(self, ctx: commands.Context, csv_file: t.Optional[str] = None)

team_leaders = await ctx.guild.create_role(name="Code Jam Team Leaders", colour=TEAM_LEADERS_COLOUR)

for team_name, members in teams.items():
await _channels.create_team_channel(ctx.guild, team_name, members, team_leaders)
for team_name, team_members in teams.items():
await _channels.create_team_channel(ctx.guild, team_name, team_members, team_leaders)

await _channels.create_team_leader_channel(ctx.guild, team_leaders)
await ctx.send(f"{Emojis.check_mark} Created Code Jam with {len(teams)} teams.")
Expand Down
7 changes: 4 additions & 3 deletions bot/exts/filters/token_remover.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from bot.bot import Bot
from bot.constants import Channels, Colours, Event, Icons
from bot.exts.moderation.modlog import ModLog
from bot.utils.members import get_or_fetch_member
from bot.utils.messages import format_user

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -99,7 +100,7 @@ async def take_action(self, msg: Message, found_token: Token) -> None:
await msg.channel.send(DELETION_MESSAGE_TEMPLATE.format(mention=msg.author.mention))

log_message = self.format_log_message(msg, found_token)
userid_message, mention_everyone = self.format_userid_log_message(msg, found_token)
userid_message, mention_everyone = await self.format_userid_log_message(msg, found_token)
log.debug(log_message)

# Send pretty mod log embed to mod-alerts
Expand All @@ -116,7 +117,7 @@ async def take_action(self, msg: Message, found_token: Token) -> None:
self.bot.stats.incr("tokens.removed_tokens")

@classmethod
def format_userid_log_message(cls, msg: Message, token: Token) -> t.Tuple[str, bool]:
async def format_userid_log_message(cls, msg: Message, token: Token) -> t.Tuple[str, bool]:
"""
Format the portion of the log message that includes details about the detected user ID.

Expand All @@ -128,7 +129,7 @@ def format_userid_log_message(cls, msg: Message, token: Token) -> t.Tuple[str, b
Returns a tuple of (log_message, mention_everyone)
"""
user_id = cls.extract_user_id(token.user_id)
user = msg.guild.get_member(user_id)
user = await get_or_fetch_member(msg.guild, user_id)

if user:
return KNOWN_USER_LOG_MESSAGE.format(
Expand Down
4 changes: 2 additions & 2 deletions bot/exts/help_channels/_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import bot
from bot import constants
from bot.exts.help_channels import _caches, _message
from bot.utils.channel import try_get_channel
from bot.utils.channel import get_or_fetch_channel

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -133,7 +133,7 @@ async def move_to_bottom(channel: discord.TextChannel, category_id: int, **optio
options should be avoided, as it may interfere with the category move we perform.
"""
# Get a fresh copy of the category from the bot to avoid the cache mismatch issue we had.
category = await try_get_channel(category_id)
category = await get_or_fetch_channel(category_id)

payload = [{"id": c.id, "position": c.position} for c in category.channels]

Expand Down
10 changes: 5 additions & 5 deletions bot/exts/help_channels/_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from bot.bot import Bot
from bot.constants import Channels, RedirectOutput
from bot.exts.help_channels import _caches, _channel, _message, _name, _stats
from bot.utils import channel as channel_utils, lock, scheduling
from bot.utils import channel as channel_utils, lock, members, scheduling

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -278,13 +278,13 @@ async def init_categories(self) -> None:
log.trace("Getting the CategoryChannel objects for the help categories.")

try:
self.available_category = await channel_utils.try_get_channel(
self.available_category = await channel_utils.get_or_fetch_channel(
constants.Categories.help_available
)
self.in_use_category = await channel_utils.try_get_channel(
self.in_use_category = await channel_utils.get_or_fetch_channel(
constants.Categories.help_in_use
)
self.dormant_category = await channel_utils.try_get_channel(
self.dormant_category = await channel_utils.get_or_fetch_channel(
constants.Categories.help_dormant
)
except discord.HTTPException:
Expand Down Expand Up @@ -434,7 +434,7 @@ async def _unclaim_channel(
await _caches.claimants.delete(channel.id)
await _caches.session_participants.delete(channel.id)

claimant = self.bot.get_guild(constants.Guild.id).get_member(claimant_id)
claimant = await members.get_or_fetch_member(self.bot.get_guild(constants.Guild.id), claimant_id)
if claimant is None:
log.info(f"{claimant_id} left the guild during their help session; the cooldown role won't be removed")
else:
Expand Down
9 changes: 5 additions & 4 deletions bot/exts/info/information.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
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.members import get_or_fetch_member
from bot.utils.time import TimestampFormats, discord_timestamp, humanize_delta

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -46,13 +47,13 @@ def get_channel_type_counts(guild: Guild) -> DefaultDict[str, int]:
@staticmethod
def join_role_stats(role_ids: list[int], guild: Guild, name: Optional[str] = None) -> dict[str, int]:
"""Return a dictionary with the number of `members` of each role given, and the `name` for this joined group."""
members = 0
member_count = 0
for role_id in role_ids:
if (role := guild.get_role(role_id)) is not None:
members += len(role.members)
member_count += len(role.members)
else:
raise NonExistentRoleError(role_id)
return {name or role.name.title(): members}
return {name or role.name.title(): member_count}

@staticmethod
def get_member_counts(guild: Guild) -> dict[str, int]:
Expand Down Expand Up @@ -244,7 +245,7 @@ async def user_info(self, ctx: Context, user_or_message: Union[MemberOrUser, Mes

async def create_user_embed(self, ctx: Context, user: MemberOrUser) -> Embed:
"""Creates an embed containing information on the `user`."""
on_server = bool(ctx.guild.get_member(user.id))
on_server = bool(await get_or_fetch_member(ctx.guild, user.id))

created = discord_timestamp(user.created_at, TimestampFormats.RELATIVE)

Expand Down
5 changes: 3 additions & 2 deletions bot/exts/moderation/infraction/infractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from bot.decorators import respect_role_hierarchy
from bot.exts.moderation.infraction import _utils
from bot.exts.moderation.infraction._scheduler import InfractionScheduler
from bot.utils.members import get_or_fetch_member
from bot.utils.messages import format_user

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -422,7 +423,7 @@ async def pardon_mute(
notify: bool = True
) -> t.Dict[str, str]:
"""Remove a user's muted role, optionally DM them a notification, and return a log dict."""
user = guild.get_member(user_id)
user = await get_or_fetch_member(guild, user_id)
log_text = {}

if user:
Expand Down Expand Up @@ -470,7 +471,7 @@ async def pardon_voice_ban(
notify: bool = True
) -> t.Dict[str, str]:
"""Optionally DM the user a pardon notification and return a log dict."""
user = guild.get_member(user_id)
user = await get_or_fetch_member(guild, user_id)
log_text = {}

if user:
Expand Down
3 changes: 2 additions & 1 deletion bot/exts/moderation/infraction/management.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from bot.pagination import LinePaginator
from bot.utils import messages, time
from bot.utils.channel import is_mod_channel
from bot.utils.members import get_or_fetch_member
from bot.utils.time import humanize_delta, until_expiration

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -190,7 +191,7 @@ async def infraction_edit(

# Get information about the infraction's user
user_id = new_infraction['user']
user = ctx.guild.get_member(user_id)
user = await get_or_fetch_member(ctx.guild, user_id)

if user:
user_text = messages.format_user(user)
Expand Down
3 changes: 2 additions & 1 deletion bot/exts/moderation/infraction/superstarify.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from bot.converters import Duration, Expiry
from bot.exts.moderation.infraction import _utils
from bot.exts.moderation.infraction._scheduler import InfractionScheduler
from bot.utils.members import get_or_fetch_member
from bot.utils.messages import format_user
from bot.utils.time import format_infraction

Expand Down Expand Up @@ -198,7 +199,7 @@ async def _pardon_action(self, infraction: _utils.Infraction, notify: bool) -> t
return

guild = self.bot.get_guild(constants.Guild.id)
user = guild.get_member(infraction["user"])
user = await get_or_fetch_member(guild, infraction["user"])

# Don't bother sending a notification if the user left the guild.
if not user:
Expand Down
23 changes: 9 additions & 14 deletions bot/exts/moderation/stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from bot.converters import Expiry
from bot.pagination import LinePaginator
from bot.utils import scheduling
from bot.utils.members import get_or_fetch_member
from bot.utils.time import discord_timestamp, format_infraction_with_duration

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -47,23 +48,17 @@ async def _reload_tasks_from_redis(self) -> None:
"""Reload outstanding tasks from redis on startup, delete the task if the member has since left the server."""
await self.bot.wait_until_guild_available()
items = await self.task_cache.items()
guild = self.bot.get_guild(Guild.id)
for key, value in items:
member = self.bot.get_guild(Guild.id).get_member(key)
member = await get_or_fetch_member(guild, key)

if not member:
Comment thread
ChrisLovering marked this conversation as resolved.
# Member isn't found in the cache
try:
member = await self.bot.get_guild(Guild.id).fetch_member(key)
except discord.errors.NotFound:
log.debug(
f"Member {key} left the guild before we could schedule "
"the revoking of their streaming permissions."
)
await self.task_cache.delete(key)
continue
except discord.HTTPException:
log.exception(f"Exception while trying to retrieve member {key} from Discord.")
continue
log.debug(
"User with ID %d left the guild before their streaming permissions could be revoked.",
key
)
await self.task_cache.delete(key)
continue

revoke_time = Arrow.utcfromtimestamp(value)
log.debug(f"Scheduling {member} ({member.id}) to have streaming permission revoked at {revoke_time}")
Expand Down
5 changes: 3 additions & 2 deletions bot/exts/moderation/watchchannels/_watchchannel.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from bot.exts.moderation.modlog import ModLog
from bot.pagination import LinePaginator
from bot.utils import CogABCMeta, messages, scheduling
from bot.utils.members import get_or_fetch_member
from bot.utils.time import get_time_delta

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -281,7 +282,7 @@ async def send_header(self, msg: Message) -> None:
user_id = msg.author.id

guild = self.bot.get_guild(GuildConfig.id)
actor = guild.get_member(self.watched_users[user_id]['actor'])
actor = await get_or_fetch_member(guild, self.watched_users[user_id]['actor'])
actor = actor.display_name if actor else self.watched_users[user_id]['actor']

inserted_at = self.watched_users[user_id]['inserted_at']
Expand Down Expand Up @@ -355,7 +356,7 @@ async def prepare_watched_users_data(

list_data["info"] = {}
for user_id, user_data in watched_iter:
member = ctx.guild.get_member(user_id)
member = await get_or_fetch_member(ctx.guild, user_id)
line = f"• `{user_id}`"
if member:
line += f" ({member.name}#{member.discriminator})"
Expand Down
9 changes: 5 additions & 4 deletions bot/exts/recruitment/talentpool/_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from bot.exts.recruitment.talentpool._review import Reviewer
from bot.pagination import LinePaginator
from bot.utils import scheduling, time
from bot.utils.members import get_or_fetch_member
from bot.utils.time import get_time_delta

AUTOREVIEW_ENABLED_KEY = "autoreview_enabled"
Expand Down Expand Up @@ -175,7 +176,7 @@ async def list_nominated_users(
lines = []

for user_id, user_data in nominations:
member = ctx.guild.get_member(user_id)
member = await get_or_fetch_member(ctx.guild, user_id)
line = f"• `{user_id}`"
if member:
line += f" ({member.name}#{member.discriminator})"
Expand Down Expand Up @@ -314,7 +315,7 @@ async def history_command(self, ctx: Context, user: MemberOrUser) -> None:
title=f"Nominations for {user.display_name} `({user.id})`",
color=Color.blue()
)
lines = [self._nomination_to_string(nomination) for nomination in result]
lines = [await self._nomination_to_string(nomination) for nomination in result]
await LinePaginator.paginate(
lines,
ctx=ctx,
Expand Down Expand Up @@ -495,13 +496,13 @@ async def end_nomination(self, user_id: int, reason: str) -> bool:

return True

def _nomination_to_string(self, nomination_object: dict) -> str:
async def _nomination_to_string(self, nomination_object: dict) -> str:
"""Creates a string representation of a nomination."""
guild = self.bot.get_guild(Guild.id)
entries = []
for site_entry in nomination_object["entries"]:
actor_id = site_entry["actor"]
actor = guild.get_member(actor_id)
actor = await get_or_fetch_member(guild, actor_id)

reason = site_entry["reason"] or "*None*"
created = time.format_infraction(site_entry["inserted_at"])
Expand Down
3 changes: 2 additions & 1 deletion bot/exts/recruitment/talentpool/_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from bot.api import ResponseCodeError
from bot.bot import Bot
from bot.constants import Channels, Colours, Emojis, Guild
from bot.utils.members import get_or_fetch_member
from bot.utils.messages import count_unique_users_reaction, pin_no_system_message
from bot.utils.scheduling import Scheduler
from bot.utils.time import get_time_delta, time_since
Expand Down Expand Up @@ -111,7 +112,7 @@ async def make_review(self, user_id: int) -> typing.Tuple[str, Optional[Emoji]]:
return "", None

guild = self.bot.get_guild(Guild.id)
member = guild.get_member(user_id)
member = await get_or_fetch_member(guild, user_id)

if not member:
return (
Expand Down
Loading