feat(polls): implement polls, fun and statistics commands
A poll must end even when nobody is there to close it, so a scheduler reads the stored end dates and finalises the results at startup and while running.
This commit is contained in:
6 files changed
+514
-14
No files matched your search
@@ -1,12 +1,107 @@
|
||||
import { SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { notImplementedEmbed } from '../../ui/embeds.js';
|
||||
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
|
||||
import { parseChoices } from '../../services/polls/poll-service.js';
|
||||
import { baseEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.USER;
|
||||
|
||||
export const data = new SlashCommandBuilder().setName('fun').setDescription('Commandes de divertissement');
|
||||
const EIGHT_BALL_ANSWERS = Object.freeze([
|
||||
'Oui, sans aucun doute.',
|
||||
'Compte là-dessus et bois de l’eau.',
|
||||
'Les signes disent que oui.',
|
||||
'Impossible de le prédire pour le moment.',
|
||||
'Concentre-toi et redemande.',
|
||||
'Ma réponse est non.',
|
||||
'Très probablement.',
|
||||
'Mes sources disent non.',
|
||||
'La réponse est floue, réessaie.',
|
||||
'Absolument !',
|
||||
'Pas dans un avenir proche.',
|
||||
'Oui, mais fais attention à toi.',
|
||||
]);
|
||||
|
||||
// TODO(M10-T07): add fun subcommands.
|
||||
const pick = (list) => list[Math.floor(Math.random() * list.length)];
|
||||
|
||||
export const data = new SlashCommandBuilder()
|
||||
.setName('fun')
|
||||
.setDescription('Commandes de divertissement')
|
||||
.addSubcommand((sub) => sub.setName('coinflip').setDescription('Pile ou face'))
|
||||
.addSubcommand((sub) =>
|
||||
sub
|
||||
.setName('dice')
|
||||
.setDescription('Lancer un dé')
|
||||
.addIntegerOption((option) =>
|
||||
option
|
||||
.setName('sides')
|
||||
.setDescription('Nombre de faces (6 par défaut)')
|
||||
.setMinValue(2)
|
||||
.setMaxValue(1000),
|
||||
),
|
||||
)
|
||||
.addSubcommand((sub) =>
|
||||
sub
|
||||
.setName('8ball')
|
||||
.setDescription('Poser une question à la boule magique')
|
||||
.addStringOption((option) =>
|
||||
option.setName('question').setDescription('Ta question').setRequired(true).setMaxLength(300),
|
||||
),
|
||||
)
|
||||
.addSubcommand((sub) =>
|
||||
sub
|
||||
.setName('choose')
|
||||
.setDescription('Choisir au hasard parmi plusieurs options')
|
||||
.addStringOption((option) =>
|
||||
option.setName('options').setDescription('Options séparées par ";" (2 à 10)').setRequired(true),
|
||||
),
|
||||
);
|
||||
|
||||
/** Lightweight, stateless fun commands (M10-T07). */
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed('/fun')] });
|
||||
const subcommand = interaction.options.getSubcommand();
|
||||
|
||||
if (subcommand === 'coinflip') {
|
||||
const result = pick(['Pile', 'Face']);
|
||||
await interaction.reply({
|
||||
embeds: [baseEmbed(COLORS.info).setTitle('Pile ou face').setDescription(`🪙 ${result} !`)],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (subcommand === 'dice') {
|
||||
const sides = interaction.options.getInteger('sides') ?? 6;
|
||||
const roll = 1 + Math.floor(Math.random() * sides);
|
||||
await interaction.reply({
|
||||
embeds: [
|
||||
baseEmbed(COLORS.info)
|
||||
.setTitle(`Lancer de dé (d${sides})`)
|
||||
.setDescription(`🎲 Tu obtiens **${roll}** !`),
|
||||
],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (subcommand === '8ball') {
|
||||
const question = interaction.options.getString('question', true);
|
||||
await interaction.reply({
|
||||
embeds: [
|
||||
baseEmbed(COLORS.info)
|
||||
.setTitle('🎱 Boule magique')
|
||||
.addFields(
|
||||
{ name: 'Question', value: question },
|
||||
{ name: 'Réponse', value: pick(EIGHT_BALL_ANSWERS) },
|
||||
),
|
||||
],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const options = parseChoices(interaction.options.getString('options', true));
|
||||
await interaction.reply({
|
||||
embeds: [
|
||||
baseEmbed(COLORS.info)
|
||||
.setTitle('Choix aléatoire')
|
||||
.addFields({ name: 'Options', value: options.map((option) => `• ${option}`).join('\n') })
|
||||
.setDescription(`Je choisis : **${pick(options)}**`),
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { SlashCommandBuilder } from 'discord.js';
|
||||
import { MessageFlags, SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { notImplementedEmbed } from '../../ui/embeds.js';
|
||||
import { buildPollEmbed, closePollById, createPoll } from '../../services/polls/poll-service.js';
|
||||
import { successEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.STAFF;
|
||||
|
||||
@@ -28,7 +29,21 @@ export const data = new SlashCommandBuilder()
|
||||
.addIntegerOption((option) => option.setName('id').setDescription('ID du sondage').setRequired(true)),
|
||||
);
|
||||
|
||||
// TODO(M10-T01..T06): implement with polls / poll_votes tables.
|
||||
/** Polls are published in the current channel and voted with buttons (M10). */
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed(`/poll ${interaction.options.getSubcommand()}`)] });
|
||||
if (interaction.options.getSubcommand() === 'close') {
|
||||
const poll = await closePollById(interaction.client, interaction.options.getInteger('id', true));
|
||||
await interaction.reply({ embeds: [buildPollEmbed(poll)] });
|
||||
return;
|
||||
}
|
||||
|
||||
const question = interaction.options.getString('question', true);
|
||||
const choicesInput = interaction.options.getString('choices', true);
|
||||
const minutes = interaction.options.getInteger('minutes');
|
||||
|
||||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
const pollId = await createPoll(interaction, { question, choicesInput, minutes });
|
||||
await interaction.editReply({
|
||||
embeds: [successEmbed(`Sondage **#${pollId}** publié dans <#${interaction.channelId}>.`)],
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,13 @@
|
||||
import { SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { notImplementedEmbed } from '../../ui/embeds.js';
|
||||
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
|
||||
import { createLogger } from '../../core/logger.js';
|
||||
import { countByAction } from '../../database/repositories/moderation-repository.js';
|
||||
import { countPolls } from '../../database/repositories/poll-repository.js';
|
||||
import { countOpenTickets } from '../../database/repositories/ticket-repository.js';
|
||||
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
|
||||
import { baseEmbed, errorEmbed } from '../../ui/embeds.js';
|
||||
|
||||
const log = createLogger('stats');
|
||||
|
||||
export const access = ACCESS_LEVELS.USER;
|
||||
|
||||
@@ -11,7 +18,97 @@ export const data = new SlashCommandBuilder()
|
||||
.addSubcommand((sub) => sub.setName('gitea').setDescription('Activité et indicateurs Gitea'))
|
||||
.addSubcommand((sub) => sub.setName('fws').setDescription('Indicateurs FWS / FWS Arch'));
|
||||
|
||||
// TODO(M11-T02..T04): implement per data source.
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed(`/stats ${interaction.options.getSubcommand()}`)] });
|
||||
const discordStatsEmbed = (interaction) => {
|
||||
const guild = interaction.guild;
|
||||
return baseEmbed()
|
||||
.setTitle(`Statistiques — ${guild.name}`)
|
||||
.setThumbnail(guild.iconURL({ size: 128 }))
|
||||
.addFields(
|
||||
{ name: 'Membres', value: String(guild.memberCount), inline: true },
|
||||
{ name: 'Salons', value: String(guild.channels.cache.size), inline: true },
|
||||
{ name: 'Rôles', value: String(guild.roles.cache.size), inline: true },
|
||||
{ name: 'Boosts', value: String(guild.premiumSubscriptionCount ?? 0), inline: true },
|
||||
{ name: 'Créé', value: `<t:${Math.floor(guild.createdTimestamp / 1000)}:R>`, inline: true },
|
||||
{ name: 'Latence', value: `${Math.round(interaction.client.ws.ping)} ms`, inline: true },
|
||||
);
|
||||
};
|
||||
|
||||
async function giteaStatsEmbed() {
|
||||
const [issues, pulls, commits, releases] = await Promise.all([
|
||||
gitea.listIssues('state=open&type=issues&limit=50'),
|
||||
gitea.listPullRequests('state=open&limit=50'),
|
||||
gitea.listCommits(5),
|
||||
gitea.listReleases(1),
|
||||
]);
|
||||
|
||||
const latestCommits = asList(commits)
|
||||
.slice(0, 5)
|
||||
.map((commit) => `\`${commit.sha?.slice(0, 7)}\` ${commit.commit?.message?.split('\n')[0] ?? ''}`)
|
||||
.join('\n');
|
||||
const release = asList(releases)[0];
|
||||
|
||||
const embed = baseEmbed(COLORS.gitea)
|
||||
.setTitle('Activité Gitea')
|
||||
.setURL(repositoryUrl())
|
||||
.setDescription(latestCommits || 'Aucun commit récent.')
|
||||
.addFields(
|
||||
{ name: 'Issues ouvertes', value: String(asList(issues).length), inline: true },
|
||||
{ name: 'PR ouvertes', value: String(asList(pulls).length), inline: true },
|
||||
);
|
||||
|
||||
if (release)
|
||||
embed.addFields({ name: 'Dernière release', value: release.tag_name ?? 'inconnue', inline: true });
|
||||
return embed;
|
||||
}
|
||||
|
||||
/** Community activity stored locally, independent from Gitea availability (M11). */
|
||||
function fwsStatsEmbed(interaction) {
|
||||
const actions = countByAction(interaction.guildId);
|
||||
const total = actions.reduce((sum, row) => sum + row.count, 0);
|
||||
|
||||
return baseEmbed(COLORS.gitea)
|
||||
.setTitle('Indicateurs FWS')
|
||||
.addFields(
|
||||
{ name: 'Tickets ouverts', value: String(countOpenTickets(interaction.guildId)), inline: true },
|
||||
{ name: 'Sondages créés', value: String(countPolls(interaction.guildId)), inline: true },
|
||||
{ name: 'Actions de modération', value: String(total), inline: true },
|
||||
{ name: 'Dépôt', value: repositoryUrl() || 'Non configuré' },
|
||||
)
|
||||
.setFooter({ text: 'Statistiques locales · FWS-Bot' });
|
||||
}
|
||||
|
||||
/** `/stats` never fails because of Gitea: the API errors are caught (M11-T03). */
|
||||
export async function execute(interaction) {
|
||||
const subcommand = interaction.options.getSubcommand();
|
||||
await interaction.deferReply();
|
||||
|
||||
if (subcommand === 'discord') {
|
||||
await interaction.editReply({ embeds: [discordStatsEmbed(interaction)] });
|
||||
return;
|
||||
}
|
||||
|
||||
if (subcommand === 'fws') {
|
||||
try {
|
||||
const releases = asList(await gitea.listReleases(1));
|
||||
const embed = fwsStatsEmbed(interaction);
|
||||
if (releases[0])
|
||||
embed.addFields({ name: 'Version FWS Arch', value: releases[0].tag_name ?? 'inconnue' });
|
||||
await interaction.editReply({ embeds: [embed] });
|
||||
} catch (error) {
|
||||
log.warn('Gitea unavailable while building /stats fws', error);
|
||||
await interaction.editReply({ embeds: [fwsStatsEmbed(interaction)] });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await interaction.editReply({ embeds: [await giteaStatsEmbed()] });
|
||||
} catch (error) {
|
||||
log.error('Could not read Gitea stats', error);
|
||||
await interaction.editReply({
|
||||
embeds: [
|
||||
errorEmbed('Les statistiques Gitea sont indisponibles. Vérifie `GITEA_URL` et `GITEA_TOKEN`.'),
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ActivityType, Events } from 'discord.js';
|
||||
import { createLogger } from '../core/logger.js';
|
||||
import { startPollScheduler } from '../services/polls/poll-service.js';
|
||||
|
||||
const log = createLogger('discord');
|
||||
|
||||
@@ -8,6 +9,7 @@ export const once = true;
|
||||
|
||||
export async function execute(client) {
|
||||
client.user.setActivity('FWS Arch', { type: ActivityType.Watching });
|
||||
startPollScheduler(client);
|
||||
log.info(`Connected as ${client.user.tag}`, {
|
||||
guilds: client.guilds.cache.size,
|
||||
commands: client.commands.size,
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
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(`Un sondage doit proposer entre ${min} et ${max} choix séparés par « ; ».`);
|
||||
}
|
||||
if (new Set(choices.map((choice) => choice.toLowerCase())).size !== choices.length) {
|
||||
throw new UserFacingError('Les choix d’un sondage doivent être différents.');
|
||||
}
|
||||
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(`Le sondage **#${pollId}** n’existe pas.`);
|
||||
if (poll.status === 'closed') throw new UserFacingError(`Le sondage **#${pollId}** est déjà fermé.`);
|
||||
|
||||
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 fermé.');
|
||||
}
|
||||
|
||||
const choices = JSON.parse(poll.choices);
|
||||
const index = Number(rawIndex);
|
||||
if (!Number.isInteger(index) || index < 0 || index >= choices.length) {
|
||||
throw new UserFacingError('Choix inconnu.');
|
||||
}
|
||||
|
||||
const result = castVote(poll.id, interaction.user.id, index);
|
||||
if (result === 'unchanged') {
|
||||
await interaction.reply({
|
||||
content: `Tu as déjà voté pour **${choices[index]}**.`,
|
||||
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'
|
||||
? `Ton vote a été changé pour **${choices[index]}**.`
|
||||
: `Vote enregistré pour **${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;
|
||||
}
|
||||
Reference in new issue
Block a user