brackt/app/services/discord.ts
Chris Parsons 5d0363a309
All checks were successful
🚀 Deploy / 🧪 Test (pull_request) Successful in 2m58s
🚀 Deploy / ʦ🔍 Typecheck & Lint (pull_request) Successful in 1m19s
🚀 Deploy / 🐳 Build (pull_request) Has been skipped
🚀 Deploy / 🚀 Deploy (pull_request) Has been skipped
🚀 Deploy / 🧪 Test (push) Successful in 2m53s
🚀 Deploy / ʦ🔍 Typecheck & Lint (push) Successful in 1m23s
🚀 Deploy / 🐳 Build (push) Successful in 1m8s
🚀 Deploy / 🚀 Deploy (push) Successful in 12s
Fix qualifying-points notifications: full-field scoreboard + manual-set announcements
The QP Discord embed's two "scoreboard" sections now reflect the whole drafted
field instead of only participants whose QP changed this sync:

- Non-scoring / Top 8 draw from a new per-league `scoreboard` (all drafted
  participants), scoped to the sports season being announced so a golf pick can't
  leak into a tennis event. Points Awarded / Knocked Out stay scoped to the sync's
  changes and remain the only pinged sections.
- Non-scoring is now a single compact "Name (points, manager)" line below Top 8,
  covering everyone not in the top 8 (the exact complement of the Top 8 filter).
- Top 8 requires qpTotal > 0 as well as rank <= 8, so early-season winless players
  tied into a low rank band no longer flood the section with "T5. Name — 0 QP".

Manually setting a bracket match result (e.g. a Wimbledon semifinal) now announces
the QP update. The set-winner / set-round-winners / complete-round paths route
through processQualifyingEvent (which snapshots, diffs, and notifies) instead of
processQualifyingBracketEvent (which scored silently). The tournament fan-out still
skips the primary window via skipEventId, so mirror windows aren't double-posted.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 10:04:22 -07:00

549 lines
19 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { buildTiedRankChecker } from "~/lib/standings-display";
interface DiscordEmbed {
title?: string;
url?: string;
description?: string;
color?: number;
footer?: { text: string };
}
interface DiscordWebhookPayload {
content?: string;
embeds?: DiscordEmbed[];
allowed_mentions?: { parse: string[]; users: string[] };
}
// Per-league serial promise chain: serializes pick notifications within a league to
// respect Discord's per-webhook rate limit (~5 req/2s) during autodraft chains.
const leagueChains = new Map<string, Promise<void>>();
export function enqueuePickNotification(leagueId: string, fn: () => Promise<void>): void {
const prev = leagueChains.get(leagueId) ?? Promise.resolve();
const next = prev.then(() => fn().catch(() => {}));
leagueChains.set(leagueId, next);
// Clean up the map entry once the chain settles, but only if no newer pick
// was enqueued after this one (reference equality guards against that race).
next.then(() => { if (leagueChains.get(leagueId) === next) leagueChains.delete(leagueId); });
}
export async function sendDiscordWebhook(
webhookUrl: string,
payload: DiscordWebhookPayload
): Promise<void> {
const body = JSON.stringify(payload);
const headers = { "Content-Type": "application/json" };
for (let attempt = 0; attempt < 3; attempt++) {
const res = await fetch(webhookUrl, { method: "POST", headers, body });
if (res.status === 429) {
// Cap the total wait at 10 s so awaited callers (e.g. settings actions) are
// never hung for a full Discord global-rate-limit window. Use || 1 instead of
// ?? 1 so NaN (non-numeric header) and 0 both fall back to a 1-second default.
// Multiply by (attempt + 1) for progressive backoff, then cap the product.
const wait = Math.min((Number(res.headers.get("Retry-After")) || 1) * (attempt + 1), 10);
await new Promise((r) => setTimeout(r, wait * 1000));
continue;
}
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`Discord webhook failed: ${res.status} ${text}`);
}
return;
}
throw new Error("Discord webhook failed after 3 retries (rate limited)");
}
/** Escape characters that trigger Discord markdown formatting. */
function escapeMarkdown(text: string): string {
return text.replace(/[_*~`|\\]/g, "\\$&");
}
/**
* Format a QP value for display. QP is genuinely fractional (e.g. a tennis R16 loser
* earns 1.5 QP from the 916 split), so we must NOT round: show whole numbers plainly
* and fractional values to at most 2 decimals with trailing zeros trimmed (1.50→1.5).
* Mirrors the web UI's formatQP (app/components/scoring/QualifyingPointsStandings.tsx)
* so Discord and the site agree.
*/
function formatQPValue(n: number): string {
return parseFloat(n.toFixed(2)).toString();
}
export interface StandingEntry {
teamId: string;
teamName: string;
username?: string;
discordUserId?: string;
totalPoints: number;
rank: number;
}
export interface ScoredMatch {
winnerName: string;
loserName: string;
winnerUsername?: string;
loserUsername?: string;
winnerDiscordUserId?: string;
loserDiscordUserId?: string;
}
export interface EliminatedTeam {
participantName: string;
username?: string;
discordUserId?: string;
}
export async function sendStandingsUpdateNotification({
webhookUrl,
seasonName,
standings,
previousStandings,
previousRanks,
sportName,
eventName,
scoredMatches,
eliminatedTeams,
}: {
webhookUrl: string;
seasonName: string;
standings: StandingEntry[];
previousStandings: Map<string, number>;
previousRanks?: Map<string, number>;
sportName?: string;
eventName?: string;
scoredMatches?: ScoredMatch[];
eliminatedTeams?: EliminatedTeam[];
}): Promise<void> {
const sections: string[] = [];
// Header: "Sport Name — Event Name"
if (sportName || eventName) {
const parts = [sportName, eventName].filter(Boolean);
sections.push(`**${parts.join(" — ")}**`);
}
// Scored matches section — only show matches where at least one manager
// (fantasy team owner) scored Brackt points or had a team eliminated.
const relevantMatches = scoredMatches?.filter(
(m) => m.winnerUsername !== undefined || m.loserUsername !== undefined
);
if (relevantMatches && relevantMatches.length > 0) {
sections.push("\n**Scored Matches**");
for (const match of relevantMatches) {
const winnerManagerLabel = match.winnerDiscordUserId
? `<@${match.winnerDiscordUserId}>`
: match.winnerUsername
? escapeMarkdown(match.winnerUsername)
: undefined;
const loserManagerLabel = match.loserDiscordUserId
? `<@${match.loserDiscordUserId}>`
: match.loserUsername
? escapeMarkdown(match.loserUsername)
: undefined;
const winnerLabel = winnerManagerLabel
? `${escapeMarkdown(match.winnerName)} (${winnerManagerLabel})`
: escapeMarkdown(match.winnerName);
const loserLabel = loserManagerLabel
? `${escapeMarkdown(match.loserName)} (${loserManagerLabel})`
: escapeMarkdown(match.loserName);
sections.push(`• **${winnerLabel}** def. ${loserLabel}`);
}
}
// Eliminated teams section — drafted teams knocked out when a bracket/knockout
// was generated (e.g. NBA teams that missed the playoffs, FIFA group-stage
// losers). These produce no score change, so they wouldn't appear above.
if (eliminatedTeams && eliminatedTeams.length > 0) {
sections.push("\n**Eliminated**");
for (const team of eliminatedTeams) {
const managerLabel = team.discordUserId
? `<@${team.discordUserId}>`
: team.username
? escapeMarkdown(team.username)
: undefined;
const label = managerLabel
? `${escapeMarkdown(team.participantName)} (${managerLabel})`
: escapeMarkdown(team.participantName);
sections.push(`• **${label}**`);
}
}
const isTied = buildTiedRankChecker(standings.map((s) => s.rank));
const rankLabel = (rank: number) => (isTied(rank) ? `T${rank}` : `${rank}`);
// A team's points genuinely changed this event (vs. merely being displaced in
// rank because someone else scored). Only real scorers are pinged; rank-only
// shufflers are still displayed, but by name and without an @-mention.
const pointsChanged = (s: StandingEntry) => {
const prevPoints = previousStandings.get(s.teamId);
return prevPoints !== undefined && prevPoints !== s.totalPoints;
};
// Standings changes section — show teams whose points or rank changed.
const changedTeams = standings.filter((s) => {
const prevRank = previousRanks?.get(s.teamId);
const rankChanged = prevRank !== undefined && prevRank !== s.rank;
return pointsChanged(s) || rankChanged;
});
if (changedTeams.length > 0) {
sections.push("\n**Standings Changes**");
for (const s of changedTeams) {
const rankPrefix = rankLabel(s.rank);
const prevPoints = previousStandings.get(s.teamId);
let pointDelta = "";
if (prevPoints !== undefined && prevPoints !== s.totalPoints) {
const diff = Math.round(s.totalPoints - prevPoints);
const sign = diff > 0 ? "+" : "";
pointDelta = ` **(${sign}${diff} pts)**`;
}
let rankDelta = "";
if (previousRanks) {
const prevRank = previousRanks.get(s.teamId);
if (prevRank !== undefined && prevRank !== s.rank) {
const moved = prevRank - s.rank; // positive = moved up
rankDelta = moved > 0 ? `${moved}` : `${Math.abs(moved)}`;
}
}
const escapedName = escapeMarkdown(s.teamName);
const managerLabel = s.discordUserId && pointsChanged(s)
? `<@${s.discordUserId}>`
: s.username
? escapeMarkdown(s.username)
: undefined;
const label = managerLabel ? `${escapedName} (${managerLabel})` : escapedName;
sections.push(`${rankPrefix}\\. ${label}${Math.round(s.totalPoints)} pts${pointDelta}${rankDelta}`);
}
}
const MAX_DESCRIPTION = 4096;
let description = sections.join("\n");
if (description.length > MAX_DESCRIPTION) {
description = description.slice(0, MAX_DESCRIPTION - 3) + "...";
}
// Collect Discord user IDs of all opted-in managers appearing in this notification.
const pingUserIds = new Set<string>();
for (const s of changedTeams) {
if (s.discordUserId && pointsChanged(s)) pingUserIds.add(s.discordUserId);
}
for (const m of relevantMatches ?? []) {
if (m.winnerDiscordUserId) pingUserIds.add(m.winnerDiscordUserId);
if (m.loserDiscordUserId) pingUserIds.add(m.loserDiscordUserId);
}
for (const t of eliminatedTeams ?? []) {
if (t.discordUserId) pingUserIds.add(t.discordUserId);
}
const pingIds = [...pingUserIds];
const payload: DiscordWebhookPayload = {
embeds: [
{
title: `📊 Standings Update — ${seasonName}`,
description,
color: 0xffd700, // Gold
footer: { text: "brackt.com" },
},
],
};
if (pingIds.length > 0) {
// Discord caps allowed_mentions.users at 100; slice to avoid a rejected payload.
const cappedIds = pingIds.slice(0, 100);
payload.content = cappedIds.map((id) => `<@${id}>`).join(" ");
payload.allowed_mentions = { parse: [], users: cappedIds };
}
await sendDiscordWebhook(webhookUrl, payload);
}
export interface QPEventEntry {
participantName: string;
qpEarned: number;
qpTotal: number;
/**
* The participant's rank in the FULL season QP standings (all participants), not
* their position among this event's scorers. Computed by the caller so the "QP
* Standings" block reflects the whole sport season — e.g. two R16 losers on 1.5 QP
* show as T9 (8 players ahead) rather than T1 among just the two of them.
*/
globalRank: number;
/** True when another participant in the full field shares this globalRank. */
globalRankTied: boolean;
ownerUsername?: string;
ownerDiscordUserId?: string;
}
/** A drafted player knocked out this sync in a non-scoring round (0 QP). */
export interface QPEliminatedEntry {
participantName: string;
ownerUsername?: string;
ownerDiscordUserId?: string;
}
/**
* Whether a scoreboard entry belongs in the "Drafted Participants in Top 8" section.
* Requires the participant to have actually scored (qpTotal > 0) AND sit in the top 8
* of the full season standings. The qpTotal>0 guard matters early in a season: when
* fewer than 8 players have scored, standard competition ranking ties every 0-QP player
* into a rank <= 8 band (e.g. everyone winless is "T5"), and a rank-only filter would
* flood the section with "T5. Name — 0 QP" rows. Rank ties among real scorers at rank 8
* are still kept ("top 8 plus ties"); globalRank 0 means unranked. The Non-scoring
* section is the exact complement (`!inTopEight`), so the field is partitioned cleanly.
*/
function inTopEight(e: QPEventEntry): boolean {
return e.qpTotal > 0 && e.globalRank >= 1 && e.globalRank <= 8;
}
export async function sendQualifyingPointsUpdateNotification({
webhookUrl,
seasonName,
sportName,
eventName,
entries,
eliminated = [],
scoreboard = [],
standingsUrl,
}: {
webhookUrl: string;
seasonName: string;
sportName?: string;
eventName?: string;
entries: QPEventEntry[];
eliminated?: QPEliminatedEntry[];
/**
* The full current scoreboard for the league — every drafted participant, not just
* those whose QP changed this sync. Drives the "Top 8" and "Non-scoring Participants"
* sections. `entries`/`eliminated` remain scoped to this sync's changes and drive the
* "Points Awarded"/"Knocked Out" sections and the ping list.
*/
scoreboard?: QPEventEntry[];
standingsUrl?: string;
}): Promise<void> {
if (entries.length === 0 && eliminated.length === 0) return;
const sections: string[] = [];
if (sportName || eventName) {
const parts = [sportName, eventName].filter(Boolean);
sections.push(`**${parts.join(" — ")}**`);
}
const awardedEntries = entries
.filter((e) => e.qpEarned > 0)
.toSorted((a, b) => b.qpEarned - a.qpEarned);
if (awardedEntries.length > 0) {
sections.push("\n**Points Awarded**");
for (const e of awardedEntries) {
const managerLabel = e.ownerDiscordUserId
? `<@${e.ownerDiscordUserId}>`
: e.ownerUsername
? escapeMarkdown(e.ownerUsername)
: undefined;
const label = managerLabel
? `${escapeMarkdown(e.participantName)} (${managerLabel})`
: escapeMarkdown(e.participantName);
sections.push(`• **${label}** — ${formatQPValue(e.qpEarned)} QP`);
}
}
// Knocked-out section — drafted players eliminated this sync in a non-scoring
// round. They earn no QP, so they'd otherwise never be surfaced to their manager.
if (eliminated.length > 0) {
sections.push("\n**Knocked Out**");
for (const e of eliminated) {
const managerLabel = e.ownerDiscordUserId
? `<@${e.ownerDiscordUserId}>`
: e.ownerUsername
? escapeMarkdown(e.ownerUsername)
: undefined;
const label = managerLabel
? `${escapeMarkdown(e.participantName)} (${managerLabel})`
: escapeMarkdown(e.participantName);
sections.push(`${label}`);
}
}
// Scoreboard sections below draw from the FULL drafted field (`scoreboard`), not just
// this sync's movers, so they read as a live standings snapshot. The two sections
// partition the field exactly via `inTopEight`, so nobody is dropped or listed twice.
// Top 8 = a drafted participant that has actually scored (qpTotal > 0) AND sits in the
// top 8 of the FULL season standings (see `inTopEight`).
const topEight = [...scoreboard]
.filter(inTopEight)
.toSorted((a, b) => a.globalRank - b.globalRank);
// Skip the section entirely when no drafted participant is in the top 8 (e.g. a
// sync that only reported knockouts) so we don't emit an empty header.
if (topEight.length > 0) {
sections.push("\n**Drafted Participants in Top 8**");
for (const e of topEight) {
const rankPrefix = e.globalRankTied ? `T${e.globalRank}` : `${e.globalRank}`;
// Plain manager username (no <@id> mention): this section is not pinged.
const managerLabel = e.ownerUsername ? ` (${escapeMarkdown(e.ownerUsername)})` : "";
sections.push(`${rankPrefix}\\. ${escapeMarkdown(e.participantName)}${managerLabel}${formatQPValue(e.qpTotal)} QP`);
}
}
// Non-scoring section — the rest of the drafted field (everyone not in the top 8, i.e.
// the exact complement of `inTopEight`: rank 9+, unranked, or scored-nothing players
// tied into the top-8 rank band). Rendered as a single compact comma-separated line of
// "Name (points, manager)", highest QP total first. Never pinged, so managers are shown
// by plain username, never as a <@id> mention.
const nonTopEight = [...scoreboard]
.filter((e) => !inTopEight(e))
.toSorted((a, b) => b.qpTotal - a.qpTotal);
if (nonTopEight.length > 0) {
sections.push("\n**Non-scoring Participants**");
const parts = nonTopEight.map((e) => {
const details = e.ownerUsername
? `${formatQPValue(e.qpTotal)}, ${escapeMarkdown(e.ownerUsername)}`
: `${formatQPValue(e.qpTotal)}`;
return `${escapeMarkdown(e.participantName)} (${details})`;
});
sections.push(parts.join(", "));
}
const MAX_DESCRIPTION = 4096;
let description = sections.join("\n");
if (description.length > MAX_DESCRIPTION) {
description = description.slice(0, MAX_DESCRIPTION - 3) + "...";
}
// Ping only managers who earned points or lost a drafted player this sync —
// never the non-scoring (zeroEntries) managers.
const pingUserIds = new Set<string>();
for (const e of [...awardedEntries, ...eliminated]) {
if (e.ownerDiscordUserId) pingUserIds.add(e.ownerDiscordUserId);
}
const pingIds = [...pingUserIds];
const payload: DiscordWebhookPayload = {
embeds: [
{
title: `🏅 Qualifying Points Update — ${seasonName}`,
url: standingsUrl,
description,
color: 0x5865f2, // Discord blurple
},
],
};
if (pingIds.length > 0) {
const cappedIds = pingIds.slice(0, 100);
payload.content = cappedIds.map((id) => `<@${id}>`).join(" ");
payload.allowed_mentions = { parse: [], users: cappedIds };
}
await sendDiscordWebhook(webhookUrl, payload);
}
export async function sendPickAnnouncementNotification({
webhookUrl,
draftUrl,
pickNumber,
round,
pickInRound,
pickedTeamName,
participantName,
sportName,
nextTeamName,
nextOwnerDiscordId,
isDraftComplete,
}: {
webhookUrl: string;
draftUrl: string;
pickNumber: number;
round: number;
pickInRound: number;
pickedTeamName: string;
participantName: string;
sportName: string;
nextTeamName?: string;
nextOwnerDiscordId?: string;
isDraftComplete: boolean;
}): Promise<void> {
const lines: string[] = [
`**${escapeMarkdown(pickedTeamName)}** selected **${escapeMarkdown(participantName)}** (${escapeMarkdown(sportName)})`,
];
if (isDraftComplete) {
lines.push("", "The draft is complete!");
} else if (nextTeamName) {
const nextLabel = nextOwnerDiscordId
? `<@${nextOwnerDiscordId}>`
: escapeMarkdown(nextTeamName);
lines.push("", `On the clock: **${escapeMarkdown(nextTeamName)}** (${nextLabel})`);
}
const description = lines.join("\n");
const payload: DiscordWebhookPayload = {
embeds: [
{
title: `Pick #${pickNumber} — Round ${round}, Pick ${pickInRound}`,
url: draftUrl,
description,
color: 0x5865f2,
},
],
};
if (nextOwnerDiscordId && !isDraftComplete) {
payload.content = `<@${nextOwnerDiscordId}>`;
payload.allowed_mentions = { parse: [], users: [nextOwnerDiscordId] };
}
await sendDiscordWebhook(webhookUrl, payload);
}
export async function sendDraftOrderNotification({
webhookUrl,
leagueName,
leagueUrl,
method,
teams,
}: {
webhookUrl: string;
leagueName: string;
leagueUrl: string;
method: "manual" | "randomized";
teams: Array<{ name: string; position: number; username?: string }>;
}): Promise<void> {
const title =
method === "manual"
? `Draft Order Manually Set — ${leagueName}`
: `Draft Order Randomized — ${leagueName}`;
const sorted = teams.toSorted((a, b) => a.position - b.position);
let description = sorted
.map((t) => {
const teamLabel = escapeMarkdown(t.name);
const usernameLabel = t.username ? ` (${escapeMarkdown(t.username)})` : "";
return `${t.position}. ${teamLabel}${usernameLabel}`;
})
.join("\n");
if (description.length > 4096) {
description = description.slice(0, 4093) + "...";
}
await sendDiscordWebhook(webhookUrl, {
embeds: [
{
title,
url: leagueUrl,
description,
color: 0x5865f2,
},
],
});
}