Skip to content
Open
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
21 changes: 11 additions & 10 deletions src/study_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ def setup(bot: discord.Client, config):
join_history: dict[int, list[datetime]] = defaultdict(list)
short_stay_history: dict[int, list[datetime]] = defaultdict(list)
user_joined_at: dict[int, datetime] = {}
study_time_role = None


@tasks.loop(seconds=cleanup_interval_s)
Expand Down Expand Up @@ -150,6 +151,8 @@ async def cleanup_stale_history():


async def on_ready(bot: discord.Client):
nonlocal study_time_role

if not cleanup_stale_history.is_running():
cleanup_stale_history.start()

Expand Down Expand Up @@ -199,14 +202,12 @@ async def on_voice_state_update(
before: discord.VoiceState,
after: discord.VoiceState,
):
await bot.wait_until_ready()

target_role = discord.utils.get(member.guild.roles, name=role_name)
if not target_role:
await send_channel_message(bot, moderation_channel_id, f'[ERROR] Unable to locate role "{role_name}" through member context')
return
if not study_time_role:
raise RuntimeError('Study Time Role is missing. Initialization failed')

now = datetime.now(timezone.utc)
await bot.wait_until_ready()

new_channel_id = after.channel.id if after.channel else None
old_channel_id = before.channel.id if before.channel else None
is_joined = new_channel_id == vc_channel_id and old_channel_id != vc_channel_id
Expand Down Expand Up @@ -256,9 +257,9 @@ async def on_voice_state_update(

user_joined_at[member.id] = now
try:
await member.add_roles(target_role)
await member.add_roles(study_time_role)
except Exception as e:
await send_channel_message(bot, moderation_channel_id, f"[ERROR] Failed to add role {target_role.name} to {member.name} ({member.id}): {e}")
await send_channel_message(bot, moderation_channel_id, f"[ERROR] Failed to add role {study_time_role.name} to {member.name} ({member.id}): {e}")

elif is_left:
# Record short stay if applicable
Expand All @@ -271,9 +272,9 @@ async def on_voice_state_update(
short_stay_history[member.id].append(now)

try:
await member.remove_roles(target_role)
await member.remove_roles(study_time_role)
except Exception as e:
await send_channel_message(bot, moderation_channel_id, f"[ERROR] Failed to remove role ${target_role.name} from {member.name} ({member.id}): {e}")
await send_channel_message(bot, moderation_channel_id, f"[ERROR] Failed to remove role ${study_time_role.name} from {member.name} ({member.id}): {e}")
except Exception as error:
await send_channel_message(bot, moderation_channel_id, f"[ERROR] An error occurred while processing role change: {error}")

Expand Down