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
@@ -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