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
# 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:

View file

@ -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 :

View file

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

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";
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 };

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 { 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);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -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,

View file

@ -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,

View file

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