Skip to content

Commit

Permalink
feat: replace console.log() with logger.<LEVEL>
Browse files Browse the repository at this point in the history
  • Loading branch information
iluxonchik committed Jul 30, 2024
1 parent 79f46f2 commit d2af14c
Show file tree
Hide file tree
Showing 12 changed files with 63 additions and 49 deletions.
6 changes: 4 additions & 2 deletions scripts/manage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { initializeDatabase } from '../src/database';
import { addAdmin, removeAdmin } from '../src/database/admin';
import { checkRequiredChannels } from '../src/commands/checkChannels';

import logger from '../src/logging';

dotenv.config();

const client: Client = new Client({
Expand All @@ -18,11 +20,11 @@ async function main(): Promise<void> {
yargs(hideBin(process.argv))
.command('addAdmin <discordUserId>', 'Add an admin', {}, async (argv): Promise<void> => {
await addAdmin(argv.discordUserId as string);
console.log(`Admin added: ${argv.discordUserId}`);
logger.info(`Admin added: ${argv.discordUserId}`);
})
.command('removeAdmin <discordUserId>', 'Remove an admin', {}, async (argv): Promise<void> => {
await removeAdmin(argv.discordUserId as string);
console.log(`Admin removed: ${argv.discordUserId}`);
logger.info(`Admin removed: ${argv.discordUserId}`);
})
.command('checkChannels', 'Check required channels', {}, async (): Promise<void> => {
await client.login(process.env.DISCORD_TOKEN);
Expand Down
21 changes: 11 additions & 10 deletions src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { CommitteeDeliberationDashboard } from './channels/deliberate/CommitteeD
import { CommitteeDeliberationHomeScreen } from './channels/deliberate/CommitteeDeliberationHomeScreen';
import { ConsiderDashboard } from './channels/consider/ConsiderDashboard';
import { ConsiderationHomeScreen } from './channels/consider/screens/ConsiderationHomeScreen';
import logger from './logging';

config();

Expand All @@ -25,7 +26,7 @@ const client = new Client({
const dashboardManager = new DashboardManager();

client.once('ready', async () => {
console.log('Bot is ready!');
logger.info('Bot is ready!');
await syncDatabase();

// Register dashboards
Expand Down Expand Up @@ -68,15 +69,15 @@ client.once('ready', async () => {
if (adminChannel) {
await adminDashboard.homeScreen.renderToTextChannel(adminChannel);
} else {
console.error('Admin channel not found');
logger.error('Admin channel not found');
}

// Render initial screen in #funding-round-init channel
const fundingRoundInitChannel = guild.channels.cache.find(channel => channel.name === 'funding-round-init') as TextChannel | undefined;
if (fundingRoundInitChannel) {
await fundingRoundInitDashboard.homeScreen.renderToTextChannel(fundingRoundInitChannel);
} else {
console.error('Funding Round Init channel not found');
logger.error('Funding Round Init channel not found');
}


Expand All @@ -85,35 +86,35 @@ client.once('ready', async () => {
if (proposeChannel) {
await proposeDashboard.homeScreen.renderToTextChannel(proposeChannel);
} else {
console.error('Propose channel not found');
logger.error('Propose channel not found');
}

// Render initial screen in #vote channel
const voteChannel = guild.channels.cache.find(channel => channel.name === 'vote') as TextChannel | undefined;
if (voteChannel) {
await voteDashboard.homeScreen.renderToTextChannel(voteChannel);
} else {
console.error('Vote channel not found');
logger.error('Vote channel not found');
}

// Render initial screen in #deliberate channel
const deliberateChannel = guild.channels.cache.find(channel => channel.name === 'deliberate') as TextChannel | undefined;
if (deliberateChannel) {
await committeeDeliberationDashboard.homeScreen.renderToTextChannel(deliberateChannel);
} else {
console.error('Deliberate channel not found');
logger.error('Deliberate channel not found');
}

// Render initial screen in #consider channel
const considerChannel = guild.channels.cache.find(channel => channel.name === 'consider') as TextChannel | undefined;
if (considerChannel) {
await considerDashboard.homeScreen.renderToTextChannel(considerChannel);
} else {
console.error('Consider channel not found');
logger.error('Consider channel not found');
}

} else {
console.error('No guild found');
logger.error('No guild found');
}

// Register other dashboards here
Expand All @@ -123,13 +124,13 @@ client.on('interactionCreate', async (interaction: Interaction<CacheType>) => {
try {

if (!interaction.isButton() && !interaction.isStringSelectMenu() && !interaction.isModalSubmit() && !interaction.isMessageComponent()){
console.log(`Interaction type not supported: ${interaction.type}`);
logger.info(`Interaction type not supported: ${interaction.type}`);
return;
}

await dashboardManager.handleInteraction(interaction);
} catch (error) {
console.error(error);
logger.error(error);
}
});

Expand Down
5 changes: 3 additions & 2 deletions src/channels/admin/screens/FundingRoundLogic.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import sequelize from '../../../config/database';
import logger from '../../../logging';
import { FundingRound, Topic, ConsiderationPhase, DeliberationPhase, FundingVotingPhase, SMEGroup, SMEGroupMembership, FundingRoundDeliberationCommitteeSelection, FundingRoundApprovalVote, TopicSMEGroupProposalCreationLimiter, Proposal } from '../../../models';
import { FundingRoundAttributes, FundingRoundStatus, FundingRoundPhase, ProposalStatus } from '../../../types';
import { Op, Transaction } from 'sequelize';
Expand Down Expand Up @@ -214,7 +215,7 @@ export class FundingRoundLogic {
insertedCount++;
}
} catch (error) {
console.error('Error in appendFundingRoundCommitteeMembers:', error);
logger.error('Error in appendFundingRoundCommitteeMembers:', error);

}
}
Expand Down Expand Up @@ -265,7 +266,7 @@ export class FundingRoundLogic {

return count;
} catch (error) {
console.error('Error in countSMEMembersInDeliberationCommittee:', error);
logger.error('Error in countSMEMembersInDeliberationCommittee:', error);
throw error;
}
}
Expand Down
4 changes: 3 additions & 1 deletion src/channels/admin/screens/ManageFundingRoundsScreen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { InteractionProperties } from '../../../core/Interaction';
import { PaginationComponent } from '../../../components/PaginationComponent';
import { FundingRoundPhase } from '../../../types';
import { TopicLogic } from './ManageTopicLogicScreen';
import logger from '../../../logging';


export class ManageFundingRoundsScreen extends Screen {
public static readonly ID = 'manageFundingRounds';
Expand Down Expand Up @@ -787,7 +789,7 @@ export class ModifyFundingRoundAction extends Action {
const startDateValue: string = phase === 'round' && fundingRound.startAt ? this.formatDate(fundingRound.startAt) : existingPhase ? this.formatDate(existingPhase.startDate) : '';
const endDateValue: string = phase === 'round' && fundingRound.startAt ? this.formatDate(fundingRound.endAt) : existingPhase ? this.formatDate(existingPhase.endDate) : '';

console.log(`startDateValue: ${startDateValue} endDateValue: ${endDateValue}`);
logger.info(`startDateValue: ${startDateValue} endDateValue: ${endDateValue}`);

const modal = new ModalBuilder()
.setCustomId(CustomIDOracle.addArgumentsToAction(this, ModifyFundingRoundAction.OPERATIONS.SUBMIT_PHASE, 'fundingRoundId', fundingRoundId, 'phase', phase))
Expand Down
15 changes: 8 additions & 7 deletions src/channels/admin/screens/ManageSMEGroupsScreen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { AnyInteraction, AnyInteractionWithValues, AnyModalMessageComponent } fr
import { PaginationComponent } from '../../../components/PaginationComponent';
import { PaginationLogic } from '../../../utils/Pagination';
import { InteractionProperties } from '../../../core/Interaction';
import logger from '../../../logging';


export class SMEGroupLogic {
Expand Down Expand Up @@ -409,7 +410,7 @@ class AddSMEGroupAction extends Action {
const successMessage = `✅ SME Group '${name}' created successfully`;
await this.screen.reRender(interaction, { successMessage: successMessage });
} catch (err) {
console.error(err);
logger.error(err);
const errorMessage = `🚫 An error occurred while creating the group '${name}'`;
await this.screen.reRender(interaction, { errorMessage: errorMessage });
}
Expand Down Expand Up @@ -503,7 +504,7 @@ class RemoveSMEGroupAction extends Action {
ephemeral: true
});
} catch (error) {
console.error('Error fetching group details:', error);
logger.error('Error fetching group details:', error);
await interaction.respond({ content: 'An error occurred while fetching group details. Please try again later.', ephemeral: true });
}
}
Expand All @@ -520,7 +521,7 @@ class RemoveSMEGroupAction extends Action {
const successMessage = 'SME Group has been successfully removed along with all its dependencies.';
await this.screen.render(interaction, { successMessage });
} catch (error) {
console.error('Error removing SME Group:', error);
logger.error('Error removing SME Group:', error);
const errorMessage = 'An error occurred while removing the SME Group. Please try again later.';
await this.screen.render(interaction, { errorMessage });
}
Expand Down Expand Up @@ -562,7 +563,7 @@ class ManageMembersAction extends PaginationComponent {
}

protected async handleOperation(interaction: TrackedInteraction, operationId: string): Promise<void> {
console.log(`Handling operation ${operationId} on ${interaction.customId}`);
logger.info(`Handling operation ${operationId} on ${interaction.customId}`);

switch (operationId) {
case ManageMembersAction.Operations.VIEW_MEMBERS:
Expand Down Expand Up @@ -605,7 +606,7 @@ class ManageMembersAction extends PaginationComponent {
const successMessage = `Successfully removed ${removedCount} member(s) from the group.`;
await this.handleViewMembers(interaction, successMessage);
} catch (error) {
console.error('Error removing members from group:', error);
logger.error('Error removing members from group:', error);
const errorMessage = 'An error occurred while removing members from the group. Please try again later.';
await this.screen.reRender(interaction, { errorMessage });
}
Expand Down Expand Up @@ -669,7 +670,7 @@ class ManageMembersAction extends PaginationComponent {
}

private async handleAddMembers(interaction: TrackedInteraction): Promise<void> {
console.log('Handling add members...');
logger.info('Handling add members...');
const groupId = CustomIDOracle.getNamedArgument(interaction.customId, 'groupId');
if (!groupId) {
await interaction.respond({ content: 'Invalid group ID.', ephemeral: true });
Expand Down Expand Up @@ -711,7 +712,7 @@ class ManageMembersAction extends PaginationComponent {
const successMessage = `Successfully added ${result.added} member(s) to the group. ${result.skipped} member(s) were already in the group and skipped.`;
await this.handleViewMembers(interaction, successMessage);
} catch (error) {
console.error('Error adding members to group:', error);
logger.error('Error adding members to group:', error);
const errorMessage = 'An error occurred while adding members to the group. Please try again later.';
await this.screen.reRender(interaction, { errorMessage });
}
Expand Down
21 changes: 11 additions & 10 deletions src/channels/admin/screens/ManageTopicLogicScreen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { TopicAttributes, TopicCommitteeAttributes } from '../../../types';
import { allowedNodeEnvironmentFlags } from 'process';
import { InteractionProperties } from '../../../core/Interaction';
import { parsed } from 'yargs';
import logger from '../../../logging';

interface TopicCommitteeWithSMEGroup extends TopicCommitteeAttributes {
smeGroupName: string;
Expand Down Expand Up @@ -610,7 +611,7 @@ class AddTopicAction extends Action {
const successMessage = `✅ Topic '${name}' created successfully`;
await this.screen.reRender(interaction, { successMessage: successMessage });
} catch (err) {
console.error(err);
logger.error(err);
const errorMessage = `🚫 An error occurred while creating the topic '${name}': ${(err as Error).message}`;
await interaction.respond({ content: errorMessage, ephemeral: true });
}
Expand Down Expand Up @@ -712,7 +713,7 @@ class RemoveTopicAction extends Action {
ephemeral: true
});
} catch (error) {
console.error('Error fetching topic details:', error);
logger.error('Error fetching topic details:', error);
await interaction.respond({ content: 'An error occurred while fetching topic details. Please try again later.', ephemeral: true });
}
}
Expand All @@ -729,7 +730,7 @@ class RemoveTopicAction extends Action {
const successMessage = 'Topic has been successfully removed.';
await this.screen.render(interaction, { successMessage });
} catch (error) {
console.error('Error removing Topic:', error);
logger.error('Error removing Topic:', error);
const errorMessage = 'An error occurred while removing the Topic. Please try again later.';
await this.screen.render(interaction, { errorMessage });
}
Expand Down Expand Up @@ -872,7 +873,7 @@ class EditTopicAction extends Action {
const successMessage = `✅ Topic '${name}' updated successfully`;
await this.screen.reRender(interaction, { successMessage: successMessage });
} catch (err) {
console.error(err);
logger.error(err);
const errorMessage = `🚫 An error occurred while updating the topic '${name}': ${(err as Error).message}`;
await this.screen.reRender(interaction, { errorMessage: errorMessage });
}
Expand Down Expand Up @@ -1200,9 +1201,9 @@ export class CommitteePaginationAction extends PaginationComponent {

const topicId = topicIdFromCustomId ? topicIdFromCustomId : topicIdFromContext;

console.log('topicIdFromCustomId:', topicIdFromCustomId);
console.log('topicIdFromContext:', topicIdFromContext);
console.log('topicId:', topicId);
logger.info('topicIdFromCustomId:', topicIdFromCustomId);
logger.info('topicIdFromContext:', topicIdFromContext);
logger.info('topicId:', topicId);


if (!topicId) {
Expand All @@ -1214,9 +1215,9 @@ export class CommitteePaginationAction extends PaginationComponent {
const totalPages = await this.getTotalPages(interaction);
const committees = await this.getItemsForPage(interaction, currentPage);

console.log('currentPage:', currentPage);
console.log('totalPages:', totalPages);
console.log('committees:', committees);
logger.info('currentPage:', currentPage);
logger.info('totalPages:', totalPages);
logger.info('committees:', committees);

const embed = new EmbedBuilder()
.setColor('#0099ff')
Expand Down
1 change: 1 addition & 0 deletions src/channels/deliberate/CommitteeDeliberationHomeScreen.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// src/channels/deliberate/CommitteeDeliberationHomeScreen.ts
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder, MessageActionRowComponentBuilder, ModalBuilder, StringSelectMenuBuilder, TextChannel, TextInputBuilder, TextInputStyle } from 'discord.js';
import { CommitteeDeliberationLogic } from '../../logic/CommitteeDeliberationLogic';
import { IHomeScreen } from '../../types/common';
Expand Down
11 changes: 6 additions & 5 deletions src/commands/checkChannels.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@

import { Client, Guild, ChannelType, CategoryChannel } from 'discord.js';
import { CONSTANTS } from '../constants';
import logger from '../logging';

export async function checkRequiredChannels(client: Client): Promise<void> {
const guild: Guild | undefined = client.guilds.cache.get(process.env.GUILD_ID!);
if (!guild) {
console.error(`${CONSTANTS.EMOJIS.ERROR} Guild not found`);
logger.error(`${CONSTANTS.EMOJIS.ERROR} Guild not found`);
return;
}

Expand All @@ -14,11 +15,11 @@ export async function checkRequiredChannels(client: Client): Promise<void> {
) as CategoryChannel | undefined;

if (!govbotCategory) {
console.log(`${CONSTANTS.EMOJIS.ERROR} 'govbot' category not found`);
logger.info(`${CONSTANTS.EMOJIS.ERROR} 'govbot' category not found`);
return;
}

console.log(`${CONSTANTS.EMOJIS.SUCCESS} 'govbot' category found`);
logger.info(`${CONSTANTS.EMOJIS.SUCCESS} 'govbot' category found`);

const requiredChannels: string[] = Object.values(CONSTANTS.CHANNELS);

Expand All @@ -28,9 +29,9 @@ export async function checkRequiredChannels(client: Client): Promise<void> {
);

if (channel) {
console.log(`${CONSTANTS.EMOJIS.SUCCESS} '${channelName}' channel found in 'govbot' category`);
logger.info(`${CONSTANTS.EMOJIS.SUCCESS} '${channelName}' channel found in 'govbot' category`);
} else {
console.log(`${CONSTANTS.EMOJIS.ERROR} '${channelName}' channel not found in 'govbot' category`);
logger.info(`${CONSTANTS.EMOJIS.ERROR} '${channelName}' channel not found in 'govbot' category`);
}
}
}
13 changes: 7 additions & 6 deletions src/core/BaseClasses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { InteractionResponse, Message, MessageComponentInteraction } from 'disco
import { CustomIDOracle } from '../CustomIDOracle';
import { AnyModalMessageComponent, AnyInteraction, HomeScreen } from '../types/common';
import { InteractionProperties } from './Interaction';
import logger from '../logging';

export interface RenderArgs {
successMessage?: string,
Expand Down Expand Up @@ -47,7 +48,7 @@ export class TrackedInteraction {
}

} catch (error) {
console.log('Error in respond: ', error);
logger.info('Error in respond: ', error);
throw error;
}
}
Expand Down Expand Up @@ -206,7 +207,7 @@ export abstract class Screen {
try {
await interaction.respond(responseArgs);
} catch (error) {
console.log('Error in render: ', error);
logger.info('Error in render: ', error);
}
return;
}
Expand All @@ -221,7 +222,7 @@ export abstract class Screen {
await interaction.respond(responseArgs);
}
} catch (error) {
console.log('Error in re-render:\n', error);
logger.info('Error in re-render:\n', error);
}
}

Expand Down Expand Up @@ -296,8 +297,8 @@ export abstract class Screen {

public registerAction(action: Action, actionId: string): void {
this.actions.set(actionId, action);
//console.log(`Action registered: ${actionId}`);
//console.log(action);
//logger.info(`Action registered: ${actionId}`);
//logger.info(action);
}
}

Expand Down Expand Up @@ -330,7 +331,7 @@ export abstract class Dashboard {
throw new Error('Home screen not set.');
}

console.log("[Dashboard] Handling interaction ", interaction.customId);
logger.info("[Dashboard] Handling interaction ", interaction.customId);

const screenId = CustomIDOracle.getScreenId(interaction.customId);
if (!screenId) {
Expand Down
Loading

0 comments on commit d2af14c

Please sign in to comment.