feat(status): rotate an editable list of bot statuses

The presence line was hard-coded, so advertising a different message meant
editing the source and restarting the bot. Statuses now live in the database
and are managed from Discord with /status — add, list, remove, pause and the
rotation interval, which applies without a restart.

An empty list falls back to a neutral "see the commands with /help" line, and
the first status added shows up right away instead of waiting a full turn.
This commit is contained in:
BlackAngelTV committed 2026-09-15 16:12:50 +02:00
1 parent ef8f09da10
commit c785e9abb7
8 files changed
+755 -2

No files matched your search

+153
View File
@@ -0,0 +1,153 @@
import { MessageFlags, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { ACCESS_LEVELS } from '../../config/constants.js';
import {
addBotStatus,
applyBotStatus,
applyStatusIfAlone,
clearBotStatusList,
FALLBACK_STATUS,
formatSeconds,
removeBotStatus,
ROTATION_MAX_SECONDS,
ROTATION_MIN_SECONDS,
saveRotationSeconds,
STATUS_TYPE_CHOICES,
statusAddedEmbed,
statusListEmbed,
toggleBotStatus,
} from '../../services/status/bot-status-service.js';
import { successEmbed } from '../../ui/embeds.js';
export const access = ACCESS_LEVELS.STAFF;
const idOption = (option) =>
option.setName('id').setDescription('Numéro affiché par /status list').setRequired(true).setMinValue(1);
export const data = new SlashCommandBuilder()
.setName('status')
.setDescription('Statuts affichés sous le nom du bot')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.addSubcommand((sub) =>
sub
.setName('add')
.setDescription('Ajouter un statut à la rotation')
.addStringOption((option) =>
option
.setName('text')
.setDescription('Texte affiché, par exemple « les tickets ouverts en un clic »')
.setRequired(true)
.setMaxLength(128),
)
.addStringOption((option) =>
option
.setName('type')
.setDescription('Type d’activité (regarde par défaut)')
.addChoices(...STATUS_TYPE_CHOICES),
)
.addStringOption((option) =>
option.setName('url').setDescription('Lien exigé par le type « en direct »'),
),
)
.addSubcommand((sub) => sub.setName('list').setDescription('Voir les statuts enregistrés'))
.addSubcommand((sub) =>
sub.setName('remove').setDescription('Retirer un statut de la rotation').addIntegerOption(idOption),
)
.addSubcommand((sub) =>
sub.setName('enable').setDescription('Remettre un statut en rotation').addIntegerOption(idOption),
)
.addSubcommand((sub) =>
sub.setName('disable').setDescription('Mettre un statut en pause').addIntegerOption(idOption),
)
.addSubcommand((sub) =>
sub
.setName('interval')
.setDescription('Rythme de la rotation')
.addIntegerOption((option) =>
option
.setName('seconds')
.setDescription('Secondes entre deux changements')
.setRequired(true)
.setMinValue(ROTATION_MIN_SECONDS)
.setMaxValue(ROTATION_MAX_SECONDS),
),
)
.addSubcommand((sub) =>
sub.setName('clear').setDescription('Vider la liste et revenir au statut par défaut'),
);
const reply = (interaction, embed) => interaction.reply({ embeds: [embed], flags: MessageFlags.Ephemeral });
/** The bot presence is global, but the rotation delay is stored per guild like other settings (M15). */
export async function execute(interaction) {
const subcommand = interaction.options.getSubcommand();
if (subcommand === 'list') {
await reply(interaction, statusListEmbed({ guildId: interaction.guildId }));
return;
}
if (subcommand === 'add') {
const status = addBotStatus({
text: interaction.options.getString('text', true),
type: interaction.options.getString('type') ?? 'watching',
url: interaction.options.getString('url'),
createdBy: interaction.user.id,
});
// A single status is shown right away: an addition should never wait for the next turn.
const applied = applyStatusIfAlone(interaction.client) !== null;
await reply(interaction, statusAddedEmbed(status, { applied }));
return;
}
if (subcommand === 'interval') {
const seconds = saveRotationSeconds(
interaction.options.getInteger('seconds', true),
interaction.guildId,
interaction.user.id,
);
await reply(
interaction,
successEmbed(
`C’est noté : les statuts changeront toutes les **${formatSeconds(seconds)}**. Ça prend effet tout de suite, sans redémarrage.`,
),
);
return;
}
if (subcommand === 'clear') {
const removed = clearBotStatusList();
applyBotStatus(interaction.client);
await reply(
interaction,
successEmbed(
removed === 0
? `La liste était déjà vide : j’affiche « ${FALLBACK_STATUS.text} ».`
: `C’est fait : ${removed} statut(s) supprimé(s). J’affiche de nouveau « ${FALLBACK_STATUS.text} » en attendant les prochains.`,
),
);
return;
}
const id = interaction.options.getInteger('id', true);
if (subcommand === 'remove') {
const status = removeBotStatus(id);
await reply(
interaction,
successEmbed(`C’est fait : « ${status.text} » ne fait plus partie de la rotation.`),
);
return;
}
const enabled = subcommand === 'enable';
const status = toggleBotStatus(id, enabled);
if (enabled) applyStatusIfAlone(interaction.client);
await reply(
interaction,
successEmbed(
enabled
? `« ${status.text} » reprend sa place dans la rotation.`
: `« ${status.text} » est en pause : il reste dans la liste, mais ne s’affiche plus.`,
),
);
}
+4
View File
@@ -58,6 +58,10 @@ export const env = Object.freeze({
emptyGraceMs: readDuration('VOICE_EMPTY_GRACE_MS', 5_000),
},
bot: {
statusIntervalSeconds: readDuration('BOT_STATUS_INTERVAL_SECONDS', 60),
},
gitea: {
url: read('GITEA_URL').replace(/\/+$/, ''),
token: read('GITEA_TOKEN'),
@@ -0,0 +1,14 @@
-- Rotating presence of the bot, editable from Discord (M15)
-- The presence is global to the bot, so these rows are not tied to a guild.
CREATE TABLE IF NOT EXISTS bot_statuses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
text TEXT NOT NULL,
type TEXT NOT NULL DEFAULT 'watching',
url TEXT,
enabled INTEGER NOT NULL DEFAULT 1,
created_by TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_bot_statuses_text ON bot_statuses (text);
CREATE INDEX IF NOT EXISTS idx_bot_statuses_enabled ON bot_statuses (enabled, id);
@@ -0,0 +1,42 @@
import { getDatabase } from '../index.js';
/** Adds a status and returns the stored row, so the command can show its id. */
export function addBotStatus({ text, type = 'watching', url = null, createdBy = null }) {
const result = getDatabase()
.prepare('INSERT INTO bot_statuses (text, type, url, created_by) VALUES (?, ?, ?, ?)')
.run(text, type, url, createdBy);
return getBotStatus(Number(result.lastInsertRowid));
}
export function getBotStatus(id) {
return getDatabase().prepare('SELECT * FROM bot_statuses WHERE id = ?').get(id) ?? null;
}
/** Every status, disabled ones included, in the order they were added. */
export function listBotStatuses() {
return getDatabase().prepare('SELECT * FROM bot_statuses ORDER BY id ASC').all();
}
/** The statuses the rotation is allowed to show. */
export function listEnabledBotStatuses() {
return getDatabase().prepare('SELECT * FROM bot_statuses WHERE enabled = 1 ORDER BY id ASC').all();
}
export function setBotStatusEnabled(id, enabled) {
return getDatabase()
.prepare('UPDATE bot_statuses SET enabled = ? WHERE id = ?')
.run(enabled ? 1 : 0, id).changes;
}
export function removeBotStatus(id) {
return getDatabase().prepare('DELETE FROM bot_statuses WHERE id = ?').run(id).changes;
}
export function clearBotStatuses() {
return getDatabase().prepare('DELETE FROM bot_statuses').run().changes;
}
export function countBotStatuses() {
const row = getDatabase().prepare('SELECT COUNT(*) AS count FROM bot_statuses').get();
return row.count;
}
+3 -2
View File
@@ -1,6 +1,7 @@
import { ActivityType, Events } from 'discord.js';
import { Events } from 'discord.js';
import { createLogger } from '../core/logger.js';
import { startPollScheduler } from '../services/polls/poll-service.js';
import { startBotStatusRotation } from '../services/status/bot-status-service.js';
import { startVoiceJanitor, sweepVoiceChannels } from '../services/voice/voice-service.js';
const log = createLogger('discord');
@@ -9,10 +10,10 @@ export const name = Events.ClientReady;
export const once = true;
export async function execute(client) {
client.user.setActivity('FWS Arch', { type: ActivityType.Watching });
startPollScheduler(client);
await sweepVoiceChannels(client);
startVoiceJanitor(client);
startBotStatusRotation(client);
log.info(`Connected as ${client.user.tag}`, {
guilds: client.guilds.cache.size,
commands: client.commands.size,
+314
View File
@@ -0,0 +1,314 @@
import { ActivityType } from 'discord.js';
import { COLORS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import {
addBotStatus as addBotStatusRow,
clearBotStatuses,
countBotStatuses,
getBotStatus,
listBotStatuses,
listEnabledBotStatuses,
removeBotStatus as removeBotStatusRow,
setBotStatusEnabled,
} from '../../database/repositories/bot-status-repository.js';
import { resolveSetting, setSetting } from '../../database/repositories/settings-repository.js';
import { baseEmbed, bullets, successEmbed } from '../../ui/embeds.js';
const log = createLogger('status');
/** Discord caps an activity name at 128 characters. */
export const STATUS_TEXT_MAX = 128;
/** Beyond that the picker in `/status list` becomes unreadable; ask for fewer, clearer lines. */
export const STATUS_MAX = 25;
export const ROTATION_MIN_SECONDS = 5;
export const ROTATION_MAX_SECONDS = 86_400;
/** Key of the rotation delay, stored per guild like the other settings (M15). */
export const ROTATION_KEY = 'bot.status.interval';
/** Shown while the list is empty, so the bot never displays nothing useful. */
export const FALLBACK_STATUS = Object.freeze({
id: null,
text: 'les commandes avec /help',
type: 'watching',
});
/**
* Accepted activity types. Discord writes the verb itself, so only the label used in the
* embeds lives here; `streaming` is the one type that requires a link.
*/
export const STATUS_TYPES = Object.freeze({
playing: { label: 'joue à', activity: ActivityType.Playing },
streaming: { label: 'en direct sur', activity: ActivityType.Streaming, needsUrl: true },
listening: { label: 'écoute', activity: ActivityType.Listening },
watching: { label: 'regarde', activity: ActivityType.Watching },
competing: { label: 'participe à', activity: ActivityType.Competing },
});
/** Choice list for the slash command. */
export const STATUS_TYPE_CHOICES = Object.freeze(
Object.entries(STATUS_TYPES).map(([value, type]) => ({ name: type.label, value })),
);
/** Strips control characters without a control-character regex, then collapses the spaces. */
const clean = (value) =>
[...String(value ?? '')]
.map((char) => {
const code = char.codePointAt(0);
return code <= 31 || code === 127 ? ' ' : char;
})
.join('')
.replace(/\s+/g, ' ')
.trim();
export function sanitizeStatusText(value) {
const text = clean(value);
if (!text) {
throw new UserFacingError(
'Il me manque le texte du statut : écris quelques mots, par exemple « les commandes avec /help ».',
);
}
if (text.length > STATUS_TEXT_MAX) {
throw new UserFacingError(
`Discord limite un statut à ${STATUS_TEXT_MAX} caractères, et ce texte en fait ${text.length}. Raccourcis‑le un peu.`,
);
}
return text;
}
export function normalizeStatusType(value) {
const key = String(value ?? 'watching')
.toLowerCase()
.trim();
if (!STATUS_TYPES[key]) {
throw new UserFacingError(
`Je ne connais pas ce type de statut. Choisis parmi : ${Object.keys(STATUS_TYPES).join(', ')}.`,
);
}
return key;
}
/** Only a streaming status uses a link, and Discord refuses it without a valid URL. */
export function validateStatusUrl(value, typeKey) {
const url = String(value ?? '').trim();
if (STATUS_TYPES[typeKey]?.needsUrl && !url) {
throw new UserFacingError(
'Le type « en direct » a besoin d’un lien (Twitch, YouTube…) : ajoute l’option `url`.',
);
}
if (!url) return null;
if (!/^https?:\/\/\S+$/i.test(url)) {
throw new UserFacingError('Un lien de diffusion doit commencer par `http://` ou `https://`.');
}
return url;
}
/** `45 s`, `5 min`, `2 h 30 min` — used by the embeds of `/status`. */
export function formatSeconds(seconds) {
const value = Math.max(0, Math.round(Number(seconds) || 0));
if (value < 60) return `${value} s`;
const minutes = Math.round(value / 60);
if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60);
const rest = minutes % 60;
return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`;
}
/** Delay used when neither the database nor the environment gives a usable value. */
const FALLBACK_ROTATION_SECONDS = 60;
/** The environment default, ignored when it is out of range rather than applied blindly. */
const envRotationSeconds = () => {
const value = Number(env.bot.statusIntervalSeconds);
return Number.isInteger(value) && value >= ROTATION_MIN_SECONDS && value <= ROTATION_MAX_SECONDS
? value
: FALLBACK_ROTATION_SECONDS;
};
export function clampRotation(value, { strict = false } = {}) {
const seconds = Number(value);
if (!Number.isInteger(seconds) || seconds < ROTATION_MIN_SECONDS || seconds > ROTATION_MAX_SECONDS) {
if (strict) {
throw new UserFacingError(
`Le rythme doit être un nombre de secondes entre ${ROTATION_MIN_SECONDS} et ${ROTATION_MAX_SECONDS} (${formatSeconds(ROTATION_MIN_SECONDS)} à ${formatSeconds(ROTATION_MAX_SECONDS)}).`,
);
}
return envRotationSeconds();
}
return seconds;
}
/** Rotation delay, overridable from Discord; the environment provides the default (M15). */
export function getRotationSeconds(guildId = env.discord.guildId) {
return clampRotation(resolveSetting(guildId, ROTATION_KEY, env.botStatusIntervalSeconds));
}
export function saveRotationSeconds(seconds, guildId = env.discord.guildId, updatedBy = null) {
const value = clampRotation(seconds, { strict: true });
setSetting(guildId, ROTATION_KEY, value, updatedBy);
return value;
}
/** Adds a status, or explains why it cannot be added (duplicate text, too many, invalid link). */
export function addBotStatus({ text, type = 'watching', url = null, createdBy = null } = {}) {
const statusText = sanitizeStatusText(text);
const typeKey = normalizeStatusType(type);
const statusUrl = validateStatusUrl(url, typeKey);
if (countBotStatuses() >= STATUS_MAX) {
throw new UserFacingError(
`La liste est déjà pleine (${STATUS_MAX} statuts) : supprime‑en un avec \`/status remove\` avant d’en ajouter un autre.`,
);
}
let status;
try {
status = addBotStatusRow({ text: statusText, type: typeKey, url: statusUrl, createdBy });
} catch (error) {
if (!/UNIQUE constraint/i.test(String(error?.message))) throw error;
log.debug('Duplicate status refused', error);
throw new UserFacingError(
`« ${statusText} » est déjà dans la liste : \`/status list\` montre les statuts existants.`,
);
}
logEvent({
guildId: env.discord.guildId,
type: 'bot.status.added',
actorId: createdBy,
payload: { id: status.id },
});
return status;
}
export function removeBotStatus(id) {
const status = getBotStatus(id);
if (!status) throw new UserFacingError(`Je ne trouve aucun statut avec le numéro **${id}**.`);
removeBotStatusRow(id);
logEvent({ guildId: env.discord.guildId, type: 'bot.status.removed', payload: { id } });
return status;
}
export function toggleBotStatus(id, enabled) {
const status = getBotStatus(id);
if (!status) throw new UserFacingError(`Je ne trouve aucun statut avec le numéro **${id}**.`);
if (Boolean(status.enabled) === enabled) {
throw new UserFacingError(
enabled
? `Le statut **#${id}** tourne déjà — il n’y a rien à changer.`
: `Le statut **#${id}** est déjà en pause — il n’y a rien à changer.`,
);
}
setBotStatusEnabled(id, enabled);
return { ...status, enabled: enabled ? 1 : 0 };
}
/** Empties the list; the fallback status takes over immediately. */
export function clearBotStatusList() {
const removed = clearBotStatuses();
logEvent({ guildId: env.discord.guildId, type: 'bot.status.cleared', payload: { removed } });
return removed;
}
/**
* Next status of the rotation: the enabled ones in insertion order, one after the other.
* Returns `null` when nothing is enabled, so the caller falls back to a default line.
*/
export function selectNextStatus(statuses, lastId = null) {
if (statuses.length === 0) return null;
const index = statuses.findIndex((status) => status.id === lastId);
return statuses[(index + 1) % statuses.length];
}
/** Shows one status in Discord. */
export function applyBotStatus(client, status = FALLBACK_STATUS) {
const type = STATUS_TYPES[status.type] ?? STATUS_TYPES.watching;
const activity = { name: status.text, type: type.activity };
if (type.needsUrl && status.url) activity.url = status.url;
client.user.setPresence({ status: 'online', activities: [activity] });
return activity;
}
/** Applies the only enabled status right away, so an addition shows up immediately. */
export function applyStatusIfAlone(client) {
const statuses = listEnabledBotStatuses();
if (statuses.length !== 1) return null;
applyBotStatus(client, statuses[0]);
return statuses[0];
}
/** Shows the next status and returns it; used by the rotation and by the tests. */
export function rotateBotStatus(client, lastId = null) {
const status = selectNextStatus(listEnabledBotStatuses(), lastId) ?? FALLBACK_STATUS;
applyBotStatus(client, status);
return status;
}
/**
* Rotates the statuses forever. The delay is read again on every turn, so `/status interval`
* takes effect without restarting the bot (M15).
*/
export function startBotStatusRotation(client, { guildId = env.discord.guildId } = {}) {
let lastId = null;
let timer = null;
const tick = () => {
try {
lastId = rotateBotStatus(client, lastId)?.id ?? null;
} catch (error) {
log.warn('Could not rotate the bot status', error);
}
timer = setTimeout(tick, getRotationSeconds(guildId) * 1000);
timer.unref?.();
};
tick();
return { stop: () => clearTimeout(timer) };
}
function describeStatus(status) {
const type = STATUS_TYPES[status.type] ?? STATUS_TYPES.watching;
const link = type.needsUrl && status.url ? ` · ${status.url}` : '';
return `« ${status.text} » — ${type.label}${link}`;
}
/** The list shown by `/status list` (M15). */
export function statusListEmbed({ guildId = env.discord.guildId, statuses = listBotStatuses() } = {}) {
const embed = baseEmbed(COLORS.primary).setTitle('🎭 Statuts du bot');
if (statuses.length === 0) {
return embed.setDescription(
`Aucun statut personnalisé pour le moment : j’affiche « ${FALLBACK_STATUS.text} » en attendant.\n\nAjoute le premier avec \`/status add\`.`,
);
}
const active = statuses.filter((status) => status.enabled).length;
embed.setDescription(
`${bullets([
`**${statuses.length}** statut(s), dont **${active}** en rotation`,
`changement toutes les **${formatSeconds(getRotationSeconds(guildId))}**`,
'la rotation suit l’ordre d’ajout et saute les statuts en pause',
])}`,
);
embed.addFields(
statuses.map((status) => ({
name: `#${status.id} · ${status.enabled ? '✅ en rotation' : '⛔ en pause'}`,
value: describeStatus(status),
})),
);
return embed;
}
/** Confirmation shown after `/status add`, including when the addition changes what is displayed. */
export function statusAddedEmbed(status, { applied = false } = {}) {
const next = applied
? 'C’était le premier statut : il s’affiche tout de suite sous le nom du bot.'
: 'Il apparaît dans la rotation ; `/status list` montre l’ensemble.';
return successEmbed(
`C’est dans la liste : **#${status.id}** — ${describeStatus(status)}.\n\n${next}`,
).setTitle('✅ Statut ajouté');
}