From 40175f67b755057d44516d705bdd03adc0ec6dae Mon Sep 17 00:00:00 2001 From: "charley.bignon" Date: Thu, 3 Dec 2026 12:17:45 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20/test=5Falert=20peut=20simuler=20un=20r?= =?UTF-8?q?=C3=A9cap=20de=20session?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Paramètre facultatif « alert » (Fin de partie / Récap de session) : le récap porte sur la dernière session du joueur, d'après ses 10 dernières parties chez Riot. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- cogs/commands.py | 38 +++++++++++++++++++++++++++++++++++--- docs/commandes.md | 8 +++++--- i18n.py | 4 ++++ sessions.py | 25 +++++++++++++++++++++++++ tests/test_commands.py | 35 +++++++++++++++++++++++++++++++++++ tests/test_prefix.py | 6 ++++++ 7 files changed, 111 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 26b352c..126d6cc 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ Puis, sur Discord : `/setup_channel` dans le salon des alertes, et `/add Faker T | `/goal` | `$goal set platinum IV 31/12` | Objectifs de rang : se fixer, voir (`show`), tout le serveur (`all`), abandonner (`remove`) | | `/setup_channel` 🔒 | `$setup_channel` | Choisir le salon des alertes | | `/language` 🔒 | `$language en` | Langue du bot sur le serveur | -| `/test_alert` 🔒 | `$test_alert Faker#T1` | Tester le rendu d'une alerte | +| `/test_alert` 🔒 | `$test_alert Faker#T1 session` | Tester le rendu d'une alerte (fin de partie ou récap de session) | 🔒 : réservé aux membres qui ont la permission « Gérer le serveur ». **Toutes** les commandes marchent avec `$`. diff --git a/cogs/commands.py b/cogs/commands.py index 43f97e0..d4d600b 100644 --- a/cogs/commands.py +++ b/cogs/commands.py @@ -17,6 +17,7 @@ from embeds.goals import build_goals_embed from embeds.leaderboard import build_week_embeds from embeds.match import build_match_embed +from embeds.session import build_session_embed from embeds.utils import COLOR_INFO from goals import ( DIVISIONS, @@ -33,7 +34,7 @@ total_lp, ) from i18n import LANGUAGES, format_day, plural, t -from leaderboard import TIMEZONE, Week +from leaderboard import COUNTED_QUEUES, TIMEZONE, Week from models import PlayerRef from ranks import APEX_TIERS, Rank, find_solo_queue from services import ( @@ -44,6 +45,7 @@ resolve_player, user_error_message, ) +from sessions import games_from_matches, split_sessions if TYPE_CHECKING: from bot import BotDiff @@ -53,6 +55,7 @@ logger = logging.getLogger("botdiff.commands") AUTOCOMPLETE_LIMIT = 25 # maximum imposé par Discord +TEST_SESSION_MATCHES = 10 # parties lues chez Riot pour /test_alert alert:Session recap # Textes des commandes : en anglais, traduits pour les clients Discord en français (i18n.CommandTranslator). RIOT_ID_DESC = _("Riot name of the player (e.g. Faker)") @@ -264,12 +267,30 @@ async def language(self, interaction: discord.Interaction, language: app_command name="test_alert", description=_("Simulate an end-of-game alert (to check how it looks)."), ) - @app_commands.describe(riot_id=RIOT_ID_DESC, tag=TAG_DESC) + @app_commands.rename(alerte=_("alert")) + @app_commands.describe( + riot_id=RIOT_ID_DESC, tag=TAG_DESC, alerte=_("Alert to simulate (end of game by default)") + ) + @app_commands.choices( + alerte=[ + app_commands.Choice(name=_("End of game"), value="game"), + app_commands.Choice(name=_("Session recap"), value="session"), + ] + ) @app_commands.default_permissions(manage_guild=True) - async def test_alert(self, interaction: discord.Interaction, riot_id: str, tag: str) -> None: + async def test_alert( + self, + interaction: discord.Interaction, + riot_id: str, + tag: str, + alerte: app_commands.Choice[str] | None = None, + ) -> None: lang = self.lang(interaction) await interaction.response.defer(thinking=True) player = await self._player(interaction, riot_id, tag) + if alerte is not None and alerte.value == "session": + await self._test_session(interaction, player, lang) + return match_ids = await self.bot.riot.recent_match_ids(player.puuid, 1, COMMAND_CACHE_S) if not match_ids: raise UserFacingError("no_recent_game", player=player.display) @@ -284,6 +305,17 @@ async def test_alert(self, interaction: discord.Interaction, riot_id: str, tag: view=view, ) + async def _test_session(self, interaction: discord.Interaction, player: PlayerRef, lang: str) -> None: + """Récap de la dernière session du joueur (même en cours), d'après ses parties chez Riot.""" + assert interaction.guild_id is not None + matches = await self.bot.riot.get_recent_matches(player.puuid, TEST_SESSION_MATCHES, COMMAND_CACHE_S) + sessions = split_sessions(games_from_matches(matches, player.puuid, COUNTED_QUEUES)) + if not sessions: + raise UserFacingError("no_recent_game", player=player.display) + tracked = TrackedPlayer(player.riot_id, player.tag, player.puuid, interaction.guild_id, None) + embed = build_session_embed(tracked, sessions[-1], lang, self.bot.variants) + await interaction.followup.send(embed=embed) + # ── Consultation ──────────────────────────────────────── @app_commands.guild_only() @app_commands.command(name="history", description=_("Show a player's last 5 games.")) diff --git a/docs/commandes.md b/docs/commandes.md index f39b1c5..c02cd09 100644 --- a/docs/commandes.md +++ b/docs/commandes.md @@ -22,7 +22,7 @@ Les deux font exactement la même chose, avec les mêmes réponses. **Toutes** l | `/goal` | `$goal set gold II` | Objectifs de rang : se fixer, voir, tout le serveur, abandonner | voir [Objectifs de rang](#objectifs-de-rang) | | `/setup_channel` | `$setup_channel` | Choisir le salon des alertes | gestionnaires | | `/language` | `$language en` | Langue du bot sur le serveur | gestionnaires | -| `/test_alert` | `$test_alert Faker#T1` | Tester le rendu d'une alerte | gestionnaires | +| `/test_alert` | `$test_alert Faker#T1 session` | Tester le rendu d'une alerte (fin de partie ou récap de session) | gestionnaires | « Gestionnaires » : membres qui ont la permission **Gérer le serveur**. Pour les commandes slash, ces permissions se changent dans *Paramètres du serveur → Intégrations → BotDiff* ; les commandes `$` vérifient toujours « Gérer le serveur ». @@ -231,8 +231,10 @@ Passe tous les messages du bot en anglais ou en français, pour tout le serveur ### `/test_alert` — tester une alerte ``` -/test_alert riot_id:Faker tag:T1 +/test_alert riot_id:Faker tag:T1 [alert:Fin de partie|Récap de session] $test_alert Faker#T1 +$test_alert Faker#T1 session ``` -Poste l'alerte de la dernière partie du joueur, comme si elle venait de se terminer, pour voir le rendu. Ne compte pas dans le classement. +- **Fin de partie** (par défaut) : poste l'alerte de la dernière partie du joueur, comme si elle venait de se terminer. Ne compte pas dans le classement. +- **Récap de session** : poste le récap de la dernière session du joueur, d'après ses 10 dernières parties chez Riot, même si elle n'est pas finie. Sans les LP (le bot ne les connaît que pour les parties qu'il a suivies), et sans rien changer au vrai récap. diff --git a/i18n.py b/i18n.py index 21a24a6..5429f6e 100644 --- a/i18n.py +++ b/i18n.py @@ -1037,6 +1037,10 @@ def format_day(lang: str, d: date) -> str: "Simulate an end-of-game alert (to check how it looks).": ( "Simuler une alerte de fin de partie (pour tester le rendu)." ), + "alert": "alerte", + "Alert to simulate (end of game by default)": "Alerte à simuler (fin de partie par défaut)", + "End of game": "Fin de partie", + "Session recap": "Récap de session", "Show a player's last 5 games.": "Afficher les 5 dernières parties d'un joueur.", "Show a player's full profile and stats.": "Afficher le profil complet et les statistiques d'un joueur.", "Change the bot's language on this server.": "Changer la langue du bot sur ce serveur.", diff --git a/sessions.py b/sessions.py index c1e08c2..34834d0 100644 --- a/sessions.py +++ b/sessions.py @@ -12,8 +12,11 @@ from __future__ import annotations from collections import Counter +from collections.abc import Container from dataclasses import dataclass +from models import Match + SESSION_GAP = 2 * 60 * 60 # 2 h sans partie : la session est finie MIN_GAMES = 1 # en dessous, pas de récap MAX_AGE = 12 * 60 * 60 # session finie depuis plus longtemps (bot arrêté) : pas de récap @@ -175,3 +178,25 @@ def finished_sessions(games: list[SessionGame], now: float) -> list[Session]: def worth_a_recap(session: Session, now: float) -> bool: return session.count >= MIN_GAMES and now - session.ended_at <= MAX_AGE + + +def games_from_matches(matches: list[Match], puuid: str, counted_queues: Container[int]) -> list[SessionGame]: + """Parties d'un joueur reconstruites à partir des matchs Riot (pour /test_alert), sans les LP.""" + games = [] + for match in matches: + p = match.participant(puuid) + if p is None or match.ended_at is None or match.queue_id not in counted_queues or match.is_remake(p): + continue + games.append( + SessionGame( + match_id=match.match_id, + win=p.win, + ended_at=match.ended_at, + duration=match.duration, + champion=p.champion, + kills=p.kills, + deaths=p.deaths, + assists=p.assists, + ) + ) + return games diff --git a/tests/test_commands.py b/tests/test_commands.py index e6130f4..2f649ad 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -3,6 +3,7 @@ from __future__ import annotations import discord +from discord import app_commands from cogs.commands import CommandsCog from riot_api import RiotAPIError @@ -16,6 +17,8 @@ embeds_of, files_of, invoke, + make_match, + make_participant, variants_of, ) @@ -193,6 +196,38 @@ async def test_test_alert(bot, cmds, riot) -> None: assert button_labels(msg["view"]) == ["Profil", "Détails", "DPM.LOL"] +async def test_test_alert_recap_de_session(bot, cmds, riot, monkeypatch) -> None: + """Dernière session d'après les parties Riot : l'ARAM et la vieille partie n'en font pas partie.""" + import tests.conftest as conftest + + end = 1_800_000_000_000 # millisecondes, comme chez Riot + games = { + "EUW1_501": (True, end - 5 * 3600_000, 420), # plus de 2 h de pause avant la suivante : autre session + "EUW1_502": (True, end - 70 * 60_000, 420), + "EUW1_503": (True, end - 35 * 60_000, 450), # ARAM : ignorée + "EUW1_504": (False, end - 35 * 60_000, 440), + "EUW1_505": (False, end, 420), + } + matches = dict(conftest.MATCHES) + for match_id, (win, ended, queue) in games.items(): + data = make_match(match_id, [make_participant(PA, 100, win, "Yasuo")], queue=queue) + data["info"]["gameEndTimestamp"] = ended + matches[match_id] = data + monkeypatch.setattr(conftest, "MATCHES", matches) + riot.match_ids[PA] = sorted(games, reverse=True) + + it = FakeInteraction(bot) + await invoke( + cmds, cmds.test_alert, it, "Alice", "EUW", app_commands.Choice(name="Session recap", value="session") + ) + embed = embeds_of(it.sent[0])[0] + assert embed.title == "🌙 Fin de session pour Alice#EUW" + assert embed.description.split("\n")[0] in variants_of( + "session_bad", player="Alice#EUW", wins=1, losses=2 + ) + assert "✅❌❌" in embed.description and "LP" not in embed.description + + def test_permissions() -> None: admin = discord.Permissions(manage_guild=True) commands = {c.name: c for c in CommandsCog.__cog_app_commands__} diff --git a/tests/test_prefix.py b/tests/test_prefix.py index 5b9f131..4342d7c 100644 --- a/tests/test_prefix.py +++ b/tests/test_prefix.py @@ -164,3 +164,9 @@ async def test_sous_commandes_goal(prefix, db) -> None: (reply,) = await send(prefix, "$goal all") assert reply["content"].startswith("🎯 Aucun objectif") + + +async def test_test_alert_session_en_prefixe(prefix, riot) -> None: + riot.match_ids[PA] = ["EUW1_100"] # partie sans horodatage : pas de session + (reply,) = await send(prefix, "$test_alert Alice#EUW session", author=member(USER_ID, manage_guild=True)) + assert reply["content"] == "❌ Aucune partie récente pour **Alice#EUW**."