Explain missing channel access in /invitation; log DM requests
All checks were successful
Deploy Palico Bot / deploy (push) Successful in 6s

- /invitation checks the bot can view and post in the channel, and turns
  Discord's 50001/50013 into a clear reply instead of a generic error
- The DM route logs one line per request (user ID and status, never the text)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-29 11:22:10 +01:00
parent 6895d20459
commit 2471b5f6f7
3 changed files with 110 additions and 4 deletions

View file

@ -7,6 +7,19 @@ import {
checkInvitation, checkInvitation,
} from "../../features/invitation.js"; } 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 = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("invitation") .setName("invitation")
@ -43,6 +56,11 @@ const command = {
await interaction.deferReply({ ephemeral: true }); await interaction.deferReply({ ephemeral: true });
if (!botCanPost(interaction)) {
await interaction.editReply(NO_ACCESS_MESSAGE);
return;
}
let checked; let checked;
try { try {
checked = await checkInvitation(interaction.guild, interaction.client, input); checked = await checkInvitation(interaction.guild, interaction.client, input);
@ -54,10 +72,18 @@ const command = {
throw error; throw error;
} }
await channel.send({ try {
content: buildInvitationMessage(checked.link), await channel.send({
allowedMentions: { parse: [] }, 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( await interaction.editReply(
[ [
"Message publié. Pense à l'épingler (`/deletemsgs` garde les messages épinglés) et à désépingler l'ancien.", "Message publié. Pense à l'épingler (`/deletemsgs` garde les messages épinglés) et à désépingler l'ancien.",

View file

@ -1,18 +1,30 @@
import { Router } from "express"; import { Router } from "express";
import { DirectMessageError, sendDirectMessage } from "../../features/directMessages.js"; import { DirectMessageError, sendDirectMessage } from "../../features/directMessages.js";
const USER_ID_PATTERN = /^\d{17,20}$/;
// Une ligne par demande, sans le texte du message : « DM <identifiant> → <statut> ».
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 }`. // Messages privés envoyés pour une application de confiance (clé d'API) : `{ userId, content }`.
function notificationsRouter({ client }) { function notificationsRouter({ client }) {
const router = Router(); const router = Router();
router.post("/dm", async (req, res) => { router.post("/dm", async (req, res) => {
const userId = req.body?.userId;
try { try {
await sendDirectMessage(client, req.body); await sendDirectMessage(client, req.body);
logDirectMessage(userId, 204);
res.status(204).end(); res.status(204).end();
} catch (error) { } catch (error) {
if (error instanceof DirectMessageError) { if (error instanceof DirectMessageError) {
logDirectMessage(userId, `${error.status} ${error.code}`);
return res.status(error.status).json({ error: error.message, code: error.code }); return res.status(error.status).json({ error: error.message, code: error.code });
} }
logDirectMessage(userId, 500);
throw error; throw error;
} }
}); });

View file

@ -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/);
}
});