djs-builder 0.4.6 → 0.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/.tsbuildinfo +1 -1
  2. package/dist/discord/events-handler/events loader.d.ts +3 -0
  3. package/dist/discord/events-handler/events loader.d.ts.map +1 -0
  4. package/dist/discord/events-handler/events loader.js +20 -0
  5. package/dist/discord/events-handler/events loader.js.map +1 -0
  6. package/dist/discord/events-handler/events.d.ts.map +1 -1
  7. package/dist/discord/events-handler/events.js +14 -11
  8. package/dist/discord/events-handler/events.js.map +1 -1
  9. package/dist/discord/events-handler/prefix-register.d.ts.map +1 -1
  10. package/dist/discord/events-handler/prefix-register.js +7 -4
  11. package/dist/discord/events-handler/prefix-register.js.map +1 -1
  12. package/dist/discord/events-handler/prefixLoader.d.ts +1 -14
  13. package/dist/discord/events-handler/prefixLoader.d.ts.map +1 -1
  14. package/dist/discord/events-handler/prefixLoader.js +12 -91
  15. package/dist/discord/events-handler/prefixLoader.js.map +1 -1
  16. package/dist/discord/events-handler/slash-register.d.ts.map +1 -1
  17. package/dist/discord/events-handler/slash-register.js +14 -7
  18. package/dist/discord/events-handler/slash-register.js.map +1 -1
  19. package/dist/discord/events-handler/slash-responder.d.ts.map +1 -1
  20. package/dist/discord/events-handler/slash-responder.js +7 -5
  21. package/dist/discord/events-handler/slash-responder.js.map +1 -1
  22. package/dist/discord/events-handler/slashLoader.d.ts +1 -2
  23. package/dist/discord/events-handler/slashLoader.d.ts.map +1 -1
  24. package/dist/discord/events-handler/slashLoader.js +10 -79
  25. package/dist/discord/events-handler/slashLoader.js.map +1 -1
  26. package/dist/discord/functions/logger.d.ts +5 -0
  27. package/dist/discord/functions/logger.d.ts.map +1 -0
  28. package/dist/discord/functions/logger.js +38 -0
  29. package/dist/discord/functions/logger.js.map +1 -0
  30. package/lib/discord/events-handler/events loader.ts +22 -0
  31. package/lib/discord/events-handler/events.ts +19 -16
  32. package/lib/discord/events-handler/prefix-register.ts +8 -4
  33. package/lib/discord/events-handler/prefixLoader.ts +15 -74
  34. package/lib/discord/events-handler/slash-register.ts +14 -8
  35. package/lib/discord/events-handler/slash-responder.ts +27 -25
  36. package/lib/discord/events-handler/slashLoader.ts +10 -76
  37. package/lib/discord/functions/logger.ts +39 -0
  38. package/package.json +1 -1
@@ -2,6 +2,7 @@ import { Collection } from 'discord.js';
2
2
  import { promises as fsPromises } from 'fs';
3
3
  import { join, resolve } from 'path';
4
4
  import { Command } from '../types/utils';
5
+ import { logSuccess, logError, logInfo } from '../functions/logger';
5
6
 
6
7
  export const commands = new Collection<string, Command>();
7
8
  export const aliases = new Collection<string, string>();
@@ -56,20 +57,23 @@ export async function readCommands(client: any, prefix: { path: string }): Promi
56
57
  developer: defaultCommand.developer,
57
58
  owner: defaultCommand.owner,
58
59
  });
60
+
61
+ logSuccess(`Loaded command: ${defaultCommand.name}`);
59
62
  }
60
63
  } catch (error: any) {
61
- console.error(`Error in file: ${filePath}`);
62
- console.error(error.message);
64
+ logError(`Error in file: ${filePath}`);
65
+ logError(error.message);
63
66
  }
64
67
  }
65
68
  }
66
69
 
67
70
  client.prefixCommands = commandDetails;
68
71
  client.prefixSize = commandDetails.length;
72
+ logSuccess(`Successfully loaded ${commandDetails.length} commands.`);
69
73
  return commandDetails;
70
74
  } catch (error: any) {
71
- console.error(`⚠️ Error reading directory: ${prefix.path}`);
72
- console.error(error.message);
75
+ logError(`Error reading directory: ${prefix.path}`);
76
+ logError(error.message);
73
77
  return [];
74
78
  }
75
79
  }
@@ -1,79 +1,20 @@
1
- import { Collection } from 'discord.js';
2
- import { promises as fsPromises } from 'fs';
3
- import { join, resolve, basename } from 'path';
4
- import { Command } from '../types/utils';
5
- import { botData } from './login';
1
+ import { logSuccess, logError, logInfo } from '../functions/logger';
2
+ import { commands, aliases, commandNames, readCommands } from './prefix-register';
6
3
 
7
- export const commands = new Collection<string, Command>();
8
- export const aliases = new Collection<string, string>();
9
- export const commandNames = new Set<string>();
4
+ export async function prefixLoader(client: any, prefixPath: string) {
5
+ commands.clear();
6
+ aliases.clear();
7
+ commandNames.clear();
10
8
 
11
- export async function prefixLoader(client: any, basePath: string = ''): Promise<Array<{ name: string; usage: string | undefined; description: string | undefined; aliases: string[] | undefined; cooldown: number | undefined; developer: boolean | undefined; owner: boolean | undefined }>> {
12
- const commandDetails: Array<{ name: string; usage: string | undefined; description: string | undefined; aliases: string[] | undefined; cooldown: number | undefined; developer: boolean | undefined; owner: boolean | undefined }> = [];
13
- const prefixPath = botData.get('prefixPath') as string;
14
- const resolvedBasePath = resolve(process.cwd(), prefixPath);
15
-
16
- try {
17
- const resolvedPath = resolve(resolvedBasePath, basePath);
18
- await fsPromises.access(resolvedPath);
19
- const files = await fsPromises.readdir(resolvedPath, { withFileTypes: true });
20
-
21
- for (const file of files) {
22
- const filePath = join(resolvedPath, file.name);
23
-
24
- if (file.isDirectory()) {
25
- if (basename(filePath) !== basename(__filename)) { // Avoid processing the current file
26
- const subCommandDetails = await prefixLoader(client, join(basePath, file.name));
27
- commandDetails.push(...subCommandDetails);
28
- }
29
- } else if (file.isFile()) {
30
- try {
31
- const commandModule = await import(filePath);
32
- const command: Command = commandModule.default || commandModule;
33
-
34
- if (command && (command.execute || command.run)) {
35
- const defaultCommand: Command = {
36
- description: "No description provided.",
37
- cooldown: undefined,
38
- usage: "No usage information provided.",
39
- aliases: [],
40
- developer: false,
41
- owner: false,
42
- ...command
43
- };
9
+ logInfo(`Reloading prefix commands from ${prefixPath}`);
44
10
 
45
- commands.set(defaultCommand.name, defaultCommand);
46
- commandNames.add(defaultCommand.name);
47
-
48
- if (defaultCommand.aliases && Array.isArray(defaultCommand.aliases)) {
49
- defaultCommand.aliases.forEach(alias => {
50
- aliases.set(alias, defaultCommand.name);
51
- commandNames.add(alias);
52
- });
53
- }
54
-
55
- commandDetails.push({
56
- name: defaultCommand.name,
57
- usage: defaultCommand.usage || 'No usage information provided.',
58
- description: defaultCommand.description || 'No description provided.',
59
- aliases: defaultCommand.aliases || [],
60
- cooldown: defaultCommand.cooldown,
61
- developer: defaultCommand.developer,
62
- owner: defaultCommand.owner,
63
- });
64
- }
65
- } catch (error: any) {
66
- console.error(`Error in file: ${filePath}`);
67
- console.error(error.message);
68
- }
69
- }
70
- }
71
- client.prefixCommands = commandDetails;
72
- client.prefixSize = commandDetails.length;
73
- return commandDetails;
11
+ try {
12
+ const newCommandDetails = await readCommands(client, { path: prefixPath });
13
+ logSuccess(`Successfully reloaded ${newCommandDetails.length} prefix commands.`);
14
+ return true
74
15
  } catch (error: any) {
75
- console.error(`⚠️ Error reading directory: ${prefixPath}`);
76
- console.error(error.message);
77
- return [];
16
+ logError(`Error reloading prefix commands: ${error.message}`);
17
+ return false
18
+
78
19
  }
79
- }
20
+ }
@@ -4,11 +4,11 @@ import { Routes } from 'discord-api-types/v10';
4
4
  import { readdir } from 'fs/promises';
5
5
  import path from 'path';
6
6
  import { SlashOptions } from '../types/starter';
7
+ import { logSuccess, logError, logInfo } from '../functions/logger';
7
8
 
8
9
  export async function registerSlashCommands(client: any, token: string, slash: SlashOptions): Promise<Collection<string, any>> {
9
-
10
10
  if (!token) {
11
- throw new Error("⚠️ \x1b[33m%sPlease provide valid bot token to register slash commands.\x1b[0m");
11
+ throw new Error("⚠️ Please provide valid bot token to register slash commands.");
12
12
  }
13
13
 
14
14
  const slashCommands = new Collection<string, any>();
@@ -31,10 +31,11 @@ export async function registerSlashCommands(client: any, token: string, slash: S
31
31
  command.data.cooldown = command.cooldown || 0;
32
32
  }
33
33
  slashCommands.set(command.data.name, command);
34
+ logInfo(`Loaded command: ${command.data.name}`);
34
35
  }
35
36
  } catch (error: any) {
36
- console.error(`⚠️ Error in file: ${path.join(folderPath, file)}`);
37
- console.error(error.message);
37
+ logError(`Error in file: ${path.join(folderPath, file)}`);
38
+ logError(error.message);
38
39
  }
39
40
  }
40
41
  } else {
@@ -45,10 +46,11 @@ export async function registerSlashCommands(client: any, token: string, slash: S
45
46
  command.data.cooldown = command.cooldown || 0;
46
47
  }
47
48
  slashCommands.set(command.data.name, command);
49
+ logInfo(`Loaded command: ${command.data.name}`);
48
50
  }
49
51
  } catch (error: any) {
50
- console.error(`⚠️ Error in file: ${path.join(resolvedPath, dirent.name)}`);
51
- console.error(error.message);
52
+ logError(`Error in file: ${path.join(resolvedPath, dirent.name)}`);
53
+ logError(error.message);
52
54
  }
53
55
  }
54
56
  }
@@ -56,20 +58,24 @@ export async function registerSlashCommands(client: any, token: string, slash: S
56
58
  if (slash.global && !slash.serverId) {
57
59
  const slashCommandArray = Array.from(slashCommands.values()).map(command => command.data.toJSON());
58
60
  await rest.put(Routes.applicationCommands((client.user?.id || '')), { body: slashCommandArray, headers: { Authorization: `Bot ${token}` } });
61
+ logSuccess('Successfully registered global slash commands.');
59
62
  } else if (!slash.global && slash.serverId) {
60
63
  const guild = client.guilds.cache.get(slash.serverId) as Guild | undefined;
61
64
  if (guild) {
62
65
  const slashCommandArray = Array.from(slashCommands.values()).map(command => command.data.toJSON());
63
66
  await rest.put(Routes.applicationGuildCommands((client.user?.id || ''), guild.id), { body: slashCommandArray, headers: { Authorization: `Bot ${token}` } });
67
+ logSuccess(`Successfully registered guild slash commands for server ID: ${slash.serverId}`);
64
68
  } else {
65
- console.error(`⚠️ Guild with ID ${slash.serverId} not found.`);
69
+ logError(`Guild with ID ${slash.serverId} not found.`);
66
70
  }
67
71
  } else {
68
72
  const slashCommandArray = Array.from(slashCommands.values()).map(command => command.data.toJSON());
69
73
  await rest.put(Routes.applicationCommands((client.user?.id || '')), { body: slashCommandArray, headers: { Authorization: `Bot ${token}` } });
74
+ logSuccess('Successfully registered global slash commands.');
70
75
  }
71
76
  } catch (error: any) {
72
- console.error('⚠️ Error registering slash commands:', error.message);
77
+ logError('Error registering slash commands:');
78
+ logError(error.message);
73
79
  }
74
80
 
75
81
  client.slashCommands = slashCommands;
@@ -1,12 +1,13 @@
1
1
  import { Client, Collection, Interaction, EmbedBuilder, Snowflake, PermissionResolvable } from 'discord.js';
2
2
  import { registerSlashCommands } from './slash-register';
3
3
  import { SlashOptions } from '../types/starter';
4
+ import { logWarning, logError, logInfo } from '../functions/logger';
4
5
 
5
6
  export async function loadSlash(client: Client, token: string, options: SlashOptions): Promise<void> {
6
7
  const slashCommands = await registerSlashCommands(client, token, options);
7
8
 
8
9
  if (!slashCommands || slashCommands.size === 0) {
9
- console.warn('\x1b[33m%s\x1b[0m', '⚠️ No registered slash commands. SlashHandler won\'t work.');
10
+ logWarning('No registered slash commands. SlashHandler won\'t work.');
10
11
  return;
11
12
  }
12
13
 
@@ -58,7 +59,8 @@ export async function loadSlash(client: Client, token: string, options: SlashOpt
58
59
  interactionCooldowns.set(interaction.user.id, userCooldowns);
59
60
  }
60
61
 
61
-
62
+ const startExecutionTime = Date.now();
63
+
62
64
  try {
63
65
  if (command.run) {
64
66
  if (command.run.length === 2) {
@@ -66,17 +68,16 @@ export async function loadSlash(client: Client, token: string, options: SlashOpt
66
68
  } else {
67
69
  await command.run(interaction);
68
70
  }
69
- }
70
- else if (command.execute) {
71
+ }
72
+ else if (command.execute) {
71
73
  if (command.execute.length === 2) {
72
74
  await command.execute(interaction, client);
73
75
  } else {
74
76
  await command.execute(interaction);
75
77
  }
76
78
  } else {
77
- console.warn('⚠️ \x1b[33m%s\x1b[0m', `Command "${command.data.name}" has neither run nor execute method.`);
79
+ logWarning(`Command "${command.data.name}" has neither run nor execute method.`);
78
80
  }
79
- const startExecutionTime = Date.now();
80
81
 
81
82
  const channel = interaction.guild.channels.cache.get(options.logsId || '') as any;
82
83
  const userName = interaction.user.username;
@@ -84,38 +85,39 @@ export async function loadSlash(client: Client, token: string, options: SlashOpt
84
85
  const serverName = interaction.guild.name || 'Unknown Server';
85
86
  const serverId = interaction.guild.id || 'Unknown ID';
86
87
  let messageLink = '';
87
-
88
+
88
89
  if (interaction.channel) {
89
90
  messageLink = `https://discord.com/channels/${serverId}/${interaction.channel.id}/${interaction.id}`;
90
91
  } else {
91
92
  messageLink = 'Unknown';
92
93
  }
93
-
94
-
94
+
95
95
  const embedLog = new EmbedBuilder()
96
- .setColor("Blue")
97
- .setThumbnail(interaction.client.user?.displayAvatarURL())
98
- .setTitle("Use Slash Command")
99
- .setTimestamp()
100
- .addFields(
101
- { name: "📧 Cmd:", value: `- ${command.data.name}`, inline: true },
102
- { name: "🤪 User:", value: `- ${userName} (<@${userId}>)`, inline: true },
103
- { name: "\u200B", value: "\u200B", inline: true },
104
- { name: "🏠 Server:", value: `- ${serverName}.\n- [\`${serverId}\`].`, inline: true },
105
- { name: "📩 Message:", value: `- [Link](${messageLink})`, inline: true },
106
- { name: "\u200B", value: "\u200B", inline: true },
107
- { name: "⏳ Date:", value: `- <t:${Math.floor(Date.now() / 1000)}:R>`, inline: true }
108
- );
96
+ .setColor("Blue")
97
+ .setThumbnail(interaction.client.user?.displayAvatarURL())
98
+ .setTitle("Use Slash Command")
99
+ .setTimestamp()
100
+ .addFields(
101
+ { name: "📧 Cmd:", value: `- ${command.data.name}`, inline: true },
102
+ { name: "🤪 User:", value: `- ${userName} (<@${userId}>)`, inline: true },
103
+ { name: "\u200B", value: "\u200B", inline: true },
104
+ { name: "🏠 Server:", value: `- ${serverName}.\n- [\`${serverId}\`].`, inline: true },
105
+ { name: "📩 Message:", value: `- [Link](${messageLink})`, inline: true },
106
+ { name: "\u200B", value: "\u200B", inline: true },
107
+ { name: "⏳ Date:", value: `- <t:${Math.floor(Date.now() / 1000)}:R>`, inline: true }
108
+ );
109
+
109
110
  if (options.logsId && channel) {
110
111
  await channel.send({ embeds: [embedLog] });
111
112
  }
112
113
 
113
114
  const executionTime = Date.now() - startExecutionTime;
114
115
  if (executionTime > 3000) {
115
- console.log('⚠️ \x1b[33m%s\x1b[0m', `Command "${command.data.name}" took ${executionTime}ms to execute.`);
116
+ logInfo(`Command "${command.data.name}" took ${executionTime}ms to execute.`);
116
117
  }
117
- } catch (error) {
118
- console.error('\x1b[31m%s\x1b[0m', `⚠️ Error executing command "${command.data.name}":`, error);
118
+ } catch (error: any) {
119
+ logError(`Error executing command "${command.data.name}":`);
120
+ logError(error.message);
119
121
  if (interaction.channel) {
120
122
  await interaction.channel.send({ content: 'An error occurred while executing the command.' });
121
123
  }
@@ -1,83 +1,17 @@
1
- import { Collection, Guild } from 'discord.js';
2
- import { REST } from '@discordjs/rest';
3
- import { Routes } from 'discord-api-types/v10';
4
- import { readdir } from 'fs/promises';
5
- import { botData } from './login';
6
- import path from 'path';
7
- export async function slashLoader(client: any): Promise<Collection<string, any>> {
1
+ import { logSuccess, logError, logInfo } from '../functions/logger';
2
+ import { registerSlashCommands } from './slash-register';
8
3
 
9
- const slashCommandsPath = botData.get('slashCommands') as string;
10
- const serverIdSlash = botData.get('serverIdSlash') as string;
11
- const globalSlash = botData.get('globalSlash') as string;
12
- const botToken = botData.get('botToken') as string;
13
-
4
+ export async function slashLoader(client: any, token: string, slashPath: string, global: boolean, serverId?: string) {
5
+ client.slashCommands.clear();
14
6
 
15
- if (!botToken) {
16
- throw new Error("⚠️ \x1b[33m%sPlease provide valid bot token to register slash commands.\x1b[0m");
17
- }
18
-
19
- const slashCommands = new Collection<string, any>();
20
- const rest = new REST({ version: '10' }).setToken(botToken);
7
+ logInfo(`Reloading slash commands from ${slashPath}`);
21
8
 
22
9
  try {
23
- const resolvedPath = path.join(process.cwd(), slashCommandsPath);
24
- const dirents = await readdir(resolvedPath, { withFileTypes: true });
25
-
26
- for (const dirent of dirents) {
27
- if (dirent.isDirectory()) {
28
- const folderPath = path.join(resolvedPath, dirent.name);
29
- const files = await readdir(folderPath);
30
-
31
- for (const file of files) {
32
- try {
33
- const command = require(path.join(folderPath, file));
34
- if (command.data) {
35
- if (command.cooldown && !isNaN(command.cooldown)) {
36
- command.data.cooldown = command.cooldown || 0;
37
- }
38
- slashCommands.set(command.data.name, command);
39
- }
40
- } catch (error: any) {
41
- console.error(`⚠️ Error in file: ${path.join(folderPath, file)}`);
42
- console.error(error.message);
43
- }
44
- }
45
- } else {
46
- try {
47
- const command = require(path.join(resolvedPath, dirent.name));
48
- if (command.data) {
49
- if (command.cooldown && !isNaN(command.cooldown)) {
50
- command.data.cooldown = command.cooldown || 0;
51
- }
52
- slashCommands.set(command.data.name, command);
53
- }
54
- } catch (error: any) {
55
- console.error(`⚠️ Error in file: ${path.join(resolvedPath, dirent.name)}`);
56
- console.error(error.message);
57
- }
58
- }
59
- }
60
-
61
- if (globalSlash === 'true' && !serverIdSlash) {
62
- const slashCommandArray = Array.from(slashCommands.values()).map(command => command.data.toJSON());
63
- await rest.put(Routes.applicationCommands((client.user?.id || '')), { body: slashCommandArray, headers: { Authorization: `Bot ${botToken}` } });
64
- } else if (globalSlash === 'false' && serverIdSlash) {
65
- const guild = client.guilds.cache.get(serverIdSlash) as Guild | undefined;
66
- if (guild) {
67
- const slashCommandArray = Array.from(slashCommands.values()).map(command => command.data.toJSON());
68
- await rest.put(Routes.applicationGuildCommands((client.user?.id || ''), guild.id), { body: slashCommandArray, headers: { Authorization: `Bot ${botToken}` } });
69
- } else {
70
- console.error(`⚠️ Guild with ID ${serverIdSlash} not found.`);
71
- }
72
- } else {
73
- const slashCommandArray = Array.from(slashCommands.values()).map(command => command.data.toJSON());
74
- await rest.put(Routes.applicationCommands((client.user?.id || '')), { body: slashCommandArray, headers: { Authorization: `Bot ${botToken}` } });
75
- }
10
+ const newSlashCommands = await registerSlashCommands(client, token, { path: slashPath, global, serverId });
11
+ logSuccess(`Successfully reloaded ${newSlashCommands.size} slash commands.`);
12
+ return true
76
13
  } catch (error: any) {
77
- console.error('⚠️ Error registering slash commands:', error.message);
14
+ logError(`Error reloading slash commands: ${error.message}`);
15
+ return false
78
16
  }
79
-
80
- client.slashCommands = slashCommands;
81
- client.slashSize = slashCommands.size;
82
- return slashCommands;
83
17
  }
@@ -0,0 +1,39 @@
1
+ const successEmoji = '✅';
2
+ const errorEmoji = '❌';
3
+ const infoEmoji = 'ℹ️';
4
+ const warningEmoji = '⚠️';
5
+
6
+ const green = '\x1b[32m';
7
+ const red = '\x1b[31m';
8
+ const cyan = '\x1b[36m';
9
+ const reset = '\x1b[0m';
10
+ const yellow = '\x1b[33m';
11
+
12
+
13
+ function getTimestamp(): string {
14
+ const now = new Date();
15
+ const year = now.getFullYear();
16
+ const month = String(now.getMonth() + 1).padStart(2, '0');
17
+ const day = String(now.getDate()).padStart(2, '0');
18
+ const hours = String(now.getHours()).padStart(2, '0');
19
+ const minutes = String(now.getMinutes()).padStart(2, '0');
20
+ const seconds = String(now.getSeconds()).padStart(2, '0');
21
+ return `[${year}-${month}-${day} ${hours}:${minutes}:${seconds}]`;
22
+ }
23
+
24
+ export function logSuccess(message: string) {
25
+ console.log(`${getTimestamp()} ${green}${successEmoji}${reset} ${green}${message}${reset}`);
26
+ }
27
+
28
+ export function logError(message: string) {
29
+ console.error(`${getTimestamp()} ${red}${errorEmoji}${reset} ${red}${message}${reset}`);
30
+ }
31
+
32
+ export function logInfo(message: string) {
33
+ console.log(`${getTimestamp()} ${cyan}${infoEmoji}${reset} ${cyan}${message}${reset}`);
34
+ }
35
+
36
+
37
+ export function logWarning(message: string) {
38
+ console.warn(`${getTimestamp()} ${yellow}${warningEmoji}${reset} ${yellow}${message}${reset}`);
39
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "djs-builder",
3
- "version": "0.4.6",
3
+ "version": "0.4.7",
4
4
  "description": "Discord.js bot builder. Supports Ts and Js.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",