Let trusted apps add an embed and a link button to Discord direct messages
All checks were successful
Deploy Palico Bot / deploy (push) Successful in 7s
All checks were successful
Deploy Palico Bot / deploy (push) Successful in 7s
- POST /api/notifications/dm accepts optional embed (title, description, url, color, thumbnail, fields, footer, timestamp) and link fields; plain text stays required for phone notifications. - Every value is checked against Discord's limits, and urls and thumbnails must use https; a refused embed answers 400 INVALID_EMBED. - Sokko TCG uses it to show the destination, the result and the loot of its expedition alerts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2471b5f6f7
commit
6ca17264e0
4 changed files with 131 additions and 5 deletions
|
|
@ -1,8 +1,12 @@
|
|||
// Envoie un message privé Discord à la demande d'une application de confiance (Sokko TCG : alertes d'expédition).
|
||||
// Le texte est envoyé tel quel, sans aucune mention active.
|
||||
// Le texte est envoyé tel quel, sans aucune mention active ; un embed et un bouton de lien peuvent l'accompagner.
|
||||
import { ButtonStyle, ComponentType } from "discord.js";
|
||||
|
||||
const USER_ID_PATTERN = /^\d{17,20}$/;
|
||||
const MAX_CONTENT_LENGTH = 2000;
|
||||
// Limites des embeds Discord (titre, description, champs, pied, total des textes).
|
||||
const EMBED_LIMITS = Object.freeze({ title: 256, description: 4096, fields: 25, fieldName: 256, fieldValue: 1024, footer: 2048, total: 6000 });
|
||||
const MAX_LINK_LABEL = 80;
|
||||
// Codes de l'API Discord : utilisateur inconnu, messages privés impossibles (aucun serveur commun ou messages fermés).
|
||||
const UNKNOWN_USER = 10013;
|
||||
const CANNOT_SEND = 50007;
|
||||
|
|
@ -15,16 +19,82 @@ class DirectMessageError extends Error {
|
|||
}
|
||||
}
|
||||
|
||||
async function sendDirectMessage(client, { userId, content } = {}) {
|
||||
const invalid = (message) => new DirectMessageError(400, "INVALID_EMBED", message);
|
||||
|
||||
function isHttpsUrl(value) {
|
||||
try {
|
||||
return typeof value === "string" && value.length <= 2048 && new URL(value).protocol === "https:";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function text(value, max, label, { required = false } = {}) {
|
||||
if (value == null && !required) return undefined;
|
||||
if (typeof value !== "string" || !value.trim() || value.length > max) throw invalid(`${label} vide ou de plus de ${max} caractères`);
|
||||
return value;
|
||||
}
|
||||
|
||||
// Embed accepté : titre obligatoire ; description, adresse, couleur, vignette, champs, pied et horodatage facultatifs.
|
||||
function buildEmbed(embed) {
|
||||
if (embed == null) return null;
|
||||
if (typeof embed !== "object" || Array.isArray(embed)) throw invalid("Embed invalide");
|
||||
const result = { title: text(embed.title, EMBED_LIMITS.title, "Titre", { required: true }) };
|
||||
if (embed.description != null) result.description = text(embed.description, EMBED_LIMITS.description, "Description");
|
||||
if (embed.url != null) {
|
||||
if (!isHttpsUrl(embed.url)) throw invalid("Adresse de l'embed invalide : https uniquement");
|
||||
result.url = embed.url;
|
||||
}
|
||||
if (embed.color != null) {
|
||||
if (!Number.isInteger(embed.color) || embed.color < 0 || embed.color > 0xffffff) throw invalid("Couleur invalide");
|
||||
result.color = embed.color;
|
||||
}
|
||||
if (embed.thumbnail != null) {
|
||||
if (!isHttpsUrl(embed.thumbnail)) throw invalid("Vignette invalide : https uniquement");
|
||||
result.thumbnail = { url: embed.thumbnail };
|
||||
}
|
||||
if (embed.fields != null) {
|
||||
if (!Array.isArray(embed.fields) || embed.fields.length > EMBED_LIMITS.fields) throw invalid(`${EMBED_LIMITS.fields} champs au plus`);
|
||||
result.fields = embed.fields.map((field) => ({
|
||||
name: text(field?.name, EMBED_LIMITS.fieldName, "Nom de champ", { required: true }),
|
||||
value: text(field?.value, EMBED_LIMITS.fieldValue, "Valeur de champ", { required: true }),
|
||||
inline: field?.inline === true
|
||||
}));
|
||||
}
|
||||
if (embed.footer != null) result.footer = { text: text(embed.footer, EMBED_LIMITS.footer, "Pied") };
|
||||
if (embed.timestamp != null) {
|
||||
const date = new Date(embed.timestamp);
|
||||
if (Number.isNaN(date.getTime())) throw invalid("Horodatage invalide");
|
||||
result.timestamp = date.toISOString();
|
||||
}
|
||||
const total = [result.title, result.description, result.footer?.text, ...(result.fields || []).flatMap((field) => [field.name, field.value])].filter(Boolean).join("").length;
|
||||
if (total > EMBED_LIMITS.total) throw invalid(`Embed de plus de ${EMBED_LIMITS.total} caractères`);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Bouton de lien sous le message : un libellé et une adresse https.
|
||||
function buildLink(link) {
|
||||
if (link == null) return null;
|
||||
if (typeof link !== "object" || !isHttpsUrl(link.url)) throw invalid("Lien invalide : https uniquement");
|
||||
const label = text(link.label, MAX_LINK_LABEL, "Libellé du lien", { required: true });
|
||||
return { type: ComponentType.ActionRow, components: [{ type: ComponentType.Button, style: ButtonStyle.Link, label, url: link.url }] };
|
||||
}
|
||||
|
||||
async function sendDirectMessage(client, { userId, content, embed = null, link = null } = {}) {
|
||||
if (typeof userId !== "string" || !USER_ID_PATTERN.test(userId)) {
|
||||
throw new DirectMessageError(400, "INVALID_USER", "Identifiant Discord invalide");
|
||||
}
|
||||
if (typeof content !== "string" || !content.trim() || content.length > MAX_CONTENT_LENGTH) {
|
||||
throw new DirectMessageError(400, "INVALID_CONTENT", `Message vide ou de plus de ${MAX_CONTENT_LENGTH} caractères`);
|
||||
}
|
||||
const message = { content, allowedMentions: { parse: [] } };
|
||||
const builtEmbed = buildEmbed(embed);
|
||||
const row = buildLink(link);
|
||||
if (builtEmbed) message.embeds = [builtEmbed];
|
||||
if (row) message.components = [row];
|
||||
try {
|
||||
const user = await client.users.fetch(userId);
|
||||
await user.send({ content, allowedMentions: { parse: [] } });
|
||||
await user.send(message);
|
||||
} catch (error) {
|
||||
if (error?.code === UNKNOWN_USER) {
|
||||
throw new DirectMessageError(404, "UNKNOWN_USER", "Utilisateur Discord introuvable");
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue