feat(rules): write the rules from the dashboard and republish them
The rules lived in a channel nobody but a staff member with a shell could edit, and the welcome message pointed at it. They are now written in markdown under Settings and published as a single pinned embed, and a new publication deletes the message the bot posted last time instead of piling copies up in the channel.
This commit is contained in:
11 files changed
+452
-8
No files matched your search
@@ -17,6 +17,11 @@ export const SETTING_SECTIONS = Object.freeze([
|
||||
summary: 'Ce que le bot fait quand quelqu’un rejoint ou quitte.',
|
||||
},
|
||||
{ id: 'moderation', title: 'Modération', summary: 'Comportement par défaut des sanctions.' },
|
||||
{
|
||||
id: 'rules',
|
||||
title: 'Règlement',
|
||||
summary: 'Message publié et épinglé dans le salon des règles.',
|
||||
},
|
||||
{ id: 'tickets', title: 'Tickets', summary: 'Cycle de vie des tickets de support.' },
|
||||
{
|
||||
id: 'voice',
|
||||
@@ -110,6 +115,17 @@ export const GUILD_SETTINGS = Object.freeze([
|
||||
advanced: true,
|
||||
},
|
||||
|
||||
// --- Règlement ---------------------------------------------------------------
|
||||
{
|
||||
key: 'rules.markdown',
|
||||
section: 'rules',
|
||||
label: 'Règlement (markdown)',
|
||||
help: 'Publié et épinglé dans le salon des règles (`CHANNEL_RULES_ID`). Markdown de Discord : **gras**, *italique*, `code`, listes, titres. Publier remplace le message précédent.',
|
||||
type: 'text',
|
||||
default: '',
|
||||
maxLength: 4000,
|
||||
},
|
||||
|
||||
// --- Tickets ---------------------------------------------------------------
|
||||
{
|
||||
key: 'tickets.deleteChannelOnClose',
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
-- The rules message published from the dashboard (M19)
|
||||
--
|
||||
-- The bot republishes the rules by deleting the previous message and sending
|
||||
-- the new one, so it has to remember which message it owns. Without this the
|
||||
-- channel would slowly fill with outdated copies.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS rules_messages (
|
||||
guild_id TEXT PRIMARY KEY,
|
||||
channel_id TEXT NOT NULL,
|
||||
message_id TEXT NOT NULL,
|
||||
updated_by TEXT,
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
@@ -0,0 +1,24 @@
|
||||
import { getDatabase } from '../index.js';
|
||||
|
||||
/** The rules message the bot published, so the next version can replace it. */
|
||||
export function setRulesMessage({ guildId, channelId, messageId, updatedBy = null }) {
|
||||
getDatabase()
|
||||
.prepare(
|
||||
`INSERT INTO rules_messages (guild_id, channel_id, message_id, updated_by)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (guild_id) DO UPDATE SET
|
||||
channel_id = excluded.channel_id,
|
||||
message_id = excluded.message_id,
|
||||
updated_by = excluded.updated_by,
|
||||
updated_at = datetime('now')`,
|
||||
)
|
||||
.run(guildId, channelId, messageId, updatedBy);
|
||||
}
|
||||
|
||||
export function getRulesMessage(guildId) {
|
||||
return getDatabase().prepare('SELECT * FROM rules_messages WHERE guild_id = ?').get(guildId) ?? null;
|
||||
}
|
||||
|
||||
export function clearRulesMessage(guildId) {
|
||||
return getDatabase().prepare('DELETE FROM rules_messages WHERE guild_id = ?').run(guildId).changes;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { COLORS } from '../../config/constants.js';
|
||||
import { env } from '../../config/env.js';
|
||||
import { createLogger } from '../../core/logger.js';
|
||||
import { logEvent } from '../../database/repositories/event-log-repository.js';
|
||||
import { getRulesMessage, setRulesMessage } from '../../database/repositories/rules-repository.js';
|
||||
import { baseEmbed } from '../../ui/embeds.js';
|
||||
|
||||
/**
|
||||
* Rules of the server, written from the dashboard and published as a single
|
||||
* pinned message in `CHANNEL_RULES_ID` (M19).
|
||||
*
|
||||
* Publishing deletes the message the bot posted last time before sending the
|
||||
* new one: the channel keeps a single set of rules, and members following the
|
||||
* channel see the update rather than a second copy.
|
||||
*/
|
||||
|
||||
const log = createLogger('rules');
|
||||
|
||||
/** Discord refuses an embed description longer than that. */
|
||||
export const RULES_MAX_LENGTH = 4000;
|
||||
|
||||
const TITLE = '📜 Règlement';
|
||||
|
||||
/**
|
||||
* Replaces the published rules with `markdown`.
|
||||
* @param {import('discord.js').Client} client
|
||||
* @param {{ guildId: string, markdown: string, actorId?: string | null, channelId?: string }} options
|
||||
* @returns {Promise<{ messageId: string, url: string | null, channelId: string, pinned: boolean }>}
|
||||
*/
|
||||
export async function publishRules(
|
||||
client,
|
||||
{ guildId, markdown, actorId = null, channelId = env.channels.rules },
|
||||
) {
|
||||
if (!channelId) {
|
||||
throw new Error('Aucun salon des règles configuré : renseigne CHANNEL_RULES_ID dans le .env.');
|
||||
}
|
||||
|
||||
const content = String(markdown ?? '').trim();
|
||||
if (content === '') throw new Error('Le règlement est vide.');
|
||||
if (content.length > RULES_MAX_LENGTH) {
|
||||
throw new Error(`${RULES_MAX_LENGTH} caractères maximum pour un règlement.`);
|
||||
}
|
||||
|
||||
const channel = await client.channels.fetch(channelId).catch(() => null);
|
||||
if (!channel?.isSendable()) {
|
||||
throw new Error('Salon des règles introuvable, ou le bot n’y peut pas écrire.');
|
||||
}
|
||||
|
||||
await deletePublishedRules(client, guildId);
|
||||
|
||||
const embed = baseEmbed(COLORS.primary)
|
||||
.setTitle(TITLE)
|
||||
.setDescription(content)
|
||||
.setFooter({ text: 'Mis à jour depuis le tableau de bord FWS-Bot' })
|
||||
.setTimestamp(new Date());
|
||||
|
||||
const message = await channel.send({ embeds: [embed] });
|
||||
|
||||
// Pinning is a convenience, not a requirement: a bot without “Gérer les
|
||||
// messages” still publishes the rules.
|
||||
const pinned = await message
|
||||
.pin()
|
||||
.then(() => true)
|
||||
.catch((error) => {
|
||||
log.warn('Could not pin the rules message', error);
|
||||
return false;
|
||||
});
|
||||
|
||||
setRulesMessage({ guildId, channelId, messageId: message.id, updatedBy: actorId });
|
||||
logEvent({
|
||||
guildId,
|
||||
type: 'web.rules.published',
|
||||
actorId,
|
||||
payload: { channelId, messageId: message.id, pinned },
|
||||
});
|
||||
log.info('Rules published from the dashboard', { channelId, messageId: message.id, actor: actorId });
|
||||
|
||||
return { messageId: message.id, url: message.url ?? null, channelId, pinned };
|
||||
}
|
||||
|
||||
/** Removes the message the bot published last time, if it is still there. */
|
||||
export async function deletePublishedRules(client, guildId) {
|
||||
const stored = getRulesMessage(guildId);
|
||||
if (!stored) return false;
|
||||
|
||||
const channel = await client.channels.fetch(stored.channel_id).catch(() => null);
|
||||
const message = await channel?.messages?.fetch(stored.message_id).catch(() => null);
|
||||
const deleted = await message
|
||||
?.delete()
|
||||
.then(() => true)
|
||||
.catch((error) => {
|
||||
// A message deleted by hand, or a channel the bot no longer sees, must
|
||||
// not stop the republication.
|
||||
log.warn('Could not delete the previous rules message', error);
|
||||
return false;
|
||||
});
|
||||
|
||||
if (deleted !== false) return Boolean(deleted);
|
||||
return false;
|
||||
}
|
||||
|
||||
/** What the dashboard needs to show the current state of the rules. */
|
||||
export function rulesStatus(guildId, channelId = env.channels.rules) {
|
||||
const stored = getRulesMessage(guildId);
|
||||
return {
|
||||
channelId: channelId || null,
|
||||
configured: Boolean(channelId),
|
||||
messageId: stored?.message_id ?? null,
|
||||
publishedAt: stored?.updated_at ?? null,
|
||||
publishedBy: stored?.updated_by ?? null,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ChannelType, REST, Routes } from 'discord.js';
|
||||
import { ACCESS_LABELS, ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { env } from '../../config/env.js';
|
||||
import { readSetting, writeSetting } from '../../config/guild-settings.js';
|
||||
import { ExternalApiError } from '../../core/errors.js';
|
||||
import { createLogger } from '../../core/logger.js';
|
||||
import { canActOn, getAccessLevel } from '../../core/permissions.js';
|
||||
@@ -16,6 +17,7 @@ import {
|
||||
setNotificationChannel,
|
||||
} from '../../database/repositories/notification-repository.js';
|
||||
import { moderationLabel, sendModerationLog } from '../../services/moderation/moderation-service.js';
|
||||
import { publishRules, rulesStatus } from '../../services/rules/rules-service.js';
|
||||
import { badRequest, forbidden, notFound } from '../http.js';
|
||||
|
||||
/** Discord server management from the dashboard (M16-T05). */
|
||||
@@ -292,6 +294,39 @@ export function registerDiscordRoutes(router) {
|
||||
{ access: ACCESS_LEVELS.STAFF },
|
||||
);
|
||||
|
||||
// --- Server rules ----------------------------------------------------------
|
||||
|
||||
router.get(
|
||||
'/api/discord/rules',
|
||||
() => ({ markdown: readSetting('rules.markdown', guildId()), ...rulesStatus(guildId()) }),
|
||||
{ access: ACCESS_LEVELS.STAFF },
|
||||
);
|
||||
|
||||
/** Publishes the rules, replacing the message the bot posted last time. */
|
||||
router.post(
|
||||
'/api/discord/rules',
|
||||
async ({ context, body, actor }) => {
|
||||
const markdown = writeSetting('rules.markdown', body.markdown, {
|
||||
guildId: guildId(),
|
||||
updatedBy: actor.userId,
|
||||
});
|
||||
|
||||
try {
|
||||
const published = await publishRules(context.client, {
|
||||
guildId: guildId(),
|
||||
markdown,
|
||||
actorId: actor.userId,
|
||||
});
|
||||
return { ok: true, ...published, ...rulesStatus(guildId()) };
|
||||
} catch (error) {
|
||||
// The text is saved either way: a channel that is simply not configured
|
||||
// yet must not throw away what was written.
|
||||
throw badRequest(error.message);
|
||||
}
|
||||
},
|
||||
{ access: ACCESS_LEVELS.DEV },
|
||||
);
|
||||
|
||||
// --- Notification routing --------------------------------------------------
|
||||
router.get(
|
||||
'/api/discord/notifications',
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
stat,
|
||||
table,
|
||||
toast,
|
||||
textarea,
|
||||
toggle,
|
||||
} from '../core/ui.js';
|
||||
|
||||
@@ -76,7 +77,11 @@ function settingControl(setting, value, apply) {
|
||||
|
||||
function behaviourCard(data, level, reload) {
|
||||
const editable = level >= LEVELS.DEV;
|
||||
const schema = Array.isArray(data.schema) ? data.schema : [];
|
||||
// The rules get their own card: a plain text field would not carry the
|
||||
// markdown editor nor the publishing button.
|
||||
const schema = (Array.isArray(data.schema) ? data.schema : []).filter(
|
||||
(setting) => setting.key !== 'rules.markdown',
|
||||
);
|
||||
const values = data.values ?? {};
|
||||
|
||||
// Falling back to one section keeps the page useful against an API that does
|
||||
@@ -492,6 +497,88 @@ function referenceCard(data) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the rules in markdown and republishes them: the previous message is
|
||||
* deleted, the new one is sent and pinned in `CHANNEL_RULES_ID`.
|
||||
*/
|
||||
function rulesCard(level, reload) {
|
||||
const host = h('div', { class: 'stack' });
|
||||
const editable = level >= LEVELS.DEV;
|
||||
|
||||
renderAsync(
|
||||
host,
|
||||
() => api.get('/api/discord/rules'),
|
||||
(data) => {
|
||||
const editor = textarea({
|
||||
value: data.markdown ?? '',
|
||||
placeholder: '## Règlement\n\n1. …\n2. …',
|
||||
rows: 12,
|
||||
maxlength: 4000,
|
||||
disabled: !editable,
|
||||
});
|
||||
const counter = h('span', { class: 'field-help' });
|
||||
const refresh = () => {
|
||||
counter.textContent = `${editor.value.length} / 4000 caractères`;
|
||||
};
|
||||
editor.addEventListener('input', refresh);
|
||||
refresh();
|
||||
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'stack' },
|
||||
!data.configured &&
|
||||
notice(
|
||||
'Aucun salon des règles dans le .env : renseigne `CHANNEL_RULES_ID` puis redémarre le bot.',
|
||||
'error',
|
||||
),
|
||||
field('Règlement (markdown)', editor, {
|
||||
help: 'Markdown de Discord : **gras**, *italique*, `code`, listes, titres. Publié et épinglé dans le salon des règles.',
|
||||
}),
|
||||
counter,
|
||||
h(
|
||||
'div',
|
||||
{ class: 'row' },
|
||||
editable &&
|
||||
button(
|
||||
'Publier le règlement',
|
||||
async (event) => {
|
||||
// The button stays disabled until the answer arrives: a second
|
||||
// click would publish the rules twice.
|
||||
event.currentTarget.disabled = true;
|
||||
try {
|
||||
const result = await api.post('/api/discord/rules', { markdown: editor.value });
|
||||
toast(
|
||||
result.pinned
|
||||
? 'Règlement publié et épinglé.'
|
||||
: 'Règlement publié, mais l’épinglage a échoué.',
|
||||
result.pinned ? 'success' : 'info',
|
||||
);
|
||||
reload();
|
||||
} catch (error) {
|
||||
toast(error.message, 'error');
|
||||
event.currentTarget.disabled = false;
|
||||
}
|
||||
},
|
||||
{ tone: 'primary', disabled: !data.configured },
|
||||
),
|
||||
data.publishedAt
|
||||
? h('span', {
|
||||
class: 'muted',
|
||||
text: `Dernier règlement publié ${formatRelative(data.publishedAt)}.`,
|
||||
})
|
||||
: h('span', { class: 'muted', text: 'Aucun règlement publié pour l’instant.' }),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return card(
|
||||
'Règlement du serveur',
|
||||
{ subtitle: 'Un seul message, épinglé dans le salon des règles, remis à jour à chaque publication.' },
|
||||
host,
|
||||
);
|
||||
}
|
||||
|
||||
export function render(host, { state }) {
|
||||
const level = state.me.accessLevel;
|
||||
const reload = () => render(host, { state });
|
||||
@@ -532,6 +619,7 @@ export function render(host, { state }) {
|
||||
),
|
||||
|
||||
behaviourCard(data, level, reload),
|
||||
rulesCard(level, reload),
|
||||
connectionsCard(data),
|
||||
level >= LEVELS.OWNER ? sessionsCard(reload) : null,
|
||||
level >= LEVELS.OWNER ? tokensCard(reload) : null,
|
||||
|
||||
Reference in new issue
Block a user