Files
src
.gitignore
package.json
README.md
Code
8 577
src/index.js
const {
Client,
EmbedBuilder,
Events,
GatewayIntentBits,
PermissionFlagsBits
} = require('discord.js');
const config = require('./config');
const { buildCommands } = require('./commands');
const PredictionStore = require('./storage');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const store = new PredictionStore(config.dataFile);
function hasModeratorPermission(interaction) {
const permissions = interaction.memberPermissions;
return Boolean(
permissions && (
permissions.has(PermissionFlagsBits.Administrator)
|| permissions.has(PermissionFlagsBits.ManageGuild)
|| permissions.has(PermissionFlagsBits.ManageMessages)
)
);
}
async function requireModerator(interaction) {
if (interaction.inGuild() && hasModeratorPermission(interaction)) {
return true;
}
await interaction.reply({
content: 'This command is restricted to administrators and moderators.',
ephemeral: true
});
return false;
}
function trimTeamName(name) {
return name.trim().replace(/\s+/g, ' ');
}
function formatNames(players) {
if (players.length === 0) {
return 'None';
}
const names = players.map(player => player.username);
const full = names.join(', ');
if (full.length <= 1000) {
return full;
}
let result = '';
let included = 0;
for (const name of names) {
const next = result ? `${result}, ${name}` : name;
if (next.length > 940) {
break;
}
result = next;
included += 1;
}
return `${result} (+${names.length - included} more)`;
}
function formatLeaderboard(entries) {
if (entries.length === 0) {
return 'No users have submitted a prediction yet.';
}
const lines = [];
for (let index = 0; index < entries.length && index < 50; index += 1) {
const entry = entries[index];
const line = `${index + 1}. @${entry.username} - ${entry.points} BF Points`;
if (`${lines.join('\n')}\n${line}`.length > 3800) {
break;
}
lines.push(line);
}
if (lines.length < entries.length) {
lines.push(`...and ${entries.length - lines.length} more users.`);
}
return lines.join('\n');
}
async function handlePredictionStart(interaction) {
if (!(await requireModerator(interaction))) {
return;
}
const team1 = trimTeamName(interaction.options.getString('team1', true));
const team2 = trimTeamName(interaction.options.getString('team2', true));
const previousMatch = await store.startMatch(team1, team2);
const embed = new EmbedBuilder()
.setColor(0x2ecc71)
.setTitle('Predictions are open')
.setDescription(`**${team1}** vs **${team2}**`)
.addFields({
name: 'How to predict',
value: 'Use `/predict` with the score for each team. Your latest prediction replaces your previous one.'
});
if (previousMatch) {
embed.addFields({
name: 'Previous session',
value: `The previous ${previousMatch.team1} vs ${previousMatch.team2} session was closed.`
});
}
await interaction.reply({ embeds: [embed], allowedMentions: { parse: [] } });
}
async function handlePredict(interaction) {
const score1 = interaction.options.getInteger('team1_score', true);
const score2 = interaction.options.getInteger('team2_score', true);
try {
const result = await store.recordPrediction(
interaction.user.id,
interaction.user.username,
score1,
score2
);
const action = result.overwritten ? 'updated' : 'recorded';
await interaction.reply({
content: `Your prediction of **${score1}-${score2}** for **${result.match.team1}** vs **${result.match.team2}** was ${action}.`,
ephemeral: true,
allowedMentions: { parse: [] }
});
} catch (error) {
if (error.code === 'NO_ACTIVE_MATCH') {
await interaction.reply({
content: 'There is no active prediction session right now.',
ephemeral: true
});
return;
}
throw error;
}
}
async function handleMatchResult(interaction) {
if (!(await requireModerator(interaction))) {
return;
}
const score1 = interaction.options.getInteger('team1_score', true);
const score2 = interaction.options.getInteger('team2_score', true);
const result = await store.settleMatch(score1, score2);
if (!result) {
await interaction.reply({
content: 'There is no active prediction session to settle.',
ephemeral: true
});
return;
}
const { match } = result;
const embed = new EmbedBuilder()
.setColor(0xf1c40f)
.setTitle('Match result')
.setDescription(`**${match.team1} ${score1} - ${score2} ${match.team2}**`)
.addFields(
{ name: 'Exact score (+10 BF)', value: formatNames(result.exact), inline: false },
{ name: 'Correct outcome (+5 BF)', value: formatNames(result.outcome), inline: false },
{ name: 'Summary', value: `${result.predictionCount} predictions evaluated\n${result.totalAwarded} BF points awarded`, inline: false }
);
await interaction.reply({ embeds: [embed], allowedMentions: { parse: [] } });
}
async function handleLeaderboard(interaction) {
const leaderboard = store.getLeaderboard();
const embed = new EmbedBuilder()
.setColor(0x3498db)
.setTitle('BF Points Leaderboard')
.setDescription(formatLeaderboard(leaderboard));
await interaction.reply({ embeds: [embed], allowedMentions: { parse: [] } });
}
async function handleReset(interaction) {
if (!(await requireModerator(interaction))) {
return;
}
await store.resetPoints();