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 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-29 12:04:43 +01:00
parent a1cefe6da5
commit 362c7772ba
16 changed files with 245 additions and 176 deletions

View file

@ -1,18 +1,33 @@
name: Deploy Palico Bot 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: on:
push: push:
branches: pull_request:
- main
jobs: jobs:
deploy: check:
runs-on: docker runs-on: docker
# Image fixée ici : celle du label « docker » (node:20-bullseye) n'est plus maintenue, # 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). # et son miroir de sécurité renvoie 404 (échec du run 4).
container: container:
image: node:24-bookworm 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: steps:
- name: Deploy on WebApps - name: Deploy on WebApps
env: env:

View file

@ -59,10 +59,14 @@ cp src/static/gameservers-list.example.json src/static/gameservers-list.json
## Déploiement ## Déploiement
Un push sur `main` lance `.forgejo/workflows/deploy.yml`, qui se connecte en SSH `.forgejo/workflows/deploy.yml` lance `npm ci` puis `npm run check` (syntaxe et
à la VM et exécute `/usr/local/bin/deploy-palico-bot` (mise à jour du dépôt, tests) à chaque push, sur toutes les branches. Sur `main`, et seulement si ces
dépendances, redémarrage du service `palico-bot`). Le workflow ne lance ni les contrôles réussissent, il se connecte ensuite en SSH à la VM et exécute
contrôles ni les tests : lancer `npm run check` avant de pousser. `/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 : Variables facultatives :

View file

@ -1,34 +1,34 @@
import { SlashCommandBuilder } from "discord.js"; import { MessageFlags, SlashCommandBuilder } from "discord.js";
const command = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("maketeam") .setName("maketeam")
.setDescription("Crée des equipes au hasard") .setDescription("Crée des equipes au hasard")
.addIntegerOption((option) => .addIntegerOption((option) =>
option option
.setName("number") .setName("number")
.setDescription("Nombre d'équipe") .setDescription("Nombre d'équipe")
.setMinValue(1) .setMinValue(1)
.setMaxValue(20) .setMaxValue(20)
.setRequired(true) .setRequired(true)
) )
.addStringOption((option) => .addStringOption((option) =>
option option
.setName("players") .setName("players")
.setDescription("Liste des joueurs, séparés par un espace") .setDescription("Liste des joueurs, séparés par un espace")
.setMinLength(1) .setMinLength(1)
.setMaxLength(1000) .setMaxLength(1000)
.setRequired(true) .setRequired(true)
), ),
async execute(interaction) { async execute(interaction) {
const teamNumber = interaction.options.getInteger("number"); const teamNumber = interaction.options.getInteger("number");
const players = interaction.options.getString("players"); const players = interaction.options.getString("players");
const playersArray = players.trim().split(/\s+/); const playersArray = players.trim().split(/\s+/);
if (teamNumber > playersArray.length) { if (teamNumber > playersArray.length) {
await interaction.reply({ await interaction.reply({
content: "Le nombre d'équipes ne peut pas dépasser le nombre de joueurs.", content: "Le nombre d'équipes ne peut pas dépasser le nombre de joueurs.",
ephemeral: true, flags: MessageFlags.Ephemeral,
}); });
return; return;
} }
@ -42,22 +42,22 @@ const command = {
shuffledPlayers[index], shuffledPlayers[index],
]; ];
} }
shuffledPlayers.forEach((player, index) => { shuffledPlayers.forEach((player, index) => {
const teamIndex = index % teamNumber; const teamIndex = index % teamNumber;
teams[teamIndex].push(player); teams[teamIndex].push(player);
}); });
let message = ""; let message = "";
let teamList = ""; let teamList = "";
teams.forEach((team, index) => { teams.forEach((team, index) => {
teamList = `${teamList}\n${index + 1}. ${team.join(", ")}`; teamList = `${teamList}\n${index + 1}. ${team.join(", ")}`;
}); });
message = `Yop ! Voici les équipes proposés :\n${teamList}`; message = `Yop ! Voici les équipes proposés :\n${teamList}`;
await interaction.reply(message); await interaction.reply(message);
}, },
}; };
export { command }; export { command };

View file

@ -1,8 +1,8 @@
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { requirePermission } from "../../features/permissions.js"; import { requirePermission } from "../../features/permissions.js";
const command = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("deletemsgs") .setName("deletemsgs")
.setDescription("Supprime tous les messages, sauf ceux épinglés") .setDescription("Supprime tous les messages, sauf ceux épinglés")
.setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages), .setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages),
@ -15,12 +15,12 @@ const command = {
if (!textChannel?.isTextBased() || !textChannel.messages) { if (!textChannel?.isTextBased() || !textChannel.messages) {
await interaction.reply({ await interaction.reply({
content: "Cette commande doit être utilisée dans un salon textuel.", content: "Cette commande doit être utilisée dans un salon textuel.",
ephemeral: true, flags: MessageFlags.Ephemeral,
}); });
return; return;
} }
await interaction.deferReply({ ephemeral: true }); await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const fetched = await textChannel.messages.fetch({ limit: 100 }); const fetched = await textChannel.messages.fetch({ limit: 100 });
const notPinned = fetched.filter((message) => !message.pinned); const notPinned = fetched.filter((message) => !message.pinned);
const deleted = await textChannel.bulkDelete(notPinned, true); const deleted = await textChannel.bulkDelete(notPinned, true);
@ -28,5 +28,5 @@ const command = {
await interaction.editReply(`Et voilà, ${deleted.size} message(s) supprimé(s) ! 🐱`); await interaction.editReply(`Et voilà, ${deleted.size} message(s) supprimé(s) ! 🐱`);
}, },
}; };
export { command }; export { command };

View file

@ -1,4 +1,4 @@
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { config } from "../../config.js"; import { config } from "../../config.js";
import { requirePermission } from "../../features/permissions.js"; import { requirePermission } from "../../features/permissions.js";
import { import {
@ -40,7 +40,7 @@ const command = {
if (!interaction.guild || !channel?.isTextBased()) { if (!interaction.guild || !channel?.isTextBased()) {
await interaction.reply({ await interaction.reply({
content: "Cette commande doit être utilisée dans un salon textuel du serveur.", content: "Cette commande doit être utilisée dans un salon textuel du serveur.",
ephemeral: true, flags: MessageFlags.Ephemeral,
}); });
return; return;
} }
@ -49,12 +49,12 @@ const command = {
if (!input) { if (!input) {
await interaction.reply({ await interaction.reply({
content: "Aucun lien : passe l'option `lien` ou définis `INVITE_LINK`.", content: "Aucun lien : passe l'option `lien` ou définis `INVITE_LINK`.",
ephemeral: true, flags: MessageFlags.Ephemeral,
}); });
return; return;
} }
await interaction.deferReply({ ephemeral: true }); await interaction.deferReply({ flags: MessageFlags.Ephemeral });
if (!botCanPost(interaction)) { if (!botCanPost(interaction)) {
await interaction.editReply(NO_ACCESS_MESSAGE); await interaction.editReply(NO_ACCESS_MESSAGE);

View file

@ -1,28 +1,28 @@
import { SlashCommandBuilder } from "discord.js"; import { MessageFlags, SlashCommandBuilder } from "discord.js";
const command = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("listcommand") .setName("listcommand")
.setDescription("Affiche la liste des commandes disponibles"), .setDescription("Affiche la liste des commandes disponibles"),
async execute(interaction) { async execute(interaction) {
let message = `Voila la liste des commandes que tu peux utiliser : let message = `Voila la liste des commandes que tu peux utiliser :
__Categorie Utililaires__ : __Categorie Utililaires__ :
\`/deletemsgs\`: Supprime les 100 derniers messages non épinglés \`/deletemsgs\`: Supprime les 100 derniers messages non épinglés
\`/invitation\`: Publie le message d'invitation temporaire (lien vérifié) \`/invitation\`: Publie le message d'invitation temporaire (lien vérifié)
__Categorie Vocal__ : __Categorie Vocal__ :
\`/muteall\`: Rends tout le monde muet \`/muteall\`: Rends tout le monde muet
\`/unmuteall\`: Rends la parole à tout le monde \`/unmuteall\`: Rends la parole à tout le monde
\`/deafall\`: Rends tout le monde sourd \`/deafall\`: Rends tout le monde sourd
\`/undeafall\`: Rends l'ouïe à tout le monde \`/undeafall\`: Rends l'ouïe à tout le monde
__Categorie Jeux__ : __Categorie Jeux__ :
\`/dice\`: Lance un ou plusieurs dés avec un nombre de faces choisi \`/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) \`/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 }); await interaction.reply({ content: message, flags: MessageFlags.Ephemeral });
}, },
}; };
export { command }; export { command };

View file

@ -1,12 +1,12 @@
import { SlashCommandBuilder } from "discord.js"; import { MessageFlags, SlashCommandBuilder } from "discord.js";
const command = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("ping") .setName("ping")
.setDescription("Reponds avec Pong"), .setDescription("Reponds avec Pong"),
async execute(interaction) { async execute(interaction) {
await interaction.reply({ content: "Euh... Pong ! 🐱", ephemeral: true }); await interaction.reply({ content: "Euh... Pong ! 🐱", flags: MessageFlags.Ephemeral });
}, },
}; };
export { command }; export { command };

View file

@ -1,17 +1,19 @@
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { changeVoiceStatus } from "../../features/utilities.js"; import { changeVoiceStatus } from "../../features/utilities.js";
import { requirePermission } from "../../features/permissions.js"; import { requirePermission } from "../../features/permissions.js";
const command = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("deafall") .setName("deafall")
.setDescription("Deaf tout le monde dans le lounge") .setDescription("Deaf tout le monde dans le lounge")
.setDefaultMemberPermissions(PermissionFlagsBits.DeafenMembers), .setDefaultMemberPermissions(PermissionFlagsBits.DeafenMembers),
async execute(interaction) { async execute(interaction) {
if (!(await requirePermission(interaction, PermissionFlagsBits.DeafenMembers))) return; 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 changeVoiceStatus(interaction.client, "deaf", "all");
await interaction.reply("On n'entends plus rien ! 🐱"); await interaction.editReply("On n'entends plus rien ! 🐱");
}, },
}; };
export { command }; export { command };

View file

@ -1,17 +1,19 @@
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { changeVoiceStatus } from "../../features/utilities.js"; import { changeVoiceStatus } from "../../features/utilities.js";
import { requirePermission } from "../../features/permissions.js"; import { requirePermission } from "../../features/permissions.js";
const command = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("muteall") .setName("muteall")
.setDescription("Mute tout le monde dans le lounge") .setDescription("Mute tout le monde dans le lounge")
.setDefaultMemberPermissions(PermissionFlagsBits.MuteMembers), .setDefaultMemberPermissions(PermissionFlagsBits.MuteMembers),
async execute(interaction) { async execute(interaction) {
if (!(await requirePermission(interaction, PermissionFlagsBits.MuteMembers))) return; 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 changeVoiceStatus(interaction.client, "mute", "all");
await interaction.reply("Voila, tout le monde est mioute ! 🐱"); await interaction.editReply("Voila, tout le monde est mioute ! 🐱");
}, },
}; };
export { command }; export { command };

View file

@ -1,17 +1,19 @@
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { changeVoiceStatus } from "../../features/utilities.js"; import { changeVoiceStatus } from "../../features/utilities.js";
import { requirePermission } from "../../features/permissions.js"; import { requirePermission } from "../../features/permissions.js";
const command = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("undeafall") .setName("undeafall")
.setDescription("Undeaf tout le monde dans le lounge") .setDescription("Undeaf tout le monde dans le lounge")
.setDefaultMemberPermissions(PermissionFlagsBits.DeafenMembers), .setDefaultMemberPermissions(PermissionFlagsBits.DeafenMembers),
async execute(interaction) { async execute(interaction) {
if (!(await requirePermission(interaction, PermissionFlagsBits.DeafenMembers))) return; 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 changeVoiceStatus(interaction.client, "undeaf", "all");
await interaction.reply("Voila, les oreilles sont réparées ! 🐱"); await interaction.editReply("Voila, les oreilles sont réparées ! 🐱");
}, },
}; };
export { command }; export { command };

View file

@ -1,17 +1,19 @@
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js"; import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { changeVoiceStatus } from "../../features/utilities.js"; import { changeVoiceStatus } from "../../features/utilities.js";
import { requirePermission } from "../../features/permissions.js"; import { requirePermission } from "../../features/permissions.js";
const command = { const command = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("unmuteall") .setName("unmuteall")
.setDescription("Unmute tout le monde dans le lounge") .setDescription("Unmute tout le monde dans le lounge")
.setDefaultMemberPermissions(PermissionFlagsBits.MuteMembers), .setDefaultMemberPermissions(PermissionFlagsBits.MuteMembers),
async execute(interaction) { async execute(interaction) {
if (!(await requirePermission(interaction, PermissionFlagsBits.MuteMembers))) return; 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 changeVoiceStatus(interaction.client, "unmute", "all");
await interaction.reply("Et.... unmioute ! 🐱"); await interaction.editReply("Et.... unmioute ! 🐱");
}, },
}; };
export { command }; export { command };

View file

@ -1,36 +1,48 @@
import { Events } from "discord.js"; import { Events, MessageFlags } from "discord.js";
const event = { const ERROR_MESSAGE = "Oups, une erreur est survenue pendant la commande 😿";
name: Events.InteractionCreate,
async execute(interaction) { const event = {
if (!interaction.isChatInputCommand()) return; 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; const command = interaction.client.commands.get(interaction.commandName)?.command;
if (!command) { if (!command) {
console.error( console.error(
`No command matching ${interaction.commandName} was found.` `No command matching ${interaction.commandName} was found.`
); );
return; return;
} }
try { try {
await command.execute(interaction); await command.execute(interaction);
} catch (error) { } catch (error) {
console.error(error); console.error(`Command ${interaction.commandName} failed`, error);
if (interaction.replied || interaction.deferred) { // Le message d'erreur peut lui-même échouer (interaction expirée) : on le journalise
await interaction.followUp({ // au lieu de laisser une promesse rejetée sans gestionnaire.
content: "There was an error while executing this command!", try {
ephemeral: true, if (interaction.replied || interaction.deferred) {
}); await interaction.followUp({ content: ERROR_MESSAGE, flags: MessageFlags.Ephemeral });
} else { } else {
await interaction.reply({ await interaction.reply({ content: ERROR_MESSAGE, flags: MessageFlags.Ephemeral });
content: "There was an error while executing this command!", }
ephemeral: true, } catch (replyError) {
}); console.error("Unable to report the command error to the user", replyError);
} }
} }
}, },
}; };
export { event }; export { event };

View file

@ -1,3 +1,5 @@
import { MessageFlags } from "discord.js";
async function requirePermission(interaction, permission) { async function requirePermission(interaction, permission) {
if (interaction.memberPermissions?.has(permission)) { if (interaction.memberPermissions?.has(permission)) {
return true; return true;
@ -5,7 +7,7 @@ async function requirePermission(interaction, permission) {
await interaction.reply({ await interaction.reply({
content: "Tu n'as pas la permission d'utiliser cette commande.", content: "Tu n'as pas la permission d'utiliser cette commande.",
ephemeral: true, flags: MessageFlags.Ephemeral,
}); });
return false; return false;
} }

View file

@ -1,6 +1,6 @@
import fs from "fs"; import fs from "fs";
import { config } from "../config.js"; import { config } from "../config.js";
async function changeVoiceStatus(client, status, members) { async function changeVoiceStatus(client, status, members) {
const changeStatus = async (type, value, selectedMembers) => { const changeStatus = async (type, value, selectedMembers) => {
const operations = []; const operations = [];
@ -16,7 +16,15 @@ async function changeVoiceStatus(client, status, members) {
} }
break; 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); 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}`); throw new Error(`Statut vocal inconnu : ${status}`);
} }
} }
function getJSONData(file) { function getJSONData(file) {
const jsonFile = fs.readFileSync(file); const jsonFile = fs.readFileSync(file);
const data = JSON.parse(jsonFile); const data = JSON.parse(jsonFile);
return data; return data;
} }
function getRandomInt(max) { function getRandomInt(max) {
return Math.floor(Math.random() * max); return Math.floor(Math.random() * max);
} }
export { export {
changeVoiceStatus, changeVoiceStatus,
getJSONData, getJSONData,

View file

@ -51,8 +51,15 @@ function createApp(
app.use(helmet()); app.use(helmet());
app.use(express.json({ limit: "32kb" })); 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) => { 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, // Messages privés pour les applications de confiance : connexions locales uniquement,

View file

@ -114,3 +114,16 @@ test("only loopback connections count as local", () => {
assert.equal(isLoopbackAddress(address), false); 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));
}
});