Skip to content

Commit

Permalink
refactor(events): apply same strategy of loading commands to events
Browse files Browse the repository at this point in the history
Adapt helper to log information as well.
Fix dockerfile warning with stage names
  • Loading branch information
Tinaël Devresse committed Oct 24, 2024
1 parent 82f91da commit bbe6474
Show file tree
Hide file tree
Showing 8 changed files with 76 additions and 34 deletions.
6 changes: 3 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM node:lts-alpine AS BUILD
FROM node:lts-alpine AS build

WORKDIR /app

Expand All @@ -12,13 +12,13 @@ RUN yarn install --production
RUN zip -r app.zip ./node_modules ./build ./yarn.lock ./.env

# ------------------------------------------------------------
FROM node:lts-alpine AS APP
FROM node:lts-alpine AS app

WORKDIR /app

RUN apk --no-cache add unzip

COPY --from=BUILD /app/app.zip .
COPY --from=build /app/app.zip .
RUN unzip app.zip && rm app.zip && mv ./build/* . && rm -rf ./build

CMD ["sh", "-c", "sleep 2 && node ./index.js"]
28 changes: 16 additions & 12 deletions src/datadrop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { readConfig } from './config.js';
import { User } from './models/User.js';
import { IDatabaseService } from './models/IDatabaseService.js';
import { Command } from './models/Command.js';
import { Event } from './models/Event.js';

export class DatadropClient extends Client {
#config: Configuration;
Expand Down Expand Up @@ -145,22 +146,25 @@ export class DatadropClient extends Client {
});
}

#bindEvents(): void {
async #bindEvents(): Promise<void> {
const eventDirectory = path.join(import.meta.dirname, 'events');
this.logger.debug(`Chargement de ${eventDirectory}`);
readFilesFrom(eventDirectory, (eventName: string, props: any) => {
this.logger.info(`Event '${eventName}' chargé`);
this.on(eventName, props.bind(null, this));
});
await readFilesFrom(eventDirectory, (eventFileName: string, event: Event) => {
this.logger.info(`Event '${event.name}' ('${eventFileName}') chargé`);

if (event.once) {
this.once(event.name, event.execute.bind(null, this));
} else {
this.on(event.name, event.execute.bind(null, this));
}
}, this.logger);
}

#bindCommands(): void {
async #bindCommands(): Promise<void> {
const commandDirectory = path.join(import.meta.dirname, 'commands');
this.logger.debug(`Chargement de ${commandDirectory}`);
readFilesFrom(commandDirectory, (commandFileName: string, props: any) => {
await readFilesFrom(commandDirectory, (commandFileName: string, props: Command) => {
this.logger.info(`Commande '${props.data.name}' ('${commandFileName}') chargée`);
this.commands.set(props.data.name, props);
});
}, this.logger);
}

async start(): Promise<void> {
Expand All @@ -170,8 +174,8 @@ export class DatadropClient extends Client {
this.#listenToTempChannelsEvents();
this.#listenToVerificationEvents();

this.#bindEvents();
this.#bindCommands();
await this.#bindEvents();
await this.#bindCommands();

await this.database?.start();
this.login();
Expand Down
11 changes: 8 additions & 3 deletions src/events/guildMemberAdd.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@

import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder, GuildMember } from 'discord.js';
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder, Events, GuildMember } from 'discord.js';

import { AnnounceConfiguration } from '../models/Configuration.js';
import { DatadropClient } from '../datadrop.js';

export default async function guildMemberAdd(client: DatadropClient, member: GuildMember) {
export default {
name: Events.GuildMemberAdd,
execute: guildMemberAdd
};

async function guildMemberAdd(client: DatadropClient, member: GuildMember) {
if (member.user.bot) return;
client.logger.info(`L'utilisateur <${member.displayName} a rejoint le serveur.`);

Expand Down Expand Up @@ -35,7 +40,7 @@ export default async function guildMemberAdd(client: DatadropClient, member: Gui
} catch (err: unknown) {
client.logger.error((<Error>err).message);
}
};
}

function generateEmbed(informationsChannelid: string, faqChannelid: string, comiteeChannelid: string, rolesChannelid: string, announce: AnnounceConfiguration) {
const fields = [
Expand Down
11 changes: 8 additions & 3 deletions src/events/guildMemberRemove.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import { GuildMember } from 'discord.js';
import { Events, GuildMember } from 'discord.js';

import { DatadropClient } from '../datadrop.js';

export default async function guildMemberRemove(client: DatadropClient, member: GuildMember) {
export default {
name: Events.GuildMemberRemove,
execute: guildMemberRemove
};

async function guildMemberRemove(client: DatadropClient, member: GuildMember) {
if (member.user.bot) return;
if (member.guild.id !== client.config.guildId) return;
client.logger.info(`L'utilisateur <${member.displayName} a quitté le serveur.`);
Expand All @@ -12,4 +17,4 @@ export default async function guildMemberRemove(client: DatadropClient, member:
} catch (err: unknown) {
client.logger.error((<Error>err).message);
}
};
}
9 changes: 7 additions & 2 deletions src/events/interactionCreate.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { ActionRowBuilder, ButtonBuilder, ButtonInteraction, ButtonStyle, Interaction, italic, ModalBuilder, ModalSubmitInteraction, RepliableInteraction, TextInputBuilder, TextInputStyle } from 'discord.js';
import { ActionRowBuilder, ButtonBuilder, ButtonInteraction, ButtonStyle, Events, Interaction, italic, ModalBuilder, ModalSubmitInteraction, RepliableInteraction, TextInputBuilder, TextInputStyle } from 'discord.js';

import { DatadropClient } from 'src/datadrop.js';
import { CommandHandler } from '../services/CommandHandler.js';

export default async function interactionCreate(client: DatadropClient, interaction: Interaction) {
export default {
name: Events.InteractionCreate,
execute: interactionCreate
};

async function interactionCreate(client: DatadropClient, interaction: Interaction) {
if (interaction.isChatInputCommand() || interaction.isMessageContextMenuCommand()) {
const commandHandler = new CommandHandler(client);
if (commandHandler.shouldExecute(interaction)) {
Expand Down
12 changes: 9 additions & 3 deletions src/events/ready.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import { Role, roleMention, bold, Snowflake, ButtonStyle } from 'discord.js';
import { Role, roleMention, bold, Snowflake, ButtonStyle, Events } from 'discord.js';

import { RoleToEmojiData } from '@hunteroi/discord-selfrole';

import { DatadropClient } from '../datadrop.js';
import { Configuration } from '../models/Configuration.js';

export default async function ready(client: DatadropClient) {
export default {
name: Events.ClientReady,
once: true,
execute: ready
};

async function ready(client: DatadropClient) {
const { config } = client;
await registerRolesChannels(client, config);
await registerDynamicChannels(client, config);
Expand All @@ -14,7 +20,7 @@ export default async function ready(client: DatadropClient) {
if (config.version) client.user?.setActivity({ name: config.version });

client.logger.info(`Connecté en tant que ${client.user?.tag}, version ${config.version}!`);
};
}

async function registerRolesChannels(client: DatadropClient, config: Configuration): Promise<void> {
const { rolesChannelid, first, second, third, alumni, tutor, announce } = config;
Expand Down
26 changes: 18 additions & 8 deletions src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,33 @@
import * as fs from 'fs';
import * as fsp from 'fs/promises';
import * as path from 'path';
import { ConsoleLogger, DefaultLogger } from '@hunteroi/advanced-logger';

export function readFilesFrom(directory: string, callback: (name: string, props: any) => void): void {
fs.readdir(directory, async (err, files) => {
if (err) return console.error;
const console = new ConsoleLogger();

export async function readFilesFrom(directory: string, callback: (name: string, props: any) => void, logger: DefaultLogger = console): Promise<void> {
try {
logger.debug(`Lecture du répertoire ${directory}`);

const files = await fsp.readdir(directory);
for (const file of files) {
const filePath = path.join(directory, file);
const stats = fs.statSync(filePath);
const stats = await fsp.stat(filePath);

if (stats.isDirectory()) {
readFilesFrom(filePath, callback);
await readFilesFrom(filePath, callback, logger);
continue;
}

if (stats.isFile() && !file.endsWith('.js')) return;
if (stats.isFile() && !file.endsWith('.js')) continue;

logger.debug(`Lecture du fichier ${filePath}`);

const props = await import(filePath);
callback(file.replace('.js', ''), props.default);
}
});
} catch (err) {
logger.error(getErrorMessage(err));
}
}

export function clean(text: any): string {
Expand Down
7 changes: 7 additions & 0 deletions src/models/Event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { DatadropClient } from '../datadrop.js';

export interface Event {
name: string;
once?: boolean;
execute(client: DatadropClient, ...args: any[]): Promise<void>;
}

0 comments on commit bbe6474

Please sign in to comment.