This repository was archived by the owner on Jan 17, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js
More file actions
236 lines (201 loc) · 7.82 KB
/
bot.js
File metadata and controls
236 lines (201 loc) · 7.82 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
require("dotenv").config();
require("module-alias/register");
const {
EmbedBuilder,
Colors,
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
} = require("discord.js");
const { BotClient } = require("@src/structures");
const { checkForUpdates } = require("@helpers/BotUtils");
const { initializeMongoose } = require("@src/database/mongoose");
const { validateConfiguration } = require("@helpers/Validator");
const loadSlashCommands = require("@helpers/SlashCommandLoader");
const fs = require("fs");
const path = require("path");
// Import functions from /functions/bot
const { startPresenceUpdater } = require("@functions/bot/presenceUpdater");
// Import extenders
require("@helpers/extenders/Message");
require("@helpers/extenders/Guild");
require("@helpers/extenders/GuildChannel");
const config = require("@root/config.js");
const { LOG_CHANNEL_ID } = config;
// Import counting message handler
const { countingMessageHandler } = require("@src/commands/fun/counting");
// Blacklist path
const blacklistPath = path.join(__dirname, "./database/blacklist.json");
// ✅ Ensure 'database' folder and blacklist.json file exist
const dbFolder = path.join(__dirname, "./database");
if (!fs.existsSync(dbFolder)) {
fs.mkdirSync(dbFolder);
console.log("✅ Created 'database' folder.");
}
if (!fs.existsSync(blacklistPath)) {
fs.writeFileSync(blacklistPath, JSON.stringify({ servers: [] }, null, 2));
console.log("✅ Created 'blacklist.json' file.");
}
validateConfiguration();
const client = new BotClient();
async function shutdown(signal) {
console.log(`Received ${signal}. Shutting down gracefully...`);
try {
if (client?.isReady()) {
const channel = await client.channels.fetch(LOG_CHANNEL_ID).catch(() => null);
if (channel) {
await channel.send("⚠️ Bot is shutting down...").catch(console.error);
}
await client.destroy();
console.log("[SHUTDOWN] Discord client destroyed.");
}
const mongoose = require("mongoose");
if (mongoose.connection.readyState === 1) {
await mongoose.connection.close();
console.log("[SHUTDOWN] Mongoose connection closed.");
}
console.log("✅ Graceful shutdown complete.");
process.exit(0);
} catch (err) {
console.error("❌ Error during shutdown:", err);
process.exit(1);
}
}
process.on("SIGINT", () => shutdown("SIGINT"));
process.on("SIGTERM", () => shutdown("SIGTERM"));
(async () => {
try {
await checkForUpdates();
// start the dashboard
if (client.config.DASHBOARD.enabled) {
client.logger.log("Launching dashboard");
try {
const { launch } = require("@root/dashboard/app");
// let the dashboard initialize the database
await launch(client);
} catch (ex) {
client.logger.error("Failed to launch dashboard", ex);
}
} else {
// initialize the database
await initializeMongoose();
}
await client.login(process.env.BOT_TOKEN);
client.once("ready", async () => {
client.logger.log(`✅ Logged in as ${client.user.tag}`);
const channel = await client.channels.fetch(LOG_CHANNEL_ID).catch(() => null);
if (channel) {
const embed = new EmbedBuilder()
.setColor(Colors.Green)
.setTitle("🟢 Bot Online")
.setDescription(`Logged in as \`${client.user.tag}\``)
.setFooter({ text: `Started at ${new Date().toLocaleString()}` });
await channel.send({ embeds: [embed] }).catch(console.error);
}
// Start the presence updater after a delay
setTimeout(() => startPresenceUpdater(client), 5000);
try {
const slashCommands = loadSlashCommands(client);
client.logger.log(`✅ Loaded ${slashCommands.length} slash commands.`);
await client.application.commands.set(slashCommands);
client.logger.log("✅ Slash commands registered.");
} catch (slashErr) {
client.logger.error("❌ Failed to register slash commands:", slashErr);
}
});
// Load bot systems
client.loadCommands("src/commands");
client.loadContexts("src/contexts");
client.loadEvents("src/events");
// Counting message handler
client.on("messageCreate", async (message) => {
try {
await countingMessageHandler(message);
} catch (err) {
client.logger.error("❌ Error in countingMessageHandler:", err);
}
});
// Guild Create Blacklist Handler
client.on("guildCreate", async (guild) => {
try {
const raw = fs.readFileSync(blacklistPath, "utf8");
const blacklist = JSON.parse(raw);
if (blacklist.servers.includes(guild.id)) {
client.logger.warn(
`🚫 Blacklisted server (${guild.name} | ${guild.id}) attempted to invite the bot.`
);
await guild.leave().catch((err) =>
client.logger.error("❌ Failed to leave blacklisted server:", err)
);
}
} catch (err) {
client.logger.error("❌ Error checking blacklist on guildCreate:", err);
}
});
// Guild Create Welcome Message with Support Server Button
client.on("guildCreate", async (guild) => {
try {
setTimeout(async () => {
const embed = new EmbedBuilder()
.setTitle("🤖 Thanks for adding TACT!")
.setColor(Colors.Green)
.setDescription(
`Hello **${guild.name}**! 👋\n\n` +
`I'm **TACT**, your all-in-one Discord bot for moderation, utilities, fun, and more!\n\n` +
`📌 **Changelogs:** Use \`/changelogs\` to see the latest updates.\n` +
`📚 **Commands:** Use \`/help\` to view all available commands.\n` +
`ℹ️ **Bot Info:** Use \`/botinfo\` to learn more about what I can do.\n` +
`👨💻 **Developer Info:** Use \`/devinfo\` to find out who's behind TACT.\n\n`
)
.setFooter({ text: "Welcome aboard!" })
.setTimestamp();
const dashboardButton = new ButtonBuilder()
.setLabel("Open Dashboard")
.setStyle(ButtonStyle.Link)
.setURL("https://tact.techoraye.com/");
const supportButton = new ButtonBuilder()
.setLabel("Join Support Server")
.setStyle(ButtonStyle.Link)
.setURL("https://discord.gg/M7yyGfKdKx");
const row = new ActionRowBuilder().addComponents(dashboardButton, supportButton);
let targetChannel = guild.systemChannel;
if (
!targetChannel ||
!targetChannel.permissionsFor(guild.members.me).has("SendMessages")
) {
targetChannel = guild.channels.cache.find(
(ch) =>
ch.isTextBased() &&
ch.permissionsFor(guild.members.me).has("SendMessages") &&
!ch.isThread()
);
}
if (targetChannel) {
await targetChannel.send({ embeds: [embed], components: [row] });
client.logger.log(`✅ Sent join message in ${guild.name}`);
} else {
client.logger.warn(
`⚠️ Could not find a suitable channel in ${guild.name} to send the join message.`
);
}
}, 3000);
} catch (err) {
client.logger.error("❌ Error sending welcome message on guildCreate:", err);
}
});
} catch (err) {
console.error("❌ Bot failed to start:", err);
if (client?.isReady()) {
const channel = await client.channels.fetch(LOG_CHANNEL_ID).catch(() => null);
if (channel) {
const embed = new EmbedBuilder()
.setColor(Colors.Red)
.setTitle("🔴 Bot Initialization Failed")
.setDescription(`Error: \`${err.message || err}\``)
.setFooter({ text: `Time: ${new Date().toLocaleString()}` });
await channel.send({ embeds: [embed] }).catch(console.error);
}
}
process.exit(1);
}
})();