Overview
AutoResponse includes a robust collection of utility modules in the utils/ directory that handle logging, database operations, Discord interactions, and more. These utilities provide reusable functionality across the entire bot.
Logging Utilities
logging.js
Comprehensive logging system with color-coded output and SQLite database storage.
Location : utils/logging.js
Core Logging Functions
const { Error , Warn , Done , Info , Debug } = require ( './utils/logging' );
// Error logging (red)
Error ( 'Something went wrong!' );
// Warning logging (yellow)
Warn ( 'This is a warning message' );
// Success logging (green)
Done ( 'Operation completed successfully' );
// Info logging (grey)
Info ( 'General information message' );
// Debug logging (grey, no DB storage)
Debug ( 'Debug information' );
Event-Specific Logging
Every Discord event has its own logging function with custom formatting:
const {
messageCreate ,
messageDelete ,
interactionCreate ,
guildCreate ,
guildMemberAdd
} = require ( './utils/logging' );
// Log message creation (blue)
messageCreate ( 'ServerName - #channel - username - message content' );
// Log message deletion (red)
messageDelete ( 'ServerName - #channel - username - message (Deleted)' );
// Log interaction (magenta)
interactionCreate ( 'ServerName - #channel - username - /command' );
// Log guild join (green)
guildCreate ( 'Joined guild: ServerName (123456789)' );
// Log member join (green)
guildMemberAdd ( 'ServerName - username Joined (Approved)' );
Database Logging
All logs are automatically stored in data/logs.db:
function dbOutput ( type , message ) {
const date = new Date ();
const formattedDate = ` ${ String ( date . getMonth () + 1 ). padStart ( 2 , '0' ) } - ${ String ( date . getDate ()). padStart ( 2 , '0' ) } - ${ date . getFullYear () } ` ;
const time = date . toLocaleTimeString ();
// Creates a table per day: MM-DD-YYYY
// Columns: time, type, content
db . run ( `CREATE TABLE IF NOT EXISTS " ${ formattedDate } " (time TEXT, type TEXT, content TEXT)` );
db . run ( `INSERT INTO " ${ formattedDate } " (time, type, content) VALUES (?,?,?)` ,
[ time , type , content ]);
}
Logs are organized by date in separate tables, making it easy to query specific days. Color codes are stripped before storage.
Available Event Loggers
messageCreate() - Blue color
messageDelete() - Red color
messageUpdate() - Yellow color
messageDeleteBulk() - Red color
guildCreate() - Green color
guildDelete() - Red color
guildUpdate() - Yellow color
guildMemberAdd() - Green color
guildMemberRemove() - Red color
guildMemberUpdate() - Yellow color
interactionCreate() - Magenta color
autoModerationActionExecution() - Magenta color
ServerError() - Red with [SERVER] prefix
ServerLog() - Magenta with [SERVER] prefix
ServerDone() - Green with [SERVER] prefix
Discord Utilities
embeds.js
Pre-built embed builders for consistent Discord message formatting.
Location : utils/embeds.js
Basic Embeds
const {
SuccessEmbed ,
ErrorEmbed ,
InfoEmbed ,
LoadingEmbed
} = require ( './utils/embeds' );
// Success message (green)
const embed = SuccessEmbed ( 'Operation Complete' , 'Your action was successful!' );
await interaction . reply ({ embeds: [ embed ] });
// Error message (red)
const errorEmbed = ErrorEmbed ( 'An error occurred: ' + error . message );
await interaction . reply ({ embeds: [ errorEmbed ], ephemeral: true });
// Info message (default color)
const infoEmbed = InfoEmbed ( 'This is an informational message' );
await message . channel . send ({ embeds: [ infoEmbed ] });
// Loading indicator
const loadingEmbed = LoadingEmbed ( 'Processing' , 'Please wait...' );
await interaction . reply ({ embeds: [ loadingEmbed ] });
Specialized Embeds
// Ping embed with latency info
const { PingEmbed } = require ( './utils/embeds' );
const pingEmbed = PingEmbed (
client . ws . ping , // WebSocket ping
restPing , // REST API ping
'g' // Color code for WS ping
);
// User info embed
const { UserEmbed } = require ( './utils/embeds' );
const userEmbed = UserEmbed (
user . tag ,
user . id ,
highestRole . name ,
permissions ,
badges ,
createdTimestamp ,
joinedTimestamp ,
avatarURL ,
bannerURL
);
// Server info embed
const { ServerEmbed } = require ( './utils/embeds' );
const serverEmbed = ServerEmbed (
guild . name ,
guild . id ,
roles . length ,
guild . memberCount ,
guild . emojis . cache . size ,
guild . stickers . cache . size ,
guild . description ,
guild . iconURL (),
guild . bannerURL (),
guild . ownerId ,
formattedCreatedAt ,
features ,
channels
);
Fun & Utility Embeds
// Coinflip result
const { CoinflipEmbed } = require ( './utils/embeds' );
const coinEmbed = CoinflipEmbed ( 'Heads' ); // or 'Tails'
// Magic 8-ball
const { BallEmbed } = require ( './utils/embeds' );
const ballEmbed = BallEmbed ( author , question , result );
// Leaderboard
const { Leaderboard } = require ( './utils/embeds' );
const leaderboardEmbed = Leaderboard (
'Top Responders' ,
'Users with the most bot replies' ,
fields // Array of { name, value, inline }
);
// Stats display
const { StatsEmbed } = require ( './utils/embeds' );
const statsEmbed = StatsEmbed (
serverCount ,
installCount ,
shardCount ,
uptime ,
memoryUsage ,
slashCommandsCount ,
cpuUsage ,
totalSessions ,
remainingSessions
);
All embeds automatically include the bot’s branding (footer icon and text) and use the consistent color scheme from utils/constants.js.
reply.js
Handles automatic reply functionality with database integration.
Location : utils/reply.js
const replyToUser = require ( './utils/reply' );
// Usage in messageCreate event
await replyToUser ( message );
Functionality :
Retrieves random phrase from server database
Updates user leaderboard statistics
Sends reply with allowedMentions: { repliedUser: false }
Implementation :
module . exports = async ( message ) => {
const serverId = message . guild ? message . guild . id : "global" ;
const userTag = message . author . tag ;
const userID = message . author . id ;
const db = initializeDatabase ( serverId );
try {
const phrases = await getPhrases ( db );
if ( phrases . length > 0 ) {
const randomIndex = Math . floor ( Math . random () * phrases . length );
const randomPhrase = phrases [ randomIndex ];
// Update leaderboard
updateLeaderboard ( userTag , userID );
// Send reply
await message . reply ({
content: randomPhrase ,
allowedMentions: { repliedUser: false },
});
}
} catch ( error ) {
Error ( `Error replying to user: ${ error . message } ` );
} finally {
db . close ();
}
};
setPresence.js
Dynamically updates bot presence with statistics.
Location : utils/setPresence.js
const setPresence = require ( './utils/setPresence' );
// Update presence every 15 seconds
setInterval (() => {
setPresence ( client );
}, 15000 );
Features :
Rotates between displaying total replies and unique users
Queries all leaderboard tables for accurate stats
Uses custom browser identifier for client type
module . exports = async ( client ) => {
const activities = [
` ${ totalReplies } replies` ,
` ${ uniqueUsers . size } users`
];
client . user . setPresence ({
activities: [{
name: activities [ activityIndex ],
type: 4 // Custom status
}],
status: "online"
});
activityIndex = ( activityIndex + 1 ) % activities . length ;
};
Database Utilities
getSettings.js
Retrieves server-specific configuration from SQLite.
Location : utils/getSettings.js
const getSettings = require ( './utils/getSettings' );
const settings = await getSettings ( serverId , client );
// Returns:
// {
// replyChannels: [{ id: '123', chance: 6 }],
// trustedRoles: ['456', '789'],
// phrases: ['Hello!', 'Hi there!', 'Hey!']
// }
Database Tables :
replyChannels - Channels where auto-reply is enabled with chance values
trustedRoles - Roles with trusted permissions
phrases - Custom reply phrases for the server
updateLeaderboard.js
Tracks user reply statistics.
Location : utils/updateLeaderboard.js
const updateLeaderboard = require ( './utils/updateLeaderboard' );
// Increment reply count for user
updateLeaderboard ( userTag , userID );
Database Schema :
CREATE TABLE IF NOT EXISTS current (
username TEXT ,
userID TEXT PRIMARY KEY ,
replies INTEGER DEFAULT 0 ,
groups TEXT
)
Behavior :
Creates new user entry if not exists
Increments reply count by 1
Updates username if changed
getLeaderboards.js
Initializes and verifies leaderboard database.
Location : utils/getLeaderboards.js
const getLeaderboards = require ( './utils/getLeaderboards' );
// Initialize on bot startup
getLeaderboards ();
Command Utilities
registerCommands.js
Registers slash commands and context menu commands with Discord.
Location : utils/registerCommands.js
const { registerCommands } = require ( './utils/registerCommands' );
// Register all commands (called in ready event)
await registerCommands ( client );
Features :
Discovers commands from commands/slash/ and commands/context/
Registers with Discord REST API
Saves command IDs to data/bot/commands.json
Provides command count and status
Output :
slash ┓
┣ ping
┣ help
┣ stats
┗ settings
context ┓
┗ User Info
Successfully registered application commands. Total commands: 5
Content Processing
scanImage.js
Scans images for NSFW content using Clarifai API.
Location : utils/scanImage.js
const { scanImage } = require ( './utils/scanImage' );
// Returns true if NSFW score > 0.5
const isNSFW = await scanImage ( imageURL );
if ( isNSFW ) {
await message . delete ();
await message . channel . send ( 'NSFW content detected and removed.' );
}
Requirements :
CLARIFAI_PAT environment variable
Clarifai API access
Configuration :
const modelId = 'nsfw-recognition' ;
const threshold = 0.5 ; // 50% confidence
Helper Utilities
constants.js
Centralized constants and configuration values.
Location : utils/constants.js
const { COLORS , EMOJIS , LINKS , TEXT } = require ( './utils/constants' );
// Color codes for embeds
COLORS . default // '#2b2d31'
COLORS . blurple // '#5865F2'
COLORS . error // '#cc0000'
COLORS . done // '#00cc00'
COLORS . twitch // '#9146FF'
// Custom emojis
EMOJIS . ico_checkmark // <:ico_checkmark:1332185724218721875>
EMOJIS . ico_x // <:ico_x:1332185757799944225>
EMOJIS . ico_loading // <:ico_loading:1332185739114450957>
EMOJIS . ico_user // <:ico_user:1332185755484684308>
// Links and URLs
LINKS . server // Discord server invite
LINKS . github // GitHub repository
LINKS . brand // Bot avatar URL
// Bot information
TEXT . brand // 'AutoResponse'
TEXT . appid // Bot application ID
TEXT . ownerid // Owner user ID
Over 80 Custom Emojis The constants file includes IDs for 80+ custom emojis including Discord badges, icons, and bot-specific graphics.
markdown.js
Markdown and formatting utilities.
Location : utils/markdown.js
const { codeblock } = require ( './utils/markdown' );
// Create formatted code block
const formatted = codeblock ( 'javascript' , [
'const x = 1;' ,
'console.log(x);'
]);
ansi.js
ANSI color formatting for code blocks.
Location : utils/ansi.js
const { format } = require ( './utils/ansi' );
// Format text with ANSI color codes
const colored = format ( 'text' , 'r' ); // red
const colored = format ( 'text' , 'g' ); // green
const colored = format ( 'text' , 'm' ); // magenta
Email Utilities
sendEmail.js
Sends error notifications via email.
Location : utils/sendEmail.js
const { sendEmail } = require ( './utils/sendEmail' );
// Send error notification
await sendEmail ( 'Event Name' , error . stack );
Used in :
Error event handlers
Critical command failures
System-level issues
replyCooldowns.js
Initialize and manage reply cooldown tables per server.
Location : utils/replyCooldowns.js
const sqlite3 = require ( 'sqlite3' ). verbose ();
const path = require ( 'path' );
function initializeReplyCooldownTable ( serverId ) {
replyCooldownsDb . run (
`CREATE TABLE IF NOT EXISTS ${ serverId } (channelId TEXT PRIMARY KEY, timeRemaining INTEGER)` ,
( err ) => {
if ( err ) {
Error ( `Error creating table for server ${ serverId } : ${ err . message } ` );
}
}
);
}
Database : data/ReplyCooldowns.db with per-server tables
This utility is used internally by the messageCreate event to manage cooldowns after auto-replies are sent.
updateEmojis.js
Manage Discord application emojis (upload, delete, update constants).
Location : utils/updateEmojis.js
const { updateEmojis } = require ( './utils/updateEmojis' );
// Update all application emojis from data/bot/emojis/
await updateEmojis ();
Functionality :
Deletes all existing application emojis
Uploads new emojis from data/bot/emojis/ directory
Updates constants.js with new emoji IDs and markdown
Environment Variables :
APPID - Discord application ID
TOKEN - Bot token with emoji management permissions
This is an administrative utility typically called by the !update owner command. It requires application emoji management permissions.
updateLibraries.js
Check for and install npm package updates using npm-check-updates.
Location : utils/updateLibraries.js
const { updateLibraries } = require ( './utils/updateLibraries' );
// Update all npm dependencies
const result = await updateLibraries ();
console . log ( result ); // Returns update status or list of updated packages
Functionality :
Runs ncu -u to update package.json
Executes npm install to install updated packages
Returns formatted output showing updated packages
Returns :
"-# All libraries are up to date" if no updates
Formatted list of updated packages if changes were made
Requires npm-check-updates (ncu) to be installed globally or as a dev dependency.
Best Practices
Import What You Need Only import the specific functions you need to reduce memory usage: const { Error , Done } = require ( './utils/logging' );
Close Databases Always close database connections in finally blocks: try {
// DB operations
} finally {
db . close ();
}
Use Constants Reference centralized constants instead of hardcoding values: . setColor ( COLORS . default )
Handle Errors Wrap utility calls in try-catch and log failures: try {
await replyToUser ( message );
} catch ( error ) {
Error ( `Reply failed: ${ error . message } ` );
}
Utility Categories
logging.js - Console and database logging
ansi.js - Color formatting
embeds.js - Embed builders
reply.js - Auto-reply handler
setPresence.js - Bot status
registerCommands.js - Command registration
getSettings.js - Retrieve server config
updateLeaderboard.js - Track statistics
getLeaderboards.js - Initialize databases
replyCooldowns.js - Cooldown table management
scanImage.js - NSFW detection
markdown.js - Text formatting
constants.js - Centralized values
updateEmojis.js - Application emoji management
updateLibraries.js - Dependency updates
sendEmail.js - Error notifications
All utilities follow consistent error handling patterns and integrate with the logging system for easy debugging and monitoring.