diff --git a/src/commands/utility/invitation.js b/src/commands/utility/invitation.js index c6162f8..649f2ae 100644 --- a/src/commands/utility/invitation.js +++ b/src/commands/utility/invitation.js @@ -7,6 +7,19 @@ import { checkInvitation, } from "../../features/invitation.js"; +// Codes de l'API Discord : accès au salon refusé, permission manquante. +const MISSING_ACCESS = 50001; +const MISSING_PERMISSIONS = 50013; +const NO_ACCESS_MESSAGE = + "Message non publié : je n'ai pas accès à ce salon. Donne-moi « Voir le salon » et « Envoyer des messages », ou lance la commande dans un autre salon."; + +// Une réponse à une commande ne demande aucune permission dans le salon : publier un message, si. +function botCanPost(interaction) { + const permissions = interaction.channel.permissionsFor?.(interaction.guild.members.me); + if (!permissions) return true; // inconnu : l'envoi tranchera + return permissions.has([PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages]); +} + const command = { data: new SlashCommandBuilder() .setName("invitation") @@ -43,6 +56,11 @@ const command = { await interaction.deferReply({ ephemeral: true }); + if (!botCanPost(interaction)) { + await interaction.editReply(NO_ACCESS_MESSAGE); + return; + } + let checked; try { checked = await checkInvitation(interaction.guild, interaction.client, input); @@ -54,10 +72,18 @@ const command = { throw error; } - await channel.send({ - content: buildInvitationMessage(checked.link), - allowedMentions: { parse: [] }, - }); + try { + await channel.send({ + content: buildInvitationMessage(checked.link), + allowedMentions: { parse: [] }, + }); + } catch (error) { + if (error?.code === MISSING_ACCESS || error?.code === MISSING_PERMISSIONS) { + await interaction.editReply(NO_ACCESS_MESSAGE); + return; + } + throw error; + } await interaction.editReply( [ "Message publié. Pense à l'épingler (`/deletemsgs` garde les messages épinglés) et à désépingler l'ancien.", diff --git a/src/web/routes/notifications.js b/src/web/routes/notifications.js index 4c4622d..52596fe 100644 --- a/src/web/routes/notifications.js +++ b/src/web/routes/notifications.js @@ -1,18 +1,30 @@ import { Router } from "express"; import { DirectMessageError, sendDirectMessage } from "../../features/directMessages.js"; +const USER_ID_PATTERN = /^\d{17,20}$/; + +// Une ligne par demande, sans le texte du message : « DM → ». +function logDirectMessage(userId, status) { + const target = typeof userId === "string" && USER_ID_PATTERN.test(userId) ? userId : "?"; + console.log(`[${new Date().toLocaleString()}] DM ${target} → ${status}`); +} + // Messages privés envoyés pour une application de confiance (clé d'API) : `{ userId, content }`. function notificationsRouter({ client }) { const router = Router(); router.post("/dm", async (req, res) => { + const userId = req.body?.userId; try { await sendDirectMessage(client, req.body); + logDirectMessage(userId, 204); res.status(204).end(); } catch (error) { if (error instanceof DirectMessageError) { + logDirectMessage(userId, `${error.status} ${error.code}`); return res.status(error.status).json({ error: error.message, code: error.code }); } + logDirectMessage(userId, 500); throw error; } }); diff --git a/test/invitationCommand.test.js b/test/invitationCommand.test.js new file mode 100644 index 0000000..7eae0c9 --- /dev/null +++ b/test/invitationCommand.test.js @@ -0,0 +1,68 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +Object.assign(process.env, { + NODE_ENV: "test", + DISCORD_GUILD_ID: "1", + SHINUWA_USER_ID: "1", + WEB_SERVER_PORT: "3000", + WEB_API_KEY: "test-key", + DISCORD_APPLICATION_ID: "1", + DISCORD_TOKEN: "test-token", + VOICE_CHANNEL_ID: "1", + TEXT_CHANNEL_ID: "1", + GAME_SERVERS_MESSAGE_ID: "1", + INVITE_LINK: "https://discord.gg/AbC-12", +}); + +const { command } = await import("../src/commands/utility/invitation.js"); + +function fakeInteraction({ canPost = true, sendError = null } = {}) { + const replies = []; + const sent = []; + return { + replies, + sent, + memberPermissions: { has: () => true }, + options: { getString: () => null }, + client: {}, + guild: { + id: "1", + members: { me: {} }, + invites: { fetch: async () => ({ code: "AbC-12", temporary: true, maxUses: 0 }) }, + }, + channel: { + isTextBased: () => true, + permissionsFor: () => ({ has: () => canPost }), + async send(message) { + if (sendError) throw sendError; + sent.push(message); + }, + }, + async reply(message) { + replies.push(message); + }, + async deferReply() {}, + async editReply(message) { + replies.push(message); + }, + }; +} + +test("/invitation publishes the checked link", async () => { + const interaction = fakeInteraction(); + await command.execute(interaction); + assert.equal(interaction.sent.length, 1); + assert.match(interaction.sent[0].content, /discord\.gg\/AbC-12/); + assert.match(interaction.replies.at(-1), /^Message publié/); +}); + +test("/invitation explains when the bot cannot post in the channel", async () => { + const missingAccess = Object.assign(new Error("Missing Access"), { code: 50001 }); + for (const options of [{ canPost: false }, { sendError: missingAccess }]) { + const interaction = fakeInteraction(options); + await command.execute(interaction); + assert.equal(interaction.sent.length, 0); + assert.match(interaction.replies.at(-1), /je n'ai pas accès à ce salon/); + } +});