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`.'),
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user