Show the destination, result and loot in Sokko TCG Discord alerts, with a button to the expedition
All checks were successful
Validate and deploy Sokko G / validate (push) Successful in 23m48s
Validate and deploy Sokko G / deploy (push) Successful in 16s

- Each queued alert keeps an embed and a link button: the destination illustration as thumbnail, the tier, score and loot for a return, the difficulty and automatic departure for a new group.
- The button and the message link open #/cards/expeditions/<id>, which scrolls to the player's expedition or group and highlights it; Discord login now returns to that link.
- Without an https CARDS_PUBLIC_ORIGIN the link stays in the text, without button or thumbnail, which Discord would refuse.
- Delivery docs name palico-bot's NOTIFICATIONS_API_KEY and its local-only route on port 3101.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-29 11:35:15 +01:00
parent 734a3b6a8b
commit 82cebd0fd1
17 changed files with 184 additions and 37 deletions

View file

@ -0,0 +1,85 @@
// Rôle : construit les messages privés des alertes Discord des Expéditions : le texte (montré par la notification du téléphone),
// un embed (destination, résultat, butin, vignette de la destination) et un bouton qui ouvre directement l'expédition dans Sokko TCG.
// Module pur : il reçoit le catalogue et l'adresse publique, sans base ni horloge.
// Libellés des paliers et des objets, les mêmes que l'interface (site.json, cards.expeditions) ; un test garde les listes égales.
export const TIER_LABELS = Object.freeze({ struggle: "Retour difficile", success: "Réussite", triumph: "Triomphe" });
export const ITEM_LABELS = Object.freeze({
fragment: "Fragment de carte au trésor", engraving: "Burin de graveur", plan: "Plan d’atelier", anchor: "Ancre des Veilleurs", guideStar: "Étoile guide",
skyChart: "Carte céleste", oblivion: "Parchemin d’oubli", windRose: "Rose des vents", balm: "Baume des Veilleurs"
});
// Couleur de l'embed : or pour un Triomphe, vert pour une Réussite, gris pour un Retour difficile, sarcelle pour un groupe ouvert.
const TIER_COLORS = Object.freeze({ triumph: 0xf6c453, success: 0x34d399, struggle: 0x94a3b8 });
const GROUP_COLOR = 0x0f766e;
const FOOTER = "Sokko TCG · Guilde des Veilleurs";
// Lien direct vers une expédition (#/cards/expeditions/<id>) : la page la met en vue. Sans adresse publique, pas de lien.
export function expeditionUrl(origin, expeditionId) {
return origin ? `${origin}/#/cards/expeditions/${expeditionId}` : null;
}
// Vignette : l'illustration de la destination, ou celle de sa carte de couverture ; seulement en https, que Discord télécharge.
function thumbnailUrl(origin, catalog, destination) {
const coverImage = destination.coverCardId ? catalog.cards.find((card) => card.id === destination.coverCardId)?.image : null;
const image = destination.image || coverImage;
return origin?.startsWith("https://") && image ? `${origin}${image}` : null;
}
const meta = (setup) => `${"★".repeat(setup.stars)} · ${setup.hours} h`;
function withLink(message, url, label) {
if (!url) return message;
return { ...message, embed: { ...message.embed, url: url.startsWith("https://") ? url : undefined }, link: url.startsWith("https://") ? { label, url } : null };
}
// Groupe ouvert : qui l'ouvre, où, à quelle difficulté, et quand il partira seul.
export function groupOpenedMessage({ creatorName, setup, expeditionId, origin, catalog }) {
const url = expeditionUrl(origin, expeditionId);
const name = creatorName || "Un joueur";
const content = `${name} ouvre un groupe d’expédition vers ${setup.destination.name} (${meta(setup)}). Rejoignez-le sur le tableau de la Guilde :${url ? ` ${url}` : ""}`;
const fields = [{ name: "Difficulté", value: "★".repeat(setup.stars), inline: true }, { name: "Durée", value: `${setup.hours} h`, inline: true }];
if (setup.recruitUntil) fields.push({ name: "Départ automatique", value: `<t:${Math.floor(setup.recruitUntil / 1000)}:R>`, inline: true });
const embed = {
title: `Nouveau groupe vers ${setup.destination.name}`,
description: `${name} cherche des compagnons pour cette expédition.`,
color: GROUP_COLOR,
thumbnail: thumbnailUrl(origin, catalog, setup.destination) ?? undefined,
fields,
footer: FOOTER
};
return withLink({ content, embed }, url, "Rejoindre le groupe");
}
// Butin d'un retour, en une ligne : Éclats, poussière, cartes et objets.
export function lootLine(reward, catalog) {
const parts = [];
if (reward.eclats) parts.push(`+${reward.eclats} Éclats`);
if (reward.stardust) parts.push(`+${reward.stardust} poussière${reward.stardust > 1 ? "s" : ""}`);
for (const editionId of reward.cards || []) {
const edition = catalog.editions.find((item) => item.id === editionId);
parts.push(catalog.cards.find((card) => card.id === edition?.cardId)?.name || editionId);
}
const items = new Map();
for (const item of reward.items || []) items.set(item, (items.get(item) || 0) + 1);
for (const [item, count] of items) parts.push(`${ITEM_LABELS[item] || item}${count > 1 ? ` ×${count}` : ""}`);
const packs = reward.packs?.length || 0;
if (packs) parts.push(`${packs} paquet${packs > 1 ? "s" : ""} offert${packs > 1 ? "s" : ""}`);
return parts.join(" · ") || "Rien cette fois";
}
// Expédition de retour : destination, palier et score, butin à récupérer.
export function expeditionReturnedMessage({ setup, result, reward, expeditionId, origin, catalog }) {
const url = expeditionUrl(origin, expeditionId);
const content = `Votre expédition vers ${setup.destination.name} est de retour ! Récupérez son butin :${url ? ` ${url}` : ""}`;
const fields = [];
if (result?.tier) fields.push({ name: "Résultat", value: `${TIER_LABELS[result.tier] || result.tier}${result.scorePct != null ? ` · ${String(result.scorePct).replace(".", ",")} %` : ""}`, inline: true });
if (reward) fields.push({ name: "Butin", value: lootLine(reward, catalog) });
const embed = {
title: "Votre expédition est de retour !",
description: `${setup.destination.name} · ${meta(setup)}`,
color: TIER_COLORS[result?.tier] ?? GROUP_COLOR,
thumbnail: thumbnailUrl(origin, catalog, setup.destination) ?? undefined,
fields,
footer: FOOTER
};
return withLink({ content, embed }, url, "Voir l’expédition");
}

View file

@ -64,8 +64,9 @@ function oauthReturnCookie(value, secure, maxAge = 600) {
return cookie("sokkog_cards_oauth_return", value, secure, maxAge);
}
// Retour après la connexion Discord : une section du jeu, ou le lien direct d'une expédition (#/cards/expeditions/<id>).
function cardsReturnPath(value) {
return /^\/cards(?:\/admin(?:\/[a-z0-9-]{1,40}){0,2}|\/[a-z0-9-]{1,40})?$/.test(String(value || "")) ? value : "/cards";
return /^\/cards(?:\/admin(?:\/[a-z0-9-]{1,40}){0,2}|\/expeditions\/[a-z0-9-]{1,40}|\/[a-z0-9-]{1,40})?$/.test(String(value || "")) ? value : "/cards";
}
async function readBody(req) {

View file

@ -620,6 +620,10 @@ export const MIGRATIONS = [
`
UPDATE mirror_settings SET settings_json = json_set(settings_json, '$.margins.normal', 6) WHERE json_extract(settings_json, '$.margins.normal') = 3;
UPDATE mirror_settings SET settings_json = json_set(settings_json, '$.margins.hard', 14) WHERE json_extract(settings_json, '$.margins.hard') = 6;
`,
// Alertes Discord enrichies : chaque message en file garde son embed (destination, résultat, butin) et son bouton de lien.
`
ALTER TABLE alert_outbox ADD COLUMN extra_json TEXT CHECK (extra_json IS NULL OR json_valid(extra_json));
`
];

View file

@ -6,11 +6,12 @@ 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) => {
// `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 }),
body: JSON.stringify({ userId: discordId, content, ...(extra.embed ? { embed: extra.embed } : {}), ...(extra.link ? { link: extra.link } : {}) }),
signal: AbortSignal.timeout(timeoutMs)
});
if (response.ok) return;
@ -26,7 +27,7 @@ export async function dispatchAlerts(expeditions, send, { limit = 20 } = {}) {
let sent = 0;
for (const alert of expeditions.pendingAlerts(limit)) {
try {
await send(alert.discordId, alert.content);
await send(alert.discordId, alert.content, alert.extra);
expeditions.markAlertSent(alert.id);
sent += 1;
} catch (error) {

View file

@ -1,6 +1,7 @@
// Rôle : alertes Discord des Expéditions Sokko TCG : choix de chaque joueur, file des messages à envoyer (groupe ouvert, expédition de retour).
// Ces méthodes s'ajoutent à ExpeditionService (Object.assign sur son prototype) ; l'envoi lui-même est fait par discord-alerts.js.
import { randomUUID } from "node:crypto";
import { expeditionReturnedMessage, groupOpenedMessage } from "./alert-messages.js";
// Un vrai compte Discord : le compte de développement et les comptes supprimés n'ont pas d'identifiant numérique.
const DISCORD_ID_PATTERN = /^\d{17,20}$/;
@ -28,22 +29,21 @@ export const alertMethods = {
return this.cards.getState(playerId);
},
expeditionsLink() {
return this.publicOrigin ? ` ${this.publicOrigin}/#/cards/expeditions` : "";
},
enqueueInTx(playerId, kind, content) {
this.db.prepare("INSERT INTO alert_outbox(id, player_id, kind, content, created_at) VALUES (?, ?, ?, ?, ?)").run(randomUUID(), playerId, kind, content, this.now());
// `message` : { content, embed?, link? } (alert-messages.js), ou un simple texte.
enqueueInTx(playerId, kind, message) {
const { content, embed = null, link = null } = typeof message === "string" ? { content: message } : message;
const extra = embed || link ? JSON.stringify({ ...(embed ? { embed } : {}), ...(link ? { link } : {}) }) : null;
this.db.prepare("INSERT INTO alert_outbox(id, player_id, kind, content, extra_json, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(randomUUID(), playerId, kind, content, extra, this.now());
},
// Groupe ouvert : prévient les autres joueurs qui ont activé cette alerte.
queueGroupOpenedInTx(creatorId, setup) {
queueGroupOpenedInTx(creatorId, setup, expeditionId) {
if (!this.alertsActive()) return;
const creator = this.db.prepare("SELECT display_name FROM players WHERE id = ?").get(creatorId);
const content = `${creator?.display_name || "Un joueur"} ouvre un groupe d’expédition vers ${setup.destination.name} (${"★".repeat(setup.stars)}, ${setup.hours} h). Rejoignez-le sur le tableau de la Guilde :${this.expeditionsLink()}`;
const message = groupOpenedMessage({ creatorName: creator?.display_name, setup, expeditionId, origin: this.publicOrigin, catalog: this.cards.catalog });
for (const row of this.db.prepare(`SELECT p.id, p.discord_id FROM player_alerts a JOIN players p ON p.id = a.player_id
WHERE a.group_opened = 1 AND p.deleted_at IS NULL AND p.id != ?`).all(creatorId)) {
if (DISCORD_ID_PATTERN.test(row.discord_id)) this.enqueueInTx(row.id, "group_opened", content);
if (DISCORD_ID_PATTERN.test(row.discord_id)) this.enqueueInTx(row.id, "group_opened", message);
}
},
@ -54,7 +54,7 @@ export const alertMethods = {
this.settleForming();
let queued = 0;
this.cards.database.transaction(() => {
const rows = this.db.prepare(`SELECT e.id, e.setup_json, m.player_id, p.discord_id, a.expedition_returned FROM expedition_members m
const rows = this.db.prepare(`SELECT e.id, e.setup_json, e.result_json, m.reward_json, m.player_id, p.discord_id, a.expedition_returned FROM expedition_members m
JOIN expeditions e ON e.id = m.expedition_id JOIN players p ON p.id = m.player_id LEFT JOIN player_alerts a ON a.player_id = m.player_id
WHERE e.status = 'running' AND e.returns_at <= ? AND m.claimed_at IS NULL AND m.alerted_at IS NULL`).all(this.now());
const mark = this.db.prepare("UPDATE expedition_members SET alerted_at = ? WHERE expedition_id = ? AND player_id = ?");
@ -62,7 +62,8 @@ export const alertMethods = {
mark.run(this.now(), row.id, row.player_id);
if (!row.expedition_returned || !DISCORD_ID_PATTERN.test(row.discord_id)) continue;
const setup = JSON.parse(row.setup_json);
this.enqueueInTx(row.player_id, "expedition_returned", `Votre expédition vers ${setup.destination.name} est de retour ! Récupérez son butin :${this.expeditionsLink()}`);
const message = expeditionReturnedMessage({ setup, result: JSON.parse(row.result_json || "null"), reward: JSON.parse(row.reward_json || "null"), expeditionId: row.id, origin: this.publicOrigin, catalog: this.cards.catalog });
this.enqueueInTx(row.player_id, "expedition_returned", message);
queued += 1;
}
});
@ -72,7 +73,7 @@ export const alertMethods = {
// Messages à envoyer. Au moment de l'envoi, l'alerte doit encore être voulue : coupée par l'administration, ou désactivée par le
// joueur pour ce type de message, elle est abandonnée (marquée en échec, jamais renvoyée plus tard, quand elle serait périmée).
pendingAlerts(limit = 20) {
const pending = () => this.db.prepare(`SELECT o.id, o.kind, o.content, o.attempts, p.discord_id, a.group_opened, a.expedition_returned FROM alert_outbox o
const pending = () => this.db.prepare(`SELECT o.id, o.kind, o.content, o.extra_json, o.attempts, p.discord_id, a.group_opened, a.expedition_returned FROM alert_outbox o
JOIN players p ON p.id = o.player_id LEFT JOIN player_alerts a ON a.player_id = o.player_id
WHERE o.sent_at IS NULL AND o.failed_at IS NULL AND p.deleted_at IS NULL ORDER BY o.created_at`).all();
const drop = this.db.prepare("UPDATE alert_outbox SET failed_at = ?, last_error = ? WHERE id = ?");
@ -83,7 +84,7 @@ export const alertMethods = {
const allowed = row.kind === "group_opened" ? row.group_opened : row.kind === "expedition_returned" ? row.expedition_returned : 0;
if (!active) drop.run(this.now(), "alerts disabled", row.id);
else if (!allowed) drop.run(this.now(), "player opted out", row.id);
else if (wanted.length < limit) wanted.push({ id: row.id, content: row.content, attempts: row.attempts, discordId: row.discord_id });
else if (wanted.length < limit) wanted.push({ id: row.id, content: row.content, extra: JSON.parse(row.extra_json || "{}"), attempts: row.attempts, discordId: row.discord_id });
}
});
return wanted;

View file

@ -135,7 +135,7 @@ export const groupMethods = {
VALUES (?, 'group', ?, ?, ?, ?, ?, 'forming', ?, ?)`).run(expeditionId, plan.day, plan.setup.destination.id, plan.stars, plan.setup.testTrip ? TEST_TRIP_MS : plan.hours * HOUR_MS, playerId, JSON.stringify(plan.setup), now);
this.insertMember(expeditionId, playerId, plan.slot, 0, now, { ready: true });
if (body?.departNow === true) this.launchInTx(this.db.prepare("SELECT * FROM expeditions WHERE id = ?").get(expeditionId), now, settings);
else this.queueGroupOpenedInTx(playerId, plan.setup);
else this.queueGroupOpenedInTx(playerId, plan.setup, expeditionId);
this.db.prepare("INSERT INTO idempotency(player_id, scope, request_key, response_json, created_at) VALUES (?, 'expedition-group', ?, ?, ?)")
.run(playerId, requestKey, JSON.stringify({ expeditionId }), now);
});