refactor(all): uniformisation

This commit is contained in:
BlackAngelTV committed 2026-09-23 18:25:28 +02:00
1 parent ee538cb943
commit 50665c8edd
89 files changed
+10215 -10215

No files matched your search

+69 -69
View File
@@ -1,69 +1,69 @@
import { env } from '../../config/env.js';
import { ExternalApiError } from '../../core/errors.js';
import { withRetry } from '../../utils/retry.js';
const isTransient = (error) => error.name === 'TimeoutError' || error.status === 429 || error.status >= 500;
/** Minimal Gitea REST API client (M5-T01). */
export async function giteaRequest(endpoint, { method = 'GET', body } = {}) {
if (!env.gitea.url || !env.gitea.token) {
throw new ExternalApiError('gitea', 'Gitea is not configured');
}
return withRetry(
async () => {
const response = await fetch(`${env.gitea.url}/api/v1${endpoint}`, {
method,
headers: {
Authorization: `token ${env.gitea.token}`,
Accept: 'application/json',
...(body && { 'Content-Type': 'application/json' }),
},
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(env.gitea.timeoutMs),
});
if (!response.ok) {
const error = new ExternalApiError('gitea', `${method} ${endpoint} failed with ${response.status}`);
error.status = response.status;
throw error;
}
return response.status === 204 ? null : response.json();
},
{ retries: env.gitea.maxRetries, shouldRetry: isTransient },
);
}
/** True when both the Gitea URL and token are configured (M5-T01). */
export function isGiteaConfigured() {
return Boolean(env.gitea.url && env.gitea.token);
}
/** Gitea returns either a bare array or a `{ data: [...] }` wrapper depending on the version. */
export function asList(payload) {
if (Array.isArray(payload)) return payload;
return Array.isArray(payload?.data) ? payload.data : [];
}
/** Human readable URL of the configured repository, used in embeds. */
export function repositoryUrl() {
return env.gitea.url ? `${env.gitea.url}/${env.gitea.owner}/${env.gitea.repo}` : '';
}
const repoPath = () => `/repos/${env.gitea.owner}/${env.gitea.repo}`;
export const gitea = {
listIssues: (params = 'state=open&type=issues&limit=10') => giteaRequest(`${repoPath()}/issues?${params}`),
getIssue: (number) => giteaRequest(`${repoPath()}/issues/${number}`),
createIssue: ({ title, body }) =>
giteaRequest(`${repoPath()}/issues`, { method: 'POST', body: { title, body } }),
listPullRequests: (params = 'state=open&limit=10') => giteaRequest(`${repoPath()}/pulls?${params}`),
getPullRequest: (number) => giteaRequest(`${repoPath()}/pulls/${number}`),
createPullRequest: ({ title, body, head, base }) =>
giteaRequest(`${repoPath()}/pulls`, { method: 'POST', body: { title, body, head, base } }),
listCommits: (limit = 10) => giteaRequest(`${repoPath()}/commits?limit=${limit}`),
listReleases: (limit = 5) => giteaRequest(`${repoPath()}/releases?limit=${limit}`),
getLatestRelease: () => giteaRequest(`${repoPath()}/releases/latest`),
getReleaseByTag: (tag) => giteaRequest(`${repoPath()}/releases/tags/${encodeURIComponent(tag)}`),
listBranches: (limit = 20) => giteaRequest(`${repoPath()}/branches?limit=${limit}`),
};
import { env } from '../../config/env.js';
import { ExternalApiError } from '../../core/errors.js';
import { withRetry } from '../../utils/retry.js';
const isTransient = (error) => error.name === 'TimeoutError' || error.status === 429 || error.status >= 500;
/** Minimal Gitea REST API client (M5-T01). */
export async function giteaRequest(endpoint, { method = 'GET', body } = {}) {
if (!env.gitea.url || !env.gitea.token) {
throw new ExternalApiError('gitea', 'Gitea is not configured');
}
return withRetry(
async () => {
const response = await fetch(`${env.gitea.url}/api/v1${endpoint}`, {
method,
headers: {
Authorization: `token ${env.gitea.token}`,
Accept: 'application/json',
...(body && { 'Content-Type': 'application/json' }),
},
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(env.gitea.timeoutMs),
});
if (!response.ok) {
const error = new ExternalApiError('gitea', `${method} ${endpoint} failed with ${response.status}`);
error.status = response.status;
throw error;
}
return response.status === 204 ? null : response.json();
},
{ retries: env.gitea.maxRetries, shouldRetry: isTransient },
);
}
/** True when both the Gitea URL and token are configured (M5-T01). */
export function isGiteaConfigured() {
return Boolean(env.gitea.url && env.gitea.token);
}
/** Gitea returns either a bare array or a `{ data: [...] }` wrapper depending on the version. */
export function asList(payload) {
if (Array.isArray(payload)) return payload;
return Array.isArray(payload?.data) ? payload.data : [];
}
/** Human readable URL of the configured repository, used in embeds. */
export function repositoryUrl() {
return env.gitea.url ? `${env.gitea.url}/${env.gitea.owner}/${env.gitea.repo}` : '';
}
const repoPath = () => `/repos/${env.gitea.owner}/${env.gitea.repo}`;
export const gitea = {
listIssues: (params = 'state=open&type=issues&limit=10') => giteaRequest(`${repoPath()}/issues?${params}`),
getIssue: (number) => giteaRequest(`${repoPath()}/issues/${number}`),
createIssue: ({ title, body }) =>
giteaRequest(`${repoPath()}/issues`, { method: 'POST', body: { title, body } }),
listPullRequests: (params = 'state=open&limit=10') => giteaRequest(`${repoPath()}/pulls?${params}`),
getPullRequest: (number) => giteaRequest(`${repoPath()}/pulls/${number}`),
createPullRequest: ({ title, body, head, base }) =>
giteaRequest(`${repoPath()}/pulls`, { method: 'POST', body: { title, body, head, base } }),
listCommits: (limit = 10) => giteaRequest(`${repoPath()}/commits?limit=${limit}`),
listReleases: (limit = 5) => giteaRequest(`${repoPath()}/releases?limit=${limit}`),
getLatestRelease: () => giteaRequest(`${repoPath()}/releases/latest`),
getReleaseByTag: (tag) => giteaRequest(`${repoPath()}/releases/tags/${encodeURIComponent(tag)}`),
listBranches: (limit = 20) => giteaRequest(`${repoPath()}/branches?limit=${limit}`),
};
+97 -97
View File
@@ -1,97 +1,97 @@
import { COLORS } from '../../config/constants.js';
import { baseEmbed } from '../../ui/embeds.js';
const DESCRIPTION_MAX = 1500;
/** Truncates free text coming from the API before it reaches Discord. */
export function truncate(text, max = DESCRIPTION_MAX) {
const value = String(text ?? '').trim();
if (!value) return '';
return value.length > max ? `${value.slice(0, max - 1)}…` : value;
}
/** Falls back to a neutral word: the value always sits next to a person, never a role. */
const authorOf = (source) =>
source?.user?.login ?? source?.sender?.login ?? source?.author?.name ?? 'compte inconnu';
/** Shared header of an issue, used by `/issue` and the webhooks (M5-T02 / M9-T04). */
export function issueEmbed(issue) {
const embed = baseEmbed(COLORS.gitea)
.setTitle(`#${issue.number} ${issue.title}`)
.setDescription(truncate(issue.body) || 'Aucune description fournie.')
.addFields(
{ name: 'Ouverte par', value: authorOf(issue), inline: true },
{ name: 'État', value: issue.state === 'closed' ? 'Fermée' : 'Ouverte', inline: true },
{ name: 'Commentaires', value: String(issue.comments ?? 0), inline: true },
);
if (issue.html_url) embed.setURL(issue.html_url);
const labels = (issue.labels ?? []).map((label) => label.name).filter(Boolean);
if (labels.length > 0) embed.addFields({ name: 'Étiquettes', value: labels.join(', ') });
return embed;
}
/** Shared header of a pull request (M5-T04 / M9-T05). */
export function pullRequestEmbed(pull) {
const state = pull.merged ? 'Fusionnée' : pull.state === 'closed' ? 'Fermée' : 'Ouverte';
const embed = baseEmbed(COLORS.gitea)
.setTitle(`PR #${pull.number} ${pull.title}`)
.setDescription(truncate(pull.body) || 'Aucune description fournie.')
.addFields(
{ name: 'Proposée par', value: authorOf(pull), inline: true },
{ name: 'État', value: state, inline: true },
{ name: 'Branches', value: `${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'}`, inline: true },
);
if (pull.html_url) embed.setURL(pull.html_url);
return embed;
}
/** Release notes, shared by `/fws version`, `/fws changelog` and the webhooks. */
export function releaseEmbed(release, { withNotes = true } = {}) {
const embed = baseEmbed(COLORS.gitea)
.setTitle(`${release.name || release.tag_name}`)
.addFields(
{ name: 'Tag', value: release.tag_name ?? 'inconnu', inline: true },
{ name: 'Publiée par', value: authorOf(release), inline: true },
{ name: 'Pré-version', value: release.prerelease ? 'Oui' : 'Non', inline: true },
);
if (release.html_url) embed.setURL(release.html_url);
if (release.published_at) {
const timestamp = Math.floor(new Date(release.published_at).getTime() / 1000);
embed.addFields({ name: 'Date', value: `<t:${timestamp}:f>`, inline: true });
}
if (withNotes && release.body) embed.setDescription(truncate(release.body, 3900));
return embed;
}
/** Push notification: the last commits of a branch (M9-T06). */
export function pushEmbed(payload, maxCommits = 5) {
const commits = payload.commits ?? [];
const branch = (payload.ref ?? '').replace('refs/heads/', '');
const lines = commits
.slice(0, maxCommits)
.map((commit) => `\`${String(commit.id).slice(0, 7)}\` ${truncate(commit.message?.split('\n')[0], 90)}`);
const remaining = commits.length - lines.length;
const embed = baseEmbed(COLORS.gitea)
.setTitle(`Push sur ${branch || 'le dépôt'}`)
.setDescription(lines.join('\n') || 'Aucun commit à afficher pour cet événement.')
.addFields(
{ name: 'Poussé par', value: authorOf(payload), inline: true },
{ name: 'Commits', value: String(commits.length), inline: true },
);
if (remaining > 0) embed.addFields({ name: 'Et aussi', value: `${remaining} commit(s) de plus` });
if (payload.repository?.html_url) embed.setURL(payload.repository.html_url);
return embed;
}
/** Git references created or deleted (`create` / `delete` events). */
export function refEmbed(payload, action) {
const ref = payload.ref ?? 'inconnu';
const refType = payload.ref_type ?? 'ref';
const embed = baseEmbed(COLORS.gitea)
.setTitle(`${action === 'deleted' ? 'Suppression' : 'Création'} de ${refType} : ${ref}`)
.setDescription(`${authorOf(payload)} a ${action === 'deleted' ? 'supprimé' : 'créé'} \`${ref}\`.`);
if (payload.repository?.html_url) embed.setURL(payload.repository.html_url);
return embed;
}
import { COLORS } from '../../config/constants.js';
import { baseEmbed } from '../../ui/embeds.js';
const DESCRIPTION_MAX = 1500;
/** Truncates free text coming from the API before it reaches Discord. */
export function truncate(text, max = DESCRIPTION_MAX) {
const value = String(text ?? '').trim();
if (!value) return '';
return value.length > max ? `${value.slice(0, max - 1)}…` : value;
}
/** Falls back to a neutral word: the value always sits next to a person, never a role. */
const authorOf = (source) =>
source?.user?.login ?? source?.sender?.login ?? source?.author?.name ?? 'compte inconnu';
/** Shared header of an issue, used by `/issue` and the webhooks (M5-T02 / M9-T04). */
export function issueEmbed(issue) {
const embed = baseEmbed(COLORS.gitea)
.setTitle(`#${issue.number} ${issue.title}`)
.setDescription(truncate(issue.body) || 'Aucune description fournie.')
.addFields(
{ name: 'Ouverte par', value: authorOf(issue), inline: true },
{ name: 'État', value: issue.state === 'closed' ? 'Fermée' : 'Ouverte', inline: true },
{ name: 'Commentaires', value: String(issue.comments ?? 0), inline: true },
);
if (issue.html_url) embed.setURL(issue.html_url);
const labels = (issue.labels ?? []).map((label) => label.name).filter(Boolean);
if (labels.length > 0) embed.addFields({ name: 'Étiquettes', value: labels.join(', ') });
return embed;
}
/** Shared header of a pull request (M5-T04 / M9-T05). */
export function pullRequestEmbed(pull) {
const state = pull.merged ? 'Fusionnée' : pull.state === 'closed' ? 'Fermée' : 'Ouverte';
const embed = baseEmbed(COLORS.gitea)
.setTitle(`PR #${pull.number} ${pull.title}`)
.setDescription(truncate(pull.body) || 'Aucune description fournie.')
.addFields(
{ name: 'Proposée par', value: authorOf(pull), inline: true },
{ name: 'État', value: state, inline: true },
{ name: 'Branches', value: `${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'}`, inline: true },
);
if (pull.html_url) embed.setURL(pull.html_url);
return embed;
}
/** Release notes, shared by `/fws version`, `/fws changelog` and the webhooks. */
export function releaseEmbed(release, { withNotes = true } = {}) {
const embed = baseEmbed(COLORS.gitea)
.setTitle(`${release.name || release.tag_name}`)
.addFields(
{ name: 'Tag', value: release.tag_name ?? 'inconnu', inline: true },
{ name: 'Publiée par', value: authorOf(release), inline: true },
{ name: 'Pré-version', value: release.prerelease ? 'Oui' : 'Non', inline: true },
);
if (release.html_url) embed.setURL(release.html_url);
if (release.published_at) {
const timestamp = Math.floor(new Date(release.published_at).getTime() / 1000);
embed.addFields({ name: 'Date', value: `<t:${timestamp}:f>`, inline: true });
}
if (withNotes && release.body) embed.setDescription(truncate(release.body, 3900));
return embed;
}
/** Push notification: the last commits of a branch (M9-T06). */
export function pushEmbed(payload, maxCommits = 5) {
const commits = payload.commits ?? [];
const branch = (payload.ref ?? '').replace('refs/heads/', '');
const lines = commits
.slice(0, maxCommits)
.map((commit) => `\`${String(commit.id).slice(0, 7)}\` ${truncate(commit.message?.split('\n')[0], 90)}`);
const remaining = commits.length - lines.length;
const embed = baseEmbed(COLORS.gitea)
.setTitle(`Push sur ${branch || 'le dépôt'}`)
.setDescription(lines.join('\n') || 'Aucun commit à afficher pour cet événement.')
.addFields(
{ name: 'Poussé par', value: authorOf(payload), inline: true },
{ name: 'Commits', value: String(commits.length), inline: true },
);
if (remaining > 0) embed.addFields({ name: 'Et aussi', value: `${remaining} commit(s) de plus` });
if (payload.repository?.html_url) embed.setURL(payload.repository.html_url);
return embed;
}
/** Git references created or deleted (`create` / `delete` events). */
export function refEmbed(payload, action) {
const ref = payload.ref ?? 'inconnu';
const refType = payload.ref_type ?? 'ref';
const embed = baseEmbed(COLORS.gitea)
.setTitle(`${action === 'deleted' ? 'Suppression' : 'Création'} de ${refType} : ${ref}`)
.setDescription(`${authorOf(payload)} a ${action === 'deleted' ? 'supprimé' : 'créé'} \`${ref}\`.`);
if (payload.repository?.html_url) embed.setURL(payload.repository.html_url);
return embed;
}
+152 -152
View File
@@ -1,152 +1,152 @@
import { ActionRowBuilder, MessageFlags, ModalBuilder, TextInputBuilder, TextInputStyle } from 'discord.js';
import { ExternalApiError, UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { linkButtons } from '../../ui/buttons.js';
import { errorEmbed } from '../../ui/embeds.js';
import { issueEmbed, pullRequestEmbed } from './gitea-embeds.js';
import { gitea, isGiteaConfigured } from './gitea-client.js';
import { consume, remember } from './pending-actions.js';
const log = createLogger('gitea');
const PR_CONTEXT_TTL_MS = 10 * 60_000;
/** Fails fast with an actionable message when Gitea is not configured (M5-T01). */
export function assertGiteaConfigured() {
if (!isGiteaConfigured()) {
throw new UserFacingError(
'La partie Gitea n’est pas encore configurée : il manque `GITEA_URL` et `GITEA_TOKEN` dans le `.env`. Tout le reste du bot fonctionne sans cela.',
);
}
}
function modal(id, title, fields) {
return new ModalBuilder()
.setCustomId(id)
.setTitle(title)
.addComponents(
fields.map((field) =>
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId(field.id)
.setLabel(field.label)
.setStyle(field.paragraph ? TextInputStyle.Paragraph : TextInputStyle.Short)
.setMaxLength(field.maxLength)
.setRequired(field.required ?? true),
),
),
);
}
/** `/issue create` collects the title and description through a modal (M5-T03). */
export async function openIssueModal(interaction) {
assertGiteaConfigured();
await interaction.showModal(
modal('issue:create', 'Nouvelle issue Gitea', [
{ id: 'title', label: 'Titre', maxLength: 200 },
{ id: 'body', label: 'Description', paragraph: true, maxLength: 4000 },
]),
);
}
/** `/pr create` keeps the branch options and asks for the title through a modal. */
export async function openPullRequestModal(interaction) {
assertGiteaConfigured();
const head = interaction.options.getString('head', true);
const base = interaction.options.getString('base', true);
remember(`pr:${interaction.user.id}`, { head, base }, { ttlMs: PR_CONTEXT_TTL_MS });
await interaction.showModal(
modal('pr:create', 'Nouvelle pull request', [
{ id: 'title', label: `Titre (${head} → ${base})`, maxLength: 200 },
{ id: 'body', label: 'Description', paragraph: true, maxLength: 4000, required: false },
]),
);
}
/** Turns an API failure into a message the user can act on (M5-T08). */
export async function replyGiteaFailure(interaction, error) {
log.error('Gitea request failed', error);
const detail =
error instanceof ExternalApiError && /not configured/.test(error.message)
? 'La partie Gitea n’est pas encore configurée : il manque `GITEA_URL` et `GITEA_TOKEN` dans le `.env`.'
: 'Gitea ne répond pas pour le moment. Réessaie dans quelques instants — si ça persiste, préviens l’équipe.';
const payload = { embeds: [errorEmbed(detail)], flags: MessageFlags.Ephemeral };
if (interaction.deferred || interaction.replied) {
await interaction.followUp(payload).catch(() => {});
} else {
await interaction.reply(payload).catch(() => {});
}
}
export async function submitIssueModal(interaction) {
assertGiteaConfigured();
await interaction.deferReply();
try {
const issue = await gitea.createIssue({
title: interaction.fields.getTextInputValue('title'),
body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`,
});
logEvent({
guildId: interaction.guildId,
type: 'gitea.issue.created',
actorId: interaction.user.id,
payload: { number: issue.number },
});
await interaction.editReply({
embeds: [issueEmbed(issue)],
components: linkButtons([{ label: 'Ouvrir sur Gitea', url: issue.html_url }]),
});
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
export async function submitPullRequestModal(interaction) {
assertGiteaConfigured();
const context = consume(`pr:${interaction.user.id}`);
if (!context) {
throw new UserFacingError(
'La sélection des branches a expiré : relance `/pr create` pour les choisir à nouveau.',
);
}
await interaction.deferReply();
try {
const pull = await gitea.createPullRequest({
title: interaction.fields.getTextInputValue('title'),
body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`.trim(),
head: context.head,
base: context.base,
});
logEvent({
guildId: interaction.guildId,
type: 'gitea.pull_request.created',
actorId: interaction.user.id,
payload: { number: pull.number, head: context.head, base: context.base },
});
await interaction.editReply({
embeds: [pullRequestEmbed(pull)],
components: linkButtons([{ label: 'Ouvrir sur Gitea', url: pull.html_url }]),
});
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
/** Routes the modal submissions opened by `/issue` and `/pr` (M5-T09). */
export async function handleGiteaModal(interaction) {
switch (interaction.customId) {
case 'issue:create':
await submitIssueModal(interaction);
return;
case 'pr:create':
await submitPullRequestModal(interaction);
return;
default:
log.debug(`Ignored unknown modal ${interaction.customId}`);
}
}
import { ActionRowBuilder, MessageFlags, ModalBuilder, TextInputBuilder, TextInputStyle } from 'discord.js';
import { ExternalApiError, UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { linkButtons } from '../../ui/buttons.js';
import { errorEmbed } from '../../ui/embeds.js';
import { issueEmbed, pullRequestEmbed } from './gitea-embeds.js';
import { gitea, isGiteaConfigured } from './gitea-client.js';
import { consume, remember } from './pending-actions.js';
const log = createLogger('gitea');
const PR_CONTEXT_TTL_MS = 10 * 60_000;
/** Fails fast with an actionable message when Gitea is not configured (M5-T01). */
export function assertGiteaConfigured() {
if (!isGiteaConfigured()) {
throw new UserFacingError(
'La partie Gitea n’est pas encore configurée : il manque `GITEA_URL` et `GITEA_TOKEN` dans le `.env`. Tout le reste du bot fonctionne sans cela.',
);
}
}
function modal(id, title, fields) {
return new ModalBuilder()
.setCustomId(id)
.setTitle(title)
.addComponents(
fields.map((field) =>
new ActionRowBuilder().addComponents(
new TextInputBuilder()
.setCustomId(field.id)
.setLabel(field.label)
.setStyle(field.paragraph ? TextInputStyle.Paragraph : TextInputStyle.Short)
.setMaxLength(field.maxLength)
.setRequired(field.required ?? true),
),
),
);
}
/** `/issue create` collects the title and description through a modal (M5-T03). */
export async function openIssueModal(interaction) {
assertGiteaConfigured();
await interaction.showModal(
modal('issue:create', 'Nouvelle issue Gitea', [
{ id: 'title', label: 'Titre', maxLength: 200 },
{ id: 'body', label: 'Description', paragraph: true, maxLength: 4000 },
]),
);
}
/** `/pr create` keeps the branch options and asks for the title through a modal. */
export async function openPullRequestModal(interaction) {
assertGiteaConfigured();
const head = interaction.options.getString('head', true);
const base = interaction.options.getString('base', true);
remember(`pr:${interaction.user.id}`, { head, base }, { ttlMs: PR_CONTEXT_TTL_MS });
await interaction.showModal(
modal('pr:create', 'Nouvelle pull request', [
{ id: 'title', label: `Titre (${head} → ${base})`, maxLength: 200 },
{ id: 'body', label: 'Description', paragraph: true, maxLength: 4000, required: false },
]),
);
}
/** Turns an API failure into a message the user can act on (M5-T08). */
export async function replyGiteaFailure(interaction, error) {
log.error('Gitea request failed', error);
const detail =
error instanceof ExternalApiError && /not configured/.test(error.message)
? 'La partie Gitea n’est pas encore configurée : il manque `GITEA_URL` et `GITEA_TOKEN` dans le `.env`.'
: 'Gitea ne répond pas pour le moment. Réessaie dans quelques instants — si ça persiste, préviens l’équipe.';
const payload = { embeds: [errorEmbed(detail)], flags: MessageFlags.Ephemeral };
if (interaction.deferred || interaction.replied) {
await interaction.followUp(payload).catch(() => {});
} else {
await interaction.reply(payload).catch(() => {});
}
}
export async function submitIssueModal(interaction) {
assertGiteaConfigured();
await interaction.deferReply();
try {
const issue = await gitea.createIssue({
title: interaction.fields.getTextInputValue('title'),
body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`,
});
logEvent({
guildId: interaction.guildId,
type: 'gitea.issue.created',
actorId: interaction.user.id,
payload: { number: issue.number },
});
await interaction.editReply({
embeds: [issueEmbed(issue)],
components: linkButtons([{ label: 'Ouvrir sur Gitea', url: issue.html_url }]),
});
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
export async function submitPullRequestModal(interaction) {
assertGiteaConfigured();
const context = consume(`pr:${interaction.user.id}`);
if (!context) {
throw new UserFacingError(
'La sélection des branches a expiré : relance `/pr create` pour les choisir à nouveau.',
);
}
await interaction.deferReply();
try {
const pull = await gitea.createPullRequest({
title: interaction.fields.getTextInputValue('title'),
body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`.trim(),
head: context.head,
base: context.base,
});
logEvent({
guildId: interaction.guildId,
type: 'gitea.pull_request.created',
actorId: interaction.user.id,
payload: { number: pull.number, head: context.head, base: context.base },
});
await interaction.editReply({
embeds: [pullRequestEmbed(pull)],
components: linkButtons([{ label: 'Ouvrir sur Gitea', url: pull.html_url }]),
});
} catch (error) {
await replyGiteaFailure(interaction, error);
}
}
/** Routes the modal submissions opened by `/issue` and `/pr` (M5-T09). */
export async function handleGiteaModal(interaction) {
switch (interaction.customId) {
case 'issue:create':
await submitIssueModal(interaction);
return;
case 'pr:create':
await submitPullRequestModal(interaction);
return;
default:
log.debug(`Ignored unknown modal ${interaction.customId}`);
}
}
+32 -32
View File
@@ -1,32 +1,32 @@
/**
* In-memory store for the short-lived context of a modal flow, e.g. the branches
* of `/pr create` which are typed as options but sent with the modal (M5-T04).
* Entries expire on their own and disappear on restart.
*/
const DEFAULT_TTL_MS = 5 * 60_000;
const entries = new Map();
export function remember(key, value, { ttlMs = DEFAULT_TTL_MS, now = Date.now() } = {}) {
entries.set(key, { value, expiresAt: now + ttlMs });
return value;
}
/** Returns the stored value and forgets it, or null when missing or expired. */
export function consume(key, { now = Date.now() } = {}) {
const entry = entries.get(key);
if (!entry) return null;
entries.delete(key);
return entry.expiresAt > now ? entry.value : null;
}
export function purgeExpired(now = Date.now()) {
for (const [key, entry] of entries) {
if (entry.expiresAt <= now) entries.delete(key);
}
return entries.size;
}
export function pendingCount() {
return entries.size;
}
/**
* In-memory store for the short-lived context of a modal flow, e.g. the branches
* of `/pr create` which are typed as options but sent with the modal (M5-T04).
* Entries expire on their own and disappear on restart.
*/
const DEFAULT_TTL_MS = 5 * 60_000;
const entries = new Map();
export function remember(key, value, { ttlMs = DEFAULT_TTL_MS, now = Date.now() } = {}) {
entries.set(key, { value, expiresAt: now + ttlMs });
return value;
}
/** Returns the stored value and forgets it, or null when missing or expired. */
export function consume(key, { now = Date.now() } = {}) {
const entry = entries.get(key);
if (!entry) return null;
entries.delete(key);
return entry.expiresAt > now ? entry.value : null;
}
export function purgeExpired(now = Date.now()) {
for (const [key, entry] of entries) {
if (entry.expiresAt <= now) entries.delete(key);
}
return entries.size;
}
export function pendingCount() {
return entries.size;
}
+115 -115
View File
@@ -1,115 +1,115 @@
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 { baseEmbed } from '../../ui/embeds.js';
const log = createLogger('members');
const DEFAULT_WELCOME = 'Bienvenue sur le serveur **FWS** !';
async function sendTo(channel) {
return channel?.isSendable() ? channel : null;
}
/** Sends the welcome embed in `CHANNEL_WELCOME_ID` (M7-T01 / M7-T02). */
export async function sendWelcome(client, member) {
if (!env.channels.welcome) {
log.debug('No welcome channel configured');
return;
}
const channel = await sendTo(await client.channels.fetch(env.channels.welcome).catch(() => null));
if (!channel) {
log.warn('Welcome channel unavailable', { channelId: env.channels.welcome });
return;
}
const embed = baseEmbed(COLORS.primary)
.setTitle('🎉 Nouveau membre')
.setDescription(`${member} vient d’arriver. ${DEFAULT_WELCOME}`)
.addFields({ name: 'Membres', value: String(member.guild.memberCount), inline: true })
.setThumbnail(member.user.displayAvatarURL({ size: 128 }));
if (env.channels.rules) {
embed.addFields({ name: 'Règlement', value: `À lire ici : <#${env.channels.rules}>` });
}
await channel.send({ content: `${member}`, embeds: [embed] });
logEvent({ guildId: member.guild.id, type: 'member.welcome', payload: { userId: member.id } });
}
/** Gives the default member role (M7-T03). */
export async function assignMemberRole(member) {
const roleId = env.roles.member;
if (!roleId || member.roles.cache.has(roleId)) return;
const role = await member.guild.roles.fetch(roleId).catch(() => null);
if (!role) {
log.warn('Default member role not found', { roleId });
return;
}
if (member.guild.members.me?.roles.highest.comparePositionTo(role) <= 0) {
log.warn('Member role is above the bot role, skipping', { roleId });
return;
}
await member.roles.add(role, 'Rôle par défaut à l’arrivée').catch((error) => {
log.warn('Could not assign the member role', error);
});
}
/** Welcomes the member in a direct message with the server resources (M7-T02). */
export async function sendWelcomeDirectMessage(member) {
const links = [
env.links.website && `[Site officiel](${env.links.website})`,
env.links.docs && `[Documentation](${env.links.docs})`,
env.links.archRepo && `[Dépôt FWS Arch](${env.links.archRepo})`,
].filter(Boolean);
const embed = baseEmbed(COLORS.primary)
.setTitle(`Bienvenue sur ${member.guild.name} !`)
.setDescription(
'Merci d’avoir rejoint la communauté FWS 🌱 Prends un instant pour lire le règlement, ' +
'puis présente‑toi si tu le souhaites : on adore découvrir les nouvelles personnes.',
);
if (links.length > 0) embed.addFields({ name: 'Ressources', value: links.join('\n') });
await member.send({ embeds: [embed] }).catch(() => {
log.debug('Welcome DM could not be delivered', { userId: member.id });
});
}
/** Logs a departure in the log channel (M7-T04). */
export async function announceDeparture(client, member) {
const channelId = env.channels.logs || env.channels.modLogs;
if (!channelId) return;
const channel = await sendTo(await client.channels.fetch(channelId).catch(() => null));
if (!channel) return;
const joinedAt = member.joinedTimestamp;
const embed = baseEmbed(COLORS.warning)
.setTitle('👋 Départ d’un membre')
.setDescription(`${member.user.tag} a quitté le serveur.`)
.addFields(
{ name: 'Membres', value: String(member.guild.memberCount), inline: true },
{
name: 'Compte créé',
value: `<t:${Math.floor(member.user.createdTimestamp / 1000)}:R>`,
inline: true,
},
)
.setThumbnail(member.user.displayAvatarURL({ size: 128 }));
if (joinedAt) {
embed.addFields({ name: 'Arrivé', value: `<t:${Math.floor(joinedAt / 1000)}:R>`, inline: true });
}
await channel.send({ embeds: [embed] });
logEvent({
guildId: member.guild.id,
type: 'member.left',
payload: { userId: member.id, joinedAt: joinedAt ?? null },
});
}
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 { baseEmbed } from '../../ui/embeds.js';
const log = createLogger('members');
const DEFAULT_WELCOME = 'Bienvenue sur le serveur **FWS** !';
async function sendTo(channel) {
return channel?.isSendable() ? channel : null;
}
/** Sends the welcome embed in `CHANNEL_WELCOME_ID` (M7-T01 / M7-T02). */
export async function sendWelcome(client, member) {
if (!env.channels.welcome) {
log.debug('No welcome channel configured');
return;
}
const channel = await sendTo(await client.channels.fetch(env.channels.welcome).catch(() => null));
if (!channel) {
log.warn('Welcome channel unavailable', { channelId: env.channels.welcome });
return;
}
const embed = baseEmbed(COLORS.primary)
.setTitle('🎉 Nouveau membre')
.setDescription(`${member} vient d’arriver. ${DEFAULT_WELCOME}`)
.addFields({ name: 'Membres', value: String(member.guild.memberCount), inline: true })
.setThumbnail(member.user.displayAvatarURL({ size: 128 }));
if (env.channels.rules) {
embed.addFields({ name: 'Règlement', value: `À lire ici : <#${env.channels.rules}>` });
}
await channel.send({ content: `${member}`, embeds: [embed] });
logEvent({ guildId: member.guild.id, type: 'member.welcome', payload: { userId: member.id } });
}
/** Gives the default member role (M7-T03). */
export async function assignMemberRole(member) {
const roleId = env.roles.member;
if (!roleId || member.roles.cache.has(roleId)) return;
const role = await member.guild.roles.fetch(roleId).catch(() => null);
if (!role) {
log.warn('Default member role not found', { roleId });
return;
}
if (member.guild.members.me?.roles.highest.comparePositionTo(role) <= 0) {
log.warn('Member role is above the bot role, skipping', { roleId });
return;
}
await member.roles.add(role, 'Rôle par défaut à l’arrivée').catch((error) => {
log.warn('Could not assign the member role', error);
});
}
/** Welcomes the member in a direct message with the server resources (M7-T02). */
export async function sendWelcomeDirectMessage(member) {
const links = [
env.links.website && `[Site officiel](${env.links.website})`,
env.links.docs && `[Documentation](${env.links.docs})`,
env.links.archRepo && `[Dépôt FWS Arch](${env.links.archRepo})`,
].filter(Boolean);
const embed = baseEmbed(COLORS.primary)
.setTitle(`Bienvenue sur ${member.guild.name} !`)
.setDescription(
'Merci d’avoir rejoint la communauté FWS 🌱 Prends un instant pour lire le règlement, ' +
'puis présente‑toi si tu le souhaites : on adore découvrir les nouvelles personnes.',
);
if (links.length > 0) embed.addFields({ name: 'Ressources', value: links.join('\n') });
await member.send({ embeds: [embed] }).catch(() => {
log.debug('Welcome DM could not be delivered', { userId: member.id });
});
}
/** Logs a departure in the log channel (M7-T04). */
export async function announceDeparture(client, member) {
const channelId = env.channels.logs || env.channels.modLogs;
if (!channelId) return;
const channel = await sendTo(await client.channels.fetch(channelId).catch(() => null));
if (!channel) return;
const joinedAt = member.joinedTimestamp;
const embed = baseEmbed(COLORS.warning)
.setTitle('👋 Départ d’un membre')
.setDescription(`${member.user.tag} a quitté le serveur.`)
.addFields(
{ name: 'Membres', value: String(member.guild.memberCount), inline: true },
{
name: 'Compte créé',
value: `<t:${Math.floor(member.user.createdTimestamp / 1000)}:R>`,
inline: true,
},
)
.setThumbnail(member.user.displayAvatarURL({ size: 128 }));
if (joinedAt) {
embed.addFields({ name: 'Arrivé', value: `<t:${Math.floor(joinedAt / 1000)}:R>`, inline: true });
}
await channel.send({ embeds: [embed] });
logEvent({
guildId: member.guild.id,
type: 'member.left',
payload: { userId: member.id, joinedAt: joinedAt ?? null },
});
}
+132 -132
View File
@@ -1,132 +1,132 @@
import { COLORS, MODERATION_ACTIONS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { UserFacingError } from '../../core/errors.js';
import { canActOn } from '../../core/permissions.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { recordAction } from '../../database/repositories/moderation-repository.js';
import { baseEmbed } from '../../ui/embeds.js';
/**
* Enforces the role hierarchy before any moderation action (M3-T05 / M8-T08).
* @param {import('discord.js').ChatInputCommandInteraction} interaction
* @param {import('discord.js').GuildMember} target
*/
export function assertModerationTarget(interaction, target) {
if (!target) {
throw new UserFacingError(
'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.',
);
}
if (target.id === interaction.user.id) {
throw new UserFacingError('Tu ne peux pas t’appliquer cette action à toi‑même 😅 Vise un autre membre.');
}
if (!canActOn(interaction.member, target)) {
throw new UserFacingError(
'Cette personne a un rôle égal ou supérieur au tien : je ne peux pas la viser. Demande à quelqu’un de plus haut dans la hiérarchie si c’est nécessaire.',
);
}
const bot = interaction.guild.members.me;
if (bot && bot.roles.highest.comparePositionTo(target.roles.highest) <= 0) {
throw new UserFacingError(
`Je ne peux pas agir sur ${target.user.tag} : mon rôle est placé plus bas que le sien. Remonte mon rôle dans les paramètres du serveur, et je m’en occupe.`,
);
}
}
/**
* Records the action in SQLite and mirrors it in the moderation log channel (M8-T06).
* Call it only once the Discord action has succeeded.
*/
export async function logModerationAction(
interaction,
{ action, targetId, reason = null, durationMs = null },
) {
recordAction({
guildId: interaction.guildId,
action,
moderatorId: interaction.user.id,
targetId,
reason,
durationMs,
});
logEvent({
guildId: interaction.guildId,
type: `moderation.${action}`,
actorId: interaction.user.id,
payload: { targetId, reason, durationMs },
});
const meta = MODERATION_ACTIONS[action];
await sendModerationLog(interaction.client, interaction.guild, {
action,
color: meta?.color ?? COLORS.moderation,
targetId,
moderatorId: interaction.user.id,
reason,
durationMs,
});
}
/** Posts an entry in `CHANNEL_MOD_LOGS_ID`, if configured (M8-T06). */
export async function sendModerationLog(
client,
guild,
{ action, targetId, moderatorId, reason, durationMs },
) {
if (!env.channels.modLogs) return;
const channel = await client.channels.fetch(env.channels.modLogs).catch(() => null);
if (!channel?.isSendable()) return;
const meta = MODERATION_ACTIONS[action];
const embed = baseEmbed(meta?.color)
.setTitle(`🛡️ Modération — ${meta?.label ?? action}`)
.addFields(
{ name: 'Membre', value: targetId ? `<@${targetId}> (${targetId})` : 'Salon', inline: true },
{ name: 'Par', value: `<@${moderatorId}>`, inline: true },
{ name: 'Motif', value: reason || 'Non précisé' },
);
if (durationMs) {
embed.addFields({ name: 'Durée', value: formatDuration(durationMs), inline: true });
}
if (guild) embed.setFooter({ text: `${guild.name} · ${guild.id}` });
await channel.send({ embeds: [embed] }).catch(() => {});
}
/** Direct message sent to the member who is being moderated (M8-T07). */
export function targetNoticeEmbed({ action, guildName, reason = null, durationMs = null }) {
const meta = MODERATION_ACTIONS[action];
const embed = baseEmbed(meta?.color)
.setTitle(`Sanction sur ${guildName}`)
.setDescription(
`Action : **${meta?.label ?? action}**\n\nCette décision vient de l’équipe de modération. Tu peux répondre à ce message pour en parler calmement avec elle.`,
)
.addFields({ name: 'Motif', value: reason || 'Non précisé' });
if (durationMs) embed.addFields({ name: 'Durée', value: formatDuration(durationMs) });
return embed;
}
/** Human readable duration for embeds: `2 h 30 min`. */
export function formatDuration(durationMs) {
const minutes = Math.round(durationMs / 60_000);
if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60);
const rest = minutes % 60;
if (hours < 24) return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`;
const days = Math.floor(hours / 24);
const remainingHours = hours % 24;
return remainingHours === 0 ? `${days} j` : `${days} j ${remainingHours} h`;
}
/** Fetches the member targeted by a command, with a clear error if absent. */
export async function fetchTargetMember(interaction, userId) {
const member = await interaction.guild.members.fetch(userId).catch(() => null);
if (!member) {
throw new UserFacingError(
'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.',
);
}
return member;
}
import { COLORS, MODERATION_ACTIONS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { UserFacingError } from '../../core/errors.js';
import { canActOn } from '../../core/permissions.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import { recordAction } from '../../database/repositories/moderation-repository.js';
import { baseEmbed } from '../../ui/embeds.js';
/**
* Enforces the role hierarchy before any moderation action (M3-T05 / M8-T08).
* @param {import('discord.js').ChatInputCommandInteraction} interaction
* @param {import('discord.js').GuildMember} target
*/
export function assertModerationTarget(interaction, target) {
if (!target) {
throw new UserFacingError(
'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.',
);
}
if (target.id === interaction.user.id) {
throw new UserFacingError('Tu ne peux pas t’appliquer cette action à toi‑même 😅 Vise un autre membre.');
}
if (!canActOn(interaction.member, target)) {
throw new UserFacingError(
'Cette personne a un rôle égal ou supérieur au tien : je ne peux pas la viser. Demande à quelqu’un de plus haut dans la hiérarchie si c’est nécessaire.',
);
}
const bot = interaction.guild.members.me;
if (bot && bot.roles.highest.comparePositionTo(target.roles.highest) <= 0) {
throw new UserFacingError(
`Je ne peux pas agir sur ${target.user.tag} : mon rôle est placé plus bas que le sien. Remonte mon rôle dans les paramètres du serveur, et je m’en occupe.`,
);
}
}
/**
* Records the action in SQLite and mirrors it in the moderation log channel (M8-T06).
* Call it only once the Discord action has succeeded.
*/
export async function logModerationAction(
interaction,
{ action, targetId, reason = null, durationMs = null },
) {
recordAction({
guildId: interaction.guildId,
action,
moderatorId: interaction.user.id,
targetId,
reason,
durationMs,
});
logEvent({
guildId: interaction.guildId,
type: `moderation.${action}`,
actorId: interaction.user.id,
payload: { targetId, reason, durationMs },
});
const meta = MODERATION_ACTIONS[action];
await sendModerationLog(interaction.client, interaction.guild, {
action,
color: meta?.color ?? COLORS.moderation,
targetId,
moderatorId: interaction.user.id,
reason,
durationMs,
});
}
/** Posts an entry in `CHANNEL_MOD_LOGS_ID`, if configured (M8-T06). */
export async function sendModerationLog(
client,
guild,
{ action, targetId, moderatorId, reason, durationMs },
) {
if (!env.channels.modLogs) return;
const channel = await client.channels.fetch(env.channels.modLogs).catch(() => null);
if (!channel?.isSendable()) return;
const meta = MODERATION_ACTIONS[action];
const embed = baseEmbed(meta?.color)
.setTitle(`🛡️ Modération — ${meta?.label ?? action}`)
.addFields(
{ name: 'Membre', value: targetId ? `<@${targetId}> (${targetId})` : 'Salon', inline: true },
{ name: 'Par', value: `<@${moderatorId}>`, inline: true },
{ name: 'Motif', value: reason || 'Non précisé' },
);
if (durationMs) {
embed.addFields({ name: 'Durée', value: formatDuration(durationMs), inline: true });
}
if (guild) embed.setFooter({ text: `${guild.name} · ${guild.id}` });
await channel.send({ embeds: [embed] }).catch(() => {});
}
/** Direct message sent to the member who is being moderated (M8-T07). */
export function targetNoticeEmbed({ action, guildName, reason = null, durationMs = null }) {
const meta = MODERATION_ACTIONS[action];
const embed = baseEmbed(meta?.color)
.setTitle(`Sanction sur ${guildName}`)
.setDescription(
`Action : **${meta?.label ?? action}**\n\nCette décision vient de l’équipe de modération. Tu peux répondre à ce message pour en parler calmement avec elle.`,
)
.addFields({ name: 'Motif', value: reason || 'Non précisé' });
if (durationMs) embed.addFields({ name: 'Durée', value: formatDuration(durationMs) });
return embed;
}
/** Human readable duration for embeds: `2 h 30 min`. */
export function formatDuration(durationMs) {
const minutes = Math.round(durationMs / 60_000);
if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60);
const rest = minutes % 60;
if (hours < 24) return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`;
const days = Math.floor(hours / 24);
const remainingHours = hours % 24;
return remainingHours === 0 ? `${days} j` : `${days} j ${remainingHours} h`;
}
/** Fetches the member targeted by a command, with a clear error if absent. */
export async function fetchTargetMember(interaction, userId) {
const member = await interaction.guild.members.fetch(userId).catch(() => null);
if (!member) {
throw new UserFacingError(
'Je ne trouve pas ce membre sur le serveur : vérifie qu’il y est toujours, puis relance la commande.',
);
}
return member;
}
@@ -1,31 +1,31 @@
import { GITEA_EVENT_TYPES } from '../../config/constants.js';
import { issueEmbed, pullRequestEmbed, pushEmbed, releaseEmbed, refEmbed } from '../gitea/gitea-embeds.js';
/**
* Maps a raw Gitea webhook to `{ type, embed }`, or returns null when the event
* should not be published (M9-T03).
*/
export function buildGiteaNotification(event, payload) {
const type = GITEA_EVENT_TYPES[event];
if (!type) return null;
switch (event) {
case 'issues':
return { type, embed: issueEmbed(payload.issue ?? payload) };
case 'pull_request':
return { type, embed: pullRequestEmbed(payload.pull_request ?? payload) };
case 'push':
if (!payload.commits?.length) return null;
return { type, embed: pushEmbed(payload) };
case 'create':
case 'delete':
return {
type,
embed: refEmbed(payload, payload.ref_type && event === 'delete' ? 'deleted' : 'created'),
};
case 'release':
return { type, embed: releaseEmbed(payload.release ?? payload) };
default:
return null;
}
}
import { GITEA_EVENT_TYPES } from '../../config/constants.js';
import { issueEmbed, pullRequestEmbed, pushEmbed, releaseEmbed, refEmbed } from '../gitea/gitea-embeds.js';
/**
* Maps a raw Gitea webhook to `{ type, embed }`, or returns null when the event
* should not be published (M9-T03).
*/
export function buildGiteaNotification(event, payload) {
const type = GITEA_EVENT_TYPES[event];
if (!type) return null;
switch (event) {
case 'issues':
return { type, embed: issueEmbed(payload.issue ?? payload) };
case 'pull_request':
return { type, embed: pullRequestEmbed(payload.pull_request ?? payload) };
case 'push':
if (!payload.commits?.length) return null;
return { type, embed: pushEmbed(payload) };
case 'create':
case 'delete':
return {
type,
embed: refEmbed(payload, payload.ref_type && event === 'delete' ? 'deleted' : 'created'),
};
case 'release':
return { type, embed: releaseEmbed(payload.release ?? payload) };
default:
return null;
}
}
@@ -1,61 +1,61 @@
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { getNotificationChannel } from '../../database/repositories/notification-repository.js';
import { errorEmbed } from '../../ui/embeds.js';
const log = createLogger('notifications');
/** Fallback routing from the environment when the guild has no override (M9-T01). */
const defaultChannels = {
issues: env.channels.notifIssues,
pull_request: env.channels.notifPullRequests,
push: env.channels.notifCommits,
release: env.channels.notifReleases,
errors: env.channels.notifErrors,
announcements: env.channels.announcements,
community: env.channels.logs,
};
/** SQLite override first, then the environment default (M9-T01). */
export function resolveChannelId(type, guildId = env.discord.guildId) {
try {
if (guildId) {
const override = getNotificationChannel(guildId, type);
if (override?.channel_id) return override.channel_id;
}
} catch {
// The database is unavailable (tests, early startup): use the environment.
}
return defaultChannels[type] ?? null;
}
/** Sends a notification payload to the channel configured for its type (M9). */
export async function notify(client, type, payload) {
const channelId = resolveChannelId(type);
if (!channelId) {
log.debug(`No channel configured for notification type ${type}`);
return null;
}
const channel = await client.channels.fetch(channelId).catch(() => null);
if (!channel?.isSendable()) {
log.warn(`Notification channel unavailable for ${type}`, { channelId });
return null;
}
return channel.send(payload);
}
/** Reports an unexpected failure in the technical channel (M9-T07). */
export async function notifyError(client, error, context = 'application') {
log.error(`Notification error (${context})`, error);
return notify(client, 'errors', {
embeds: [
errorEmbed(
`Un incident est survenu dans **${context}**. Rien d’inquiétant pour les membres : je continue de fonctionner, mais l’équipe technique gagne à y jeter un œil.`,
).addFields({
name: 'Détail',
value: `\`${String(error?.message ?? error).slice(0, 500)}\``,
}),
],
});
}
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { getNotificationChannel } from '../../database/repositories/notification-repository.js';
import { errorEmbed } from '../../ui/embeds.js';
const log = createLogger('notifications');
/** Fallback routing from the environment when the guild has no override (M9-T01). */
const defaultChannels = {
issues: env.channels.notifIssues,
pull_request: env.channels.notifPullRequests,
push: env.channels.notifCommits,
release: env.channels.notifReleases,
errors: env.channels.notifErrors,
announcements: env.channels.announcements,
community: env.channels.logs,
};
/** SQLite override first, then the environment default (M9-T01). */
export function resolveChannelId(type, guildId = env.discord.guildId) {
try {
if (guildId) {
const override = getNotificationChannel(guildId, type);
if (override?.channel_id) return override.channel_id;
}
} catch {
// The database is unavailable (tests, early startup): use the environment.
}
return defaultChannels[type] ?? null;
}
/** Sends a notification payload to the channel configured for its type (M9). */
export async function notify(client, type, payload) {
const channelId = resolveChannelId(type);
if (!channelId) {
log.debug(`No channel configured for notification type ${type}`);
return null;
}
const channel = await client.channels.fetch(channelId).catch(() => null);
if (!channel?.isSendable()) {
log.warn(`Notification channel unavailable for ${type}`, { channelId });
return null;
}
return channel.send(payload);
}
/** Reports an unexpected failure in the technical channel (M9-T07). */
export async function notifyError(client, error, context = 'application') {
log.error(`Notification error (${context})`, error);
return notify(client, 'errors', {
embeds: [
errorEmbed(
`Un incident est survenu dans **${context}**. Rien d’inquiétant pour les membres : je continue de fonctionner, mais l’équipe technique gagne à y jeter un œil.`,
).addFields({
name: 'Détail',
value: `\`${String(error?.message ?? error).slice(0, 500)}\``,
}),
],
});
}
+219 -219
View File
@@ -1,219 +1,219 @@
import { MessageFlags } from 'discord.js';
import { COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import {
attachPollMessage,
castVote,
closePoll,
countVotes,
createPoll as createPollRow,
getPoll,
listDuePolls,
} from '../../database/repositories/poll-repository.js';
import { POLL_CHOICES_MAX, pollButtons } from '../../ui/buttons.js';
import { baseEmbed } from '../../ui/embeds.js';
const log = createLogger('polls');
const CHOICES_MIN = 2;
const BAR_LENGTH = 12;
const SCHEDULER_INTERVAL_MS = 30_000;
/** Splits the `choices` option on `;` and validates the count (M10-T01). */
export function parseChoices(input, { min = CHOICES_MIN, max = POLL_CHOICES_MAX } = {}) {
const choices = String(input)
.split(';')
.map((choice) => choice.trim())
.filter(Boolean);
if (choices.length < min || choices.length > max) {
throw new UserFacingError(
`Il faut entre ${min} et ${max} propositions, séparées par des points‑virgules. Exemple : \`Pizza ; Sushis ; Tacos\`.`,
);
}
if (new Set(choices.map((choice) => choice.toLowerCase())).size !== choices.length) {
throw new UserFacingError(
'Deux propositions identiques rendraient le vote ambigu : donne un libellé différent à chacune.',
);
}
return choices;
}
/** SQLite stores datetimes as UTC `YYYY-MM-DD HH:MM:SS`. */
export function toSqliteDate(date) {
return date.toISOString().slice(0, 19).replace('T', ' ');
}
function renderBar(ratio) {
const filled = Math.round(ratio * BAR_LENGTH);
return `${'█'.repeat(filled)}${'░'.repeat(BAR_LENGTH - filled)}`;
}
/** Results embed, shared by creation, voting and closing (M10-T06). */
export function buildPollEmbed(poll, counts = countVotes(poll.id)) {
const choices = JSON.parse(poll.choices);
const countFor = (index) => counts.find((row) => row.choice_index === index)?.count ?? 0;
const total = choices.reduce((sum, _choice, index) => sum + countFor(index), 0);
const lines = choices.map((choice, index) => {
const count = countFor(index);
const percent = total === 0 ? 0 : Math.round((count / total) * 100);
return `**${index + 1}. ${choice}**\n\`${renderBar(total === 0 ? 0 : count / total)}\` ${count} (${percent} %)`;
});
const embed = baseEmbed(COLORS.info)
.setTitle(`📊 Sondage #${poll.id} — ${poll.question}`)
.setDescription(lines.join('\n\n'))
.addFields(
{ name: 'Votes', value: String(total), inline: true },
{ name: 'Créé par', value: `<@${poll.creator_id}>`, inline: true },
{ name: 'Statut', value: poll.status === 'open' ? 'Ouvert' : 'Fermé', inline: true },
);
if (poll.ends_at) {
const timestamp = Math.floor(new Date(`${poll.ends_at.replace(' ', 'T')}Z`).getTime() / 1000);
embed.addFields({ name: 'Fin', value: `<t:${timestamp}:R>`, inline: true });
}
if (poll.status === 'closed') {
embed.setColor(COLORS.success);
const best = choices.reduce(
(winner, _choice, index) => (countFor(index) > countFor(winner) ? index : winner),
0,
);
const top = countFor(best);
embed.addFields({
name: 'Résultat',
value: total === 0 || top === 0 ? 'Aucun vote' : `**${choices[best]}** (${top} vote(s))`,
});
}
return embed;
}
export function buildPollComponents(poll) {
return poll.status === 'open' ? pollButtons(poll.id, JSON.parse(poll.choices)) : [];
}
/** Creates the poll message and records it (M10-T01 / M10-T02). */
export async function createPoll(interaction, { question, choicesInput, minutes = null }) {
const choices = parseChoices(choicesInput);
const endsAt = minutes ? toSqliteDate(new Date(Date.now() + minutes * 60_000)) : null;
const pollId = createPollRow({
guildId: interaction.guildId,
channelId: interaction.channelId,
creatorId: interaction.user.id,
question,
choices,
endsAt,
});
const poll = getPoll(pollId);
const message = await interaction.channel.send({
embeds: [buildPollEmbed(poll, [])],
components: buildPollComponents(poll),
});
attachPollMessage(pollId, message.id);
logEvent({
guildId: interaction.guildId,
type: 'poll.created',
actorId: interaction.user.id,
payload: { pollId, choices: choices.length },
});
return pollId;
}
async function fetchPollMessage(interaction, poll) {
if (!poll.message_id) return null;
return interaction.channel.messages.fetch(poll.message_id).catch(() => null);
}
/** Closes a poll and freezes its results (M10-T05). */
export async function closePollById(client, pollId) {
const poll = getPoll(pollId);
if (!poll) {
throw new UserFacingError(`Je ne trouve pas le sondage **#${pollId}** : il a peut‑être été supprimé.`);
}
if (poll.status === 'closed') {
throw new UserFacingError(`Le sondage **#${pollId}** est déjà fermé — les résultats sont figés.`);
}
closePoll(pollId);
const closed = { ...poll, status: 'closed' };
const channel = await client.channels.fetch(poll.channel_id).catch(() => null);
const message = channel?.isSendable()
? await channel.messages.fetch(poll.message_id).catch(() => null)
: null;
await message?.edit({ embeds: [buildPollEmbed(closed)], components: [] });
logEvent({
guildId: poll.guild_id,
type: 'poll.closed',
payload: { pollId },
});
return closed;
}
/** Registers a vote and refreshes the poll message (M10-T03 / M10-T04). */
export async function handlePollComponent(interaction) {
const [, rawId, rawIndex] = interaction.customId.split(':');
const poll = getPoll(Number(rawId));
if (!poll || poll.status !== 'open') {
throw new UserFacingError('Ce sondage est terminé : les boutons ne prennent plus les votes.');
}
const choices = JSON.parse(poll.choices);
const index = Number(rawIndex);
if (!Number.isInteger(index) || index < 0 || index >= choices.length) {
throw new UserFacingError('Cette proposition n’existe plus dans le sondage.');
}
const result = castVote(poll.id, interaction.user.id, index);
if (result === 'unchanged') {
await interaction.reply({
content: `Ton vote est déjà sur **${choices[index]}** — rien n’a bougé.`,
flags: MessageFlags.Ephemeral,
});
return;
}
const message = await fetchPollMessage(interaction, poll);
await message?.edit({ embeds: [buildPollEmbed(poll)], components: buildPollComponents(poll) });
await interaction.reply({
content:
result === 'changed'
? `C’est noté : ton vote va maintenant à **${choices[index]}**.`
: `Merci ! Ton vote est sur **${choices[index]}**.`,
flags: MessageFlags.Ephemeral,
});
}
/** Polls expire on their own even without activity (M10-T05). */
export function startPollScheduler(client) {
const timer = setInterval(async () => {
let due = [];
try {
due = listDuePolls();
} catch (error) {
log.warn('Could not read the polls to close', error);
return;
}
for (const poll of due) {
try {
await closePollById(client, poll.id);
log.info(`Closed poll #${poll.id} at its end date`);
} catch (error) {
log.error(`Could not close poll #${poll.id}`, error);
}
}
}, SCHEDULER_INTERVAL_MS);
timer.unref();
return timer;
}
import { MessageFlags } from 'discord.js';
import { COLORS } from '../../config/constants.js';
import { UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import {
attachPollMessage,
castVote,
closePoll,
countVotes,
createPoll as createPollRow,
getPoll,
listDuePolls,
} from '../../database/repositories/poll-repository.js';
import { POLL_CHOICES_MAX, pollButtons } from '../../ui/buttons.js';
import { baseEmbed } from '../../ui/embeds.js';
const log = createLogger('polls');
const CHOICES_MIN = 2;
const BAR_LENGTH = 12;
const SCHEDULER_INTERVAL_MS = 30_000;
/** Splits the `choices` option on `;` and validates the count (M10-T01). */
export function parseChoices(input, { min = CHOICES_MIN, max = POLL_CHOICES_MAX } = {}) {
const choices = String(input)
.split(';')
.map((choice) => choice.trim())
.filter(Boolean);
if (choices.length < min || choices.length > max) {
throw new UserFacingError(
`Il faut entre ${min} et ${max} propositions, séparées par des points‑virgules. Exemple : \`Pizza ; Sushis ; Tacos\`.`,
);
}
if (new Set(choices.map((choice) => choice.toLowerCase())).size !== choices.length) {
throw new UserFacingError(
'Deux propositions identiques rendraient le vote ambigu : donne un libellé différent à chacune.',
);
}
return choices;
}
/** SQLite stores datetimes as UTC `YYYY-MM-DD HH:MM:SS`. */
export function toSqliteDate(date) {
return date.toISOString().slice(0, 19).replace('T', ' ');
}
function renderBar(ratio) {
const filled = Math.round(ratio * BAR_LENGTH);
return `${'█'.repeat(filled)}${'░'.repeat(BAR_LENGTH - filled)}`;
}
/** Results embed, shared by creation, voting and closing (M10-T06). */
export function buildPollEmbed(poll, counts = countVotes(poll.id)) {
const choices = JSON.parse(poll.choices);
const countFor = (index) => counts.find((row) => row.choice_index === index)?.count ?? 0;
const total = choices.reduce((sum, _choice, index) => sum + countFor(index), 0);
const lines = choices.map((choice, index) => {
const count = countFor(index);
const percent = total === 0 ? 0 : Math.round((count / total) * 100);
return `**${index + 1}. ${choice}**\n\`${renderBar(total === 0 ? 0 : count / total)}\` ${count} (${percent} %)`;
});
const embed = baseEmbed(COLORS.info)
.setTitle(`📊 Sondage #${poll.id} — ${poll.question}`)
.setDescription(lines.join('\n\n'))
.addFields(
{ name: 'Votes', value: String(total), inline: true },
{ name: 'Créé par', value: `<@${poll.creator_id}>`, inline: true },
{ name: 'Statut', value: poll.status === 'open' ? 'Ouvert' : 'Fermé', inline: true },
);
if (poll.ends_at) {
const timestamp = Math.floor(new Date(`${poll.ends_at.replace(' ', 'T')}Z`).getTime() / 1000);
embed.addFields({ name: 'Fin', value: `<t:${timestamp}:R>`, inline: true });
}
if (poll.status === 'closed') {
embed.setColor(COLORS.success);
const best = choices.reduce(
(winner, _choice, index) => (countFor(index) > countFor(winner) ? index : winner),
0,
);
const top = countFor(best);
embed.addFields({
name: 'Résultat',
value: total === 0 || top === 0 ? 'Aucun vote' : `**${choices[best]}** (${top} vote(s))`,
});
}
return embed;
}
export function buildPollComponents(poll) {
return poll.status === 'open' ? pollButtons(poll.id, JSON.parse(poll.choices)) : [];
}
/** Creates the poll message and records it (M10-T01 / M10-T02). */
export async function createPoll(interaction, { question, choicesInput, minutes = null }) {
const choices = parseChoices(choicesInput);
const endsAt = minutes ? toSqliteDate(new Date(Date.now() + minutes * 60_000)) : null;
const pollId = createPollRow({
guildId: interaction.guildId,
channelId: interaction.channelId,
creatorId: interaction.user.id,
question,
choices,
endsAt,
});
const poll = getPoll(pollId);
const message = await interaction.channel.send({
embeds: [buildPollEmbed(poll, [])],
components: buildPollComponents(poll),
});
attachPollMessage(pollId, message.id);
logEvent({
guildId: interaction.guildId,
type: 'poll.created',
actorId: interaction.user.id,
payload: { pollId, choices: choices.length },
});
return pollId;
}
async function fetchPollMessage(interaction, poll) {
if (!poll.message_id) return null;
return interaction.channel.messages.fetch(poll.message_id).catch(() => null);
}
/** Closes a poll and freezes its results (M10-T05). */
export async function closePollById(client, pollId) {
const poll = getPoll(pollId);
if (!poll) {
throw new UserFacingError(`Je ne trouve pas le sondage **#${pollId}** : il a peut‑être été supprimé.`);
}
if (poll.status === 'closed') {
throw new UserFacingError(`Le sondage **#${pollId}** est déjà fermé — les résultats sont figés.`);
}
closePoll(pollId);
const closed = { ...poll, status: 'closed' };
const channel = await client.channels.fetch(poll.channel_id).catch(() => null);
const message = channel?.isSendable()
? await channel.messages.fetch(poll.message_id).catch(() => null)
: null;
await message?.edit({ embeds: [buildPollEmbed(closed)], components: [] });
logEvent({
guildId: poll.guild_id,
type: 'poll.closed',
payload: { pollId },
});
return closed;
}
/** Registers a vote and refreshes the poll message (M10-T03 / M10-T04). */
export async function handlePollComponent(interaction) {
const [, rawId, rawIndex] = interaction.customId.split(':');
const poll = getPoll(Number(rawId));
if (!poll || poll.status !== 'open') {
throw new UserFacingError('Ce sondage est terminé : les boutons ne prennent plus les votes.');
}
const choices = JSON.parse(poll.choices);
const index = Number(rawIndex);
if (!Number.isInteger(index) || index < 0 || index >= choices.length) {
throw new UserFacingError('Cette proposition n’existe plus dans le sondage.');
}
const result = castVote(poll.id, interaction.user.id, index);
if (result === 'unchanged') {
await interaction.reply({
content: `Ton vote est déjà sur **${choices[index]}** — rien n’a bougé.`,
flags: MessageFlags.Ephemeral,
});
return;
}
const message = await fetchPollMessage(interaction, poll);
await message?.edit({ embeds: [buildPollEmbed(poll)], components: buildPollComponents(poll) });
await interaction.reply({
content:
result === 'changed'
? `C’est noté : ton vote va maintenant à **${choices[index]}**.`
: `Merci ! Ton vote est sur **${choices[index]}**.`,
flags: MessageFlags.Ephemeral,
});
}
/** Polls expire on their own even without activity (M10-T05). */
export function startPollScheduler(client) {
const timer = setInterval(async () => {
let due = [];
try {
due = listDuePolls();
} catch (error) {
log.warn('Could not read the polls to close', error);
return;
}
for (const poll of due) {
try {
await closePollById(client, poll.id);
log.info(`Closed poll #${poll.id} at its end date`);
} catch (error) {
log.error(`Could not close poll #${poll.id}`, error);
}
}
}, SCHEDULER_INTERVAL_MS);
timer.unref();
return timer;
}
+314 -314
View File
@@ -1,314 +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é');
}
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é');
}
+295 -295
View File
@@ -1,295 +1,295 @@
import { ChannelType, PermissionFlagsBits } from 'discord.js';
import { ACCESS_LEVELS, COLORS, TICKET_CATEGORIES } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { PermissionDeniedError, UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { getAccessLevel } from '../../core/permissions.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import {
claimTicket as claimTicketRow,
closeTicket as closeTicketRow,
createTicket as createTicketRow,
getTicketByChannel,
} from '../../database/repositories/ticket-repository.js';
import { ticketButtons } from '../../ui/buttons.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
const log = createLogger('tickets');
/** Ticket scope names to the FWS access level they require. */
const SCOPE_LEVELS = {
staff: ACCESS_LEVELS.STAFF,
dev: ACCESS_LEVELS.DEV,
owner: ACCESS_LEVELS.OWNER,
};
export function findCategory(categoryId) {
return TICKET_CATEGORIES.find((category) => category.id === categoryId) ?? null;
}
/** A member may open a ticket only for a category their access level covers (M6-T02). */
export function canUseCategory(member, category) {
const level = getAccessLevel(member);
return category.scope.some((scope) => level >= SCOPE_LEVELS[scope]);
}
/** Static info about a ticket, used by the embeds below. */
function ticketEmbed(ticket, category) {
const claimed = ticket.claimed_by ? `<@${ticket.claimed_by}>` : 'Personne';
return baseEmbed(COLORS.ticket)
.setTitle(`🎫 Ticket ${category.label} #${ticket.id}`)
.setDescription(
`<@${ticket.author_id}> décris ta demande ici, avec le plus de détails possible : ` +
'contexte, étapes pour reproduire, messages d’erreur. Plus tu en dis, plus vite on t’aide.',
)
.addFields(
{ name: 'Catégorie', value: category.label, inline: true },
{ name: 'Statut', value: ticket.status === 'open' ? 'Ouvert' : 'Fermé', inline: true },
{ name: 'Pris en charge par', value: claimed, inline: true },
);
}
function channelName(categoryId, username) {
const slug = username
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-z0-9-]/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 40);
return `ticket-${categoryId}-${slug || 'membre'}`.slice(0, 100);
}
/** Permission overwrites: the author, the staff roles of the scope and the bot (M6-T04). */
function buildOverwrites(guild, client, category, authorId) {
const allow = [
PermissionFlagsBits.ViewChannel,
PermissionFlagsBits.SendMessages,
PermissionFlagsBits.ReadMessageHistory,
PermissionFlagsBits.AttachFiles,
];
const overwrites = [
{ id: guild.roles.everyone.id, deny: [PermissionFlagsBits.ViewChannel] },
{ id: authorId, allow },
{ id: client.user.id, allow: [...allow, PermissionFlagsBits.ManageChannels] },
];
for (const scope of category.scope) {
const roleId = env.roles[scope];
if (roleId) overwrites.push({ id: roleId, allow });
}
return overwrites;
}
async function fetchTicketLogChannel(client) {
if (!env.channels.ticketLogs) return null;
const channel = await client.channels.fetch(env.channels.ticketLogs).catch(() => null);
return channel?.isSendable() ? channel : null;
}
async function logTicket(client, embed) {
const channel = await fetchTicketLogChannel(client);
await channel?.send({ embeds: [embed] });
}
/** Opens a private channel for the ticket (M6-T03). */
export async function createTicket(interaction, categoryId) {
const category = findCategory(categoryId);
if (!category) {
throw new UserFacingError(
'Je ne connais pas cette catégorie de ticket : `/ticket create` te propose la liste à jour.',
);
}
if (!canUseCategory(interaction.member, category)) {
throw new UserFacingError(
`La catégorie **${category.label}** est réservée à l’équipe. Tu peux ouvrir un ticket dans une autre catégorie : \`/ticket create\` te montre celles qui te sont ouvertes.`,
);
}
if (!env.channels.ticketCategory) {
throw new UserFacingError(
'Les tickets ne sont pas encore installés : il manque `CATEGORY_TICKETS_ID` dans le `.env`. Préviens l’équipe !',
);
}
const guild = interaction.guild;
const parent = await guild.channels.fetch(env.channels.ticketCategory).catch(() => null);
if (parent?.type !== ChannelType.GuildCategory) {
throw new UserFacingError(
'`CATEGORY_TICKETS_ID` ne pointe pas vers une catégorie Discord : je ne peux pas y créer de salon. L’équipe doit corriger le `.env`.',
);
}
const channel = await guild.channels.create({
name: channelName(category.id, interaction.user.username),
type: ChannelType.GuildText,
parent: parent.id,
topic: `Ticket ${category.label} — ${interaction.user.tag}`,
permissionOverwrites: buildOverwrites(guild, interaction.client, category, interaction.user.id),
reason: `Ticket ${category.label} ouvert par ${interaction.user.tag}`,
});
let ticket;
try {
ticket = {
id: createTicketRow({
guildId: guild.id,
channelId: channel.id,
categoryId: category.id,
authorId: interaction.user.id,
}),
guild_id: guild.id,
channel_id: channel.id,
category_id: category.id,
author_id: interaction.user.id,
claimed_by: null,
status: 'open',
};
} catch (error) {
// The unique index rejects a second open ticket for the same author and category.
await channel.delete('Ticket en doublon').catch(() => {});
log.warn('Duplicate ticket rejected', error);
throw new UserFacingError(
'Tu as déjà un ticket ouvert dans cette catégorie : continue dessus, ou ferme‑le avant d’en ouvrir un autre.',
);
}
await channel.send({
content: `<@${ticket.author_id}>`,
embeds: [ticketEmbed(ticket, category)],
components: ticketButtons(),
});
logEvent({
guildId: guild.id,
type: 'ticket.created',
actorId: ticket.author_id,
payload: { ticketId: ticket.id, categoryId: category.id },
});
await logTicket(
interaction.client,
baseEmbed(COLORS.ticket)
.setTitle('🎫 Ticket ouvert')
.setDescription(`<#${channel.id}> — ${category.label}`)
.addFields({ name: 'Ouvert par', value: `<@${ticket.author_id}>`, inline: true }),
);
return channel;
}
/** Resolves the ticket of the current channel, or throws a user facing error. */
export async function getChannelTicket(interaction) {
const ticket = getTicketByChannel(interaction.channelId);
if (!ticket) {
throw new UserFacingError(
'Cette action se lance depuis un salon de ticket : ouvre‑en un avec `/ticket create`, ou place‑toi dans le bon salon.',
);
}
if (ticket.status !== 'open') {
throw new UserFacingError('Ce ticket est déjà fermé : il n’y a plus rien à faire ici.');
}
return ticket;
}
export async function claimTicket(interaction) {
const ticket = await getChannelTicket(interaction);
if (ticket.claimed_by === interaction.user.id) {
throw new UserFacingError('Tu as déjà ce ticket en charge — il n’y a rien à changer.');
}
claimTicketRow(ticket.id, interaction.user.id);
logEvent({
guildId: ticket.guild_id,
type: 'ticket.claimed',
actorId: interaction.user.id,
payload: { ticketId: ticket.id },
});
await interaction.reply({
embeds: [successEmbed(`C’est noté : <@${interaction.user.id}> prend ce ticket en charge. Merci !`)],
});
await logTicket(
interaction.client,
baseEmbed(COLORS.ticket)
.setTitle('🎫 Ticket pris en charge')
.setDescription(`#${ticket.id} — <#${ticket.channel_id}>`)
.addFields({ name: 'Avec', value: `<@${interaction.user.id}>`, inline: true }),
);
}
/** Closes the ticket: the author or any staff member may do it (M6-T06 / M6-T07). */
export async function closeTicket(interaction, reason = null) {
const ticket = await getChannelTicket(interaction);
const isStaff = getAccessLevel(interaction.member) >= ACCESS_LEVELS.STAFF;
if (interaction.user.id !== ticket.author_id && !isStaff) {
throw new PermissionDeniedError(
'Seules la personne qui a ouvert ce ticket et l’équipe peuvent le fermer. Si besoin, demande‑le dans le salon.',
);
}
closeTicketRow(ticket.id, { closedBy: interaction.user.id, reason });
logEvent({
guildId: ticket.guild_id,
type: 'ticket.closed',
actorId: interaction.user.id,
payload: { ticketId: ticket.id, reason },
});
await interaction.reply({
embeds: [
successEmbed(
`Ticket fermé par <@${interaction.user.id}> — merci ! Le salon disparaît dans 10 secondes, tu as le temps de copier ce qui t’intéresse.`,
),
],
});
await logTicket(
interaction.client,
baseEmbed(COLORS.ticket)
.setTitle('🎫 Ticket fermé')
.setDescription(`#${ticket.id} — ${findCategory(ticket.category_id)?.label ?? ticket.category_id}`)
.addFields(
{ name: 'Ouvert par', value: `<@${ticket.author_id}>`, inline: true },
{ name: 'Fermé par', value: `<@${interaction.user.id}>`, inline: true },
{ name: 'Motif', value: reason || 'Non précisé' },
),
);
const channel = interaction.channel;
setTimeout(() => channel?.delete(`Ticket #${ticket.id} fermé`).catch(() => {}), 10_000).unref();
}
/** Grants a staff member access to the ticket channel (M6-T07). */
export async function addParticipant(interaction, userId) {
const ticket = await getChannelTicket(interaction);
if (userId === ticket.author_id || userId === ticket.claimed_by) {
throw new UserFacingError('Cette personne est déjà dans le ticket — pas besoin de l’ajouter.');
}
await interaction.channel.permissionOverwrites.edit(userId, {
ViewChannel: true,
SendMessages: true,
ReadMessageHistory: true,
});
logEvent({
guildId: ticket.guild_id,
type: 'ticket.participant.added',
actorId: interaction.user.id,
payload: { ticketId: ticket.id, userId },
});
await interaction.reply({ embeds: [successEmbed(`C’est noté : <@${userId}> rejoint ce ticket.`)] });
}
/** Routes the buttons posted in ticket channels. */
export async function handleTicketComponent(interaction) {
switch (interaction.customId) {
case 'ticket:claim':
await claimTicket(interaction);
return;
case 'ticket:close':
await closeTicket(interaction);
return;
default:
log.debug(`Ignored unknown ticket component ${interaction.customId}`);
}
}
import { ChannelType, PermissionFlagsBits } from 'discord.js';
import { ACCESS_LEVELS, COLORS, TICKET_CATEGORIES } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { PermissionDeniedError, UserFacingError } from '../../core/errors.js';
import { createLogger } from '../../core/logger.js';
import { getAccessLevel } from '../../core/permissions.js';
import { logEvent } from '../../database/repositories/event-log-repository.js';
import {
claimTicket as claimTicketRow,
closeTicket as closeTicketRow,
createTicket as createTicketRow,
getTicketByChannel,
} from '../../database/repositories/ticket-repository.js';
import { ticketButtons } from '../../ui/buttons.js';
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
const log = createLogger('tickets');
/** Ticket scope names to the FWS access level they require. */
const SCOPE_LEVELS = {
staff: ACCESS_LEVELS.STAFF,
dev: ACCESS_LEVELS.DEV,
owner: ACCESS_LEVELS.OWNER,
};
export function findCategory(categoryId) {
return TICKET_CATEGORIES.find((category) => category.id === categoryId) ?? null;
}
/** A member may open a ticket only for a category their access level covers (M6-T02). */
export function canUseCategory(member, category) {
const level = getAccessLevel(member);
return category.scope.some((scope) => level >= SCOPE_LEVELS[scope]);
}
/** Static info about a ticket, used by the embeds below. */
function ticketEmbed(ticket, category) {
const claimed = ticket.claimed_by ? `<@${ticket.claimed_by}>` : 'Personne';
return baseEmbed(COLORS.ticket)
.setTitle(`🎫 Ticket ${category.label} #${ticket.id}`)
.setDescription(
`<@${ticket.author_id}> décris ta demande ici, avec le plus de détails possible : ` +
'contexte, étapes pour reproduire, messages d’erreur. Plus tu en dis, plus vite on t’aide.',
)
.addFields(
{ name: 'Catégorie', value: category.label, inline: true },
{ name: 'Statut', value: ticket.status === 'open' ? 'Ouvert' : 'Fermé', inline: true },
{ name: 'Pris en charge par', value: claimed, inline: true },
);
}
function channelName(categoryId, username) {
const slug = username
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-z0-9-]/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 40);
return `ticket-${categoryId}-${slug || 'membre'}`.slice(0, 100);
}
/** Permission overwrites: the author, the staff roles of the scope and the bot (M6-T04). */
function buildOverwrites(guild, client, category, authorId) {
const allow = [
PermissionFlagsBits.ViewChannel,
PermissionFlagsBits.SendMessages,
PermissionFlagsBits.ReadMessageHistory,
PermissionFlagsBits.AttachFiles,
];
const overwrites = [
{ id: guild.roles.everyone.id, deny: [PermissionFlagsBits.ViewChannel] },
{ id: authorId, allow },
{ id: client.user.id, allow: [...allow, PermissionFlagsBits.ManageChannels] },
];
for (const scope of category.scope) {
const roleId = env.roles[scope];
if (roleId) overwrites.push({ id: roleId, allow });
}
return overwrites;
}
async function fetchTicketLogChannel(client) {
if (!env.channels.ticketLogs) return null;
const channel = await client.channels.fetch(env.channels.ticketLogs).catch(() => null);
return channel?.isSendable() ? channel : null;
}
async function logTicket(client, embed) {
const channel = await fetchTicketLogChannel(client);
await channel?.send({ embeds: [embed] });
}
/** Opens a private channel for the ticket (M6-T03). */
export async function createTicket(interaction, categoryId) {
const category = findCategory(categoryId);
if (!category) {
throw new UserFacingError(
'Je ne connais pas cette catégorie de ticket : `/ticket create` te propose la liste à jour.',
);
}
if (!canUseCategory(interaction.member, category)) {
throw new UserFacingError(
`La catégorie **${category.label}** est réservée à l’équipe. Tu peux ouvrir un ticket dans une autre catégorie : \`/ticket create\` te montre celles qui te sont ouvertes.`,
);
}
if (!env.channels.ticketCategory) {
throw new UserFacingError(
'Les tickets ne sont pas encore installés : il manque `CATEGORY_TICKETS_ID` dans le `.env`. Préviens l’équipe !',
);
}
const guild = interaction.guild;
const parent = await guild.channels.fetch(env.channels.ticketCategory).catch(() => null);
if (parent?.type !== ChannelType.GuildCategory) {
throw new UserFacingError(
'`CATEGORY_TICKETS_ID` ne pointe pas vers une catégorie Discord : je ne peux pas y créer de salon. L’équipe doit corriger le `.env`.',
);
}
const channel = await guild.channels.create({
name: channelName(category.id, interaction.user.username),
type: ChannelType.GuildText,
parent: parent.id,
topic: `Ticket ${category.label} — ${interaction.user.tag}`,
permissionOverwrites: buildOverwrites(guild, interaction.client, category, interaction.user.id),
reason: `Ticket ${category.label} ouvert par ${interaction.user.tag}`,
});
let ticket;
try {
ticket = {
id: createTicketRow({
guildId: guild.id,
channelId: channel.id,
categoryId: category.id,
authorId: interaction.user.id,
}),
guild_id: guild.id,
channel_id: channel.id,
category_id: category.id,
author_id: interaction.user.id,
claimed_by: null,
status: 'open',
};
} catch (error) {
// The unique index rejects a second open ticket for the same author and category.
await channel.delete('Ticket en doublon').catch(() => {});
log.warn('Duplicate ticket rejected', error);
throw new UserFacingError(
'Tu as déjà un ticket ouvert dans cette catégorie : continue dessus, ou ferme‑le avant d’en ouvrir un autre.',
);
}
await channel.send({
content: `<@${ticket.author_id}>`,
embeds: [ticketEmbed(ticket, category)],
components: ticketButtons(),
});
logEvent({
guildId: guild.id,
type: 'ticket.created',
actorId: ticket.author_id,
payload: { ticketId: ticket.id, categoryId: category.id },
});
await logTicket(
interaction.client,
baseEmbed(COLORS.ticket)
.setTitle('🎫 Ticket ouvert')
.setDescription(`<#${channel.id}> — ${category.label}`)
.addFields({ name: 'Ouvert par', value: `<@${ticket.author_id}>`, inline: true }),
);
return channel;
}
/** Resolves the ticket of the current channel, or throws a user facing error. */
export async function getChannelTicket(interaction) {
const ticket = getTicketByChannel(interaction.channelId);
if (!ticket) {
throw new UserFacingError(
'Cette action se lance depuis un salon de ticket : ouvre‑en un avec `/ticket create`, ou place‑toi dans le bon salon.',
);
}
if (ticket.status !== 'open') {
throw new UserFacingError('Ce ticket est déjà fermé : il n’y a plus rien à faire ici.');
}
return ticket;
}
export async function claimTicket(interaction) {
const ticket = await getChannelTicket(interaction);
if (ticket.claimed_by === interaction.user.id) {
throw new UserFacingError('Tu as déjà ce ticket en charge — il n’y a rien à changer.');
}
claimTicketRow(ticket.id, interaction.user.id);
logEvent({
guildId: ticket.guild_id,
type: 'ticket.claimed',
actorId: interaction.user.id,
payload: { ticketId: ticket.id },
});
await interaction.reply({
embeds: [successEmbed(`C’est noté : <@${interaction.user.id}> prend ce ticket en charge. Merci !`)],
});
await logTicket(
interaction.client,
baseEmbed(COLORS.ticket)
.setTitle('🎫 Ticket pris en charge')
.setDescription(`#${ticket.id} — <#${ticket.channel_id}>`)
.addFields({ name: 'Avec', value: `<@${interaction.user.id}>`, inline: true }),
);
}
/** Closes the ticket: the author or any staff member may do it (M6-T06 / M6-T07). */
export async function closeTicket(interaction, reason = null) {
const ticket = await getChannelTicket(interaction);
const isStaff = getAccessLevel(interaction.member) >= ACCESS_LEVELS.STAFF;
if (interaction.user.id !== ticket.author_id && !isStaff) {
throw new PermissionDeniedError(
'Seules la personne qui a ouvert ce ticket et l’équipe peuvent le fermer. Si besoin, demande‑le dans le salon.',
);
}
closeTicketRow(ticket.id, { closedBy: interaction.user.id, reason });
logEvent({
guildId: ticket.guild_id,
type: 'ticket.closed',
actorId: interaction.user.id,
payload: { ticketId: ticket.id, reason },
});
await interaction.reply({
embeds: [
successEmbed(
`Ticket fermé par <@${interaction.user.id}> — merci ! Le salon disparaît dans 10 secondes, tu as le temps de copier ce qui t’intéresse.`,
),
],
});
await logTicket(
interaction.client,
baseEmbed(COLORS.ticket)
.setTitle('🎫 Ticket fermé')
.setDescription(`#${ticket.id} — ${findCategory(ticket.category_id)?.label ?? ticket.category_id}`)
.addFields(
{ name: 'Ouvert par', value: `<@${ticket.author_id}>`, inline: true },
{ name: 'Fermé par', value: `<@${interaction.user.id}>`, inline: true },
{ name: 'Motif', value: reason || 'Non précisé' },
),
);
const channel = interaction.channel;
setTimeout(() => channel?.delete(`Ticket #${ticket.id} fermé`).catch(() => {}), 10_000).unref();
}
/** Grants a staff member access to the ticket channel (M6-T07). */
export async function addParticipant(interaction, userId) {
const ticket = await getChannelTicket(interaction);
if (userId === ticket.author_id || userId === ticket.claimed_by) {
throw new UserFacingError('Cette personne est déjà dans le ticket — pas besoin de l’ajouter.');
}
await interaction.channel.permissionOverwrites.edit(userId, {
ViewChannel: true,
SendMessages: true,
ReadMessageHistory: true,
});
logEvent({
guildId: ticket.guild_id,
type: 'ticket.participant.added',
actorId: interaction.user.id,
payload: { ticketId: ticket.id, userId },
});
await interaction.reply({ embeds: [successEmbed(`C’est noté : <@${userId}> rejoint ce ticket.`)] });
}
/** Routes the buttons posted in ticket channels. */
export async function handleTicketComponent(interaction) {
switch (interaction.customId) {
case 'ticket:claim':
await claimTicket(interaction);
return;
case 'ticket:close':
await closeTicket(interaction);
return;
default:
log.debug(`Ignored unknown ticket component ${interaction.customId}`);
}
}
File diff suppressed because it is too large. Load diff