-
Notifications
You must be signed in to change notification settings - Fork 7.4k
Expand file tree
/
Copy pathbot.js
More file actions
651 lines (554 loc) · 18.1 KB
/
Copy pathbot.js
File metadata and controls
651 lines (554 loc) · 18.1 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
import { logger } from '../utils/logger.js';
export const botConfig = {
// =========================
// BOT PRESENCE (what users see under the bot name)
// =========================
// `status` options:
// - "online" = green dot
// - "idle" = yellow moon
// - "dnd" = red do-not-disturb
// - "invisible" = appears offline
presence: {
// Current online state shown on Discord.
status: "online",
// Activity lines shown under the bot name.
// `type` number mapping from Discord:
// 0 = Playing
// 1 = Streaming
// 2 = Listening
// 3 = Watching
// 4 = Custom
// 5 = Competing
activities: [
{
name: "Custom Status", // required by Discord API, not shown in the client
state: "use /help ", // this is what people actually see
type: 4, // Custom
},
],
},
// =========================
// COMMAND BEHAVIOR
// =========================
commands: {
// Bot owner user IDs (comma-separated in OWNER_IDS env var).
// Owners can access owner/admin-level bot commands.
owners: process.env.OWNER_IDS?.split(",").map((id) => id.trim()).filter(Boolean) || [],
// Default wait time between command uses (in seconds).
defaultCooldown: 3,
// If true, old commands are removed before re-registering.
deleteCommands: false,
// Optional server ID retained for tutorial compatibility; not used for command registration.
testGuildId: process.env.TEST_GUILD_ID,
// When true (or MAINTENANCE_MODE=true), only bot owners can run commands.
maintenanceMode: process.env.MAINTENANCE_MODE === "true",
// Command prefix for text-based commands (e.g., "!" for "!ping").
// Supports both slash commands and prefix commands.
prefix: process.env.PREFIX || "!",
},
// =========================
// APPLICATIONS SYSTEM
// =========================
applications: {
// Default questions shown when someone fills out an application.
defaultQuestions: [
{ question: "What is your name?", required: true },
{ question: "How old are you?", required: true },
{ question: "Why do you want to join?", required: true },
],
// Embed colors by application status.
statusColors: {
pending: "#FFA500",
approved: "#00FF00",
denied: "#FF0000",
},
// How long users must wait before submitting another application (hours).
applicationCooldown: 24,
// Auto-delete denied applications after this many days.
deleteDeniedAfter: 7,
// Auto-delete approved applications after this many days.
deleteApprovedAfter: 30,
// Role IDs allowed to manage applications.
managerRoles: [], // Will be populated from environment or database
},
// =========================
// EMBED COLORS & BRANDING
// =========================
// IMPORTANT: This is the SINGLE SOURCE OF TRUTH for all bot colors
embeds: {
colors: {
// Main brand colors.
primary: "#336699",
secondary: "#2F3136",
// Standard status colors for success/error/warning/info messages.
success: "#57F287",
error: "#ED4245",
warning: "#FEE75C",
info: "#3498DB",
// Neutral utility colors.
light: "#FFFFFF",
dark: "#202225",
gray: "#99AAB5",
// Discord-style palette shortcuts.
blurple: "#5865F2",
green: "#57F287",
yellow: "#FEE75C",
fuchsia: "#EB459E",
red: "#ED4245",
black: "#000000",
// Feature-specific colors.
giveaway: {
active: "#57F287",
ended: "#ED4245",
},
ticket: {
open: "#57F287",
claimed: "#FAA61A",
closed: "#ED4245",
pending: "#99AAB5",
},
economy: "#F1C40F",
birthday: "#E91E63",
moderation: "#9B59B6",
// Ticket priority color mapping.
priority: {
none: "#95A5A6",
low: "#3498db",
medium: "#2ecc71",
high: "#f1c40f",
urgent: "#e74c3c",
},
},
footer: {
// Default footer text used in bot embeds.
text: "Titan Bot",
// Footer icon URL (null = no icon).
icon: null,
},
// Default thumbnail URL for embeds (null = no thumbnail).
thumbnail: null,
author: {
// Optional default embed author block.
name: null,
icon: null,
url: null,
},
},
// =========================
// ECONOMY SETTINGS
// =========================
economy: {
currency: {
// Currency display name.
name: "coins",
// Plural display name.
namePlural: "coins",
// Currency symbol shown in balances.
symbol: "$",
},
// Starting balance for new users.
startingBalance: 0,
// Maximum bank amount before upgrades (if upgrades are used).
baseBankCapacity: 100000,
// Daily reward amount.
dailyAmount: 100,
// Work command random payout range.
workMin: 10,
workMax: 100,
// Beg command random payout range.
begMin: 5,
begMax: 50,
// Command cooldowns (milliseconds).
cooldowns: {
daily: 24 * 60 * 60 * 1000,
work: 60 * 60 * 1000,
crime: 2 * 60 * 60 * 1000,
rob: 4 * 60 * 60 * 1000,
},
// Chance to succeed when robbing (0.4 = 40%).
robSuccessRate: 0.4,
// Jail time after failed rob (milliseconds).
// 3600000 = 1 hour.
robFailJailTime: 3600000,
},
// =========================
// SHOP SETTINGS
// =========================
// Add shop defaults here when needed.
shop: {
},
// =========================
// TICKET SYSTEM
// =========================
tickets: {
// Category ID where new tickets are created (null = no forced category).
defaultCategory: null,
// Role IDs allowed to manage/support tickets.
supportRoles: [],
// Priority options users/staff can assign.
priorities: {
none: {
emoji: "⚪",
color: "#95A5A6",
label: "None",
},
low: {
emoji: "🟢",
color: "#2ECC71",
label: "Low",
},
medium: {
emoji: "🟡",
color: "#F1C40F",
label: "Medium",
},
high: {
emoji: "🔴",
color: "#E74C3C",
label: "High",
},
urgent: {
emoji: "🚨",
color: "#E91E63",
label: "Urgent",
},
},
// Default priority for new tickets.
defaultPriority: "none",
// Category ID where closed tickets are archived.
archiveCategory: null,
// Channel ID where ticket logs are sent.
logChannel: null,
},
// =========================
// GIVEAWAY SETTINGS
// =========================
giveaways: {
// Default giveaway duration in milliseconds.
// 86400000 = 24 hours.
defaultDuration: 86400000,
// Allowed winner count range.
minimumWinners: 1,
maximumWinners: 10,
// Allowed giveaway duration range in milliseconds.
// 300000 = 5 minutes.
minimumDuration: 300000,
// 2592000000 = 30 days.
maximumDuration: 2592000000,
// Role IDs allowed to host giveaways.
allowedRoles: [],
// Role IDs that bypass giveaway restrictions.
bypassRoles: [],
},
// =========================
// BIRTHDAY SETTINGS
// =========================
birthday: {
// Role ID given to users on their birthday.
defaultRole: null,
// Channel ID where birthday announcements are posted.
announcementChannel: null,
// Timezone used to calculate birthday dates.
timezone: "UTC",
},
// =========================
// VERIFICATION SETTINGS
// =========================
verification: {
// Message shown when posting the verification panel.
defaultMessage: "Click the button below to verify yourself and gain access to the server!",
// Text on the verification button.
defaultButtonText: "Verify",
// Automatic verification behavior.
autoVerify: {
// How automatic verification decides who is auto-approved:
// - "none" = everyone is auto-verified immediately
// - "account_age" = account must be older than set days
// - "server_size" = auto-verify everyone only in smaller servers
defaultCriteria: "none",
// Days used when `defaultCriteria` is `account_age`.
defaultAccountAgeDays: 7,
// Member count threshold used when `defaultCriteria` is `server_size`.
// Example: 1000 means auto-verify if server has fewer than 1000 members.
serverSizeThreshold: 1000,
// Allowed safety limits for account-age requirements.
// 1 = minimum day, 365 = maximum days.
minAccountAge: 1,
maxAccountAge: 365,
// If true, user receives a DM after verification.
sendDMNotification: true,
// Human-readable descriptions for each criteria mode.
criteria: {
account_age: "Account must be older than specified days",
server_size: "All users if server has less than 1000 members",
none: "All users immediately"
}
},
// Minimum time between verification attempts (milliseconds).
// 5000 = 5 seconds.
verificationCooldown: 5000,
// Maximum failed attempts allowed inside the time window below.
maxVerificationAttempts: 3,
// Time window for counting attempts (milliseconds).
// 60000 = 1 minute.
attemptWindow: 60000,
// In-memory safety limits (helps avoid unbounded memory growth).
maxCooldownEntries: 10000,
maxAttemptEntries: 10000,
// Cleanup frequency for cooldown/attempt maps (milliseconds).
// 300000 = 5 minutes.
cooldownCleanupInterval: 300000,
// Maximum metadata payload size for audit entries (bytes).
maxAuditMetadataBytes: 4096,
// Maximum number of audit entries kept in memory.
maxInMemoryAuditEntries: 1000,
// If true, log every verification action.
logAllVerifications: true,
// If true, preserve verification audit history.
keepAuditTrail: true,
},
// =========================
// WELCOME / GOODBYE MESSAGES
// =========================
welcome: {
// Welcome template posted when a user joins.
// Placeholders: {user}, {server}, {memberCount}
defaultWelcomeMessage:
"Welcome {user} to {server}! We now have {memberCount} members!",
// Goodbye template posted when a user leaves.
// Placeholders: {user}, {memberCount}
defaultGoodbyeMessage:
"{user} has left the server. We now have {memberCount} members.",
// Channel ID for welcome messages.
defaultWelcomeChannel: null,
// Channel ID for goodbye messages.
defaultGoodbyeChannel: null,
},
// =========================
// COUNTER CHANNELS
// =========================
counters: {
defaults: {
// Default naming/description templates for counter entries.
name: "{name} Counter",
description: "Server {name} counter",
// Channel type used for counters (typically "voice").
type: "voice",
// Channel name format. `{count}` is replaced automatically.
channelName: "{name}-{count}",
},
permissions: {
// Default denied permissions for the counter channel.
deny: ["VIEW_CHANNEL"],
// Default allowed permissions for the counter channel.
allow: ["VIEW_CHANNEL", "CONNECT", "SPEAK"],
},
messages: {
// Default response messages for counter actions.
created: "✅ Created counter **{name}**",
deleted: "🗑️ Deleted counter **{name}**",
updated: "🔄 Updated counter **{name}**",
},
types: {
// Built-in counter types and how each count is calculated.
members: {
name: "👥 Members",
description: "Total members in the server",
getCount: (guild) => guild.memberCount.toString(),
},
bots: {
name: "🤖 Bots",
description: "Total bot accounts in the server",
getCount: (guild) =>
guild.members.cache.filter((m) => m.user.bot).size.toString(),
},
members_only: {
name: "👤 Humans",
description: "Total human members (non-bots)",
getCount: (guild) =>
guild.members.cache.filter((m) => !m.user.bot).size.toString(),
},
},
},
// =========================
// GENERIC BOT MESSAGES
// =========================
messages: {
noPermission: "You do not have permission to use this command.",
cooldownActive: "Please wait {time} before using this command again.",
errorOccurred: "An error occurred while executing this command.",
missingPermissions:
"I am missing required permissions to perform this action.",
commandDisabled: "This command has been disabled.",
maintenanceMode: "The bot is currently in maintenance mode.",
},
// =========================
// FEATURE TOGGLES
// =========================
// Set any feature to `false` to disable it globally.
features: {
// Core systems.
economy: true,
leveling: true,
moderation: true,
logging: true,
welcome: true,
// Community engagement systems.
tickets: true,
giveaways: true,
birthday: true,
counter: true,
// Security and self-service systems.
verification: true,
reactionRoles: true,
joinToCreate: true,
// Utility/quality-of-life modules.
voice: true,
search: true,
tools: true,
utility: true,
community: true,
fun: true,
music: true,
},
};
export function validateConfig(config) {
const errors = [];
if (process.env.NODE_ENV !== 'production') {
logger.debug('Environment variables check:');
logger.debug('DISCORD_TOKEN exists:', !!process.env.DISCORD_TOKEN);
logger.debug('TOKEN exists:', !!process.env.TOKEN);
logger.debug('CLIENT_ID exists:', !!process.env.CLIENT_ID);
logger.debug('GUILD_ID exists:', !!process.env.GUILD_ID);
logger.debug('POSTGRES_HOST exists:', !!process.env.POSTGRES_HOST);
logger.debug('NODE_ENV:', process.env.NODE_ENV);
}
if (!process.env.DISCORD_TOKEN && !process.env.TOKEN) {
errors.push("Bot token is required (DISCORD_TOKEN or TOKEN environment variable)");
}
if (!process.env.CLIENT_ID) {
errors.push("Client ID is required (CLIENT_ID environment variable)");
}
if (process.env.NODE_ENV === 'production') {
// A full connection URL (DATABASE_URL / POSTGRES_URL) satisfies all Postgres
// requirements, matching how src/config/database/postgres.js resolves the pool config.
const hasConnectionUrl = Boolean(process.env.POSTGRES_URL || process.env.DATABASE_URL);
if (!hasConnectionUrl) {
if (!process.env.POSTGRES_HOST) {
errors.push("PostgreSQL connection is required in production (set DATABASE_URL/POSTGRES_URL, or POSTGRES_HOST)");
}
if (!process.env.POSTGRES_USER) {
errors.push("PostgreSQL user is required in production (set DATABASE_URL/POSTGRES_URL, or POSTGRES_USER)");
}
if (!process.env.POSTGRES_PASSWORD) {
errors.push("PostgreSQL password is required in production (set DATABASE_URL/POSTGRES_URL, or POSTGRES_PASSWORD)");
}
}
}
return errors;
}
const configErrors = validateConfig(botConfig);
if (configErrors.length > 0) {
logger.error("Bot configuration errors:", configErrors.join("\n"));
if (process.env.NODE_ENV === "production") {
process.exit(1);
}
}
export const BotConfig = botConfig;
const COMMAND_CATEGORY_FEATURE_MAP = {
birthday: "birthday",
community: "community",
economy: "economy",
fun: "fun",
giveaway: "giveaways",
jointocreate: "joinToCreate",
leveling: "leveling",
logging: "logging",
moderation: "moderation",
music: "music",
reaction_roles: "reactionRoles",
search: "search",
serverstats: "counter",
ticket: "tickets",
tools: "tools",
utility: "utility",
verification: "verification",
welcome: "welcome",
};
function normalizeCategoryKey(category) {
return String(category || "").trim().toLowerCase().replace(/\s+/g, "_");
}
export function getCommandPrefix() {
return botConfig.commands?.prefix ?? "!";
}
export function getBotOwners() {
return (botConfig.commands?.owners ?? [])
.map((id) => String(id).trim())
.filter(Boolean);
}
export function isBotOwner(userId) {
if (!userId) {
return false;
}
return getBotOwners().includes(String(userId));
}
export function isMaintenanceMode() {
return botConfig.commands?.maintenanceMode === true;
}
export function getBotMessage(key, replacements = {}) {
let message = botConfig.messages?.[key] || key;
for (const [placeholder, value] of Object.entries(replacements)) {
message = message.replace(new RegExp(`\\{${placeholder}\\}`, "g"), String(value));
}
return message;
}
export function isFeatureEnabled(featureKey) {
if (!featureKey) {
return true;
}
return botConfig.features?.[featureKey] !== false;
}
export function isCommandCategoryEnabled(category) {
const normalized = normalizeCategoryKey(category);
if (!normalized || normalized === "core") {
return true;
}
const featureKey = COMMAND_CATEGORY_FEATURE_MAP[normalized];
if (!featureKey) {
return true;
}
return isFeatureEnabled(featureKey);
}
export function getApplicationStatusColor(status) {
const colors = botConfig.applications?.statusColors || {};
const hex = colors[status];
return hex ? getColor(hex) : getColor(status === "approved" ? "success" : status === "denied" ? "error" : "warning");
}
export function getDefaultApplicationQuestions() {
return (botConfig.applications?.defaultQuestions || []).map((entry) =>
typeof entry === "string" ? entry : entry.question,
).filter(Boolean);
}
export function getColor(path, fallback = "#99AAB5") {
if (typeof path === "number") return path;
if (typeof path === "string" && path.startsWith("#")) {
return parseInt(path.replace("#", ""), 16);
}
const result = path
.split(".")
.reduce(
(obj, key) => (obj && obj[key] !== undefined ? obj[key] : fallback),
botConfig.embeds.colors,
);
if (typeof result === "string" && result.startsWith("#")) {
return parseInt(result.replace("#", ""), 16);
}
return result;
}
export function getRandomColor() {
const colors = Object.values(botConfig.embeds.colors).flatMap((color) =>
typeof color === "string" ? color : Object.values(color),
);
return colors[Math.floor(Math.random() * colors.length)];
}
export default botConfig;