-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js
More file actions
337 lines (294 loc) · 12.6 KB
/
bot.js
File metadata and controls
337 lines (294 loc) · 12.6 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
/*
* Copyright (c) 2026 zeroXmrcl (aka 0xmrcl)
*
* Licensed under a custom license.
* Use is permitted for private and internal commercial purposes only.
* Selling, sublicensing, or claiming this work as your own is prohibited.
* See the LICENSE file for full terms.
*/
import 'dotenv/config';
import pkg from './package.json' with { type: 'json' };
import {
Client,
GatewayIntentBits,
REST,
Routes,
Events,
ActivityType,
WebhookClient,
EmbedBuilder
} from 'discord.js';
import fs from 'fs';
import path from 'path';
import url from 'url';
const envBool = (v, def = false) =>
v == null ? def : ['1','true','yes','on'].includes(String(v).toLowerCase());
const envStr = (v, def = '') =>
(v == null || v === '') ? def : String(v);
// --- CONFIG ---
const TOKEN = process.env.DISCORD_TOKEN;
const CLIENT_ID = process.env.DISCORD_CLIENT_ID;
const __filename = url.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const commandsDir = path.join(__dirname, 'commands');
const settings = {
activity: {
enabled: envBool(process.env.PRESENCE_ENABLE, false),
status: envStr(process.env.PRESENCE_STATUS, 'online'),
activityType: envStr(process.env.PRESENCE_ACTIVITY, 'Custom'),
name: envStr(process.env.PRESENCE_NAME, `Released v${pkg.version}!`),
url: envStr(process.env.PRESENCE_STREAMING_URL, ''),
},
loggingWebhook: {
enabled: envBool(process.env.WEBHOOK_ENABLE, false),
webhookURL: envStr(process.env.WEBHOOK_URL, ''),
name: envStr(process.env.WEBHOOK_NAME, 'Bot Log'),
avatarURL: envStr(process.env.WEBHOOK_AVATAR_URL, ''),
footer: envStr(process.env.WEBHOOK_FOOTER, 'Client made by 0xmrcl'),
},
miscellaneous: {
showWelcome: envBool(process.env.SHOW_WELCOME, true),
activateFeatures: envBool(process.env.FEATURES_ENABLE, false),
},
version: pkg.version,
};
// -- CONFIG END ---
export const logColors = {
INFO: '\x1b[36m',
ERROR: '\x1b[31m',
WARN: '\x1b[33m',
RESET: '\x1b[0m'
};
process.on('unhandledRejection', (err) => {
console.error(`${logColors.ERROR}[ ERROR ]${logColors.RESET} unhandledRejection:`, err);
});
process.on('uncaughtException', (err) => {
console.error(`${logColors.ERROR}[ ERROR ]${logColors.RESET} uncaughtException:`, err);
process.exit(1);
});
function getActivityType(typeString) {
const types = {
'Playing': ActivityType.Playing,
'Streaming': ActivityType.Streaming,
'Listening': ActivityType.Listening,
'Watching': ActivityType.Watching,
'Competing': ActivityType.Competing,
'Custom': ActivityType.Custom
};
return types[typeString] || ActivityType.Playing;
}
function getActivityTypeName(typeNumber) {
const types = {
[ActivityType.Playing]: 'Playing',
[ActivityType.Streaming]: 'Streaming',
[ActivityType.Listening]: 'Listening',
[ActivityType.Watching]: 'Watching',
[ActivityType.Competing]: 'Competing',
[ActivityType.Custom]: 'Custom'
};
return types[typeNumber] || 'Playing';
}
if (settings.miscellaneous.showWelcome) {
console.log(`${logColors.INFO}------------- MSG -------------${logColors.RESET}`);
console.log(`${logColors.INFO}[ INFO ]${logColors.RESET} Welcome!`)
console.log(`${logColors.INFO}[ INFO ]${logColors.RESET} Made by 0xMRCL.`);
console.log(`${logColors.INFO}[ INFO ]${logColors.RESET} Running version ${settings.version}.`);
console.log(`${logColors.INFO}------------- END -------------${logColors.RESET}`);
}
if (!TOKEN || !CLIENT_ID) {
console.error(`${logColors.ERROR}[ ERROR ]${logColors.RESET} Environment missing:`);
if (!TOKEN) {
console.error(`${logColors.ERROR}[ ERROR ]${logColors.RESET} DISCORD_TOKEN missing.`);
}
if (!CLIENT_ID) {
console.error(`${logColors.ERROR}[ ERROR ]${logColors.RESET} DISCORD_CLIENT_ID missing.`);
}
process.exit(1);
}
// --- Client ---
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildVoiceStates
]
});
let logger = null;
if (settings.loggingWebhook.enabled && settings.loggingWebhook.webhookURL) {
console.log(`${logColors.INFO}[ INFO ]${logColors.RESET} WebLogging enabled.`);
logger = new WebhookClient({ url: settings.loggingWebhook.webhookURL });
} else {
console.log(`${logColors.INFO}[ INFO ]${logColors.RESET} WebLogging disabled.`);
}
async function logToWebhook(options = {}) {
if (!logger) return;
const embed = new EmbedBuilder()
.setColor(options.color || 0x0099FF) // Default blue
.setTitle(options.title || 'System Notification')
.setDescription(options.description || 'No details provided.')
.setTimestamp()
.setFooter({text: settings.loggingWebhook.footer || 'Default'});
if (options.fields) embed.addFields(options.fields);
try {
await logger.send({
embeds: [embed],
username: settings.loggingWebhook.name || 'Default',
avatarURL: settings.loggingWebhook.avatarURL,
});
} catch (err) {
console.error(`${logColors.ERROR}[ ERROR ]${logColors.RESET} Webhook failed: ${err.message}`);
}
}
// Attach to the client so commands can use it through interaction.client.logToWebhook()
client.logToWebhook = logToWebhook;
// Command Registry
async function registerCommands() {
client.commands = new Map();
// File locator
if (fs.existsSync(commandsDir)) {
const files = fs.readdirSync(commandsDir).filter(f => f.endsWith('.js'));
for (const file of files) {
const mod = await import(new URL(`./commands/${file}`, import.meta.url));
const command = mod.default ?? mod; // fallback if no default export
if (!command?.data?.name || typeof command.execute !== 'function') {
console.warn(`${logColors.WARN}[ WARN ]${logColors.RESET} Skipping ${file}: expected { data: { name }, execute() }`);
continue;
}
client.commands.set(command.data.name, command);
}
} else {
console.warn(`${logColors.WARN}[ WARN ]${logColors.RESET} ${commandsDir} is not existing. Attempting to create it...`);
try {
fs.mkdirSync(commandsDir);
console.log(`${logColors.INFO}[ INFO ]${logColors.RESET} ${commandsDir} created. Add your commands to it and restart the bot.`);
} catch (error) {
console.error(`${logColors.ERROR}[ ERROR ]${logColors.RESET} Failed to create: ${error.message}`);
return;
}
}
if (client.commands.size === 0) {
console.warn(`${logColors.WARN}[ WARN ]${logColors.RESET} No commands found in ${commandsDir}.`);
return;
}
console.log(`${logColors.INFO}[ INFO ]${logColors.RESET} ${client.commands.size} commands loaded: ${[...client.commands.keys()].join(', ') || '–'}`);
}
async function registerFeatures() {
const featuresPath = path.join(__dirname, 'features');
if (fs.existsSync(featuresPath)) {
const featureFiles = fs.readdirSync(featuresPath).filter(file => file.endsWith('.js'));
for (const file of featureFiles) {
const mod = await import(new URL(`./features/${file}`, import.meta.url));
const feature = mod.default ?? mod;
if (typeof feature === 'function') {
feature(client);
console.log(`${logColors.INFO}[ INFO ]${logColors.RESET} Loaded feature: ${file}`);
}
}
}
}
// Presence Registry
client.once(Events.ClientReady, async (c) => {
console.log(`${logColors.INFO}[ INFO ]${logColors.RESET} Logged in as ${c.user.tag}`);
// Set bot presence from settings
if (settings.activity.enabled) {
const presence = {
activities: [{
name: settings.activity.name,
type: getActivityType(settings.activity.activityType)
}],
status: settings.activity.status || 'online'
};
// if Streaming > Check URL
if (settings.activity.activityType === 'Streaming' && settings.activity.url) {
console.log(`${logColors.INFO}[ INFO ]${logColors.RESET} Using Streaming presence. ${settings.activity.url}`)
presence.activities[0].url = settings.activity.url;
} else if (settings.activity.activityType === 'Streaming') {
console.log(`${logColors.WARN}[ WARN ]${logColors.RESET} Tried to use streaming presence but no URL provided. Presence not set.`)
presence.activities = [];
}
// Set presence
c.user.setPresence(presence);
// Display Status set
if (presence.activities.length > 0) {
console.log(`${logColors.INFO}[ INFO ]${logColors.RESET} Status set: ${presence.status}; ${getActivityTypeName(presence.activities[0].type)}; ${presence.activities[0].name}`);
} else {
console.log(`${logColors.INFO}[ INFO ]${logColors.RESET} Status set: ${presence.status}; No activity`);
}
} else if (!settings.activity.enabled) {
console.log(`${logColors.INFO}[ INFO ]${logColors.RESET} Presence disabled.`)
}
// Transmitter
// Guard
if (!client.commands || client.commands.size === 0) {
console.log(`${logColors.WARN}[ WARN ]${logColors.RESET} No commands loaded; skipping global registration.`);
return;
} // Transmit
const rest = new REST({version: '10'}).setToken(TOKEN);
try {
const payload = [...client.commands.values()].map(cmd => cmd.data);
console.log(`${logColors.INFO}[ INFO ]${logColors.RESET} Registering global commands...`);
await rest.put(Routes.applicationCommands(CLIENT_ID), {body: payload});
console.log(`${logColors.INFO}[ INFO ]${logColors.RESET} Successfully registered!`);
} catch (err) {
console.error(`${logColors.ERROR}[ ERROR ]${logColors.RESET} Registry ERR (Transmitter):`, err);
}
});
// On command execution
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return;
// Access command
const command = client.commands?.get(interaction.commandName);
if (!command) {
console.warn(`${logColors.WARN}[ WARN ]${logColors.RESET} Unknown command: ${interaction.commandName}`);
try {
await interaction.reply({content: 'Unknown command.', ephemeral: true});
} catch {
console.log(`${logColors.ERROR}[ ERROR ]${logColors.RESET} Failed to reply 'unknown command' message.`)
}
return;
}
// generate logging Identifier
const logId = `Command ${interaction.id.slice(-5)}`;
const timeId = `Executed ${interaction.id.slice(-5)} in`;
const optionsText = interaction.options?.data?.length
? interaction.options.data.map(o => String(o.value)).join(', ')
: '–';
try {
console.log(`${logColors.INFO}----------- ${logId} S -----------${logColors.RESET}`);
console.time(timeId);
console.log(`Command : /${interaction.commandName}`);
console.log(`Options : ${optionsText}`);
console.log(`User : ${interaction.user.username} (${interaction.user.id})`);
console.log(`Guild : ${interaction.guild?.name ?? 'DM'}`);
await command.execute(interaction);
} catch (err) {
console.error(`${logColors.ERROR}[ ERROR ]${logId}:${logColors.RESET}`, err);
if (interaction.deferred || interaction.replied) {
await interaction.editReply('There was an error executing this command.');
} else {
await interaction.reply({content: 'There was an error executing this command.', ephemeral: true});
}
} finally {
console.timeEnd(timeId);
console.log(`${logColors.INFO}----------- ${logId} E -----------${logColors.RESET}`);
// Log to Webhook
await client.logToWebhook({
title: 'Command Execution Log',
color: 0x57F287,
fields: [
{name: 'Command', value: `\`/${interaction.commandName}\``, inline: true},
{name: 'Options', value: optionsText, inline: true},
{name: 'User', value: `${interaction.user.username} (\`${interaction.user.id}\`)`, inline: true},
{name: 'Location', value: interaction.guild ? interaction.guild.name : 'DM', inline: true},
]
});
}
});
client.on('error', (e) => console.error('Client error:', e));
async function start() {
await registerCommands();
if (settings.miscellaneous.activateFeatures){
await registerFeatures();
}
await client.login(TOKEN);
}
start();