Files
data
.gitignore
index.js
package.json
Code
4 364
index.js
require('dotenv').config();
const fs = require('node:fs/promises');
const path = require('node:path');
const {
Client,
EmbedBuilder,
GatewayIntentBits,
REST,
Routes,
SlashCommandBuilder
} = require('discord.js');
const DAILY_GOAL_MINUTES = 60;
const MAX_DAILY_MINUTES = 1440;
const timezone = process.env.BOT_TIMEZONE || 'America/Sao_Paulo';
const dataPath = path.join(__dirname, 'data', 'streaks.json');
function requiredEnvironment(name) {
const value = process.env[name]?.trim();
if (!value) {
throw new Error(`A variável ${name} é obrigatória. Configure-a no arquivo .env.`);
}
return value;
}
function getDateKey(date = new Date()) {
const parts = new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).formatToParts(date);
const values = Object.fromEntries(
parts
.filter((part) => part.type !== 'literal')
.map((part) => [part.type, part.value])
);
return `${values.year}-${values.month}-${values.day}`;
}
function previousDateKey(dateKey) {
const [year, month, day] = dateKey.split('-').map(Number);
const date = new Date(Date.UTC(year, month - 1, day - 1));
return date.toISOString().slice(0, 10);
}
function getStreak(dailyMinutes, today = getDateKey()) {
const yesterday = previousDateKey(today);
let date = dailyMinutes[today] >= DAILY_GOAL_MINUTES ? today : yesterday;
if ((dailyMinutes[date] || 0) < DAILY_GOAL_MINUTES) {
return 0;
}
let streak = 0;
while ((dailyMinutes[date] || 0) >= DAILY_GOAL_MINUTES) {
streak += 1;
date = previousDateKey(date);
}
return streak;
}
function progressBar(minutes) {
const percentage = Math.min(100, Math.round((minutes / DAILY_GOAL_MINUTES) * 100));
const filled = Math.round((percentage / 100) * 16);
return {
percentage,
bar: `${'█'.repeat(filled)}${'░'.repeat(16 - filled)}`
};
}
function minuteLabel(minutes) {
return minutes === 1 ? 'minuto' : 'minutos';
}
function streakLabel(streak) {
return streak === 1 ? 'dia' : 'dias';
}
function createStatusEmbed(displayName, dailyMinutes, streak) {
const { percentage, bar } = progressBar(dailyMinutes);
const remaining = Math.max(0, DAILY_GOAL_MINUTES - dailyMinutes);
const complete = remaining === 0;
return new EmbedBuilder()
.setColor(complete ? 0x57F287 : 0x5865F2)
.setTitle(`🔥 Ofensiva de ${displayName}`)
.setDescription([
`**Ofensiva:** ${streak} ${streakLabel(streak)}`,
`**Hoje:** ${dailyMinutes}/${DAILY_GOAL_MINUTES} minutos`,
`\`${bar} ${percentage}%\``,
complete
? '✅ Meta diária concluída. Sua ofensiva está garantida hoje!'
: `Faltam **${remaining} ${minuteLabel(remaining)}** para garantir a ofensiva.`
].join('\n'))
.setFooter({ text: `Meta diária: ${DAILY_GOAL_MINUTES} minutos • Fuso: ${timezone}` });
}
class StreakStore {
constructor(filePath) {
this.filePath = filePath;
this.data = { guilds: {} };
this.writeQueue = Promise.resolve();
}
async load() {
await fs.mkdir(path.dirname(this.filePath), { recursive: true });
try {
const content = await fs.readFile(this.filePath, 'utf8');
const parsed = JSON.parse(content);
if (!parsed || typeof parsed !== 'object' || !parsed.guilds || typeof parsed.guilds !== 'object') {
throw new Error('O arquivo de dados não possui uma estrutura válida.');
}
this.data = parsed;
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
}
await this.save();
}
}
async save() {
const content = JSON.stringify(this.data, null, 2);
const temporaryPath = `${this.filePath}.tmp`;
this.writeQueue = this.writeQueue
.catch(() => undefined)
.then(async () => {
await fs.writeFile(temporaryPath, content, 'utf8');
await fs.rename(temporaryPath, this.filePath);
});
return this.writeQueue;
}
getGuild(guildId) {
if (!this.data.guilds[guildId]) {
this.data.guilds[guildId] = { users: {} };
}
return this.data.guilds[guildId];
}
getUser(guildId, user) {
const guild = this.getGuild(guildId);
if (!guild.users[user.id]) {
guild.users[user.id] = {
displayName: user.globalName || user.username,
dailyMinutes: {}
};
}
guild.users[user.id].displayName = user.globalName || user.username;
return guild.users[user.id];
}
findUser(guildId, userId) {
return this.data.guilds[guildId]?.users?.[userId] || null;
}
getRanking(guildId, today) {
const users = this.data.guilds[guildId]?.users || {};
return Object.entries(users)
.map(([userId, user]) => ({
userId,
user,
streak: getStreak(user.dailyMinutes || {}, today)
}))
.filter((entry) => entry.streak > 0)
.sort((first, second) => second.streak - first.streak || first.user.displayName.localeCompare(second.user.displayName));
}
}
const commands = [
new SlashCommandBuilder()
.setName('jogar')
.setDescription('Registra o tempo que você jogou hoje.')
.addIntegerOption((option) => option
.setName('minutos')
.setDescription('Quantidade de minutos jogados agora.')
.setMinValue(1)
.setMaxValue(720)
.setRequired(true)),
new SlashCommandBuilder()
.setName('ofensiva')
.setDescription('Mostra a ofensiva e o progresso diário de um jogador.')
.addUserOption((option) => option