Skip to content
Vecto edited this page Sep 17, 2024 · 1 revision

This file is the main entry point for your Discord bot. It initializes the bot, handles commands, events, and various utility functions to manage guild members, bots, and settings. Here's a breakdown of the different parts of this file:

1. Imports and Client Initialization

const { Client, GatewayIntentBits, Collection, Events, PermissionsBitField } = require(`discord.js`);
const fs = require('fs');
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers,
  ],
});

Client: The main class from Discord.js that represents your bot. GatewayIntentBits: Enables specific events your bot can listen to (e.g., guild messages, members). client: Represents the bot and its state. Command and Prefix Collections: client.commands and client.prefix store bot commands and prefix-based commands respectively.

2. Loading Functions, Events, and Commands

const functions = fs.readdirSync('./src/bot/functions').filter(file => file.endsWith('.js'));
const eventFiles = fs.readdirSync('./src/bot/events').filter(file => file.endsWith('.js'));
const commandFolders = fs.readdirSync('./src/bot/commands');
const prefixFolders = fs.readdirSync('./src/bot/prefix').filter(f => f.endsWith('.js'));

Files are dynamically read from functions, events, commands, and prefix directories to load various parts of the bot.

3. Bot Start Function

const startBot = () => {
  (async () => {
    for (file of functions) {
      require(`./functions/${file}`)(client);
    }
    client.handleEvents(eventFiles, './src/bot/events');
    client.handleCommands(commandFolders, './src/bot/commands');
    await client.login(botConfig.token);
    client.token = botConfig.token;
  })();
};

This function dynamically loads and initializes the bot's events, commands, and functions, and logs the bot in using the token from botConfig.

4. Command Handling (Prefix-based)

client.on('messageCreate', async (message) => {
  const prefix = process.env.DISCORD_BOT_PREFIX;
  if (!message.content.startsWith(prefix) || message.author.bot) return;
  const args = message.content.slice(prefix.length).trim().split(/ +/);
  const command = args.shift().toLowerCase();
  const prefixcmd = client.prefix.get(command);
  if (prefixcmd) {
    prefixcmd.run(client, message, args);
  }
});

Handles commands with a specific prefix. If a message starts with the bot's prefix, the command is identified and executed.

5. Fetching Bot, Member, and Server Data getBots(): Fetches data about all bots in the server, including activity, status, and invites. getMembers(): Fetches data about guild members, including their username, ID, and profile URL. getServers(): Fetches data about all guilds (servers) the bot is in, such as server owner, member count, and invite links.

6. Additional Systems Join Role System: Automatically assigns roles to new members. Anti-Link System: Deletes messages containing specific links. AFK System: Sets users to AFK (Away From Keyboard) and replies when they're mentioned. Embed Builder: Allows users to build rich embeds using a modal interaction. Auto-responder System: Automatically replies to certain trigger phrases. Bad Words System: Deletes messages that contain banned words. app.js Documentation (API Server) This file defines and configures the main API server for your application. It uses Express.js to handle routes, middleware, and other server-side logic. Here's a breakdown of each part of the file:

1. Imports and Middleware Configuration

require('dotenv').config();
require('./utils/passportUtil');
const express = require('express');
const session = require('express-session');
const morgan = require('morgan');
const flash = require('connect-flash');
const cookieParser = require('cookie-parser');
const passport = require('passport');
const logger = require('./services/loggerService');

Environment Variables: dotenv is used to load environment variables. Passport: Configures authentication using various strategies (OAuth, local, etc.). Express.js: The main framework used for routing and handling HTTP requests. Session and Flash: Used for handling user sessions and displaying flash messages. morgan: Logs incoming requests for debugging. CookieParser: Parses cookies attached to the client requests.

2. Middlewares

api.use(express.urlencoded({ extended: true }));
api.use(express.json());
api.use(cookieParser());
api.use(flash());
api.use(corsMiddleware);
api.use(compressionMiddleware);
api.use(rateLimiter);

Body Parsers: express.urlencoded and express.json parse the request body in URL-encoded or JSON formats. CORS, Compression, and Rate Limiting: Middleware that handles cross-origin requests, response compression, and rate limiting to prevent abuse.

3. Session Configuration

api.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
}));

Configures session handling with a secret from environment variables. Sessions are used to track logged-in users across requests.

4. Logging (Morgan)

morgan.token('remote-addr', (req) => req.headers['x-forwarded-for'] || req.connection.remoteAddress);
const logFormat = '[API] :remote-addr - :method :url :status :response-time ms - :res[content-length]';
api.use(morgan(logFormat, { stream: { write: (message) => logger.info(message.trim()) } }));

Morgan is used to log each request, with custom tokens to capture useful information (e.g., request method, URL, status).

5. View Engine Configuration

api.set('view engine', 'ejs');
api.set('views', path.join(__dirname, '../views'));

EJS is set as the view engine for rendering dynamic templates. Static Files: The static directory for serving assets like CSS and JavaScript is set to public.

6. Passport Initialization

api.use(passport.initialize());
api.use(passport.session());

Initializes and sets up Passport for authentication. Passport sessions allow users to remain logged in between requests.

7. Routes

const authRoutes = require('./routes/authRoutes');
const versionRoutes = require('./routes/versionRoutes');
// ... (Other routes)

api.use('/api/auth', authRoutes);
api.use('/api/versions', versionRoutes);
// ... (Other routes)

Loads and uses various route modules (e.g., authRoutes, versionRoutes, etc.). Each route handles a specific part of the application (e.g., authentication, versions, games).

8. API Start Function

const startApi = () => {
  const https = process.env.API_HTTPS || 'http';
  const port = process.env.API_PORT || '3000';
  const baseURL = process.env.API_BASE_URL || 'localhost';

  api.listen(port, () => {
    logger.info(`API is running on ${https}://${baseURL}:${port}`);
  });
};

This function starts the Express.js server, logging the API URL and port it's running on. It uses environment variables to configure the base URL, port, and protocol. Summary index.js is responsible for managing the Discord bot's functionality, such as handling commands, managing guilds, and integrating various services. app.js sets up an Express API server with various routes, middlewares, and configurations for session handling, passport authentication, and request logging.

Clone this wiki locally