Skip to content

Commit

Permalink
optimized role adding and removing
Browse files Browse the repository at this point in the history
  • Loading branch information
99oblivius committed Jul 22, 2024
1 parent 4a78716 commit b2438ab
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 20 deletions.
34 changes: 19 additions & 15 deletions src/matches/match.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ async def finalize_match(self, players_dict, users_match_stats, users_summary_da
return

ranks = await self.bot.store.get_ranks(self.guild_id)
rank_ids = set(r.role_id for r in ranks)
rank_ids = { r.role_id for r in ranks }

for player in self.players:
user_id = player.user_id
Expand All @@ -221,22 +221,26 @@ async def finalize_match(self, players_dict, users_match_stats, users_summary_da
current_stats.update({"win": win, "mmr_change": mmr_change, "ping": ping})

summary_data = users_summary_data[user_id]
new_mmr = summary_data.mmr + current_stats['mmr_change']

new_rank_role = get_rank_role(guild, ranks, summary_data.mmr + current_stats['mmr_change'])
member = guild.get_member(user_id)
current_rank_roles = set(role for role in member.roles if role.id in rank_ids)
if current_rank_roles != {new_rank_role}:
roles_to_remove = current_rank_roles - {new_rank_role}
roles_to_add = {new_rank_role} - current_rank_roles

if roles_to_remove:
asyncio.create_task(member.remove_roles(*roles_to_remove, reason="Updating MMR rank"))
log.info(f"{roles_to_add} role(s) removed from {member.display_name}")

if roles_to_add:
asyncio.create_task(member.add_roles(*roles_to_add, reason="Updating MMR rank"))
log.info(f"{roles_to_add} role(s) added to {member.display_name}")
new_rank_id = next((r.role_id for r in sorted(ranks, key=lambda x: x.mmr_threshold, reverse=True) if new_mmr >= r.mmr_threshold), None)

member = guild.get_member(user_id)
if member:
current_rank_role_ids = set(role.id for role in member.roles if role.id in rank_ids)

if new_rank_id not in current_rank_role_ids:

roles_to_remove = [guild.get_role(role_id) for role_id in current_rank_role_ids]
roles_to_remove = [role for role in roles_to_remove if role is not None]
if roles_to_remove:
asyncio.create_task(member.remove_roles(*roles_to_remove, reason="Updating MMR rank"))
log.info(f"Roles {', '.join(role.name for role in roles_to_remove)} removed from {member.display_name}")

new_role = guild.get_role(new_rank_id)
if new_role:
asyncio.create_task(member.add_roles(new_role, reason="Updating MMR rank"))
log.info(f"Role {new_role.name} added to {member.display_name}")

users_summary_stats[user_id] = self.update_summary_stats(summary_data, current_stats)
final_updates[user_id] = current_stats
Expand Down
6 changes: 3 additions & 3 deletions src/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import uuid
from datetime import datetime, timedelta, timezone
from functools import partial
from typing import List
from typing import List, Tuple
import asyncio
import base64
import re
Expand All @@ -28,7 +28,7 @@
from PIL import Image, ImageDraw, ImageFont
import aiohttp

from nextcord import Embed, Guild
from nextcord import Embed, Guild, Role

from config import VALORS_THEME1
from utils.models import MMBotMatchPlayers, MMBotRanks, MMBotMatches, MMBotUserMatchStats, Side, MMBotQueueUsers
Expand Down Expand Up @@ -85,7 +85,7 @@ def abandon_cooldown(count: int, last_abandon: datetime | None=None) -> int:
cooldown_seconds = (cooldown_end - datetime.now(timezone.utc)).total_seconds()
return max(0, int(cooldown_seconds))

def get_rank_role(guild: Guild, ranks: List[MMBotRanks], mmr: int):
def get_rank_role(guild: Guild, ranks: List[MMBotRanks], mmr: int) -> Role:
ranks = sorted([(r.mmr_threshold, guild.get_role(r.role_id)) for r in ranks], key=lambda x: x[0])
return next((role for threshold, role in reversed(ranks) if mmr > threshold), None)

Expand Down
2 changes: 1 addition & 1 deletion src/views/match/banning.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ async def ban_callback(self, button: nextcord.ui.Button, interaction: nextcord.I
return await interaction.response.send_message("This button is no longer in use", ephemeral=True)
# what button
maps = await self.bot.store.get_maps(interaction.guild.id)
maps = [m for m in maps if m[0] != self.last_played_map]
maps = [m for m in maps if m.map != self.last_played_map]
settings = await self.bot.store.get_settings(interaction.guild.id)
ban_maps = shifted_window([m.map for m in maps], settings.mm_maps_phase, settings.mm_maps_range)

Expand Down
2 changes: 1 addition & 1 deletion src/views/match/map_pick.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ async def pick_callback(self, button: nextcord.ui.Button, interaction: nextcord.
return await interaction.response.send_message("This button is no longer in use", ephemeral=True)
# what button
maps = await self.bot.store.get_maps(interaction.guild.id)
maps = [m for m in maps if m[0] != self.last_played_map]
maps = [m for m in maps if m.map != self.last_played_map]
settings = await self.bot.store.get_settings(interaction.guild.id)
pick_maps = shifted_window([m.map for m in maps], settings.mm_maps_phase, settings.mm_maps_range)
slot_id = int(button.custom_id.split(':')[-1])
Expand Down

0 comments on commit b2438ab

Please sign in to comment.