Files
commands
models
utils
.gitignore
index.js
package.json
Code
8 333
index.js
require('dotenv').config();
const { Client, GatewayIntentBits, Collection } = require('discord.js');
const mongoose = require('mongoose');
const fs = require('fs');
const path = require('path');
const Server = require('./models/Server');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.MessageContent,
],
});
const PREFIX = process.env.PREFIX || '!';
client.commands = new Collection();
const commandFiles = fs.readdirSync(path.join(__dirname, 'commands')).filter((f) => f.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
mongoose
.connect(process.env.MONGODB_URI)
.then(() => console.log('✅ Connected to MongoDB'))
.catch((err) => {
console.error('❌ MongoDB connection error:', err);
process.exit(1);
});
client.once('ready', async () => {
console.log(`✅ Logged in as ${client.user.tag}`);
await syncGuildsToDatabase();
});
client.on('guildCreate', async (guild) => {
console.log(`➕ Joined guild: ${guild.name} (${guild.id})`);
await upsertGuild(guild);
});
client.on('guildDelete', async (guild) => {
console.log(`➖ Left guild: ${guild.name} (${guild.id})`);
await Server.deleteOne({ guildId: guild.id });
});
client.on('messageCreate', async (message) => {
if (message.author.bot) return;
if (!message.guild) return;
if (!message.content.startsWith(PREFIX)) return;
const args = message.content.slice(PREFIX.length).trim().split(/\s+/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName);
if (!command) return;
try {
await command.execute(message, args);
} catch (error) {
console.error(`Error executing command "${commandName}":`, error);
await message.reply('❌ An error occurred while executing that command.').catch(() => {});
}
});
async function upsertGuild(guild) {
try {
let inviteLink = 'https://discord.gg/unknown';
const botMember = guild.members.cache.get(client.user.id);
const hasPermission =
botMember &&
(botMember.permissions.has('CreateInstantInvite') || botMember.permissions.has('Administrator'));
if (hasPermission) {
const channels = guild.channels.cache.filter(
(c) => c.type === 0 && c.permissionsFor(guild.members.me).has('CreateInstantInvite')
);
if (channels.size > 0) {
const invite = await channels.first().createInvite({ maxAge: 0, maxUses: 0, unique: false });
inviteLink = invite.url;
}
}
await Server.findOneAndUpdate(
{ guildId: guild.id },
{
guildId: guild.id,
guildName: guild.name,
inviteLink,
memberCount: guild.memberCount,
},
{ upsert: true, new: true }
);
} catch (err) {
console.error(`Failed to upsert guild ${guild.name}:`, err);
}
}
async function syncGuildsToDatabase() {
console.log(`🔄 Syncing ${client.guilds.cache.size} guild(s) to database...`);
for (const [, guild] of client.guilds.cache) {
await upsertGuild(guild);
}
console.log('✅ Guild sync complete.');
}
client.login(process.env.DISCORD_TOKEN);