Under the Hood
This document provides a detailed, technical breakdown of how the CrossBan Discord bot operates, focusing on its code structure, execution flow, and key components. It's aimed at developers or those with programming knowledge. The bot is written in TypeScript using Discord.js and PostgreSQL.
Overview
CrossBan synchronizes bans across multiple Discord servers. It listens for ban/unban events via Discord's audit logs, stores data in a PostgreSQL database, and propagates actions to connected guilds based on configurations. It uses Docker for deployment and handles logging via webhooks and in-channel messages.
Key technologies:
Discord.js: For interacting with Discord API.
PostgreSQL: For persistent storage.
Node.js/TypeScript: Runtime and language.
Docker: Containerization.
The bot's core is event-driven, with modules loaded dynamically at startup.
Architecture
The bot is modular:
Main Entry (index.ts): Initializes the client, loads commands/components/events, and starts the bot.
Modules:
Commands: Slash commands (e.g., config).
Components: Interactive elements (e.g., buttons for unban reviews).
Events: Handlers for Discord events (e.g., audit log entries).
Utilities: Logger, ban sync manager, unban logger.
Database: Manager for queries and schema initialization.
Config: Environment-based settings.
Files are loaded dynamically using require() based on file extensions (.ts in dev, .js in prod).
Startup Process
The bot starts in index.ts via an async IIFE (Immediately Invoked Function Expression).
Client Initialization
Creates a Discord client with intents for guilds, members, messages, and moderation.
Limits cache for performance (e.g., 128 messages per manager).
Module Loading
Functions like loadCommands(), loadComponents(), and loadEvents() scan directories and load files:
loadCommands(): Readscommands/folder, filters by extension, requires each file, and checks fordataandrunproperties. Stores in a Collection.loadComponents(): Similar forcomponents/, checks forprefixandrun.loadEvents(): Scansevents/subfolders (matching Discord Events enum), loads handlers.
Example for commands:
Interaction Handler Setup
Attaches a handler for interactions (commands, buttons, selects).
Client Ready Event
Deploys slash commands using
deployCommands().Initializes unban logger and ban sync manager.
Sets bot activity to show server count.
Loads truth sources from DB into config.
Database Initialization
Calls
dbManager.initialize()to run SQL schemas fromschemas/folder.Cleans up obsolete guilds/truth sources.
Loads truth sources into memory.
Login and Enable Features
client.login(config.botToken)connects to Discord.Enables ban sync manager.
In dev mode, enables logging.
Event Handling
Events are handled via guildAuditLogEntryCreate in banEventHandler.ts.
Ban/Unban Detection
Ignores non-ban events, non-configured guilds, bot actions, or non-truth-source executors.
Processing Bans
For MemberBanAdd:
Calls
banSyncManager.handleBan()with user ID, source guild, executor, and reason.Creates a
BanEventin DB.Syncs to auto-ban enabled guilds.
For MemberBanRemove:
Calls
banSyncManager.removeBan()to unban across guilds.
Ban Synchronization
Handled by banSyncManager.ts.
Handling Bans
Inserts ban event into
ban_eventstable.Creates guild ban record for source.
Syncs to target guilds.
Syncing to Guilds
Fetches guilds with auto-ban enabled.
Bans user in each target guild via Discord API.
Records in DB.
Handling Unbans
Marks ban as inactive in DB.
Syncs unban: Auto-unban or send review log.
For review mode:
Uses
unbanLoggerto send a message with select menu for unban/ignore.
Database Interactions
Managed by manager.ts using pg (PostgreSQL client).
Initialization
Reads
.sqlfiles fromschemas/and executes them to create tables (e.g.,guilds,ban_events,guild_bans,truth_sources).
Key Operations
Guild Configs: CRUD for settings (enabled, auto-ban, unban mode, logging channel).
Ban Events: Insert and query global bans.
Guild Bans: Track per-guild ban status.
Truth Sources: Manage trusted users per guild.
Example query:
Logging and Unban Handling
General Logging
logger.ts uses a queue for sequential webhook sends:
Queues logs to avoid rate limits.
Enabled when
LOGGING_WEBHOOKis set in.env.
Unban Logging
unbanLogger.ts builds messages using Discord's component builders:
Creates containers with text, separators, thumbnails for unban details.
For review type, adds a select menu for actions.
Sends raw payload via REST API to logging channel.
Configuration Management
config.ts loads from .env files:
Parses
GUILDSas array.Manages truth sources in memory (Map of Sets).
Provides methods to add/remove sources and check if a user is a truth source.
Example:
Error Handling and Edge Cases
Unhandled rejections/exceptions are logged.
Database queries use parameterized statements to prevent SQL injection.
Client checks for availability before actions.
Rate limiting is handled via delays (e.g., 1s in unban flow).
Last updated
Was this helpful?