Fix vulnerable deps, shutdown and game server colours; tidy commands
Fixes:
- Update dependencies within their ranges: npm audit reported 8
vulnerabilities (proxy-addr, multer, body-parser, undici...), now 0.
- Close open connections on shutdown: an open jukebox page kept its
/api/events stream alive, so every restart waited for the 10 s
forced exit and ended with code 1.
- Restore the ANSI escape characters of the game servers message, lost
in a269824 (the status showed "[2;32mOnline[0m" as plain text). They
are now written as \u001b so they cannot silently disappear again.
- Rename MusicQueue.listeners(), which shadowed EventEmitter's own
listeners(eventName), to humanListeners().
- Deploy: check the VM's SSH host key (new DEPLOY_KNOWN_HOSTS secret)
instead of StrictHostKeyChecking=no; run checks on push only, since
PR branches are already checked by their push.
Commands:
- /listcommand is built from the loaded commands and their descriptions.
- /deletemsgs reports messages older than 14 days that it cannot delete.
- Vocal commands act on the caller's voice channel, falling back to
VOICE_CHANNEL_ID.
- /maketeam accepts comma-separated names, so names can contain spaces.
- The game servers message is edited whenever its content changes, and
a failed first update is retried instead of stopping the refresh.
Cleanup:
- Shared command loader (src/loadCommands.js); drop the unused
"[disabled]" folders mechanism and the NODE_ENV requirement.
- SHINUWA_USER_ID becomes OWNER_USER_ID (the old name still works).
- One shuffle helper instead of three copies; remove dead code
(validateAudioFile, PORT fallback, needless async).
- README: prerequisites first, consistent Node version, deploy secrets.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
60080df7dc
commit
e08dba41a3
30 changed files with 638 additions and 643 deletions
|
|
@ -1,67 +1,64 @@
|
|||
import { SlashCommandBuilder, subtext } from "discord.js";
|
||||
import { setTimeout } from "node:timers/promises";
|
||||
import { getRandomInt } from "../../features/utilities.js";
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("dice")
|
||||
.setDescription("Lance un ou plusieurs dés")
|
||||
.addIntegerOption((option) =>
|
||||
option
|
||||
import { SlashCommandBuilder, subtext } from "discord.js";
|
||||
import { setTimeout } from "node:timers/promises";
|
||||
import { getRandomInt } from "../../features/utilities.js";
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("dice")
|
||||
.setDescription("Lance un ou plusieurs dés")
|
||||
.addIntegerOption((option) =>
|
||||
option
|
||||
.setName("number")
|
||||
.setDescription("Nombre de dés a lancer")
|
||||
.setDescription("Nombre de dés à lancer")
|
||||
.setMinValue(1)
|
||||
.setMaxValue(20)
|
||||
.setRequired(true)
|
||||
)
|
||||
.addIntegerOption((option) =>
|
||||
option
|
||||
)
|
||||
.addIntegerOption((option) =>
|
||||
option
|
||||
.setName("faces")
|
||||
.setDescription("Nombre de faces sur le dé")
|
||||
.setMinValue(2)
|
||||
.setMaxValue(1000)
|
||||
.setRequired(true)
|
||||
),
|
||||
async execute(interaction) {
|
||||
const number = interaction.options.getInteger("number");
|
||||
const faces = interaction.options.getInteger("faces");
|
||||
var sum = 0;
|
||||
var message = "Alors du coup... 🥁\n";
|
||||
var tails = 0;
|
||||
var heads = 0;
|
||||
|
||||
if (faces === 2) {
|
||||
message = message + subtext(`Pile = 1 et Face = 2\n`);
|
||||
}
|
||||
|
||||
await interaction.reply(message);
|
||||
|
||||
for (let i = 0; i < number; i++) {
|
||||
await setTimeout(1_500);
|
||||
let random = getRandomInt(faces) + 1;
|
||||
random === 1 ? tails++ : heads++;
|
||||
sum = sum + random;
|
||||
|
||||
message = message + `[ ${random} ] ${i === number - 1 ? "\n" : " "}`;
|
||||
),
|
||||
async execute(interaction) {
|
||||
const number = interaction.options.getInteger("number");
|
||||
const faces = interaction.options.getInteger("faces");
|
||||
let sum = 0;
|
||||
let message = "Alors du coup... 🥁\n";
|
||||
let tails = 0;
|
||||
let heads = 0;
|
||||
|
||||
if (faces === 2) {
|
||||
message += subtext("Pile = 1 et Face = 2\n");
|
||||
}
|
||||
|
||||
await interaction.reply(message);
|
||||
|
||||
for (let i = 0; i < number; i++) {
|
||||
await setTimeout(1_500);
|
||||
const random = getRandomInt(faces) + 1;
|
||||
if (random === 1) tails++;
|
||||
else heads++;
|
||||
sum += random;
|
||||
|
||||
message += `[ ${random} ] ${i === number - 1 ? "\n" : " "}`;
|
||||
await interaction.editReply(message);
|
||||
}
|
||||
|
||||
if (number > 1 && faces > 2) {
|
||||
await setTimeout(1_000);
|
||||
message = message + subtext(`Soit au total : ${sum}`);
|
||||
}
|
||||
|
||||
if (number > 1 && faces === 2) {
|
||||
await setTimeout(1_000);
|
||||
message =
|
||||
message +
|
||||
subtext(
|
||||
`Soit au total : ${sum}, ou bien ${tails} piles et ${heads} faces \n`
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (number > 1 && faces > 2) {
|
||||
await setTimeout(1_000);
|
||||
message += subtext(`Soit au total : ${sum}`);
|
||||
}
|
||||
|
||||
if (number > 1 && faces === 2) {
|
||||
await setTimeout(1_000);
|
||||
message += subtext(`Soit au total : ${sum}, ou bien ${tails} piles et ${heads} faces\n`);
|
||||
}
|
||||
|
||||
await interaction.editReply(message);
|
||||
},
|
||||
};
|
||||
|
||||
export { command };
|
||||
},
|
||||
};
|
||||
|
||||
export { command };
|
||||
|
|
|
|||
|
|
@ -1,13 +1,24 @@
|
|||
import { MessageFlags, SlashCommandBuilder } from "discord.js";
|
||||
import { shuffle } from "../../features/utilities.js";
|
||||
|
||||
// « Alice Bob » ou « Jean Pierre, Marie » : dès qu'il y a une virgule, seules les virgules
|
||||
// séparent les joueurs.
|
||||
function parsePlayers(input) {
|
||||
const separator = input.includes(",") ? "," : /\s+/;
|
||||
return input
|
||||
.split(separator)
|
||||
.map((player) => player.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("maketeam")
|
||||
.setDescription("Crée des equipes au hasard")
|
||||
.setDescription("Crée des équipes au hasard")
|
||||
.addIntegerOption((option) =>
|
||||
option
|
||||
.setName("number")
|
||||
.setDescription("Nombre d'équipe")
|
||||
.setDescription("Nombre d'équipes")
|
||||
.setMinValue(1)
|
||||
.setMaxValue(20)
|
||||
.setRequired(true)
|
||||
|
|
@ -15,7 +26,7 @@ const command = {
|
|||
.addStringOption((option) =>
|
||||
option
|
||||
.setName("players")
|
||||
.setDescription("Liste des joueurs, séparés par un espace")
|
||||
.setDescription("Joueurs séparés par des espaces, ou par des virgules si un nom contient un espace")
|
||||
.setMinLength(1)
|
||||
.setMaxLength(1000)
|
||||
.setRequired(true)
|
||||
|
|
@ -23,9 +34,9 @@ const command = {
|
|||
async execute(interaction) {
|
||||
const teamNumber = interaction.options.getInteger("number");
|
||||
const players = interaction.options.getString("players");
|
||||
const playersArray = players.trim().split(/\s+/);
|
||||
const playersArray = parsePlayers(players);
|
||||
|
||||
if (teamNumber > playersArray.length) {
|
||||
if (playersArray.length === 0 || teamNumber > playersArray.length) {
|
||||
await interaction.reply({
|
||||
content: "Le nombre d'équipes ne peut pas dépasser le nombre de joueurs.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
|
|
@ -34,30 +45,16 @@ const command = {
|
|||
}
|
||||
|
||||
const teams = Array.from({ length: teamNumber }, () => []);
|
||||
const shuffledPlayers = [...playersArray];
|
||||
for (let index = shuffledPlayers.length - 1; index > 0; index--) {
|
||||
const randomIndex = Math.floor(Math.random() * (index + 1));
|
||||
[shuffledPlayers[index], shuffledPlayers[randomIndex]] = [
|
||||
shuffledPlayers[randomIndex],
|
||||
shuffledPlayers[index],
|
||||
];
|
||||
}
|
||||
|
||||
shuffledPlayers.forEach((player, index) => {
|
||||
shuffle(playersArray).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);
|
||||
const teamList = teams
|
||||
.map((team, index) => `${index + 1}. ${team.join(", ")}`)
|
||||
.join("\n");
|
||||
await interaction.reply(`Yop ! Voici les équipes proposées :\n\n${teamList}`);
|
||||
},
|
||||
};
|
||||
|
||||
export { command };
|
||||
export { command, parsePlayers };
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { requirePermission } from "../../features/permissions.js";
|
|||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("deletemsgs")
|
||||
.setDescription("Supprime tous les messages, sauf ceux épinglés")
|
||||
.setDescription("Supprime les 100 derniers messages, sauf ceux épinglés")
|
||||
.setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages),
|
||||
async execute(interaction) {
|
||||
if (!(await requirePermission(interaction, PermissionFlagsBits.ManageMessages))) {
|
||||
|
|
@ -23,9 +23,20 @@ const command = {
|
|||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
const fetched = await textChannel.messages.fetch({ limit: 100 });
|
||||
const notPinned = fetched.filter((message) => !message.pinned);
|
||||
// Discord refuse la suppression groupée des messages de plus de 14 jours : ils restent.
|
||||
const deleted = await textChannel.bulkDelete(notPinned, true);
|
||||
const tooOld = notPinned.size - deleted.size;
|
||||
|
||||
await interaction.editReply(`Et voilà, ${deleted.size} message(s) supprimé(s) ! 🐱`);
|
||||
await interaction.editReply(
|
||||
[
|
||||
`Et voilà, ${deleted.size} message(s) supprimé(s) ! 🐱`,
|
||||
tooOld > 0
|
||||
? `${tooOld} message(s) de plus de 14 jours restent : Discord ne permet pas de les supprimer en lot.`
|
||||
: null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n")
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,33 +1,31 @@
|
|||
import { MessageFlags, SlashCommandBuilder } from "discord.js";
|
||||
|
||||
// Liste construite à partir des commandes chargées : une commande ajoutée y apparaît d'office,
|
||||
// avec sa description.
|
||||
function buildCommandList(commands) {
|
||||
const byCategory = new Map();
|
||||
for (const command of commands) {
|
||||
const lines = byCategory.get(command.category) ?? [];
|
||||
lines.push(`\`/${command.data.name}\` : ${command.data.description}`);
|
||||
byCategory.set(command.category, lines);
|
||||
}
|
||||
|
||||
const sections = [...byCategory].map(
|
||||
([category, lines]) => `__${category}__\n${lines.join("\n")}`
|
||||
);
|
||||
return `Voilà la liste des commandes que tu peux utiliser :\n\n${sections.join("\n\n")}`;
|
||||
}
|
||||
|
||||
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 Jukebox__ :
|
||||
\`/play\`: Ajoute un morceau (fichier, lien direct ou morceau de la bibliothèque)
|
||||
\`/skip\`: Passe au morceau suivant
|
||||
\`/queue\`: Affiche la file d'attente
|
||||
|
||||
__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 });
|
||||
await interaction.reply({
|
||||
content: buildCommandList(interaction.client.commands.values()),
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
export { command };
|
||||
export { buildCommandList, command };
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { MessageFlags, SlashCommandBuilder } from "discord.js";
|
|||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("ping")
|
||||
.setDescription("Reponds avec Pong"),
|
||||
.setDescription("Répond avec Pong"),
|
||||
async execute(interaction) {
|
||||
await interaction.reply({ content: "Euh... Pong ! 🐱", flags: MessageFlags.Ephemeral });
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
|
||||
import { changeVoiceStatus } from "../../features/utilities.js";
|
||||
import { changeVoiceStatus, commandVoiceChannel } from "../../features/utilities.js";
|
||||
import { requirePermission } from "../../features/permissions.js";
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("deafall")
|
||||
.setDescription("Deaf tout le monde dans le lounge")
|
||||
.setDescription("Rend tout le monde sourd dans le salon vocal")
|
||||
.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 changeVoiceStatus(commandVoiceChannel(interaction), "deaf");
|
||||
await interaction.editReply("On n'entends plus rien ! 🐱");
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
|
||||
import { changeVoiceStatus } from "../../features/utilities.js";
|
||||
import { changeVoiceStatus, commandVoiceChannel } from "../../features/utilities.js";
|
||||
import { requirePermission } from "../../features/permissions.js";
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("muteall")
|
||||
.setDescription("Mute tout le monde dans le lounge")
|
||||
.setDescription("Rend tout le monde muet dans le salon vocal")
|
||||
.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 changeVoiceStatus(commandVoiceChannel(interaction), "mute");
|
||||
await interaction.editReply("Voila, tout le monde est mioute ! 🐱");
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
|
||||
import { changeVoiceStatus } from "../../features/utilities.js";
|
||||
import { changeVoiceStatus, commandVoiceChannel } from "../../features/utilities.js";
|
||||
import { requirePermission } from "../../features/permissions.js";
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("undeafall")
|
||||
.setDescription("Undeaf tout le monde dans le lounge")
|
||||
.setDescription("Rend l'ouïe à tout le monde dans le salon vocal")
|
||||
.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 changeVoiceStatus(commandVoiceChannel(interaction), "undeaf");
|
||||
await interaction.editReply("Voila, les oreilles sont réparées ! 🐱");
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
import { PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
|
||||
import { changeVoiceStatus } from "../../features/utilities.js";
|
||||
import { changeVoiceStatus, commandVoiceChannel } from "../../features/utilities.js";
|
||||
import { requirePermission } from "../../features/permissions.js";
|
||||
|
||||
const command = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName("unmuteall")
|
||||
.setDescription("Unmute tout le monde dans le lounge")
|
||||
.setDescription("Rend la parole à tout le monde dans le salon vocal")
|
||||
.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 changeVoiceStatus(commandVoiceChannel(interaction), "unmute");
|
||||
await interaction.editReply("Et.... unmioute ! 🐱");
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
// OWNER_USER_ID : la personne qui gère les serveurs de jeux (mentionnée dans leur message).
|
||||
// Ancien nom, encore accepté : SHINUWA_USER_ID.
|
||||
process.env.OWNER_USER_ID ||= process.env.SHINUWA_USER_ID;
|
||||
|
||||
const requiredVariables = [
|
||||
"NODE_ENV",
|
||||
"DISCORD_GUILD_ID",
|
||||
"SHINUWA_USER_ID",
|
||||
"OWNER_USER_ID",
|
||||
"WEB_SERVER_PORT",
|
||||
"WEB_API_KEY",
|
||||
"DISCORD_APPLICATION_ID",
|
||||
|
|
@ -76,9 +79,8 @@ if (notificationsApiKey && notificationsApiKey === process.env.WEB_API_KEY) {
|
|||
}
|
||||
|
||||
const config = Object.freeze({
|
||||
environnement: process.env.NODE_ENV,
|
||||
discordGuildId: process.env.DISCORD_GUILD_ID,
|
||||
shinuwaUserId: process.env.SHINUWA_USER_ID,
|
||||
ownerUserId: process.env.OWNER_USER_ID,
|
||||
webServerPort,
|
||||
webApiKey: process.env.WEB_API_KEY,
|
||||
webTrustedProxies,
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ const event = {
|
|||
name: Events.InteractionCreate,
|
||||
async execute(interaction) {
|
||||
if (interaction.isAutocomplete()) {
|
||||
const command = interaction.client.commands.get(interaction.commandName)?.command;
|
||||
const command = interaction.client.commands.get(interaction.commandName);
|
||||
try {
|
||||
await command?.autocomplete?.(interaction);
|
||||
} catch (error) {
|
||||
|
|
@ -17,7 +17,7 @@ const event = {
|
|||
|
||||
if (!interaction.isChatInputCommand()) return;
|
||||
|
||||
const command = interaction.client.commands.get(interaction.commandName)?.command;
|
||||
const command = interaction.client.commands.get(interaction.commandName);
|
||||
|
||||
if (!command) {
|
||||
console.error(
|
||||
|
|
|
|||
|
|
@ -12,11 +12,8 @@ const event = {
|
|||
// File rechargée au démarrage : reprendre si quelqu'un est déjà dans le salon vocal.
|
||||
client.musicQueue?.evaluateAloneStatus();
|
||||
|
||||
try {
|
||||
await showGameServers(client);
|
||||
} catch (error) {
|
||||
console.error("Unable to initialize game server status", error);
|
||||
}
|
||||
// Les erreurs sont journalisées et retentées par showGameServers lui-même.
|
||||
await showGameServers(client);
|
||||
},
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -4,8 +4,14 @@ import { getJSONData } from "./utilities.js";
|
|||
|
||||
const PROBE_TIMEOUT = 3_000;
|
||||
const REFRESH_INTERVAL = 120_000;
|
||||
// Couleurs ANSI des blocs « ```ansi » de Discord. Échappements écrits en \u001b : un caractère
|
||||
// ESC brut est invisible dans l'éditeur et a déjà disparu lors d'une modification.
|
||||
const ONLINE = "\u001b[2;32mOnline\u001b[0m";
|
||||
const OFFLINE = "\u001b[2;31mOffline\u001b[0m";
|
||||
|
||||
var currentStatus = [];
|
||||
// Dernier message publié : on ne le réédite que si son contenu change (état d'un serveur,
|
||||
// mais aussi serveur ajouté ou adresse modifiée dans la liste).
|
||||
let publishedMessage = null;
|
||||
|
||||
// Essaie d'ouvrir une connexion TCP : vrai si le port répond dans le délai.
|
||||
function probeTcp(host, port, { timeout = PROBE_TIMEOUT, connect = net.connect } = {}) {
|
||||
|
|
@ -47,35 +53,29 @@ async function readServers(probe) {
|
|||
return { ...data, servers };
|
||||
}
|
||||
|
||||
async function checkServersStatus(client) {
|
||||
const data = await readServers();
|
||||
const newStatus = data.servers.map((server) => server.active);
|
||||
function buildMessage(data) {
|
||||
const servers = data.servers
|
||||
.map(
|
||||
(server) =>
|
||||
"```ansi\n" +
|
||||
`${server.game} : ${server.active ? ONLINE : OFFLINE}\n` +
|
||||
`${server.address}\n` +
|
||||
"```"
|
||||
)
|
||||
.join("");
|
||||
|
||||
if (JSON.stringify(newStatus) === JSON.stringify(currentStatus)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await updateMessage(client, data);
|
||||
currentStatus = newStatus;
|
||||
return true;
|
||||
return (
|
||||
"Hello 😺 ! Voila les serveurs de jeux qu'on a chez nous :\n\n" +
|
||||
servers +
|
||||
`\nPour mettre en ligne un serveur, faut voir avec <@${config.ownerUserId}> , c'est lui qui gère ca !\n`
|
||||
);
|
||||
}
|
||||
|
||||
async function updateMessage(client, data) {
|
||||
var newMessage = `Hello 😺 ! Voila les serveurs de jeux qu'on a chez nous :\n\n`;
|
||||
|
||||
data.servers.forEach((server) => {
|
||||
newMessage =
|
||||
newMessage +
|
||||
"```ansi\n" +
|
||||
`${server.game} : ` +
|
||||
`${server.active ? "[2;32mOnline[0m" : "[2;31mOffline[0m"}\n` +
|
||||
`${server.address}\n` +
|
||||
"```";
|
||||
});
|
||||
|
||||
newMessage =
|
||||
newMessage +
|
||||
`\nPour mettre en ligne un serveur, faut voir avec <@${config.shinuwaUserId}> , c'est lui qui gère ca !\n`;
|
||||
async function refreshMessage(client) {
|
||||
const content = buildMessage(await readServers());
|
||||
if (content === publishedMessage) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const channel = client.channels.cache.get(config.textChannelId);
|
||||
if (!channel?.isTextBased()) {
|
||||
|
|
@ -83,23 +83,23 @@ async function updateMessage(client, data) {
|
|||
}
|
||||
|
||||
const message = await channel.messages.fetch(config.gameServersMessageId);
|
||||
await message.edit(newMessage);
|
||||
await message.edit(content);
|
||||
publishedMessage = content;
|
||||
console.log(
|
||||
`[${new Date().toLocaleString()}] showGameServers: Game servers message updated`
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
async function showGameServers(client) {
|
||||
const data = await readServers();
|
||||
currentStatus = data.servers.map((server) => server.active);
|
||||
|
||||
await updateMessage(client, data);
|
||||
const interval = setInterval(() => {
|
||||
checkServersStatus(client).catch((error) =>
|
||||
// Un échec (salon ou message introuvable, liste illisible) est journalisé et retenté au
|
||||
// rafraîchissement suivant, y compris au démarrage.
|
||||
function showGameServers(client) {
|
||||
const refresh = () =>
|
||||
refreshMessage(client).catch((error) =>
|
||||
console.error("Unable to update game server status", error)
|
||||
);
|
||||
}, REFRESH_INTERVAL);
|
||||
interval.unref();
|
||||
setInterval(refresh, REFRESH_INTERVAL).unref();
|
||||
return refresh();
|
||||
}
|
||||
|
||||
export { probeTcp, serverStatus, showGameServers };
|
||||
export { buildMessage, probeTcp, serverStatus, showGameServers };
|
||||
|
|
|
|||
|
|
@ -1,59 +1,40 @@
|
|||
import fs from "fs";
|
||||
import fs from "node:fs";
|
||||
import { config } from "../config.js";
|
||||
|
||||
async function changeVoiceStatus(client, status, members) {
|
||||
const changeStatus = async (type, value, selectedMembers) => {
|
||||
const operations = [];
|
||||
switch (type) {
|
||||
case "mute":
|
||||
for (const member of selectedMembers.values()) {
|
||||
operations.push(member.voice.setMute(value));
|
||||
}
|
||||
break;
|
||||
case "deaf":
|
||||
for (const member of selectedMembers.values()) {
|
||||
operations.push(member.voice.setDeaf(value));
|
||||
}
|
||||
break;
|
||||
}
|
||||
// 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 VOICE_ACTIONS = {
|
||||
mute: (member) => member.voice.setMute(true),
|
||||
unmute: (member) => member.voice.setMute(false),
|
||||
deaf: (member) => member.voice.setDeaf(true),
|
||||
undeaf: (member) => member.voice.setDeaf(false),
|
||||
};
|
||||
|
||||
const voiceChannel = client.channels.cache.get(config.voiceChannelId);
|
||||
if (!voiceChannel?.isVoiceBased()) {
|
||||
// Salon vocal où se trouve la personne qui lance la commande, sinon celui de la configuration.
|
||||
function commandVoiceChannel(interaction) {
|
||||
const channel =
|
||||
interaction.member?.voice?.channel ??
|
||||
interaction.client.channels.cache.get(config.voiceChannelId);
|
||||
if (!channel?.isVoiceBased()) {
|
||||
throw new Error("Salon vocal configuré introuvable");
|
||||
}
|
||||
const connectedMembers = voiceChannel.members.filter(
|
||||
(member) => !member.user.bot
|
||||
);
|
||||
return channel;
|
||||
}
|
||||
|
||||
if (members === "all") {
|
||||
members = connectedMembers;
|
||||
// Applique l'action à tous les membres humains du salon.
|
||||
async function changeVoiceStatus(channel, action) {
|
||||
const apply = VOICE_ACTIONS[action];
|
||||
if (!apply) {
|
||||
throw new Error(`Statut vocal inconnu : ${action}`);
|
||||
}
|
||||
|
||||
switch (status) {
|
||||
case "mute":
|
||||
await changeStatus("mute", true, members);
|
||||
break;
|
||||
case "unmute":
|
||||
await changeStatus("mute", false, members);
|
||||
break;
|
||||
case "deaf":
|
||||
await changeStatus("deaf", true, members);
|
||||
break;
|
||||
case "undeaf":
|
||||
await changeStatus("deaf", false, members);
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Statut vocal inconnu : ${status}`);
|
||||
const members = channel.members.filter((member) => !member.user.bot);
|
||||
// Un membre qui quitte le salon pendant l'opération ne doit pas faire échouer les autres.
|
||||
const results = await Promise.allSettled(members.map(apply));
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -68,8 +49,19 @@ function getRandomInt(max) {
|
|||
return Math.floor(Math.random() * max);
|
||||
}
|
||||
|
||||
// Mélange de Fisher-Yates, sur place ; renvoie le tableau.
|
||||
function shuffle(array) {
|
||||
for (let index = array.length - 1; index > 0; index--) {
|
||||
const randomIndex = getRandomInt(index + 1);
|
||||
[array[index], array[randomIndex]] = [array[randomIndex], array[index]];
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
export {
|
||||
changeVoiceStatus,
|
||||
commandVoiceChannel,
|
||||
getJSONData,
|
||||
getRandomInt,
|
||||
shuffle,
|
||||
};
|
||||
|
|
|
|||
43
src/loadCommands.js
Normal file
43
src/loadCommands.js
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
|
||||
const COMMANDS_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "commands");
|
||||
|
||||
// Nom affiché de chaque dossier de src/commands (catégorie de /listcommand).
|
||||
const CATEGORY_LABELS = {
|
||||
utility: "Utilitaires",
|
||||
jukebox: "Jukebox",
|
||||
vocal: "Vocal",
|
||||
game: "Jeux",
|
||||
};
|
||||
|
||||
// Charge les commandes de src/commands/<catégorie>/*.js. Chaque fichier exporte
|
||||
// `command = { data, execute, autocomplete? }`.
|
||||
async function loadCommands() {
|
||||
const commands = [];
|
||||
const folders = fs
|
||||
.readdirSync(COMMANDS_DIR, { withFileTypes: true })
|
||||
.filter((entry) => entry.isDirectory())
|
||||
.map((entry) => entry.name)
|
||||
.sort();
|
||||
|
||||
for (const folder of folders) {
|
||||
const files = fs
|
||||
.readdirSync(path.join(COMMANDS_DIR, folder))
|
||||
.filter((file) => file.endsWith(".js"))
|
||||
.sort();
|
||||
for (const file of files) {
|
||||
const filePath = path.join(COMMANDS_DIR, folder, file);
|
||||
const { command } = await import(pathToFileURL(filePath).href);
|
||||
if (!command?.data || typeof command.execute !== "function") {
|
||||
console.warn(`[WARNING] The command at ${filePath} is missing "data" or "execute".`);
|
||||
continue;
|
||||
}
|
||||
commands.push({ ...command, category: CATEGORY_LABELS[folder] ?? folder });
|
||||
}
|
||||
}
|
||||
return commands;
|
||||
}
|
||||
|
||||
export { loadCommands };
|
||||
|
|
@ -69,10 +69,6 @@ function invalidAudioError(cause) {
|
|||
return error;
|
||||
}
|
||||
|
||||
async function validateAudioFile(filePath) {
|
||||
await probeAudioFile(filePath);
|
||||
}
|
||||
|
||||
// Décode le fichier, normalise le volume et encode en Ogg Opus avec le ffmpeg natif : Discord
|
||||
// reçoit l'Opus tel quel, sans réencodage en JavaScript. Fermer le flux arrête ffmpeg.
|
||||
function createOpusStream(filePath, { spawnProcess = spawn } = {}) {
|
||||
|
|
@ -131,4 +127,4 @@ function createOpusStream(filePath, { spawnProcess = spawn } = {}) {
|
|||
return output;
|
||||
}
|
||||
|
||||
export { LOUDNORM_FILTER, createOpusStream, probeAudioFile, validateAudioFile };
|
||||
export { createOpusStream, probeAudioFile };
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import {
|
|||
} from "@discordjs/voice";
|
||||
import { Events } from "discord.js";
|
||||
import { config } from "../config.js";
|
||||
import { shuffle } from "../features/utilities.js";
|
||||
import { createOpusStream } from "../media/validateAudioFile.js";
|
||||
import { serializeTrack, serializeTracks } from "../web/serializers.js";
|
||||
import {
|
||||
|
|
@ -306,7 +307,7 @@ class MusicQueue extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
async remove(trackId) {
|
||||
remove(trackId) {
|
||||
const index = this.queue.findIndex((track) => track.id === trackId);
|
||||
if (index === -1) {
|
||||
if (this.currentTrack && this.currentTrack.id === trackId) {
|
||||
|
|
@ -356,13 +357,7 @@ class MusicQueue extends EventEmitter {
|
|||
|
||||
// Mélange les morceaux à venir (le morceau en cours n'est pas touché).
|
||||
shuffle() {
|
||||
for (let index = this.queue.length - 1; index > 0; index--) {
|
||||
const randomIndex = Math.floor(Math.random() * (index + 1));
|
||||
[this.queue[index], this.queue[randomIndex]] = [
|
||||
this.queue[randomIndex],
|
||||
this.queue[index],
|
||||
];
|
||||
}
|
||||
shuffle(this.queue);
|
||||
this.emit("queueUpdate", this.snapshot());
|
||||
return this.snapshot();
|
||||
}
|
||||
|
|
@ -546,7 +541,7 @@ class MusicQueue extends EventEmitter {
|
|||
}
|
||||
|
||||
// Membres humains du salon configuré, sans le bot lui-même ni les autres bots.
|
||||
listeners() {
|
||||
humanListeners() {
|
||||
const channel = this.client.channels.cache.get(config.voiceChannelId);
|
||||
const clientId = this.client.user?.id;
|
||||
if (!channel || !clientId) {
|
||||
|
|
@ -559,7 +554,7 @@ class MusicQueue extends EventEmitter {
|
|||
}
|
||||
|
||||
hasListeners() {
|
||||
return (this.listeners()?.length ?? 0) > 0;
|
||||
return (this.humanListeners()?.length ?? 0) > 0;
|
||||
}
|
||||
|
||||
isBotAlone() {
|
||||
|
|
@ -569,7 +564,7 @@ class MusicQueue extends EventEmitter {
|
|||
return false;
|
||||
}
|
||||
|
||||
return this.listeners().length === 0;
|
||||
return this.humanListeners().length === 0;
|
||||
}
|
||||
|
||||
// Avec la persistance, la file (morceau en cours en tête) est enregistrée et ses fichiers
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
updatePermanentTracks,
|
||||
} from "../storage/storageManager.js";
|
||||
import { serializeTrack, serializeTracks } from "../serializers.js";
|
||||
import { shuffle } from "../../features/utilities.js";
|
||||
|
||||
function libraryRouter({ queue }) {
|
||||
const router = Router();
|
||||
|
|
@ -50,10 +51,7 @@ function libraryRouter({ queue }) {
|
|||
router.post("/enqueue-all", (req, res) => {
|
||||
const entries = getPermanentLibrary();
|
||||
if (req.body?.shuffle === true) {
|
||||
for (let index = entries.length - 1; index > 0; index--) {
|
||||
const randomIndex = Math.floor(Math.random() * (index + 1));
|
||||
[entries[index], entries[randomIndex]] = [entries[randomIndex], entries[index]];
|
||||
}
|
||||
shuffle(entries);
|
||||
}
|
||||
|
||||
const tracks = entries.map((entry) =>
|
||||
|
|
|
|||
|
|
@ -27,8 +27,8 @@ function queueRouter({ queue }) {
|
|||
res.status(201).json({ track: serializeTrack(track) });
|
||||
});
|
||||
|
||||
router.delete("/:trackId", async (req, res) => {
|
||||
const removed = await queue.remove(req.params.trackId);
|
||||
router.delete("/:trackId", (req, res) => {
|
||||
const removed = queue.remove(req.params.trackId);
|
||||
if (!removed) {
|
||||
return res.status(404).json({ error: "Piste introuvable" });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -173,7 +173,7 @@ function startWebServer(dependencies) {
|
|||
.catch((error) => console.error("Unable to complete library metadata", error));
|
||||
|
||||
const app = createApp(dependencies);
|
||||
const port = Number(process.env.PORT || config.webServerPort || 3000);
|
||||
const port = config.webServerPort;
|
||||
|
||||
const server = app.listen(port, () => {
|
||||
console.log(
|
||||
|
|
|
|||
|
|
@ -12,20 +12,8 @@ const TEMP_FILE_MAX_AGE = 24 * 60 * 60 * 1000;
|
|||
const MAX_LIBRARY_SIZE = 2 * 1024 * 1024 * 1024;
|
||||
|
||||
function ensureStorageLayout() {
|
||||
if (!fs.existsSync(STORAGE_ROOT)) {
|
||||
fs.mkdirSync(STORAGE_ROOT, { recursive: true });
|
||||
}
|
||||
|
||||
if (!fs.existsSync(PERMANENT_DIR)) {
|
||||
fs.mkdirSync(PERMANENT_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
if (!fs.existsSync(TEMP_DIR)) {
|
||||
fs.mkdirSync(TEMP_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
if (!fs.existsSync(RUNTIME_DIR)) {
|
||||
fs.mkdirSync(RUNTIME_DIR, { recursive: true });
|
||||
for (const directory of [PERMANENT_DIR, TEMP_DIR, RUNTIME_DIR]) {
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
}
|
||||
|
||||
if (!fs.existsSync(LIBRARY_FILE)) {
|
||||
|
|
@ -117,7 +105,7 @@ function registerUploadedFile(
|
|||
const extension = /^\.[a-z0-9]{1,10}$/.test(rawExtension)
|
||||
? rawExtension
|
||||
: "";
|
||||
storedName = `${randomUUID()}${extension.toLowerCase()}`;
|
||||
storedName = `${randomUUID()}${extension}`;
|
||||
finalPath = path.join(PERMANENT_DIR, storedName);
|
||||
fs.renameSync(file.path, finalPath);
|
||||
permanentEntry = {
|
||||
|
|
@ -219,7 +207,7 @@ function deleteFileSafe(filePath) {
|
|||
}
|
||||
|
||||
try {
|
||||
fs.existsSync(filePath) && fs.unlinkSync(filePath);
|
||||
fs.rmSync(filePath, { force: true });
|
||||
} catch (error) {
|
||||
console.error(`Failed to delete file ${filePath}`, error);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue