Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
26 lines (26 loc) · 8.65 KB
/
Copy pathmain.js
File metadata and controls
26 lines (26 loc) · 8.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
require('dotenv').config({ quiet: true });
const path=require('node:path');
const {Client,Collection,Events,GatewayIntentBits,Partials,REST,Routes,MessageFlags}=require('discord.js');
const {ok,boot,error,warn,info}=require('./lib/logger');
const {loadConfig}=require('./lib/config');const {createDatabase}=require('./lib/database');const {loadModules,refreshCommands,moduleDirectories}=require('./lib/module-loader');const {authorize}=require('./lib/permissions');
const {preflight}=require('./lib/guards');
const config=loadConfig();
const enabled=name=>config[name]?.enabled===true||(name==='dashboard'&&config.adminPanel?.enabled===true);
const builtInModules=moduleDirectories(path.join(__dirname,'modules')).map(([name])=>name).filter(enabled);
const customModulesEnabled=config.customModules?.enabled===true;
const anyEventModules=builtInModules.length>0||customModulesEnabled;
const intents=[GatewayIntentBits.Guilds];
if(anyEventModules||config.prefix?.enabled===true)intents.push(GatewayIntentBits.GuildMessages,GatewayIntentBits.MessageContent);
if(anyEventModules)intents.push(GatewayIntentBits.GuildMessageReactions,GatewayIntentBits.GuildVoiceStates,GatewayIntentBits.GuildModeration);
if(['welcome','logging','autorole','countryballs','voice','automod'].some(enabled)||customModulesEnabled)intents.push(GatewayIntentBits.GuildMembers);
const client=new Client({intents:[...new Set(intents)],partials:[Partials.Channel,Partials.Message,Partials.GuildMember,Partials.User,Partials.Reaction]});client.config=config;client.brand={serverName:config.branding?.serverName||'RealmsNetwork',botName:config.branding?.botName||'RealmsNetwork Bot',color:config.branding?.embedColor||'#8b5cf6',footer:config.branding?.footer||config.branding?.serverName||'RealmsNetwork',supportUrl:config.branding?.supportUrl||''};client.commands=new Collection();client.contextMenus=new Collection();client.prefixCommands=new Map();client.modules=new Collection();client.cooldowns=new Map();client.metrics={commands:0,prefixCommands:0,errors:0,startedAt:Date.now(),events:0};client.framework=Object.freeze({version:4,release:'0.2.0',name:'RealmsNetwork Bot Framework',reloadCommands:()=>refreshCommands(client,config),registerPrefixCommand:(name,handler)=>client.prefixCommands.set(String(name).toLowerCase(),handler)});
async function deployCommands(){const c=config.commands||{};if(c.autoDeploy!==true||!process.env.DISCORD_TOKEN||!process.env.DISCORD_CLIENT_ID)return;const body=[...client.commands.values()].map(x=>x.data.toJSON()).concat([...client.contextMenus.values()].map(x=>x.data.toJSON()));const rest=new REST({version:'10'}).setToken(process.env.DISCORD_TOKEN);const route=c.guildOnly!==false&&config.guildId&&config.guildId!=='YOUR_GUILD_ID_HERE'?Routes.applicationGuildCommands(process.env.DISCORD_CLIENT_ID,config.guildId):Routes.applicationCommands(process.env.DISCORD_CLIENT_ID);await rest.put(route,{body});ok(`Synced ${body.length} application commands`);}
function commandSignature(){return JSON.stringify({slash:[...client.commands.values()].map(x=>x.data.toJSON()).sort((a,b)=>a.name.localeCompare(b.name)),context:[...client.contextMenus.values()].map(x=>x.data.toJSON()).sort((a,b)=>String(a.name).localeCompare(String(b.name))) });}
function cooldownSeconds(command){return Math.max(0,Number(command.cooldown??config.commands?.defaultCooldownSeconds??0));}function checkCooldown(command,userId){const seconds=cooldownSeconds(command);if(!seconds)return 0;const key=`${userId}:${command.data.name}`,now=Date.now(),previous=client.cooldowns.get(key)||0,remaining=seconds*1000-(now-previous);if(remaining>0)return Math.ceil(remaining/1000);client.cooldowns.set(key,now);if(client.cooldowns.size>Number(config.runtime?.cacheSize||1000)*2)for(const[k,ts]of client.cooldowns)if(now-ts>seconds*1000)client.cooldowns.delete(k);return 0;}
function getCommand(interaction){if(interaction.isChatInputCommand())return client.commands.get(interaction.commandName);if(interaction.isUserContextMenuCommand()||interaction.isMessageContextMenuCommand())return client.contextMenus.get(interaction.commandName);return null;}
async function executeInteraction(interaction){const command=getCommand(interaction);if(!command)return;try{if(!authorize(interaction,command,client.config))return interaction.reply({content:client.config.branding?.permissionDenied||'You do not have permission to use this command.',flags:MessageFlags.Ephemeral});const guardError=preflight(interaction,command,client.config);if(guardError)return interaction.reply({content:guardError,flags:MessageFlags.Ephemeral});const left=checkCooldown(command,interaction.user.id);if(left)return interaction.reply({content:`Please wait **${left}s** before using this again.`,flags:MessageFlags.Ephemeral});if(command.defer&&!interaction.deferred&&!interaction.replied){const options=command.ephemeral===true?{flags:MessageFlags.Ephemeral}:{};await interaction.deferReply(options);}client.metrics.commands++;await command.execute(interaction,client);}catch(e){client.metrics.errors++;error(`[Command] ${interaction.commandName}: ${e?.message||e}`);const payload={content:client.config.branding?.errorMessage||'Something went wrong while running that command.',flags:MessageFlags.Ephemeral};if(interaction.deferred&&!interaction.replied)await interaction.editReply({content:payload.content}).catch(()=>{});else if(interaction.replied)await interaction.followUp(payload).catch(()=>{});else await interaction.reply(payload).catch(()=>{});}}
async function executePrefix(message){const p=config.prefix||{};if(p.enabled!==true||!message.guild||message.author.bot)return;const prefixes=Array.isArray(p.prefixes)&&p.prefixes.length?p.prefixes:['!'];const prefix=prefixes.find(x=>message.content.startsWith(x))||(p.mentionPrefix&&client.user&&message.content.startsWith(`<@${client.user.id}>`)?`<@${client.user.id}>`:null);if(!prefix)return;const body=message.content.slice(prefix.length).trim();if(!body)return;const parts=body.split(/\s+/),name=parts.shift().toLowerCase(),handler=client.prefixCommands.get(name);if(!handler)return;try{if(handler.cooldown&&checkCooldown({data:{name},cooldown:handler.cooldown},message.author.id))return;client.metrics.prefixCommands++;await handler(message,{args:parts,prefix,name,client,config});}catch(e){client.metrics.errors++;error(`[Prefix] ${name}: ${e?.message||e}`);if(config.prefix.errorMessage)await message.reply(config.prefix.errorMessage).catch(()=>{});}}
function startAutoRefresh(){const c=config.commands||{};if(c.autoRefresh!==true)return;let signature=commandSignature();const timer=setInterval(async()=>{try{await refreshCommands(client,config,true);const next=commandSignature();if(next!==signature){signature=next;await deployCommands();info(`Command registry updated: ${client.commands.size+client.contextMenus.size} commands`);}}catch(e){warn(`[Commands] Auto-refresh failed: ${e.message}`);}},Math.max(1000,Number(c.refreshIntervalMs||5000)));timer.unref?.();}
async function start(){if(!process.env.DISCORD_TOKEN||process.env.DISCORD_TOKEN==='YOUR_BOT_TOKEN_HERE')throw new Error('DISCORD_TOKEN is missing');boot('Initializing database...');client.db=await createDatabase(config);boot('Loading enabled modules...');await loadModules(client,config);ok(`Loaded ${client.modules.size} enabled module(s)`);client.on(Events.InteractionCreate,executeInteraction);if(config.prefix?.enabled===true)client.on(Events.MessageCreate,message=>{client.metrics.events++;return executePrefix(message);});client.once(Events.ClientReady,async c=>{client.metrics.readyAt=Date.now();ok(`Online as ${c.user.tag} | ${c.guilds.cache.size} guilds | ${client.commands.size+client.contextMenus.size} commands | ${client.modules.size} modules | db=${client.db.type}`);await deployCommands().catch(e=>error(`[Commands] Deploy failed: ${e.message}`));startAutoRefresh();});process.once('SIGINT',shutdown);process.once('SIGTERM',shutdown);process.on('uncaughtException',e=>{client.metrics.errors++;error(`[Runtime] Uncaught exception: ${e?.stack||e}`);if(config.runtime?.crashProtection===false)process.exit(1);});process.on('unhandledRejection',e=>{client.metrics.errors++;error(`[Runtime] Unhandled rejection: ${e?.stack||e}`);});await client.login(process.env.DISCORD_TOKEN);}
let shuttingDown=false;async function shutdown(){if(shuttingDown)return;shuttingDown=true;boot('Shutting down...');for(const module of client.modules.values())try{await module.definition?.destroy?.(client,module.config,module.advanced);}catch(e){error(`[Module] Destroy failed for ${module.name}: ${e.message}`);}try{await client.db?.close?.();}catch{}try{client.destroy();}catch{}ok('Shutdown complete');process.exit(0);}
if(require.main===module)start().catch(e=>{error(`[Startup] ${e?.stack||e}`);process.exit(1);});module.exports={client,config,start,deployCommands,executeInteraction,shutdown};