Add an authenticated route that sends Discord direct messages for trusted apps
Some checks failed
Deploy Palico Bot / deploy (push) Failing after 3s
Some checks failed
Deploy Palico Bot / deploy (push) Failing after 3s
- POST /api/notifications/dm takes a user id and a text, sends it as a direct message with no active mentions, and answers 204, 400, 404 or 422. - The send logic lives in src/features/directMessages.js with its own tests; the route gets its own per-minute rate limit behind the existing API key. - Sokko TCG uses it for its opt-in Expedition alerts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
20624a5c9c
commit
3655b1ad74
6 changed files with 183 additions and 56 deletions
39
src/features/directMessages.js
Normal file
39
src/features/directMessages.js
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
// 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.
|
||||
|
||||
const USER_ID_PATTERN = /^\d{17,20}$/;
|
||||
const MAX_CONTENT_LENGTH = 2000;
|
||||
// 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;
|
||||
|
||||
class DirectMessageError extends Error {
|
||||
constructor(status, code, message) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
async function sendDirectMessage(client, { userId, content } = {}) {
|
||||
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`);
|
||||
}
|
||||
try {
|
||||
const user = await client.users.fetch(userId);
|
||||
await user.send({ content, allowedMentions: { parse: [] } });
|
||||
} catch (error) {
|
||||
if (error?.code === UNKNOWN_USER) {
|
||||
throw new DirectMessageError(404, "UNKNOWN_USER", "Utilisateur Discord introuvable");
|
||||
}
|
||||
if (error?.code === CANNOT_SEND) {
|
||||
throw new DirectMessageError(422, "DM_CLOSED", "Cet utilisateur n'accepte pas les messages privés du bot");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export { DirectMessageError, sendDirectMessage, MAX_CONTENT_LENGTH };
|
||||
Loading…
Add table
Add a link
Reference in a new issue