Skip to content

Commit 31ea8cc

Browse files
authored
Add events structure (#9)
* Create events file * Create ready event
1 parent a36a46f commit 31ea8cc

File tree

3 files changed

+53
-1
lines changed

3 files changed

+53
-1
lines changed

src/App.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import { Client, GatewayIntentBits } from 'discord.js';
22
import { BOT_TOKEN } from './config/environment';
3+
import { registerEventHandlers } from './events/events';
34

45
const app: Client = new Client({
5-
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
6+
intents: [GatewayIntentBits.Guilds],
67
});
78

89
const initialize = async (): Promise<void> => {
910
try {
1011
await app.login(BOT_TOKEN);
12+
registerEventHandlers({ app });
1113
} catch (error) {
1214
throw error;
1315
}

src/events/events.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { Client } from 'discord.js';
2+
import fs from 'fs';
3+
import path from 'path';
4+
5+
interface Props {
6+
app: Client;
7+
}
8+
type ExportedEventModule = {
9+
default: (data: EventModule) => void;
10+
};
11+
export type EventModule = {
12+
app: Client;
13+
};
14+
export function registerEventHandlers({ app }: Props): void {
15+
const loadModules = (directoryPath: string) => {
16+
fs.readdir(directoryPath, { withFileTypes: true }, (error, files) => {
17+
if (error) {
18+
//TODO: Replace with error handling
19+
console.log(error);
20+
}
21+
files &&
22+
files.forEach((file) => {
23+
const filePath = path.join(directoryPath, file.name);
24+
if (file.isDirectory()) {
25+
return loadModules(filePath);
26+
}
27+
if (file.name === 'index.js') {
28+
const modulePath = `.${filePath.replace('dist/events', '')}`;
29+
const currentModule = require(modulePath) as ExportedEventModule;
30+
currentModule.default({ app });
31+
}
32+
});
33+
});
34+
};
35+
loadModules('./dist/events');
36+
}

src/events/ready/index.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { Client } from 'discord.js';
2+
3+
interface Props {
4+
app: Client;
5+
}
6+
export default function ({ app }: Props) {
7+
app.once('ready', async () => {
8+
try {
9+
console.log("I'm booting up! (◕ᴗ◕✿)");
10+
} catch (error) {
11+
console.log(error);
12+
}
13+
});
14+
}

0 commit comments

Comments
 (0)