Files
src
.gitignore
bot.js
package.json
README.md
Code
9 785
bot.js
require('dotenv').config();
const { Client, Events, GatewayIntentBits } = require('discord.js');
const { initializeDatabase, closeDatabase } = require('./src/database');
const { handleMessage } = require('./src/moderation');
const gifConfigCommand = require('./src/commands/gifconfig');
if (!process.env.DISCORD_TOKEN) {
throw new Error('DISCORD_TOKEN is required. Set it in the environment or .env file.');
}
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent]
});
client.once(Events.ClientReady, async (readyClient) => {
try {
const commands = [gifConfigCommand.command.toJSON()];
if (process.env.DISCORD_GUILD_ID) {
const guild = await readyClient.guilds.fetch(process.env.DISCORD_GUILD_ID);
await guild.commands.set(commands);
console.log(`Registered slash commands in guild ${guild.id}.`);
} else {
await readyClient.application.commands.set(commands);
console.log('Registered global slash commands. Global command updates may take time to appear.');
}
} catch (error) {
console.error('Slash command registration failed:', error);
}
console.log(`Bot is ready! Logged in as ${readyClient.user.tag}`);
console.log('KODARI_READY');
});
client.on(Events.MessageCreate, async (message) => {
try {
await handleMessage(message);
} catch (error) {
console.error(`GIF moderation failed for guild ${message.guildId ?? 'DM'}:`, error);
}
});
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand() || interaction.commandName !== 'gifconfig') return;
try {
await gifConfigCommand.execute(interaction);
} catch (error) {
console.error('GIF configuration command failed:', error);
const response = { content: 'The command could not be completed. Check the bot logs and database connection.', ephemeral: true };
if (interaction.deferred || interaction.replied) {
await interaction.followUp(response).catch(() => {});
} else {
await interaction.reply(response).catch(() => {});
}
}
});
client.on(Events.Error, (error) => console.error('Discord client error:', error));
process.on('unhandledRejection', (error) => console.error('Unhandled promise rejection:', error));
async function shutdown(signal) {
console.log(`Received ${signal}; shutting down.`);
client.destroy();
try {
await closeDatabase();
} catch (error) {
console.error('Error closing PostgreSQL pool:', error);
}
process.exit(0);
}
process.once('SIGINT', () => shutdown('SIGINT'));
process.once('SIGTERM', () => shutdown('SIGTERM'));
async function start() {
try {
await initializeDatabase();
console.log('PostgreSQL connection established and schema is ready.');
await client.login(process.env.DISCORD_TOKEN);
} catch (error) {
console.error('Bot startup failed:', error);
await closeDatabase().catch(() => {});
process.exitCode = 1;
}
}
start();
