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,4 +1,4 @@
import { SlashCommandBuilder } from "discord.js";
import { MessageFlags, SlashCommandBuilder } from "discord.js";
const command = {
data: new SlashCommandBuilder()
@ -28,7 +28,7 @@ const command = {
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;
}

View file

@ -1,4 +1,4 @@
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import { requirePermission } from "../../features/permissions.js";
const command = {
@ -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);

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,4 +1,4 @@
import { SlashCommandBuilder } from "discord.js";
import { MessageFlags, SlashCommandBuilder } from "discord.js";
const command = {
data: new SlashCommandBuilder()
@ -21,7 +21,7 @@ const command = {
\`/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 });
},
};

View file

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

View file

@ -9,8 +9,10 @@ const command = {
.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 ! 🐱");
await interaction.editReply("On n'entends plus rien ! 🐱");
},
};

View file

@ -9,8 +9,10 @@ const command = {
.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 ! 🐱");
await interaction.editReply("Voila, tout le monde est mioute ! 🐱");
},
};

View file

@ -9,8 +9,10 @@ const command = {
.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 ! 🐱");
await interaction.editReply("Voila, les oreilles sont réparées ! 🐱");
},
};

View file

@ -9,8 +9,10 @@ const command = {
.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 ! 🐱");
await interaction.editReply("Et.... unmioute ! 🐱");
},
};

View file

@ -1,8 +1,20 @@
import { Events } from "discord.js";
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;
@ -17,17 +29,17 @@ const event = {
try {
await command.execute(interaction);
} catch (error) {
console.error(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: "There was an error while executing this command!",
ephemeral: true,
});
await interaction.followUp({ content: ERROR_MESSAGE, flags: MessageFlags.Ephemeral });
} else {
await interaction.reply({
content: "There was an error while executing this command!",
ephemeral: true,
});
await interaction.reply({ content: ERROR_MESSAGE, flags: MessageFlags.Ephemeral });
}
} catch (replyError) {
console.error("Unable to report the command error to the user", replyError);
}
}
},

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

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

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