Skip to content

Commit

Permalink
improved force abandon view and added all necessary functionalities +…
Browse files Browse the repository at this point in the history
… fixed lack of mmr change in add abandon db method
  • Loading branch information
99oblivius committed Sep 21, 2024
1 parent 87cf214 commit e9c668b
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 21 deletions.
4 changes: 2 additions & 2 deletions src/cogs/matches/cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,8 @@ async def mm_abandon(self, interaction: nextcord.Interaction):
title="Abandon",
description=f"""Are you certain you want to abandon this match?
_You abandoned a total of `{previous_abandons}` times in the last 2 months._
_You will have a cooldown of `{format_duration(cooldown)}` and lose `{mmr_loss}` mmr_""")
await interaction.response.send_message(embed=embed, view=AbandonView(self.bot, match), ephemeral=True)
_You will have a cooldown of `{format_duration(cooldown)}` and lose `{mmr_loss[1:]}` mmr_""")
await interaction.response.send_message(embed=embed, view=AbandonView(self.bot, match, mmr_loss), ephemeral=True)

@nextcord.slash_command(name="last_match", description="Display stats from the last match", guild_ids=[GUILD_ID])
async def display_last_match(self, interaction: nextcord.Interaction):
Expand Down
41 changes: 32 additions & 9 deletions src/utils/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from typing import Any, Callable, Dict, List, Tuple
import random

from sqlalchemy import delete, desc, func, inspect, or_, text, update
from sqlalchemy import delete, desc, func, inspect, or_, text, update, case, bindparam
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, create_async_engine
from sqlalchemy.ext.declarative import DeclarativeMeta
Expand Down Expand Up @@ -739,23 +739,46 @@ async def get_abandon_count_last_period(self, guild_id: int, user_id: int, perio
return count, last_abandon

@log_db_operation
async def add_match_abandons(self, guild_id: int, match_id: int, abandoned_user_ids: List[int]) -> None:
async def add_match_abandons(self, guild_id: int, match_id: int, abandoned_user_ids: List[int], mmr_losses: List[int]) -> None:
if len(abandoned_user_ids) != len(mmr_losses):
raise ValueError("Length of abandoned_user_ids must match length of mmr_losses")

async with self._session_maker() as session:
async with session.begin():
abandons = [
{
'guild_id': guild_id,
'user_id': user_id,
'match_id': match_id,
}
for user_id in abandoned_user_ids
'guild_id': guild_id,
'user_id': user_id,
'match_id': match_id
} for user_id in abandoned_user_ids
]
await session.execute(insert(MMBotUserAbandons).values(abandons))

mmr_updates = [
{'user_id': uid, 'mmr_change': mmr_loss}
for uid, mmr_loss in zip(abandoned_user_ids, mmr_losses)
]
await session.execute(
update(MMBotUserMatchStats)
.where(MMBotUserMatchStats.match_id == match_id)
.values(abandoned=True))
await session.commit()
.values(
abandoned=True,
mmr_change=case(
*((
MMBotUserMatchStats.user_id == update['user_id'],
update['mmr_change']
) for update in mmr_updates),
else_=MMBotUserMatchStats.mmr_change)))

await session.execute(
update(MMBotUserSummaryStats)
.where(MMBotUserSummaryStats.user_id.in_(abandoned_user_ids))
.values(mmr=case(
*((
MMBotUserSummaryStats.user_id == update['user_id'],
MMBotUserSummaryStats.mmr + update['mmr_change']
) for update in mmr_updates),
else_=MMBotUserSummaryStats.mmr)))

#########
# QUEUE #
Expand Down
5 changes: 3 additions & 2 deletions src/views/match/abandon.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,12 @@


class AbandonView(nextcord.ui.View):
def __init__(self, bot, match=None, *args, **kwargs):
def __init__(self, bot, match=None, mmr_loss=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.bot = bot
self.timeout = None
self.match = match
self.mmr_loss = mmr_loss

@nextcord.ui.button(
label="Yes",
Expand All @@ -46,7 +47,7 @@ async def abandon(self, button: nextcord.ui.Button, interaction: nextcord.Integr
return await interaction.followup.send("Something went wrong. Try again...", ephemeral=True)

log.info(f"{interaction.user.display_name} abandoned match {self.match.id}")
await self.bot.store.add_match_abandons(interaction.guild.id, self.match.id, [interaction.user.id])
await self.bot.store.add_match_abandons(interaction.guild.id, self.match.id, [interaction.user.id], [self.mmr_loss])
await interaction.guild.get_channel(self.match.match_thread).send(f"@here Match Abandoned by {interaction.user.mention}")

settings = await self.bot.store.get_settings(interaction.guild.id)
Expand Down
41 changes: 33 additions & 8 deletions src/views/match/force_abandon.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
import asyncio
import nextcord

from matches.functions import calculate_mmr_change
from config import PLACEMENT_MATCHES
from utils.utils import abandon_cooldown, format_duration
from utils.logger import Logger as log
from utils.models import *

Expand Down Expand Up @@ -59,25 +62,47 @@ async def force_abandon(self, button: nextcord.ui.Button, interaction: nextcord.
async def confirm_callback(interaction: nextcord.Integration):
async with self.abandon_lock:
if not self.abandoned:
loop = asyncio.get_event_loop()
await interaction.response.defer(ephemeral=True)

from matches import cleanup_match
if not await cleanup_match(loop, self.match.id):
if not await cleanup_match(asyncio.get_event_loop(), self.match.id):
log.error(f"{interaction.user.display_name} had an issue force abandoning match {self.match.id}")
return await interaction.followup.send("Something went wrong. Try again...", ephemeral=True)

missing_str = ', '.join((p.user_id for p in self.missing_players))
log.info(f"{interaction.user.display_name} abandoned forcefully match {self.match.id} due to lates: {missing_str}")
mmr_losses = []
for player in self.missing_players:
played_games = await self.bot.store.get_user_played_games(interaction.user.id, player.user_id)
previous_abandons, _ = await self.bot.store.get_abandon_count_last_period(interaction.guild.id, player.user_id)
cooldown = abandon_cooldown(previous_abandons + 1)

ally_mmr = self.match.a_mmr if player.team == Team.A else self.match.b_mmr
enemy_mmr = self.match.b_mmr if player.team == Team.A else self.match.a_mmr

mmr_change = calculate_mmr_change(
{},
abandoned=True,
ally_team_avg_mmr=ally_mmr,
enemy_team_avg_mmr=enemy_mmr,
placements=played_games[player.user_id] <= PLACEMENT_MATCHES)
mmr_losses.append(mmr_change)
abandons_str = f"`{previous_abandons + 1}` abandon{'s' if previous_abandons != 0 else ''}"
embed = nextcord.Embed(
title=f"You were abandoned for being late to Match #{self.match.id}",
description=f"You lost `{mmr_change}` and gained a cooldown of `{format_duration(cooldown)}` due to {abandons_str} in the past 2 months.",
color=0xff0000)
asyncio.create_task(self.bot.get_user(player.user_id).send(embed=embed))

await interaction.response.defer(ephemeral=True)

missing_mentions = ', '.join((f'<@{p.user_id}>' for p in self.missing_players))
log.info(f"{interaction.user.display_name} abandoned forcefully match {self.match.id} due to lates: {missing_mentions}")

await self.bot.store.add_match_abandons(interaction.guild.id, self.match.id, [p.user_id for p in self.missing_players])
await self.bot.store.add_match_abandons(interaction.guild.id, self.match.id, [p.user_id for p in self.missing_players], mmr_losses)
await interaction.guild.get_channel(self.match.match_thread).send(f"@here Match Abandoned by Staff")

log_channel = interaction.guild.get_channel(settings.mm_log_channel)
try:
log_message = await log_channel.fetch_message(self.match.log_message)
embed = log_message.embeds[0]
embed.description = f"Match abandoned by Staff ({interaction.user.mention})"
embed.description = f"Match abandoned due to {missing_mentions} being late"
await log_message.edit(embed=embed)
except Exception: pass
await interaction.followup.send("You successfully force abandoned the match", ephemeral=True)
Expand Down

0 comments on commit e9c668b

Please sign in to comment.