From 362c7772ba8fe19606469c9ce20589654691895a Mon Sep 17 00:00:00 2001 From: Shinuwa Date: Sun, 29 Nov 2026 12:04:43 +0100 Subject: [PATCH] Make Discord commands and the deploy pipeline sturdier - Defer the voice commands' reply: updating every member can take longer than the 3 seconds Discord allows; one member leaving no longer fails the whole operation. - Replace the deprecated ephemeral option with MessageFlags, answer command errors in French and log when that answer itself fails; route autocomplete interactions to the command. - Add /readyz, which answers 503 while the bot is not connected to Discord. - Run npm ci and npm run check on every push; deploy main only when they pass. Co-Authored-By: Claude Opus 5.5 --- .forgejo/workflows/deploy.yml | 21 ++++++-- README.md | 12 +++-- src/commands/game/maketeam.js | 70 ++++++++++++------------ src/commands/utility/deletemsgs.js | 16 +++--- src/commands/utility/invitation.js | 8 +-- src/commands/utility/listcommand.js | 56 ++++++++++---------- src/commands/utility/ping.js | 20 +++---- src/commands/vocal/deafall.js | 18 ++++--- src/commands/vocal/muteall.js | 18 ++++--- src/commands/vocal/undeafall.js | 18 ++++--- src/commands/vocal/unmuteall.js | 18 ++++--- src/events/interactionCreate.js | 82 +++++++++++++++++------------ src/features/permissions.js | 4 +- src/features/utilities.js | 38 +++++++------ src/web/server.js | 9 +++- test/webServer.test.js | 13 +++++ 16 files changed, 245 insertions(+), 176 deletions(-) diff --git a/.forgejo/workflows/deploy.yml b/.forgejo/workflows/deploy.yml index 8d9f98d..eee2496 100644 --- a/.forgejo/workflows/deploy.yml +++ b/.forgejo/workflows/deploy.yml @@ -1,18 +1,33 @@ name: Deploy Palico Bot +# Les contrôles tournent sur chaque branche ; le déploiement, seulement après un push sur +# main dont les contrôles ont réussi. on: push: - branches: - - main + pull_request: jobs: - deploy: + check: runs-on: docker # Image fixée ici : celle du label « docker » (node:20-bullseye) n'est plus maintenue, # et son miroir de sécurité renvoie 404 (échec du run 4). container: image: node:24-bookworm + steps: + - uses: actions/checkout@v4 + - name: Install dependencies + run: npm ci + - name: Syntax checks and tests + run: npm run check + + deploy: + needs: check + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + runs-on: docker + container: + image: node:24-bookworm + steps: - name: Deploy on WebApps env: diff --git a/README.md b/README.md index f8eb37f..01844d1 100644 --- a/README.md +++ b/README.md @@ -59,10 +59,14 @@ cp src/static/gameservers-list.example.json src/static/gameservers-list.json ## Déploiement -Un push sur `main` lance `.forgejo/workflows/deploy.yml`, qui se connecte en SSH -à la VM et exécute `/usr/local/bin/deploy-palico-bot` (mise à jour du dépôt, -dépendances, redémarrage du service `palico-bot`). Le workflow ne lance ni les -contrôles ni les tests : lancer `npm run check` avant de pousser. +`.forgejo/workflows/deploy.yml` lance `npm ci` puis `npm run check` (syntaxe et +tests) à chaque push, sur toutes les branches. Sur `main`, et seulement si ces +contrôles réussissent, il se connecte ensuite en SSH à la VM et exécute +`/usr/local/bin/deploy-palico-bot` (mise à jour du dépôt, dépendances, redémarrage +du service `palico-bot`). + +Supervision : `/healthz` répond dès que le processus tourne ; `/readyz` répond +`503` tant que le bot n'est pas connecté à Discord. Variables facultatives : diff --git a/src/commands/game/maketeam.js b/src/commands/game/maketeam.js index fb6c761..da24db7 100644 --- a/src/commands/game/maketeam.js +++ b/src/commands/game/maketeam.js @@ -1,34 +1,34 @@ -import { SlashCommandBuilder } from "discord.js"; - -const command = { - data: new SlashCommandBuilder() - .setName("maketeam") - .setDescription("Crée des equipes au hasard") - .addIntegerOption((option) => - option +import { MessageFlags, SlashCommandBuilder } from "discord.js"; + +const command = { + data: new SlashCommandBuilder() + .setName("maketeam") + .setDescription("Crée des equipes au hasard") + .addIntegerOption((option) => + option .setName("number") .setDescription("Nombre d'équipe") .setMinValue(1) .setMaxValue(20) .setRequired(true) - ) - .addStringOption((option) => - option + ) + .addStringOption((option) => + option .setName("players") .setDescription("Liste des joueurs, séparés par un espace") .setMinLength(1) .setMaxLength(1000) .setRequired(true) - ), - async execute(interaction) { - const teamNumber = interaction.options.getInteger("number"); - const players = interaction.options.getString("players"); + ), + async execute(interaction) { + const teamNumber = interaction.options.getInteger("number"); + const players = interaction.options.getString("players"); const playersArray = players.trim().split(/\s+/); if (teamNumber > playersArray.length) { await interaction.reply({ content: "Le nombre d'équipes ne peut pas dépasser le nombre de joueurs.", - ephemeral: true, + flags: MessageFlags.Ephemeral, }); return; } @@ -42,22 +42,22 @@ const command = { shuffledPlayers[index], ]; } - - shuffledPlayers.forEach((player, index) => { - const teamIndex = index % teamNumber; - teams[teamIndex].push(player); - }); - - let message = ""; - let teamList = ""; - - teams.forEach((team, index) => { - teamList = `${teamList}\n${index + 1}. ${team.join(", ")}`; - }); - - message = `Yop ! Voici les équipes proposés :\n${teamList}`; - await interaction.reply(message); - }, -}; - -export { command }; + + shuffledPlayers.forEach((player, index) => { + const teamIndex = index % teamNumber; + teams[teamIndex].push(player); + }); + + let message = ""; + let teamList = ""; + + teams.forEach((team, index) => { + teamList = `${teamList}\n${index + 1}. ${team.join(", ")}`; + }); + + message = `Yop ! Voici les équipes proposés :\n${teamList}`; + await interaction.reply(message); + }, +}; + +export { command }; diff --git a/src/commands/utility/deletemsgs.js b/src/commands/utility/deletemsgs.js index dc7a194..ab527c7 100644 --- a/src/commands/utility/deletemsgs.js +++ b/src/commands/utility/deletemsgs.js @@ -1,8 +1,8 @@ -import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; +import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { requirePermission } from "../../features/permissions.js"; - -const command = { - data: new SlashCommandBuilder() + +const command = { + data: new SlashCommandBuilder() .setName("deletemsgs") .setDescription("Supprime tous les messages, sauf ceux épinglés") .setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages), @@ -15,12 +15,12 @@ const command = { if (!textChannel?.isTextBased() || !textChannel.messages) { await interaction.reply({ content: "Cette commande doit être utilisée dans un salon textuel.", - ephemeral: true, + flags: MessageFlags.Ephemeral, }); return; } - await interaction.deferReply({ ephemeral: true }); + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); const fetched = await textChannel.messages.fetch({ limit: 100 }); const notPinned = fetched.filter((message) => !message.pinned); const deleted = await textChannel.bulkDelete(notPinned, true); @@ -28,5 +28,5 @@ const command = { await interaction.editReply(`Et voilà, ${deleted.size} message(s) supprimé(s) ! 🐱`); }, }; - -export { command }; + +export { command }; diff --git a/src/commands/utility/invitation.js b/src/commands/utility/invitation.js index 649f2ae..0f6758d 100644 --- a/src/commands/utility/invitation.js +++ b/src/commands/utility/invitation.js @@ -1,4 +1,4 @@ -import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; +import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { config } from "../../config.js"; import { requirePermission } from "../../features/permissions.js"; import { @@ -40,7 +40,7 @@ const command = { if (!interaction.guild || !channel?.isTextBased()) { await interaction.reply({ content: "Cette commande doit être utilisée dans un salon textuel du serveur.", - ephemeral: true, + flags: MessageFlags.Ephemeral, }); return; } @@ -49,12 +49,12 @@ const command = { if (!input) { await interaction.reply({ content: "Aucun lien : passe l'option `lien` ou définis `INVITE_LINK`.", - ephemeral: true, + flags: MessageFlags.Ephemeral, }); return; } - await interaction.deferReply({ ephemeral: true }); + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); if (!botCanPost(interaction)) { await interaction.editReply(NO_ACCESS_MESSAGE); diff --git a/src/commands/utility/listcommand.js b/src/commands/utility/listcommand.js index ea192b3..6551b46 100644 --- a/src/commands/utility/listcommand.js +++ b/src/commands/utility/listcommand.js @@ -1,28 +1,28 @@ -import { SlashCommandBuilder } from "discord.js"; - -const command = { - data: new SlashCommandBuilder() - .setName("listcommand") - .setDescription("Affiche la liste des commandes disponibles"), - async execute(interaction) { - let message = `Voila la liste des commandes que tu peux utiliser : - __Categorie Utililaires__ : - \`/deletemsgs\`: Supprime les 100 derniers messages non épinglés - \`/invitation\`: Publie le message d'invitation temporaire (lien vérifié) - - __Categorie Vocal__ : - \`/muteall\`: Rends tout le monde muet - \`/unmuteall\`: Rends la parole à tout le monde - \`/deafall\`: Rends tout le monde sourd - \`/undeafall\`: Rends l'ouïe à tout le monde - - __Categorie Jeux__ : - \`/dice\`: Lance un ou plusieurs dés avec un nombre de faces choisi - \`/maketeam\`: Crée un certain nombre d'équipes en renseignant des joueurs (séparés par un espace) - `; - - await interaction.reply({ content: message, ephemeral: true }); - }, -}; - -export { command }; +import { MessageFlags, SlashCommandBuilder } from "discord.js"; + +const command = { + data: new SlashCommandBuilder() + .setName("listcommand") + .setDescription("Affiche la liste des commandes disponibles"), + async execute(interaction) { + let message = `Voila la liste des commandes que tu peux utiliser : + __Categorie Utililaires__ : + \`/deletemsgs\`: Supprime les 100 derniers messages non épinglés + \`/invitation\`: Publie le message d'invitation temporaire (lien vérifié) + + __Categorie Vocal__ : + \`/muteall\`: Rends tout le monde muet + \`/unmuteall\`: Rends la parole à tout le monde + \`/deafall\`: Rends tout le monde sourd + \`/undeafall\`: Rends l'ouïe à tout le monde + + __Categorie Jeux__ : + \`/dice\`: Lance un ou plusieurs dés avec un nombre de faces choisi + \`/maketeam\`: Crée un certain nombre d'équipes en renseignant des joueurs (séparés par un espace) + `; + + await interaction.reply({ content: message, flags: MessageFlags.Ephemeral }); + }, +}; + +export { command }; diff --git a/src/commands/utility/ping.js b/src/commands/utility/ping.js index 46190ad..95ea08c 100644 --- a/src/commands/utility/ping.js +++ b/src/commands/utility/ping.js @@ -1,12 +1,12 @@ -import { SlashCommandBuilder } from "discord.js"; - -const command = { +import { MessageFlags, SlashCommandBuilder } from "discord.js"; + +const command = { data: new SlashCommandBuilder() - .setName("ping") - .setDescription("Reponds avec Pong"), + .setName("ping") + .setDescription("Reponds avec Pong"), async execute(interaction) { - await interaction.reply({ content: "Euh... Pong ! 🐱", ephemeral: true }); - }, -}; - -export { command }; + await interaction.reply({ content: "Euh... Pong ! 🐱", flags: MessageFlags.Ephemeral }); + }, +}; + +export { command }; diff --git a/src/commands/vocal/deafall.js b/src/commands/vocal/deafall.js index 9ec7ec5..9f7247a 100644 --- a/src/commands/vocal/deafall.js +++ b/src/commands/vocal/deafall.js @@ -1,17 +1,19 @@ import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { changeVoiceStatus } from "../../features/utilities.js"; import { requirePermission } from "../../features/permissions.js"; - -const command = { - data: new SlashCommandBuilder() + +const command = { + data: new SlashCommandBuilder() .setName("deafall") .setDescription("Deaf tout le monde dans le lounge") .setDefaultMemberPermissions(PermissionFlagsBits.DeafenMembers), async execute(interaction) { if (!(await requirePermission(interaction, PermissionFlagsBits.DeafenMembers))) return; + // Changer l'état de chaque membre peut dépasser les 3 s qu'accorde Discord pour répondre. + await interaction.deferReply(); await changeVoiceStatus(interaction.client, "deaf", "all"); - await interaction.reply("On n'entends plus rien ! 🐱"); - }, -}; - -export { command }; + await interaction.editReply("On n'entends plus rien ! 🐱"); + }, +}; + +export { command }; diff --git a/src/commands/vocal/muteall.js b/src/commands/vocal/muteall.js index 86f5dda..945c647 100644 --- a/src/commands/vocal/muteall.js +++ b/src/commands/vocal/muteall.js @@ -1,17 +1,19 @@ import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { changeVoiceStatus } from "../../features/utilities.js"; import { requirePermission } from "../../features/permissions.js"; - -const command = { - data: new SlashCommandBuilder() + +const command = { + data: new SlashCommandBuilder() .setName("muteall") .setDescription("Mute tout le monde dans le lounge") .setDefaultMemberPermissions(PermissionFlagsBits.MuteMembers), async execute(interaction) { if (!(await requirePermission(interaction, PermissionFlagsBits.MuteMembers))) return; + // Changer l'état de chaque membre peut dépasser les 3 s qu'accorde Discord pour répondre. + await interaction.deferReply(); await changeVoiceStatus(interaction.client, "mute", "all"); - await interaction.reply("Voila, tout le monde est mioute ! 🐱"); - }, -}; - -export { command }; + await interaction.editReply("Voila, tout le monde est mioute ! 🐱"); + }, +}; + +export { command }; diff --git a/src/commands/vocal/undeafall.js b/src/commands/vocal/undeafall.js index 878b82d..e081208 100644 --- a/src/commands/vocal/undeafall.js +++ b/src/commands/vocal/undeafall.js @@ -1,17 +1,19 @@ import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { changeVoiceStatus } from "../../features/utilities.js"; import { requirePermission } from "../../features/permissions.js"; - -const command = { - data: new SlashCommandBuilder() + +const command = { + data: new SlashCommandBuilder() .setName("undeafall") .setDescription("Undeaf tout le monde dans le lounge") .setDefaultMemberPermissions(PermissionFlagsBits.DeafenMembers), async execute(interaction) { if (!(await requirePermission(interaction, PermissionFlagsBits.DeafenMembers))) return; + // Changer l'état de chaque membre peut dépasser les 3 s qu'accorde Discord pour répondre. + await interaction.deferReply(); await changeVoiceStatus(interaction.client, "undeaf", "all"); - await interaction.reply("Voila, les oreilles sont réparées ! 🐱"); - }, -}; - -export { command }; + await interaction.editReply("Voila, les oreilles sont réparées ! 🐱"); + }, +}; + +export { command }; diff --git a/src/commands/vocal/unmuteall.js b/src/commands/vocal/unmuteall.js index cb83668..1f7fa69 100644 --- a/src/commands/vocal/unmuteall.js +++ b/src/commands/vocal/unmuteall.js @@ -1,17 +1,19 @@ import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { changeVoiceStatus } from "../../features/utilities.js"; import { requirePermission } from "../../features/permissions.js"; - -const command = { - data: new SlashCommandBuilder() + +const command = { + data: new SlashCommandBuilder() .setName("unmuteall") .setDescription("Unmute tout le monde dans le lounge") .setDefaultMemberPermissions(PermissionFlagsBits.MuteMembers), async execute(interaction) { if (!(await requirePermission(interaction, PermissionFlagsBits.MuteMembers))) return; + // Changer l'état de chaque membre peut dépasser les 3 s qu'accorde Discord pour répondre. + await interaction.deferReply(); await changeVoiceStatus(interaction.client, "unmute", "all"); - await interaction.reply("Et.... unmioute ! 🐱"); - }, -}; - -export { command }; + await interaction.editReply("Et.... unmioute ! 🐱"); + }, +}; + +export { command }; diff --git a/src/events/interactionCreate.js b/src/events/interactionCreate.js index 435e7a1..02ea72d 100644 --- a/src/events/interactionCreate.js +++ b/src/events/interactionCreate.js @@ -1,36 +1,48 @@ -import { Events } from "discord.js"; - -const event = { - name: Events.InteractionCreate, - async execute(interaction) { - if (!interaction.isChatInputCommand()) return; - +import { Events, MessageFlags } from "discord.js"; + +const ERROR_MESSAGE = "Oups, une erreur est survenue pendant la commande 😿"; + +const event = { + name: Events.InteractionCreate, + async execute(interaction) { + if (interaction.isAutocomplete()) { + const command = interaction.client.commands.get(interaction.commandName)?.command; + try { + await command?.autocomplete?.(interaction); + } catch (error) { + console.error(`Autocomplete failed for ${interaction.commandName}`, error); + } + return; + } + + if (!interaction.isChatInputCommand()) return; + const command = interaction.client.commands.get(interaction.commandName)?.command; - - if (!command) { - console.error( - `No command matching ${interaction.commandName} was found.` - ); - return; - } - - try { - await command.execute(interaction); - } catch (error) { - console.error(error); - if (interaction.replied || interaction.deferred) { - await interaction.followUp({ - content: "There was an error while executing this command!", - ephemeral: true, - }); - } else { - await interaction.reply({ - content: "There was an error while executing this command!", - ephemeral: true, - }); - } - } - }, -}; - -export { event }; + + if (!command) { + console.error( + `No command matching ${interaction.commandName} was found.` + ); + return; + } + + try { + await command.execute(interaction); + } catch (error) { + console.error(`Command ${interaction.commandName} failed`, error); + // Le message d'erreur peut lui-même échouer (interaction expirée) : on le journalise + // au lieu de laisser une promesse rejetée sans gestionnaire. + try { + if (interaction.replied || interaction.deferred) { + await interaction.followUp({ content: ERROR_MESSAGE, flags: MessageFlags.Ephemeral }); + } else { + await interaction.reply({ content: ERROR_MESSAGE, flags: MessageFlags.Ephemeral }); + } + } catch (replyError) { + console.error("Unable to report the command error to the user", replyError); + } + } + }, +}; + +export { event }; diff --git a/src/features/permissions.js b/src/features/permissions.js index 268ad95..ecdd252 100644 --- a/src/features/permissions.js +++ b/src/features/permissions.js @@ -1,3 +1,5 @@ +import { MessageFlags } from "discord.js"; + async function requirePermission(interaction, permission) { if (interaction.memberPermissions?.has(permission)) { return true; @@ -5,7 +7,7 @@ async function requirePermission(interaction, permission) { await interaction.reply({ content: "Tu n'as pas la permission d'utiliser cette commande.", - ephemeral: true, + flags: MessageFlags.Ephemeral, }); return false; } diff --git a/src/features/utilities.js b/src/features/utilities.js index 9bd332d..ce22090 100644 --- a/src/features/utilities.js +++ b/src/features/utilities.js @@ -1,6 +1,6 @@ -import fs from "fs"; +import fs from "fs"; import { config } from "../config.js"; - + async function changeVoiceStatus(client, status, members) { const changeStatus = async (type, value, selectedMembers) => { const operations = []; @@ -16,7 +16,15 @@ async function changeVoiceStatus(client, status, members) { } break; } - await Promise.all(operations); + // Un membre qui quitte le salon pendant l'opération ne doit pas faire échouer les autres. + const results = await Promise.allSettled(operations); + const failures = results.filter((result) => result.status === "rejected"); + if (failures.length > 0) { + console.error( + `changeVoiceStatus: ${failures.length} member(s) could not be updated`, + failures[0].reason + ); + } }; const voiceChannel = client.channels.cache.get(config.voiceChannelId); @@ -48,18 +56,18 @@ async function changeVoiceStatus(client, status, members) { throw new Error(`Statut vocal inconnu : ${status}`); } } - -function getJSONData(file) { - const jsonFile = fs.readFileSync(file); - const data = JSON.parse(jsonFile); - - return data; -} - -function getRandomInt(max) { - return Math.floor(Math.random() * max); -} - + +function getJSONData(file) { + const jsonFile = fs.readFileSync(file); + const data = JSON.parse(jsonFile); + + return data; +} + +function getRandomInt(max) { + return Math.floor(Math.random() * max); +} + export { changeVoiceStatus, getJSONData, diff --git a/src/web/server.js b/src/web/server.js index 8f99cf9..a4e5757 100644 --- a/src/web/server.js +++ b/src/web/server.js @@ -51,8 +51,15 @@ function createApp( app.use(helmet()); app.use(express.json({ limit: "32kb" })); + // /healthz : le processus répond (sonde de vie). /readyz : le bot est aussi connecté à + // Discord, sinon 503 (à utiliser pour la supervision). + const discordReady = () => dependencies.client?.isReady?.() ?? false; app.get("/healthz", (_req, res) => { - res.json({ status: "ok" }); + res.json({ status: "ok", discord: discordReady() ? "ready" : "not-ready" }); + }); + app.get("/readyz", (_req, res) => { + const ready = discordReady(); + res.status(ready ? 200 : 503).json({ status: ready ? "ready" : "not-ready" }); }); // Messages privés pour les applications de confiance : connexions locales uniquement, diff --git a/test/webServer.test.js b/test/webServer.test.js index da68460..701108f 100644 --- a/test/webServer.test.js +++ b/test/webServer.test.js @@ -114,3 +114,16 @@ test("only loopback connections count as local", () => { assert.equal(isLoopbackAddress(address), false); } }); + +test("/readyz reports whether the bot is connected to Discord", async () => { + const app = createApp({ queue: fakeQueue, client: { isReady: () => false } }); + const server = app.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", resolve)); + const base = `http://127.0.0.1:${server.address().port}`; + try { + assert.equal((await fetch(`${base}/healthz`)).status, 200); + assert.equal((await fetch(`${base}/readyz`)).status, 503); + } finally { + await new Promise((resolve) => server.close(resolve)); + } +});