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:
8 files changed
+755
-2
No files matched your search
@@ -50,6 +50,9 @@ CATEGORY_VOICE_ID=
|
|||||||
# Délai avant qu'un salon généré devenu vide soit supprimé, en ms (0 = immédiat)
|
# Délai avant qu'un salon généré devenu vide soit supprimé, en ms (0 = immédiat)
|
||||||
VOICE_EMPTY_GRACE_MS=5000
|
VOICE_EMPTY_GRACE_MS=5000
|
||||||
|
|
||||||
|
# --- Statuts du bot (M15) -----------------------------------------------------
|
||||||
|
# Rythme par défaut de la rotation, en secondes (modifiable à chaud par /status interval)
|
||||||
|
BOT_STATUS_INTERVAL_SECONDS=60
|
||||||
|
|
||||||
# --- Gitea (M5-T01) ----------------------------------------------------------
|
# --- Gitea (M5-T01) ----------------------------------------------------------
|
||||||
GITEA_URL=https://gitea.nocode-var.tech
|
GITEA_URL=https://gitea.nocode-var.tech
|
||||||
|
|||||||
@@ -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.`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -58,6 +58,10 @@ export const env = Object.freeze({
|
|||||||
emptyGraceMs: readDuration('VOICE_EMPTY_GRACE_MS', 5_000),
|
emptyGraceMs: readDuration('VOICE_EMPTY_GRACE_MS', 5_000),
|
||||||
},
|
},
|
||||||
|
|
||||||
|
bot: {
|
||||||
|
statusIntervalSeconds: readDuration('BOT_STATUS_INTERVAL_SECONDS', 60),
|
||||||
|
},
|
||||||
|
|
||||||
gitea: {
|
gitea: {
|
||||||
url: read('GITEA_URL').replace(/\/+$/, ''),
|
url: read('GITEA_URL').replace(/\/+$/, ''),
|
||||||
token: read('GITEA_TOKEN'),
|
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;
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { ActivityType, Events } from 'discord.js';
|
import { Events } from 'discord.js';
|
||||||
import { createLogger } from '../core/logger.js';
|
import { createLogger } from '../core/logger.js';
|
||||||
import { startPollScheduler } from '../services/polls/poll-service.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';
|
import { startVoiceJanitor, sweepVoiceChannels } from '../services/voice/voice-service.js';
|
||||||
|
|
||||||
const log = createLogger('discord');
|
const log = createLogger('discord');
|
||||||
@@ -9,10 +10,10 @@ export const name = Events.ClientReady;
|
|||||||
export const once = true;
|
export const once = true;
|
||||||
|
|
||||||
export async function execute(client) {
|
export async function execute(client) {
|
||||||
client.user.setActivity('FWS Arch', { type: ActivityType.Watching });
|
|
||||||
startPollScheduler(client);
|
startPollScheduler(client);
|
||||||
await sweepVoiceChannels(client);
|
await sweepVoiceChannels(client);
|
||||||
startVoiceJanitor(client);
|
startVoiceJanitor(client);
|
||||||
|
startBotStatusRotation(client);
|
||||||
log.info(`Connected as ${client.user.tag}`, {
|
log.info(`Connected as ${client.user.tag}`, {
|
||||||
guilds: client.guilds.cache.size,
|
guilds: client.guilds.cache.size,
|
||||||
commands: client.commands.size,
|
commands: client.commands.size,
|
||||||
|
|||||||
@@ -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é');
|
||||||
|
}
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { after, before, beforeEach, describe, it } from 'node:test';
|
||||||
|
import { UserFacingError } from '../src/core/errors.js';
|
||||||
|
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
|
||||||
|
import {
|
||||||
|
addBotStatus as addRow,
|
||||||
|
countBotStatuses,
|
||||||
|
getBotStatus,
|
||||||
|
listBotStatuses,
|
||||||
|
listEnabledBotStatuses,
|
||||||
|
removeBotStatus,
|
||||||
|
setBotStatusEnabled,
|
||||||
|
} from '../src/database/repositories/bot-status-repository.js';
|
||||||
|
import { setSetting } from '../src/database/repositories/settings-repository.js';
|
||||||
|
import {
|
||||||
|
addBotStatus,
|
||||||
|
applyStatusIfAlone,
|
||||||
|
clampRotation,
|
||||||
|
clearBotStatusList,
|
||||||
|
FALLBACK_STATUS,
|
||||||
|
formatSeconds,
|
||||||
|
getRotationSeconds,
|
||||||
|
normalizeStatusType,
|
||||||
|
ROTATION_KEY,
|
||||||
|
ROTATION_MAX_SECONDS,
|
||||||
|
ROTATION_MIN_SECONDS,
|
||||||
|
rotateBotStatus,
|
||||||
|
sanitizeStatusText,
|
||||||
|
saveRotationSeconds,
|
||||||
|
selectNextStatus,
|
||||||
|
STATUS_MAX,
|
||||||
|
STATUS_TEXT_MAX,
|
||||||
|
statusListEmbed,
|
||||||
|
toggleBotStatus,
|
||||||
|
validateStatusUrl,
|
||||||
|
} from '../src/services/status/bot-status-service.js';
|
||||||
|
|
||||||
|
const GUILD = 'g';
|
||||||
|
|
||||||
|
describe('bot status repository', () => {
|
||||||
|
before(() => initDatabase(':memory:'));
|
||||||
|
after(() => closeDatabase());
|
||||||
|
beforeEach(() => getDatabase().exec('DELETE FROM bot_statuses'));
|
||||||
|
|
||||||
|
it('stores a status and reads it back', () => {
|
||||||
|
const status = addRow({ text: 'les commandes avec /help', type: 'watching', createdBy: 'u1' });
|
||||||
|
assert.equal(status.text, 'les commandes avec /help');
|
||||||
|
assert.equal(status.type, 'watching');
|
||||||
|
assert.equal(status.enabled, 1);
|
||||||
|
assert.equal(status.created_by, 'u1');
|
||||||
|
assert.equal(getBotStatus(status.id).text, status.text);
|
||||||
|
assert.equal(countBotStatuses(), 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the insertion order and separates the paused ones', () => {
|
||||||
|
const first = addRow({ text: 'un' });
|
||||||
|
addRow({ text: 'deux' });
|
||||||
|
const third = addRow({ text: 'trois' });
|
||||||
|
setBotStatusEnabled(third.id, false);
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
listBotStatuses().map((status) => status.text),
|
||||||
|
['un', 'deux', 'trois'],
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
listEnabledBotStatuses().map((status) => status.text),
|
||||||
|
['un', 'deux'],
|
||||||
|
);
|
||||||
|
assert.equal(first.id < third.id, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses the same text twice and forgets a removed status', () => {
|
||||||
|
const status = addRow({ text: 'déjà là' });
|
||||||
|
assert.throws(() => addRow({ text: 'déjà là' }), /UNIQUE constraint/i);
|
||||||
|
|
||||||
|
assert.equal(removeBotStatus(status.id), 1);
|
||||||
|
assert.equal(getBotStatus(status.id), null);
|
||||||
|
assert.equal(removeBotStatus(status.id), 0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('bot status helpers', () => {
|
||||||
|
it('normalises the text and refuses what Discord would reject', () => {
|
||||||
|
assert.equal(sanitizeStatusText(' les tickets '), 'les tickets');
|
||||||
|
assert.equal(sanitizeStatusText('a\nb'), 'a b');
|
||||||
|
assert.equal(sanitizeStatusText('x'.repeat(STATUS_TEXT_MAX)).length, STATUS_TEXT_MAX);
|
||||||
|
assert.throws(() => sanitizeStatusText(' '), UserFacingError);
|
||||||
|
assert.throws(() => sanitizeStatusText('x'.repeat(STATUS_TEXT_MAX + 1)), UserFacingError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts the known types and explains the others', () => {
|
||||||
|
assert.equal(normalizeStatusType(), 'watching');
|
||||||
|
assert.equal(normalizeStatusType('PLAYING'), 'playing');
|
||||||
|
assert.throws(() => normalizeStatusType('danse'), UserFacingError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires a link for a stream and validates the ones it gets', () => {
|
||||||
|
assert.throws(() => validateStatusUrl(null, 'streaming'), UserFacingError);
|
||||||
|
assert.throws(() => validateStatusUrl('twitch.tv/fws', 'streaming'), UserFacingError);
|
||||||
|
assert.equal(validateStatusUrl('https://twitch.tv/fws', 'streaming'), 'https://twitch.tv/fws');
|
||||||
|
assert.equal(validateStatusUrl(null, 'watching'), null);
|
||||||
|
assert.equal(validateStatusUrl('https://exemple.fr', 'playing'), 'https://exemple.fr');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('formats a delay the way the embeds show it', () => {
|
||||||
|
assert.equal(formatSeconds(30), '30 s');
|
||||||
|
assert.equal(formatSeconds(60), '1 min');
|
||||||
|
assert.equal(formatSeconds(3600), '1 h');
|
||||||
|
assert.equal(formatSeconds(9000), '2 h 30 min');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('bot status rotation', () => {
|
||||||
|
before(() => initDatabase(':memory:'));
|
||||||
|
after(() => closeDatabase());
|
||||||
|
beforeEach(() => {
|
||||||
|
getDatabase().exec('DELETE FROM bot_statuses');
|
||||||
|
getDatabase().exec(`DELETE FROM guild_settings WHERE key = '${ROTATION_KEY}'`);
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = () => {
|
||||||
|
const presences = [];
|
||||||
|
return { presences, user: { setPresence: (payload) => presences.push(payload) } };
|
||||||
|
};
|
||||||
|
|
||||||
|
it('walks the enabled statuses one after the other, then starts over', () => {
|
||||||
|
const first = addBotStatus({ text: 'un' });
|
||||||
|
const second = addBotStatus({ text: 'deux' });
|
||||||
|
const third = addBotStatus({ text: 'trois', type: 'listening' });
|
||||||
|
setBotStatusEnabled(third.id, false);
|
||||||
|
|
||||||
|
const statuses = listEnabledBotStatuses();
|
||||||
|
assert.equal(selectNextStatus(statuses).id, first.id);
|
||||||
|
assert.equal(selectNextStatus(statuses, first.id).id, second.id);
|
||||||
|
assert.equal(selectNextStatus(statuses, second.id).id, first.id);
|
||||||
|
assert.equal(selectNextStatus([]), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the statuses in Discord with the right activity type', () => {
|
||||||
|
addBotStatus({ text: 'les tickets', type: 'listening' });
|
||||||
|
addBotStatus({ text: 'en direct', type: 'streaming', url: 'https://twitch.tv/fws' });
|
||||||
|
const fake = client();
|
||||||
|
|
||||||
|
const first = rotateBotStatus(fake);
|
||||||
|
const second = rotateBotStatus(fake, first.id);
|
||||||
|
|
||||||
|
assert.deepEqual(fake.presences[0].activities[0], { name: 'les tickets', type: 2 });
|
||||||
|
assert.equal(fake.presences[1].activities[0].url, 'https://twitch.tv/fws');
|
||||||
|
assert.equal(second.id !== first.id, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to the default line instead of showing nothing', () => {
|
||||||
|
const fake = client();
|
||||||
|
assert.equal(rotateBotStatus(fake), FALLBACK_STATUS);
|
||||||
|
assert.equal(fake.presences[0].activities[0].name, FALLBACK_STATUS.text);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows a lone status right away', () => {
|
||||||
|
const status = addBotStatus({ text: 'seul statut' });
|
||||||
|
const fake = client();
|
||||||
|
assert.equal(applyStatusIfAlone(fake).id, status.id);
|
||||||
|
|
||||||
|
addBotStatus({ text: 'un autre' });
|
||||||
|
assert.equal(applyStatusIfAlone(fake), null, 'with several statuses the rotation decides');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses the same text twice and stops at the maximum', () => {
|
||||||
|
addBotStatus({ text: 'unique' });
|
||||||
|
assert.throws(() => addBotStatus({ text: 'unique' }), UserFacingError);
|
||||||
|
|
||||||
|
for (let index = countBotStatuses(); index < STATUS_MAX; index += 1) {
|
||||||
|
addBotStatus({ text: `statut ${index}` });
|
||||||
|
}
|
||||||
|
assert.equal(countBotStatuses(), STATUS_MAX);
|
||||||
|
assert.throws(() => addBotStatus({ text: 'un de trop' }), UserFacingError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('pauses and resumes a status without losing it', () => {
|
||||||
|
const status = addBotStatus({ text: 'en pause' });
|
||||||
|
const paused = toggleBotStatus(status.id, false);
|
||||||
|
assert.equal(paused.enabled, 0);
|
||||||
|
assert.equal(listEnabledBotStatuses().length, 0);
|
||||||
|
assert.throws(() => toggleBotStatus(status.id, false), UserFacingError);
|
||||||
|
|
||||||
|
toggleBotStatus(status.id, true);
|
||||||
|
assert.equal(listEnabledBotStatuses()[0].id, status.id);
|
||||||
|
assert.throws(() => toggleBotStatus(999, true), UserFacingError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('empties the list and forgets every status', () => {
|
||||||
|
addBotStatus({ text: 'un' });
|
||||||
|
addBotStatus({ text: 'deux' });
|
||||||
|
assert.equal(clearBotStatusList(), 2);
|
||||||
|
assert.equal(countBotStatuses(), 0);
|
||||||
|
assert.equal(clearBotStatusList(), 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the rotation delay between the allowed bounds, database first', () => {
|
||||||
|
assert.equal(clampRotation(30), 30);
|
||||||
|
assert.equal(clampRotation(ROTATION_MIN_SECONDS - 1), 60, 'an unusable value falls back to the default');
|
||||||
|
assert.equal(clampRotation(ROTATION_MAX_SECONDS + 1), 60);
|
||||||
|
assert.throws(() => clampRotation(1, { strict: true }), UserFacingError);
|
||||||
|
|
||||||
|
saveRotationSeconds(45, GUILD, 'u1');
|
||||||
|
assert.equal(getRotationSeconds(GUILD), 45);
|
||||||
|
|
||||||
|
setSetting(GUILD, ROTATION_KEY, 'pas un nombre', 'u1');
|
||||||
|
assert.equal(getRotationSeconds(GUILD), 60, 'a corrupted setting never breaks the rotation');
|
||||||
|
assert.equal(getRotationSeconds('autre-serveur'), 60);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lists the statuses with their state and the current rhythm', () => {
|
||||||
|
const empty = statusListEmbed({ guildId: GUILD, statuses: [] });
|
||||||
|
assert.match(empty.data.description, /Aucun statut personnalisé/);
|
||||||
|
|
||||||
|
const status = addBotStatus({ text: 'les commandes avec /help' });
|
||||||
|
const embed = statusListEmbed({ guildId: GUILD, statuses: listBotStatuses() });
|
||||||
|
assert.match(embed.data.description, /\*\*1\*\* statut\(s\), dont \*\*1\*\* en rotation/);
|
||||||
|
assert.equal(embed.data.fields[0].name, `#${status.id} · ✅ en rotation`);
|
||||||
|
assert.match(embed.data.fields[0].value, /les commandes avec \/help/);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user