fix(rules): show the rules field with a save button and edit the message
The rules lived in a card of their own that never showed up next to the settings, so the section read as an empty toggle nobody could fill in. The markdown now renders as a real field with an "Enregistrer" button, and saving edits the message already pinned instead of deleting it and posting a new one: same link, same place, pin kept.
This commit is contained in:
7 files changed
+150
-162
No files matched your search
+2
-1
@@ -126,7 +126,8 @@ Full template: [`.env.example`](.env.example). Default values in brackets.
|
|||||||
| Variable | Usage |
|
| Variable | Usage |
|
||||||
| -------------------------------- | --------------------------------------------------------------------------- |
|
| -------------------------------- | --------------------------------------------------------------------------- |
|
||||||
| `CHANNEL_WELCOME_ID` | Welcome messages |
|
| `CHANNEL_WELCOME_ID` | Welcome messages |
|
||||||
| `CHANNEL_RULES_ID` | Rules: link sent to newcomers, and where the dashboard pins the message |
|
| `CHANNEL_RULES_ID` | Rules: link sent to newcomers, and where the dashboard pins the message. |
|
||||||
|
| | Later saves edit that same message |
|
||||||
| `CHANNEL_ANNOUNCEMENTS_ID` | FWS announcements |
|
| `CHANNEL_ANNOUNCEMENTS_ID` | FWS announcements |
|
||||||
| `CHANNEL_LOGS_ID` | Functional logs |
|
| `CHANNEL_LOGS_ID` | Functional logs |
|
||||||
| `CHANNEL_MOD_LOGS_ID` | Moderation logs |
|
| `CHANNEL_MOD_LOGS_ID` | Moderation logs |
|
||||||
|
|||||||
@@ -128,7 +128,7 @@ Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre pare
|
|||||||
| Variable | Usage |
|
| Variable | Usage |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `CHANNEL_WELCOME_ID` | Messages de bienvenue |
|
| `CHANNEL_WELCOME_ID` | Messages de bienvenue |
|
||||||
| `CHANNEL_RULES_ID` | Règlement : lien envoyé aux nouveaux, et salon où le tableau de bord publie le message épinglé |
|
| `CHANNEL_RULES_ID` | Règlement : lien envoyé aux nouveaux, et salon où le tableau de bord publie le message épinglé (les enregistrements suivants le modifient) |
|
||||||
| `CHANNEL_ANNOUNCEMENTS_ID` | Annonces FWS |
|
| `CHANNEL_ANNOUNCEMENTS_ID` | Annonces FWS |
|
||||||
| `CHANNEL_LOGS_ID` | Logs fonctionnels |
|
| `CHANNEL_LOGS_ID` | Logs fonctionnels |
|
||||||
| `CHANNEL_MOD_LOGS_ID` | Logs de modération |
|
| `CHANNEL_MOD_LOGS_ID` | Logs de modération |
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ Le commutateur en bas de la barre latérale masque ou révèle les panneaux tech
|
|||||||
| **Serveur Discord** | Membres, rôles, modération, annonces, routage des notifications, inventaire des commandes |
|
| **Serveur Discord** | Membres, rôles, modération, annonces, routage des notifications, inventaire des commandes |
|
||||||
| **Tickets & vocaux** | Tickets, sondages, salons vocaux temporaires, rotation des statuts du bot |
|
| **Tickets & vocaux** | Tickets, sondages, salons vocaux temporaires, rotation des statuts du bot |
|
||||||
| **Journaux** | Événements fonctionnels et fichiers de logs techniques, secrets masqués |
|
| **Journaux** | Événements fonctionnels et fichiers de logs techniques, secrets masqués |
|
||||||
| **Paramètres** | Comportement du bot, règlement du serveur, connexions, sessions, jetons d'API, maintenance |
|
| **Paramètres** | Comportement du bot, règlement, connexions, sessions, jetons d'API, maintenance |
|
||||||
| **Configuration .env** | L'assistant pas à pas, accessible aussi une fois le bot configuré |
|
| **Configuration .env** | L'assistant pas à pas, accessible aussi une fois le bot configuré |
|
||||||
|
|
||||||
## 4. Assistant de configuration
|
## 4. Assistant de configuration
|
||||||
@@ -212,7 +212,7 @@ Les changements prennent effet immédiatement, sans redémarrage, contrairement
|
|||||||
|
|
||||||
### Rédiger et publier le règlement
|
### Rédiger et publier le règlement
|
||||||
|
|
||||||
La carte **Règlement du serveur** écrit les règles en markdown (celui de Discord : `**gras**`, `*italique*`, `code`, listes, titres) et les publie dans `CHANNEL_RULES_ID` sous forme d'un embed épinglé. Publier supprime le message précédent avant d'envoyer le nouveau : le salon ne garde qu'une seule version, épinglée, et l'identifiant du message est retenu en base (`rules_messages`) pour pouvoir le remplacer la fois suivante. Un message supprimé à la main, un salon devenu inaccessible ou une épinglage refusé n'empêchent pas la publication ; l'échec de l'épinglage est simplement signalé. Le texte est enregistré même si la publication échoue, pour ne pas perdre ce qui a été écrit. Niveau **Dev** requis.
|
La section **Règlement** de la page Paramètres écrit les règles en markdown (celui de Discord : `**gras**`, `*italique*`, `code`, listes, titres) et **Enregistrer** les publie dans `CHANNEL_RULES_ID` sous forme d'un embed épinglé. L'identifiant du message est retenu en base (`rules_messages`) : les enregistrements suivants **modifient ce message**, même lien, même place dans le salon et épingle conservée, au lieu d'empiler les versions. Un message supprimé à la main, un salon devenu inaccessible ou un bot qui ne peut plus éditer font repartir sur un nouveau message ; un épinglage refusé est signalé sans bloquer la publication. Le texte est enregistré même si la publication échoue, pour ne pas perdre ce qui a été écrit. Niveau **Dev** requis.
|
||||||
|
|
||||||
## 10. Publier les commandes slash
|
## 10. Publier les commandes slash
|
||||||
|
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ export const SETTING_SECTIONS = Object.freeze([
|
|||||||
{
|
{
|
||||||
id: 'rules',
|
id: 'rules',
|
||||||
title: 'Règlement',
|
title: 'Règlement',
|
||||||
summary: 'Message publié et épinglé dans le salon des règles.',
|
summary: 'Message affiché et épinglé dans le salon des règles.',
|
||||||
},
|
},
|
||||||
{ id: 'tickets', title: 'Tickets', summary: 'Cycle de vie des tickets de support.' },
|
{ id: 'tickets', title: 'Tickets', summary: 'Cycle de vie des tickets de support.' },
|
||||||
{
|
{
|
||||||
@@ -120,8 +120,8 @@ export const GUILD_SETTINGS = Object.freeze([
|
|||||||
key: 'rules.markdown',
|
key: 'rules.markdown',
|
||||||
section: 'rules',
|
section: 'rules',
|
||||||
label: 'Règlement (markdown)',
|
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.',
|
help: 'Enregistré et épinglé dans le salon des règles (`CHANNEL_RULES_ID`). Markdown de Discord : **gras**, *italique*, `code`, listes, titres. Enregistrer modifie le message déjà publié.',
|
||||||
type: 'text',
|
type: 'markdown',
|
||||||
default: '',
|
default: '',
|
||||||
maxLength: 4000,
|
maxLength: 4000,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -6,12 +6,13 @@ import { getRulesMessage, setRulesMessage } from '../../database/repositories/ru
|
|||||||
import { baseEmbed } from '../../ui/embeds.js';
|
import { baseEmbed } from '../../ui/embeds.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Rules of the server, written from the dashboard and published as a single
|
* Rules of the server, written from the dashboard and kept in a single pinned
|
||||||
* pinned message in `CHANNEL_RULES_ID` (M19).
|
* message in `CHANNEL_RULES_ID` (M19).
|
||||||
*
|
*
|
||||||
* Publishing deletes the message the bot posted last time before sending the
|
* Saving edits the message already published, so the channel keeps one set of
|
||||||
* new one: the channel keeps a single set of rules, and members following the
|
* rules — same link, same position, and the pin survives. A new message is
|
||||||
* channel see the update rather than a second copy.
|
* only sent when the bot has none yet, or when the previous one was deleted by
|
||||||
|
* hand.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const log = createLogger('rules');
|
const log = createLogger('rules');
|
||||||
@@ -21,11 +22,18 @@ export const RULES_MAX_LENGTH = 4000;
|
|||||||
|
|
||||||
const TITLE = '📜 Règlement';
|
const TITLE = '📜 Règlement';
|
||||||
|
|
||||||
|
const rulesEmbed = (content) =>
|
||||||
|
baseEmbed(COLORS.primary)
|
||||||
|
.setTitle(TITLE)
|
||||||
|
.setDescription(content)
|
||||||
|
.setFooter({ text: 'Mis à jour depuis le tableau de bord FWS-Bot' })
|
||||||
|
.setTimestamp(new Date());
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Replaces the published rules with `markdown`.
|
* Publishes the rules, editing the message already there when there is one.
|
||||||
* @param {import('discord.js').Client} client
|
* @param {import('discord.js').Client} client
|
||||||
* @param {{ guildId: string, markdown: string, actorId?: string | null, channelId?: string }} options
|
* @param {{ guildId: string, markdown: string, actorId?: string | null, channelId?: string }} options
|
||||||
* @returns {Promise<{ messageId: string, url: string | null, channelId: string, pinned: boolean }>}
|
* @returns {Promise<{ messageId: string, url: string | null, channelId: string, pinned: boolean, edited: boolean }>}
|
||||||
*/
|
*/
|
||||||
export async function publishRules(
|
export async function publishRules(
|
||||||
client,
|
client,
|
||||||
@@ -46,57 +54,70 @@ export async function publishRules(
|
|||||||
throw new Error('Salon des règles introuvable, ou le bot n’y peut pas écrire.');
|
throw new Error('Salon des règles introuvable, ou le bot n’y peut pas écrire.');
|
||||||
}
|
}
|
||||||
|
|
||||||
await deletePublishedRules(client, guildId);
|
const edited = await editPublishedRules(client, guildId, content);
|
||||||
|
const message = edited ?? (await channel.send({ embeds: [rulesEmbed(content)] }));
|
||||||
|
|
||||||
const embed = baseEmbed(COLORS.primary)
|
// Only a brand new message has to be pinned: an edited one keeps its pin.
|
||||||
.setTitle(TITLE)
|
const pinned = edited
|
||||||
.setDescription(content)
|
? true
|
||||||
.setFooter({ text: 'Mis à jour depuis le tableau de bord FWS-Bot' })
|
: await message
|
||||||
.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()
|
.pin()
|
||||||
.then(() => true)
|
.then(() => true)
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
|
// A bot without “Gérer les messages” still publishes the rules.
|
||||||
log.warn('Could not pin the rules message', error);
|
log.warn('Could not pin the rules message', error);
|
||||||
return false;
|
return false;
|
||||||
});
|
});
|
||||||
|
|
||||||
setRulesMessage({ guildId, channelId, messageId: message.id, updatedBy: actorId });
|
setRulesMessage({
|
||||||
|
guildId,
|
||||||
|
channelId,
|
||||||
|
messageId: message.id,
|
||||||
|
updatedBy: actorId,
|
||||||
|
});
|
||||||
logEvent({
|
logEvent({
|
||||||
guildId,
|
guildId,
|
||||||
type: 'web.rules.published',
|
type: 'web.rules.published',
|
||||||
actorId,
|
actorId,
|
||||||
payload: { channelId, messageId: message.id, pinned },
|
payload: { channelId, messageId: message.id, pinned, edited: Boolean(edited) },
|
||||||
|
});
|
||||||
|
log.info('Rules saved from the dashboard', {
|
||||||
|
channelId,
|
||||||
|
messageId: message.id,
|
||||||
|
edited: Boolean(edited),
|
||||||
|
actor: actorId,
|
||||||
});
|
});
|
||||||
log.info('Rules published from the dashboard', { channelId, messageId: message.id, actor: actorId });
|
|
||||||
|
|
||||||
return { messageId: message.id, url: message.url ?? null, channelId, pinned };
|
return {
|
||||||
|
messageId: message.id,
|
||||||
|
url: message.url ?? null,
|
||||||
|
channelId,
|
||||||
|
pinned,
|
||||||
|
edited: Boolean(edited),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Removes the message the bot published last time, if it is still there. */
|
/**
|
||||||
export async function deletePublishedRules(client, guildId) {
|
* Rewrites the message the bot published last time.
|
||||||
|
* @returns the edited message, or null when there is none to edit
|
||||||
|
*/
|
||||||
|
async function editPublishedRules(client, guildId, content) {
|
||||||
const stored = getRulesMessage(guildId);
|
const stored = getRulesMessage(guildId);
|
||||||
if (!stored) return false;
|
if (!stored) return null;
|
||||||
|
|
||||||
const channel = await client.channels.fetch(stored.channel_id).catch(() => null);
|
const channel = await client.channels.fetch(stored.channel_id).catch(() => null);
|
||||||
const message = await channel?.messages?.fetch(stored.message_id).catch(() => null);
|
const message = await channel?.messages?.fetch(stored.message_id).catch(() => null);
|
||||||
const deleted = await message
|
if (!message?.editable) return null;
|
||||||
?.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 message
|
||||||
return false;
|
.edit({ embeds: [rulesEmbed(content)] })
|
||||||
|
.then((edited) => edited ?? message)
|
||||||
|
.catch((error) => {
|
||||||
|
// A message deleted by hand, or one the bot may no longer edit, must not
|
||||||
|
// stop the publication: a fresh one takes its place.
|
||||||
|
log.warn('Could not edit the previous rules message', error);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** What the dashboard needs to show the current state of the rules. */
|
/** What the dashboard needs to show the current state of the rules. */
|
||||||
|
|||||||
@@ -56,6 +56,30 @@ function settingControl(setting, value, apply) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Markdown is a long text: a single-line input would hide what is written.
|
||||||
|
if (setting.type === 'markdown') {
|
||||||
|
const editor = textarea({
|
||||||
|
value: value ?? '',
|
||||||
|
rows: 12,
|
||||||
|
maxlength: setting.maxLength,
|
||||||
|
placeholder: '## Règlement\n\n1. …\n2. …',
|
||||||
|
});
|
||||||
|
return field(
|
||||||
|
setting.label,
|
||||||
|
h(
|
||||||
|
'div',
|
||||||
|
{ class: 'stack' },
|
||||||
|
editor,
|
||||||
|
h(
|
||||||
|
'div',
|
||||||
|
{ class: 'row' },
|
||||||
|
button('Enregistrer', () => apply(editor.value), { tone: 'primary' }),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
{ help: setting.help },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const control = input({
|
const control = input({
|
||||||
value: value ?? '',
|
value: value ?? '',
|
||||||
type: setting.type === 'int' ? 'number' : 'text',
|
type: setting.type === 'int' ? 'number' : 'text',
|
||||||
@@ -77,11 +101,7 @@ function settingControl(setting, value, apply) {
|
|||||||
|
|
||||||
function behaviourCard(data, level, reload) {
|
function behaviourCard(data, level, reload) {
|
||||||
const editable = level >= LEVELS.DEV;
|
const editable = level >= LEVELS.DEV;
|
||||||
// The rules get their own card: a plain text field would not carry the
|
const schema = Array.isArray(data.schema) ? data.schema : [];
|
||||||
// markdown editor nor the publishing button.
|
|
||||||
const schema = (Array.isArray(data.schema) ? data.schema : []).filter(
|
|
||||||
(setting) => setting.key !== 'rules.markdown',
|
|
||||||
);
|
|
||||||
const values = data.values ?? {};
|
const values = data.values ?? {};
|
||||||
|
|
||||||
// Falling back to one section keeps the page useful against an API that does
|
// Falling back to one section keeps the page useful against an API that does
|
||||||
@@ -115,6 +135,20 @@ function behaviourCard(data, level, reload) {
|
|||||||
|
|
||||||
const apply = async (next) => {
|
const apply = async (next) => {
|
||||||
try {
|
try {
|
||||||
|
// The rules are a message on Discord, not a stored value: saving
|
||||||
|
// them has to publish them.
|
||||||
|
if (setting.key === 'rules.markdown') {
|
||||||
|
const published = await api.post('/api/discord/rules', { markdown: next });
|
||||||
|
values[setting.key] = next;
|
||||||
|
toast(
|
||||||
|
published.edited
|
||||||
|
? 'Règlement mis à jour dans le salon des règles.'
|
||||||
|
: 'Règlement publié et épinglé dans le salon des règles.',
|
||||||
|
published.pinned ? 'success' : 'info',
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const saved = await api.put(`/api/settings/values/${setting.key}`, { value: next });
|
const saved = await api.put(`/api/settings/values/${setting.key}`, { value: next });
|
||||||
toast(`« ${setting.label} » enregistré.`);
|
toast(`« ${setting.label} » enregistré.`);
|
||||||
values[setting.key] = saved.value;
|
values[setting.key] = saved.value;
|
||||||
@@ -497,88 +531,6 @@ 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 }) {
|
export function render(host, { state }) {
|
||||||
const level = state.me.accessLevel;
|
const level = state.me.accessLevel;
|
||||||
const reload = () => render(host, { state });
|
const reload = () => render(host, { state });
|
||||||
@@ -619,7 +571,6 @@ export function render(host, { state }) {
|
|||||||
),
|
),
|
||||||
|
|
||||||
behaviourCard(data, level, reload),
|
behaviourCard(data, level, reload),
|
||||||
rulesCard(level, reload),
|
|
||||||
connectionsCard(data),
|
connectionsCard(data),
|
||||||
level >= LEVELS.OWNER ? sessionsCard(reload) : null,
|
level >= LEVELS.OWNER ? sessionsCard(reload) : null,
|
||||||
level >= LEVELS.OWNER ? tokensCard(reload) : null,
|
level >= LEVELS.OWNER ? tokensCard(reload) : null,
|
||||||
|
|||||||
+45
-30
@@ -7,44 +7,46 @@ import { publishRules, rulesStatus } from '../src/services/rules/rules-service.j
|
|||||||
// channel is passed explicitly here rather than read from the environment.
|
// channel is passed explicitly here rather than read from the environment.
|
||||||
const RULES_CHANNEL = '1234567890123456789';
|
const RULES_CHANNEL = '1234567890123456789';
|
||||||
|
|
||||||
/** A Discord client reduced to what publishing the rules touches. */
|
/** A Discord client reduced to what saving the rules touches. */
|
||||||
function harness({ pinFails = false } = {}) {
|
function harness({ pinFails = false, notEditable = false } = {}) {
|
||||||
const state = { sent: [], deleted: [], pinned: [], messages: new Map() };
|
const state = { sent: [], edited: [], pinned: [], messages: new Map() };
|
||||||
|
|
||||||
|
// Discord edits a message in place: the id, the link and the pin stay.
|
||||||
|
const withEdit = (message) => ({
|
||||||
|
...message,
|
||||||
|
edit: async ({ embeds }) => {
|
||||||
|
state.edited.push({ id: message.id, description: embeds[0].toJSON().description });
|
||||||
|
return message;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const channel = {
|
const channel = {
|
||||||
isSendable: () => true,
|
isSendable: () => true,
|
||||||
async send(payload) {
|
async send(payload) {
|
||||||
const id = `message-${state.sent.length + 1}`;
|
const id = `message-${state.sent.length + 1}`;
|
||||||
state.sent.push({ id, payload });
|
state.sent.push({ id, payload });
|
||||||
state.messages.set(id, {
|
state.messages.set(id, { id, editable: !notEditable });
|
||||||
id,
|
|
||||||
delete: async () => {
|
|
||||||
state.deleted.push(id);
|
|
||||||
state.messages.delete(id);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return {
|
return {
|
||||||
id,
|
...withEdit({ id, url: `https://discord.test/${id}` }),
|
||||||
url: `https://discord.test/${id}`,
|
|
||||||
pin: async () => {
|
pin: async () => {
|
||||||
if (pinFails) throw new Error('Missing Permissions');
|
if (pinFails) throw new Error('Missing Permissions');
|
||||||
state.pinned.push(id);
|
state.pinned.push(id);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
messages: { fetch: async (id) => state.messages.get(id) ?? null },
|
messages: {
|
||||||
|
fetch: async (id) => {
|
||||||
|
const message = state.messages.get(id);
|
||||||
|
return message ? withEdit(message) : null;
|
||||||
|
},
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
return { state, client: { channels: { fetch: async () => channel } } };
|
return { state, client: { channels: { fetch: async () => channel } } };
|
||||||
}
|
}
|
||||||
|
|
||||||
const publish = (client, markdown = '## Règlement\n\n1. Reste.bg') =>
|
const publish = (client, markdown = '## Règlement\n\n1. Reste.bg') =>
|
||||||
publishRules(client, {
|
publishRules(client, { guildId: 'g', markdown, actorId: 'mod', channelId: RULES_CHANNEL });
|
||||||
guildId: 'g',
|
|
||||||
markdown,
|
|
||||||
actorId: 'mod',
|
|
||||||
channelId: RULES_CHANNEL,
|
|
||||||
});
|
|
||||||
|
|
||||||
const description = (entry) => entry.payload.embeds[0].toJSON().description;
|
const description = (entry) => entry.payload.embeds[0].toJSON().description;
|
||||||
|
|
||||||
@@ -53,7 +55,7 @@ describe('rules service', () => {
|
|||||||
after(() => closeDatabase());
|
after(() => closeDatabase());
|
||||||
beforeEach(() => getDatabase().exec('DELETE FROM rules_messages;'));
|
beforeEach(() => getDatabase().exec('DELETE FROM rules_messages;'));
|
||||||
|
|
||||||
it('publishes the rules and remembers the message', async () => {
|
it('sends and pins the rules the first time', async () => {
|
||||||
const { state, client } = harness();
|
const { state, client } = harness();
|
||||||
|
|
||||||
const result = await publish(client, '**Pas de contenu illégal.**');
|
const result = await publish(client, '**Pas de contenu illégal.**');
|
||||||
@@ -61,32 +63,45 @@ describe('rules service', () => {
|
|||||||
assert.equal(state.sent.length, 1);
|
assert.equal(state.sent.length, 1);
|
||||||
assert.equal(description(state.sent[0]), '**Pas de contenu illégal.**');
|
assert.equal(description(state.sent[0]), '**Pas de contenu illégal.**');
|
||||||
assert.deepEqual(state.pinned, ['message-1']);
|
assert.deepEqual(state.pinned, ['message-1']);
|
||||||
assert.equal(result.pinned, true);
|
assert.deepEqual({ pinned: result.pinned, edited: result.edited }, { pinned: true, edited: false });
|
||||||
assert.equal(rulesStatus('g').messageId, 'message-1');
|
assert.equal(rulesStatus('g', RULES_CHANNEL).messageId, 'message-1');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('deletes the previous message instead of piling copies up', async () => {
|
it('edits the published message instead of sending a second one', async () => {
|
||||||
const { state, client } = harness();
|
const { state, client } = harness();
|
||||||
|
|
||||||
await publish(client, 'Version 1');
|
await publish(client, 'Version 1');
|
||||||
await publish(client, 'Version 2');
|
const result = await publish(client, 'Version 2');
|
||||||
|
|
||||||
assert.deepEqual(state.deleted, ['message-1']);
|
assert.equal(state.sent.length, 1, 'a second message was sent');
|
||||||
assert.deepEqual(state.sent.map(description), ['Version 1', 'Version 2']);
|
assert.deepEqual(state.edited, [{ id: 'message-1', description: 'Version 2' }]);
|
||||||
assert.equal(rulesStatus('g').messageId, 'message-2');
|
assert.equal(result.messageId, 'message-1', 'the message id must not change');
|
||||||
|
assert.equal(result.edited, true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('publishes even when the previous message was deleted by hand', async () => {
|
it('sends a new one when the previous message is gone', async () => {
|
||||||
const { state, client } = harness();
|
const { state, client } = harness();
|
||||||
|
|
||||||
await publish(client, 'Version 1');
|
await publish(client, 'Version 1');
|
||||||
state.messages.delete('message-1');
|
state.messages.clear();
|
||||||
|
|
||||||
const result = await publish(client, 'Version 2');
|
const result = await publish(client, 'Version 2');
|
||||||
|
|
||||||
|
assert.equal(state.sent.length, 2);
|
||||||
|
assert.equal(result.edited, false);
|
||||||
assert.equal(result.messageId, 'message-2');
|
assert.equal(result.messageId, 'message-2');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('sends a new one when the bot may no longer edit it', async () => {
|
||||||
|
const { state, client } = harness({ notEditable: true });
|
||||||
|
|
||||||
|
await publish(client, 'Version 1');
|
||||||
|
const result = await publish(client, 'Version 2');
|
||||||
|
|
||||||
|
assert.equal(state.sent.length, 2);
|
||||||
|
assert.equal(result.edited, false);
|
||||||
|
});
|
||||||
|
|
||||||
it('publishes even when the bot cannot pin', async () => {
|
it('publishes even when the bot cannot pin', async () => {
|
||||||
const { state, client } = harness({ pinFails: true });
|
const { state, client } = harness({ pinFails: true });
|
||||||
|
|
||||||
@@ -94,7 +109,7 @@ describe('rules service', () => {
|
|||||||
|
|
||||||
assert.deepEqual(state.pinned, []);
|
assert.deepEqual(state.pinned, []);
|
||||||
assert.equal(result.pinned, false);
|
assert.equal(result.pinned, false);
|
||||||
assert.equal(rulesStatus('g').messageId, 'message-1');
|
assert.equal(rulesStatus('g', RULES_CHANNEL).messageId, 'message-1');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('refuses an empty or oversized regulation', async () => {
|
it('refuses an empty or oversized regulation', async () => {
|
||||||
|
|||||||
Reference in new issue
Block a user