Files
src
package.json
Code
6 659
src/index.js
const { Client, GatewayIntentBits, REST, Routes } = require('discord.js');
const config = require('./config');
const AeternumDatabase = require('./db');
const { commands, handleInteraction } = require('./commands');
if (!config.token || !config.clientId) {
throw new Error('DISCORD_TOKEN e DISCORD_CLIENT_ID sono obbligatori nel file .env.');
}
const db = new AeternumDatabase(config.databasePath);
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
async function registerCommands() {
const rest = new REST({ version: '10' }).setToken(config.token);
const route = config.devGuildId
? Routes.applicationGuildCommands(config.clientId, config.devGuildId)
: Routes.applicationCommands(config.clientId);
await rest.put(route, { body: commands });
console.log(`Registrati ${commands.length} comandi slash.`);
}
client.once('ready', () => {
console.log(`Connesso come ${client.user.tag}.`);
setInterval(() => {
for (const id of db.getAllUserIds()) {
const before = db.getUser(id);
const after = db.applyNeeds(id, config.hungerDecayMinutes, config.hungerDecayAmount);
if (!after || !before) continue;
const low = after.hunger <= config.lowNeedThreshold || after.thirst <= config.lowNeedThreshold;
if (low && Date.now() - after.last_low_warning_at >= config.lowNeedWarningMinutes * 60 * 1000) {
db.setLowWarningTime(id, Date.now());
const user = client.users.cache.get(id);
if (user) user.send(`⚠️ Attenzione: i tuoi bisogni sono bassi. Fame: ${after.hunger}/100, sete: ${after.thirst}/100.`).catch(() => {});
}
}
}, 60_000);
});
client.on('interactionCreate', interaction => {
handleInteraction(interaction, db, config).catch(error => {
console.error(error);
const response = { content: 'Si è verificato un errore durante l operazione.', ephemeral: true };
if (interaction.replied || interaction.deferred) interaction.followUp(response).catch(() => {});
else interaction.reply(response).catch(() => {});
});
});
registerCommands()
.then(() => client.login(config.token))
.catch(error => {
console.error('Registrazione comandi fallita:', error);
db.close();
process.exitCode = 1;
});
process.on('SIGINT', () => {
db.close();
client.destroy();
process.exit(0);
});