sokko-g/services/cards/discord-alerts.js
Shinuwa 73bd5ae21c Give Sokko TCG's server files headers that explain their role, callers and pitfalls
Each core file of services/cards now says where it sits, its entry points,
who calls it and what to watch for: admin checks living in the service, the
methods added to ExpeditionService and TeamService by Object.assign, the
InTx suffix, settings defaults that do not change an existing database, and
rules shared with the browser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 09:47:18 +01:00

46 lines
2 KiB
JavaScript

/**
* @file Envoie les alertes Discord des Expéditions par l'API de messages privés de palico-bot, depuis la file
* tenue par expedition-alerts.js.
*
* Utilisé par : api.js, toutes les 30 secondes, quand CARDS_DISCORD_ALERTS_URL et CARDS_DISCORD_ALERTS_KEY sont
* définies.
* @see .env.example
*/
const TIMEOUT_MS = 10_000;
// Réponses définitives de palico-bot : corps refusé, compte Discord inconnu, messages privés impossibles.
const PERMANENT_STATUSES = new Set([400, 404, 422]);
// `url` : adresse complète de la route palico-bot (…/api/notifications/dm) ; `key` : sa clé d'API (WEB_API_KEY).
export function createDiscordAlertSender({ url, key, fetchImpl = fetch, timeoutMs = TIMEOUT_MS }) {
// `extra` : { embed?, link? } que palico-bot ajoute au texte (embed de la destination, bouton vers l'expédition).
return async (discordId, content, extra = {}) => {
const response = await fetchImpl(url, {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}` },
body: JSON.stringify({ userId: discordId, content, ...(extra.embed ? { embed: extra.embed } : {}), ...(extra.link ? { link: extra.link } : {}) }),
signal: AbortSignal.timeout(timeoutMs)
});
if (response.ok) return;
const error = new Error(`palico-bot answered ${response.status}`);
error.permanent = PERMANENT_STATUSES.has(response.status);
throw error;
};
}
// Un passage : annonce les expéditions rentrées, puis envoie les messages en attente, un par un.
export async function dispatchAlerts(expeditions, send, { limit = 20 } = {}) {
expeditions.queueReturnAlerts();
let sent = 0;
for (const alert of expeditions.pendingAlerts(limit)) {
try {
await send(alert.discordId, alert.content, alert.extra);
expeditions.markAlertSent(alert.id);
sent += 1;
} catch (error) {
expeditions.markAlertFailed(alert.id, error.message, { permanent: Boolean(error.permanent) });
}
}
return sent;
}