sokko-g/services/cards/discord-alerts.js
Shinuwa 320498d878 Send opt-in Discord alerts for Sokko TCG Expeditions through palico-bot
- Players turn on alerts one by one in their account: someone opens an expedition group, or one of their expeditions returns; both stay off until chosen.
- Opening a group queues a direct message for each other subscribed player; every 30 seconds the server queues returned expeditions once and sends pending messages to palico-bot's direct message route.
- Permanent refusals (unknown account, closed direct messages) or five failures stop retries; only real Discord accounts receive alerts, and sent rows are purged after 30 days.
- CARDS_DISCORD_ALERTS_URL and CARDS_DISCORD_ALERTS_KEY enable the feature; Administration › Guilde can turn every alert off, and the privacy notice explains what is sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 17:09:29 +01:00

37 lines
1.6 KiB
JavaScript

// Rôle : envoie les alertes Discord des Expéditions par l'API de messages privés de palico-bot, depuis la file tenue par le service.
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 }) {
return async (discordId, content) => {
const response = await fetchImpl(url, {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}` },
body: JSON.stringify({ userId: discordId, content }),
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);
expeditions.markAlertSent(alert.id);
sent += 1;
} catch (error) {
expeditions.markAlertFailed(alert.id, error.message, { permanent: Boolean(error.permanent) });
}
}
return sent;
}