From 1045efaab39b966b786dad14a3b49f3b0eeb57c5 Mon Sep 17 00:00:00 2001 From: Wiktoria Van Harneveldt Date: Sat, 14 Nov 2026 15:54:12 +0100 Subject: [PATCH 1/4] feat: create logger function --- src/util/logger.test.ts | 45 +++++++++++++++++++++++++++++++++++++++++ src/util/logger.ts | 18 +++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 src/util/logger.test.ts create mode 100644 src/util/logger.ts diff --git a/src/util/logger.test.ts b/src/util/logger.test.ts new file mode 100644 index 0000000..feadedd --- /dev/null +++ b/src/util/logger.test.ts @@ -0,0 +1,45 @@ +import assert from 'node:assert/strict'; +import { afterEach, describe, it, mock } from 'node:test'; +import { createLogger } from './logger.js'; + +void describe('createLogger', () => { + afterEach(() => { + mock.restoreAll(); + }); + + void it('prefixes log output with the feature name', () => { + const consoleLog = mock.method(console, 'log', () => {}); + + createLogger('showcase').log('created post', 42); + + assert.deepEqual(consoleLog.mock.calls[0]?.arguments, [ + '[showcase]', + 'created post', + 42, + ]); + }); + + void it('prefixes warnings with the feature name', () => { + const consoleWarn = mock.method(console, 'warn', () => {}); + + createLogger('guides').warn('missing access'); + + assert.deepEqual(consoleWarn.mock.calls[0]?.arguments, [ + '[guides]', + 'missing access', + ]); + }); + + void it('prefixes errors and keeps the error object as an argument', () => { + const consoleError = mock.method(console, 'error', () => {}); + const error = new Error('boom'); + + createLogger('tags').error('Error deleting tag:', error); + + assert.deepEqual(consoleError.mock.calls[0]?.arguments, [ + '[tags]', + 'Error deleting tag:', + error, + ]); + }); +}); diff --git a/src/util/logger.ts b/src/util/logger.ts new file mode 100644 index 0000000..b0d964d --- /dev/null +++ b/src/util/logger.ts @@ -0,0 +1,18 @@ +export type Logger = { + log: (...messages: unknown[]) => void; + warn: (...messages: unknown[]) => void; + error: (...messages: unknown[]) => void; +}; + +/** + * Every line is prefixed with `[feature]` so logs can be filtered by feature name. + */ +export const createLogger = (feature: string): Logger => { + const prefix = `[${feature}]`; + + return { + log: (...messages) => console.log(prefix, ...messages), + warn: (...messages) => console.warn(prefix, ...messages), + error: (...messages) => console.error(prefix, ...messages), + }; +}; From 584811e6b5a3b3a73e2d7ca1214a9710e1d475fa Mon Sep 17 00:00:00 2001 From: Wiktoria Van Harneveldt Date: Sat, 14 Nov 2026 15:55:01 +0100 Subject: [PATCH 2/4] feat: log env related files --- src/env.ts | 13 ++++++++----- src/loadEnvFile.ts | 15 +++++++++------ 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/src/env.ts b/src/env.ts index 5c86bbc..267ba09 100644 --- a/src/env.ts +++ b/src/env.ts @@ -1,5 +1,8 @@ // oxlint-disable id-length import '@/loadEnvFile.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('env'); function optionalEnv(key: string): string | undefined { return process.env[key]; @@ -8,8 +11,8 @@ function optionalEnv(key: string): string | undefined { function requireEnv(key: string): string { const value = process.env[key]; if (!value) { - console.error(`❌ Required environment variable ${key} is not set`); - console.error('Please check your .env file or CI/CD configuration'); + logger.error(`❌ Required environment variable ${key} is not set`); + logger.error('Please check your .env file or CI/CD configuration'); process.exit(1); } return value; @@ -57,10 +60,10 @@ export const config = { export type Config = typeof config; -console.log('✅ Configuration loaded successfully'); -console.log( +logger.log('✅ Configuration loaded successfully'); +logger.log( `📋 Client ID: ${config.discord.clientId ? config.discord.clientId : '❌ missing'}` ); -console.log( +logger.log( `🔑 Token: ${config.discord.token ? '***configured***' : '❌ missing'}` ); diff --git a/src/loadEnvFile.ts b/src/loadEnvFile.ts index 149fcaf..54788d8 100644 --- a/src/loadEnvFile.ts +++ b/src/loadEnvFile.ts @@ -1,9 +1,12 @@ import { existsSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('env'); function loadEnvFile(filePath: string) { if (!existsSync(filePath)) { - console.warn(`Warning: File ${filePath} not found`); + logger.warn(`Warning: File ${filePath} not found`); return; } @@ -24,15 +27,15 @@ function loadEnvFile(filePath: string) { } } } - console.log(`✅ Loaded: ${filePath}`); + logger.log(`✅ Loaded: ${filePath}`); } catch (error) { - console.warn(`Warning: Could not load ${filePath}`); - console.warn(error); + logger.warn(`Warning: Could not load ${filePath}`); + logger.warn(error); } } const nodeEnv = process.env.NODE_ENV || 'development'; -console.log(`🌍 Environment: ${nodeEnv}`); +logger.log(`🌍 Environment: ${nodeEnv}`); const ENV_FILES = { test: join(process.cwd(), '.env.test'), @@ -44,6 +47,6 @@ const envFile = ENV_FILES[nodeEnv as keyof typeof ENV_FILES]; if (envFile) { loadEnvFile(envFile); } else { - console.error(`❌ Environment file ${nodeEnv} not found`); + logger.error(`❌ Environment file ${nodeEnv} not found`); process.exit(1); } From de564b7ea363027fa66e779ad641935e3301550f Mon Sep 17 00:00:00 2001 From: Wiktoria Van Harneveldt Date: Sat, 14 Nov 2026 16:02:31 +0100 Subject: [PATCH 3/4] feat: give them all a prefix when logging --- src/common/events/load-events.ts | 7 +++- .../interactions/autocomplete-interaction.ts | 5 ++- src/common/interactions/button-interaction.ts | 5 ++- src/common/interactions/modal-interaction.ts | 5 ++- .../interactions/select-menu-interaction.ts | 5 ++- src/features/auto-roles/index.ts | 5 ++- src/features/docs/utils.ts | 9 +++-- src/features/interaction-create/index.ts | 13 +++--- src/features/moderation/repel.ts | 15 ++++--- src/features/onboarding/index.ts | 5 ++- src/features/public-guides/index.ts | 5 ++- src/features/quote/index.ts | 5 ++- src/features/ready/index.ts | 35 +++++++++++----- src/features/report-message/index.ts | 5 ++- src/features/showcase-digest/handlers.ts | 7 +++- src/features/showcase-digest/triggers.ts | 13 +++--- src/features/showcase-digest/util.ts | 9 +++-- src/features/showcase/create-showcase.ts | 9 +++-- src/features/showcase/delete-showcase.ts | 7 +++- src/features/showcase/edit-showcase.ts | 9 +++-- src/features/spam-detection/actions.ts | 5 ++- src/features/tags/delete-tag.ts | 5 ++- src/features/tags/edit-tag.ts | 5 ++- src/loadEnvFile.ts | 2 +- src/scripts/deploy-commands.ts | 9 +++-- src/scripts/sync-guides.ts | 23 ++++++----- .../user-bot-messages-service.ts | 5 ++- src/util/advent-scheduler.ts | 23 ++++++----- src/util/cache/recent-message-store.ts | 40 +++++++++++-------- src/util/channel-logging.ts | 9 +++-- src/util/channel-prefetch.ts | 7 +++- src/util/post-guides.ts | 27 +++++++------ src/util/server-guard.ts | 9 +++-- 33 files changed, 229 insertions(+), 118 deletions(-) diff --git a/src/common/events/load-events.ts b/src/common/events/load-events.ts index 9eb2092..0669b5f 100644 --- a/src/common/events/load-events.ts +++ b/src/common/events/load-events.ts @@ -1,14 +1,17 @@ import type { Client } from 'discord.js'; import { events } from './index.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('events'); export const loadEvents = (client: Client) => { for (const event of events) { - console.log(`Loading event: ${event.name}`); + logger.log(`Loading event: ${event.name}`); client[event.once ? 'once' : 'on'](event.name, async (...args) => { try { await event.execute(...args); } catch (error) { - console.error(`Error executing event ${event.name}:`, error); + logger.error(`Error executing event ${event.name}:`, error); } }); } diff --git a/src/common/interactions/autocomplete-interaction.ts b/src/common/interactions/autocomplete-interaction.ts index 3060073..90c847a 100644 --- a/src/common/interactions/autocomplete-interaction.ts +++ b/src/common/interactions/autocomplete-interaction.ts @@ -1,4 +1,7 @@ import type { AutocompleteInteraction } from 'discord.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('interactions'); export type AutoCompleteSubmitInteraction = { commandName: string; @@ -13,7 +16,7 @@ export const autoCompleteInteractions = new Map< export const registerAutocompleteInteraction = ( interaction: AutoCompleteSubmitInteraction ) => { - console.log( + logger.log( `Registering autocomplete interaction: ${interaction.commandName}` ); autoCompleteInteractions.set(interaction.commandName, interaction); diff --git a/src/common/interactions/button-interaction.ts b/src/common/interactions/button-interaction.ts index 1b51220..13d67fb 100644 --- a/src/common/interactions/button-interaction.ts +++ b/src/common/interactions/button-interaction.ts @@ -1,5 +1,8 @@ import type { ButtonInteraction } from 'discord.js'; import { parseCustomId } from '@/util/custom-id.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('interactions'); export type ButtonSubmitInteraction = { commandName: string; @@ -14,7 +17,7 @@ export const buttonSubmitInteractions = new Map< export const registerButtonSubmitInteraction = ( interaction: ButtonSubmitInteraction ) => { - console.log( + logger.log( `Registering button submit interaction: ${interaction.commandName}` ); buttonSubmitInteractions.set(interaction.commandName, interaction); diff --git a/src/common/interactions/modal-interaction.ts b/src/common/interactions/modal-interaction.ts index 949bc17..f9e17c2 100644 --- a/src/common/interactions/modal-interaction.ts +++ b/src/common/interactions/modal-interaction.ts @@ -1,5 +1,8 @@ import type { ModalSubmitInteraction as ModalInteraction } from 'discord.js'; import { parseCustomId } from '@/util/custom-id.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('interactions'); export type ModalSubmitInteraction = { commandName: string; @@ -14,7 +17,7 @@ export const modalSubmitInteractions = new Map< export const registerModalSubmitInteraction = ( interaction: ModalSubmitInteraction ) => { - console.log( + logger.log( `Registering modal submit interaction: ${interaction.commandName}` ); modalSubmitInteractions.set(interaction.commandName, interaction); diff --git a/src/common/interactions/select-menu-interaction.ts b/src/common/interactions/select-menu-interaction.ts index 38aa1f1..549a50d 100644 --- a/src/common/interactions/select-menu-interaction.ts +++ b/src/common/interactions/select-menu-interaction.ts @@ -1,5 +1,8 @@ import type { StringSelectMenuInteraction } from 'discord.js'; import { parseCustomId } from '@/util/custom-id.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('interactions'); export type SelectMenuSubmitInteraction = { commandName: string; @@ -14,7 +17,7 @@ export const selectMenuSubmitInteractions = new Map< export const registerSelectMenuSubmitInteraction = ( interaction: SelectMenuSubmitInteraction ) => { - console.log( + logger.log( `Registering select menu submit interaction: ${interaction.commandName}` ); selectMenuSubmitInteractions.set(interaction.commandName, interaction); diff --git a/src/features/auto-roles/index.ts b/src/features/auto-roles/index.ts index c278014..579f885 100644 --- a/src/features/auto-roles/index.ts +++ b/src/features/auto-roles/index.ts @@ -5,6 +5,9 @@ import { Events } from 'discord.js'; import { createEvent } from '@/common/events/create-event.js'; import { config } from '@/env.js'; import { hasAllRoles } from '@/util/member.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('auto-roles'); export const autoRoleEvent = createEvent( { @@ -22,7 +25,7 @@ export const autoRoleEvent = createEvent( try { await newMember.roles.add(config.roleIds.c); } catch (error) { - console.error(`Failed to add roleC to ${newMember.user.tag}:`, error); + logger.error(`Failed to add roleC to ${newMember.user.tag}:`, error); } } } diff --git a/src/features/docs/utils.ts b/src/features/docs/utils.ts index faa1af9..6bb7afe 100644 --- a/src/features/docs/utils.ts +++ b/src/features/docs/utils.ts @@ -2,6 +2,9 @@ import { type CommandInteraction, MessageFlags } from 'discord.js'; import { logToChannel } from '@/util/channel-logging.js'; import type { FeatureData } from './baseline.js'; import type { ProviderConfig } from './types.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('docs'); export const SEARCH_TERM = '%SEARCH%'; export const TERM = '%TERM%'; @@ -31,7 +34,7 @@ export const executeDocCommand = async ( try { await interaction.deferReply({ flags: MessageFlags.Ephemeral }); } catch (error) { - console.error(`deferReply FAILED:`, error); + logger.error(`deferReply FAILED:`, error); return; } @@ -90,12 +93,12 @@ export const executeDocCommand = async ( }, }); } else if (componentInteraction.isButton()) { - console.log('Documentation command cancelled by user.'); + logger.log('Documentation command cancelled by user.'); await interaction.deleteReply(); } }); } catch (error) { - console.error(`executeDocCommand FAILED:`, error); + logger.error(`executeDocCommand FAILED:`, error); await interaction.editReply({ content: `Error: ${String(error)}` }); } }; diff --git a/src/features/interaction-create/index.ts b/src/features/interaction-create/index.ts index 8c8dded..fcf5fce 100644 --- a/src/features/interaction-create/index.ts +++ b/src/features/interaction-create/index.ts @@ -6,6 +6,9 @@ import { handleButtonInteraction } from '@/common/interactions/button-interactio import { handleModalInteraction } from '@/common/interactions/modal-interaction.js'; import { handleSelectMenuInteraction } from '@/common/interactions/select-menu-interaction.js'; import { isAllowedServer } from '@/util/server-guard.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('interactions'); export const interactionCreateEvent = createEvent( { @@ -13,7 +16,7 @@ export const interactionCreateEvent = createEvent( }, async (interaction) => { if (!interaction.guildId || !isAllowedServer(interaction.guildId)) { - console.log( + logger.log( `âš ī¸ Command blocked from unauthorized server: ${interaction.guildId}` ); if (interaction.isRepliable()) { @@ -25,7 +28,7 @@ export const interactionCreateEvent = createEvent( return; } if (interaction.isButton()) { - console.log( + logger.log( `Received button interaction with custom ID: ${interaction.customId}` ); await handleButtonInteraction(interaction); @@ -33,7 +36,7 @@ export const interactionCreateEvent = createEvent( } if (interaction.isModalSubmit()) { - console.log( + logger.log( `Received modal submit interaction with custom ID: ${interaction.customId}` ); await handleModalInteraction(interaction); @@ -41,7 +44,7 @@ export const interactionCreateEvent = createEvent( } if (interaction.isStringSelectMenu()) { - console.log( + logger.log( `Received select menu interaction with custom ID: ${interaction.customId}` ); await handleSelectMenuInteraction(interaction); @@ -49,7 +52,7 @@ export const interactionCreateEvent = createEvent( } if (interaction.isAutocomplete()) { - console.log( + logger.log( `Received autocomplete interaction with custom ID: ${interaction.commandName}` ); await handleAutoCompleteInteraction(interaction); diff --git a/src/features/moderation/repel.ts b/src/features/moderation/repel.ts index 3a22b7b..8e38878 100644 --- a/src/features/moderation/repel.ts +++ b/src/features/moderation/repel.ts @@ -22,6 +22,9 @@ import { buildCommandString } from '../../util/build-command-string.js'; import { getPublicChannels } from '../../util/channel.js'; import { logToChannel } from '../../util/channel-logging.js'; import { SERVER_CHANNELS } from '@/constants/channels.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('moderation'); const DEFAULT_LOOK_BACK_MS = 10 * MINUTE; const DEFAULT_TIMEOUT_DURATION_MS = 1 * HOUR; @@ -149,7 +152,7 @@ const getTargetFromInteraction = async ( try { target = await interaction.guild.members.fetch(targetFromOption.id); } catch (error) { - console.error('Error fetching target as guild member:', error); + logger.error('Error fetching target as guild member:', error); target = targetFromOption; } return target; @@ -173,14 +176,14 @@ const handleTimeout = async ({ await target.timeout(durationInMilliseconds, 'Repel command executed'); return durationInMilliseconds; } catch (error) { - console.error('Error applying timeout to user:', error); + logger.error('Error applying timeout to user:', error); return 0; } }; const getTextChannels = (interaction: ChatInputCommandInteraction) => { if (!interaction.inGuild() || !interaction.guild) { - console.error('Interaction is not in a guild'); + logger.error('Interaction is not in a guild'); return []; } const channels = Array.from(getPublicChannels(interaction.guild).values()); @@ -254,7 +257,7 @@ const handleDeleteMessages = async ({ await channel.bulkDelete(messagesToDelete, true); deleted += messagesToDelete.length; } catch (error) { - console.error( + logger.error( `Error deleting messages in channel ${channel.name}:`, error ); @@ -264,7 +267,7 @@ const handleDeleteMessages = async ({ }) ); if (failedChannels.length > 0) { - console.error( + logger.error( `Failed to delete messages in ${failedChannels.length} channel(s).` ); } @@ -565,7 +568,7 @@ export const repelCommand = createSlashCommand({ content: `Deleted ${deleted} message(s).`, }); } catch (error) { - console.error('Error executing repel command:', error); + logger.error('Error executing repel command:', error); } }, }); diff --git a/src/features/onboarding/index.ts b/src/features/onboarding/index.ts index 5170693..de867cd 100644 --- a/src/features/onboarding/index.ts +++ b/src/features/onboarding/index.ts @@ -3,6 +3,9 @@ import { createSlashCommand } from '../../common/commands/create-commands.js'; import { config } from '../../env.js'; import { addRoleToUser } from '../../util/add-role-to-user.js'; import { containerComponent } from './component.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('onboarding'); export const onboardingCommand = createSlashCommand({ data: { @@ -64,7 +67,7 @@ export const onboardingCommand = createSlashCommand({ content: `Failed to add role. Please contact an administrator.`, flags: MessageFlags.Ephemeral, }); - console.error('Error adding role:\n', error); + logger.error('Error adding role:\n', error); } } }); diff --git a/src/features/public-guides/index.ts b/src/features/public-guides/index.ts index f56607c..b349904 100644 --- a/src/features/public-guides/index.ts +++ b/src/features/public-guides/index.ts @@ -10,6 +10,9 @@ import { initializeGuidesChannel, syncGuidesToChannel, } from '@/util/post-guides.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('guides'); export const publicGuidesCommand = createSlashCommand({ data: { @@ -49,7 +52,7 @@ export const publicGuidesCommand = createSlashCommand({ '✅ Guides have been synchronized successfully.' ); } catch (error) { - console.error('Error synchronizing guides:', error); + logger.error('Error synchronizing guides:', error); await interaction.editReply( '❌ An error occurred while synchronizing guides. Please check the logs for details.' ); diff --git a/src/features/quote/index.ts b/src/features/quote/index.ts index dceaa45..439b23c 100644 --- a/src/features/quote/index.ts +++ b/src/features/quote/index.ts @@ -2,6 +2,9 @@ import { Client, Events, type Message } from 'discord.js'; import { createEvent } from '@/common/events/create-event.js'; import { UserBotMessagesService } from '@/services/user-bot-messages/user-bot-messages-service.js'; import { createQuoteEmbed } from './embed.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('quote'); export const quoteEvent = createEvent( { @@ -91,7 +94,7 @@ export const quoteEvent = createEvent( for (const result of results) { if (result.status === 'rejected') { - console.error('Failed to send quote message:', result.reason); + logger.error('Failed to send quote message:', result.reason); } } diff --git a/src/features/ready/index.ts b/src/features/ready/index.ts index 0475cf9..f231abe 100644 --- a/src/features/ready/index.ts +++ b/src/features/ready/index.ts @@ -9,6 +9,13 @@ import { syncGuidesToChannel } from '@/util/post-guides.js'; import { leaveIfNotAllowedServer } from '@/util/server-guard.js'; import { syncArchiveCategoryChannels } from '../archive-channels/util.js'; import { UserBotMessagesService } from '@/services/user-bot-messages/user-bot-messages-service.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('ready'); +const guidesLogger = createLogger('guides'); +const adventOfCodeLogger = createLogger('advent-of-code'); +const showcaseDigestLogger = createLogger('showcase-digest'); +const archiveChannelsLogger = createLogger('archive-channels'); export const readyEvent = createEvent( { @@ -16,20 +23,20 @@ export const readyEvent = createEvent( once: true, }, async (client) => { - console.log(`Ready! Logged in as ${client.user.tag}`); + logger.log(`Ready! Logged in as ${client.user.tag}`); // Check all guilds and leave any unauthorized ones - console.log(`🔍 Checking ${client.guilds.cache.size} guild(s)...`); + logger.log(`🔍 Checking ${client.guilds.cache.size} guild(s)...`); for (const guild of client.guilds.cache.values()) { await leaveIfNotAllowedServer(guild); } const guild = client.guilds.cache.get(config.discord.serverId); if (!guild) { - console.error( + logger.error( `❌ Bot is not in the configured server with ID ${config.discord.serverId}` ); - console.error('Please check your .env file or CI/CD configuration'); + logger.error('Please check your .env file or CI/CD configuration'); process.exit(1); } @@ -40,7 +47,7 @@ export const readyEvent = createEvent( } // Sync guides to channel try { - console.log( + guidesLogger.log( `🔄 Starting guide sync to channel ${config.channelIds.guides}...` ); await syncGuidesToChannel(client, config.channelIds.guides); @@ -48,34 +55,40 @@ export const readyEvent = createEvent( if (error && typeof error === 'object' && 'code' in error) { const discordError = error as { code: number; message?: string }; if (discordError.code === 50001) { - console.warn( + guidesLogger.warn( 'âš ī¸ Bot does not have access to the guides channel. Please check bot permissions and channel ID.' ); } else { - console.error('❌ Failed to sync guides:', error); + guidesLogger.error('❌ Failed to sync guides:', error); } } else { - console.error('❌ Failed to sync guides:', error); + guidesLogger.error('❌ Failed to sync guides:', error); } } try { initializeAdventScheduler(client, config.channelIds.adventOfCode); } catch (error) { - console.error('❌ Failed to initialize Advent of Code scheduler:', error); + adventOfCodeLogger.error( + '❌ Failed to initialize Advent of Code scheduler:', + error + ); } try { initializeShowcaseDigestScheduler(); } catch (error) { - console.error('Failed to initialize showcase digest scheduler:', error); + showcaseDigestLogger.error( + 'Failed to initialize showcase digest scheduler:', + error + ); } // Make sure all channels in the archived category are properly archived on startup try { await syncArchiveCategoryChannels(); } catch (error) { - console.error( + archiveChannelsLogger.error( '❌ Failed to ensure archived channels are properly archived:', error ); diff --git a/src/features/report-message/index.ts b/src/features/report-message/index.ts index 608f7b7..5c6b166 100644 --- a/src/features/report-message/index.ts +++ b/src/features/report-message/index.ts @@ -1,6 +1,9 @@ import { createMessageContextMenuCommand } from '@/common/commands/create-commands.js'; import { SERVER_CHANNELS } from '@/constants/channels.js'; import { Colors, EmbedBuilder, MessageFlags } from 'discord.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('report-message'); export const reportMessage = createMessageContextMenuCommand({ data: { @@ -52,7 +55,7 @@ export const reportMessage = createMessageContextMenuCommand({ content: 'Thanks. The message was reported to moderators.', }); } catch (error) { - console.error(error); + logger.error(error); await interaction.editReply({ content: 'Failed to report the message.', }); diff --git a/src/features/showcase-digest/handlers.ts b/src/features/showcase-digest/handlers.ts index 19b1207..34ef459 100644 --- a/src/features/showcase-digest/handlers.ts +++ b/src/features/showcase-digest/handlers.ts @@ -20,6 +20,9 @@ import { type Post, ShowcaseDigestValidationError, } from './util.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('showcase-digest'); const postProcessor = async (posts: Collection) => { const postsUnordered: Post[] = await convertPosts(posts, REACT_EMOJI); @@ -107,13 +110,13 @@ export const digestHandler = async ( await createShowcaseDigest(); } catch (error: unknown) { if (error instanceof ShowcaseDigestValidationError) { - console.error(error.message); + logger.error(error.message); await interaction.reply({ flags: MessageFlags.Ephemeral, content: error.getExternalMessage(), }); } else { - console.error('An unexpected error caught:', error); + logger.error('An unexpected error caught:', error); await interaction.reply({ flags: MessageFlags.Ephemeral, content: 'Something went wrong, please try again.', diff --git a/src/features/showcase-digest/triggers.ts b/src/features/showcase-digest/triggers.ts index e65f9d8..a86dae6 100644 --- a/src/features/showcase-digest/triggers.ts +++ b/src/features/showcase-digest/triggers.ts @@ -2,6 +2,9 @@ import * as cron from 'node-cron'; import { createSlashCommand } from '@/common/commands/create-commands.js'; import { LOOKBACK_N } from './config.js'; import { digestHandler, createShowcaseDigest } from './handlers.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('showcase-digest'); export const createDigestCommand = createSlashCommand({ data: { @@ -17,23 +20,23 @@ export const createDigestCommand = createSlashCommand({ const SHOWCASE_DIGEST_CRONS = ['0 16 * * 5#1', '0 16 * * 5#3']; const runScheduledShowcaseDigest = async (): Promise => { - console.log('Running scheduled showcase digest...'); + logger.log('Running scheduled showcase digest...'); try { await createShowcaseDigest(); - console.log(`Successfully displayed showcase digest!`); + logger.log(`Successfully displayed showcase digest!`); } catch (error) { - console.error(error); + logger.error(error); } }; export function initializeShowcaseDigestScheduler(): void { - console.log('Initializing showcase digest scheduler...'); + logger.log('Initializing showcase digest scheduler...'); SHOWCASE_DIGEST_CRONS.forEach((expression) => { cron.schedule(expression, runScheduledShowcaseDigest, { timezone: 'UTC' }); }); - console.log( + logger.log( 'Showcase digest scheduler initialized (runs 1st and 3rd Fridays at 16:00 UTC)' ); } diff --git a/src/features/showcase-digest/util.ts b/src/features/showcase-digest/util.ts index e7d2195..15091d8 100644 --- a/src/features/showcase-digest/util.ts +++ b/src/features/showcase-digest/util.ts @@ -1,5 +1,8 @@ import { DAY } from '@/constants/time.js'; import { Collection, ForumThreadChannel, MessageReaction } from 'discord.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('showcase-digest'); export type Post = { id: string; messageCount: number; likes: number }; @@ -38,9 +41,9 @@ export const convertPosts = async ( return settled.flatMap((result) => { if (result.status === 'rejected') { if (result.reason instanceof ShowcaseDigestValidationError) { - console.error(result.reason.message); + logger.error(result.reason.message); } else { - console.error( + logger.error( 'Unexpected error in scheduled showcase digest:', result.reason ); @@ -59,7 +62,7 @@ export const filterPostsByCreationTime = ( return posts.filter((post) => { const creationTime = post.createdAt?.getTime(); if (!creationTime) { - console.error('Creation time is missing from post on showcase-digest'); + logger.error('Creation time is missing from post on showcase-digest'); return false; } return creationTime > now - DAY * lookbackN; diff --git a/src/features/showcase/create-showcase.ts b/src/features/showcase/create-showcase.ts index 108edc4..b3da430 100644 --- a/src/features/showcase/create-showcase.ts +++ b/src/features/showcase/create-showcase.ts @@ -24,6 +24,9 @@ import { deleteShowcase, deleteShowcaseModal } from './delete-showcase.js'; import { editShowcaseInteraction } from './edit-showcase.js'; import { buildShowcaseModal, createShowcaseMessageContent } from './util.js'; import { SERVER_CHANNELS } from '@/constants/channels.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('showcase'); export const showModal = async ( interaction: ButtonInteraction | ChatInputCommandInteraction @@ -36,7 +39,7 @@ export const showModal = async ( await interaction.showModal(modal); } catch (error) { - console.error('Error showing showcase modal:', error); + logger.error('Error showing showcase modal:', error); await interaction.reply({ content: 'There was an error showing the showcase modal. Please try again later.', @@ -140,14 +143,14 @@ const modalHandler: ModalSubmitInteraction = { silent: true, }); } catch (error) { - console.error('Failed to log showcase creation:', error); + logger.error('Failed to log showcase creation:', error); } await interaction.editReply({ content: `Your project has been showcased successfully! You can view it here: ${thread.url}`, }); } catch (error) { - console.error('Error creating showcase thread:', error); + logger.error('Error creating showcase thread:', error); await interaction.editReply({ content: 'There was an error showcasing your project. Please try again later.', diff --git a/src/features/showcase/delete-showcase.ts b/src/features/showcase/delete-showcase.ts index b2f634a..6422794 100644 --- a/src/features/showcase/delete-showcase.ts +++ b/src/features/showcase/delete-showcase.ts @@ -12,6 +12,9 @@ import { customId, parseCustomId } from '@/util/custom-id.js'; import { isUserInServer, isUserModerator } from '@/util/member.js'; import { SERVER_CHANNELS } from '@/constants/channels.js'; import { buildDeleteShowcaseModal, parseShowcaseMessage } from './util.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('showcase'); const logShowcaseDeletion = async ({ projectName, @@ -118,7 +121,7 @@ export const deleteShowcase: ButtonSubmitInteraction = { flags: MessageFlags.Ephemeral, }); } catch (error) { - console.error('Error deleting showcase:', error); + logger.error('Error deleting showcase:', error); await interaction.reply({ content: '❌ An error occurred while trying to delete the showcase.', flags: MessageFlags.Ephemeral, @@ -188,7 +191,7 @@ export const deleteShowcaseModal: ModalSubmitInteraction = { reason: deleteReason, }); } catch (error) { - console.error('Error deleting showcase via modal:', error); + logger.error('Error deleting showcase via modal:', error); await interaction.reply({ content: '❌ An error occurred while trying to delete the showcase.', flags: MessageFlags.Ephemeral, diff --git a/src/features/showcase/edit-showcase.ts b/src/features/showcase/edit-showcase.ts index 771c039..e486cd9 100644 --- a/src/features/showcase/edit-showcase.ts +++ b/src/features/showcase/edit-showcase.ts @@ -23,6 +23,9 @@ import { resolveTagNames, } from './util.js'; import { SERVER_CHANNELS } from '@/constants/channels.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('showcase'); export const editShowcaseInteraction: ButtonSubmitInteraction = { commandName: 'edit_showcase', @@ -99,7 +102,7 @@ export const editShowcaseInteraction: ButtonSubmitInteraction = { await interaction.showModal(modal); } catch (error) { - console.error('Error editing showcase:', error); + logger.error('Error editing showcase:', error); await interaction.reply({ content: '❌ An error occurred while trying to edit the showcase.', flags: MessageFlags.Ephemeral, @@ -306,7 +309,7 @@ const modalHandler: ModalSubmitInteraction = { allowedMentions: { parse: [] }, }); } catch (error) { - console.error('Failed to log showcase edit:', error); + logger.error('Failed to log showcase edit:', error); } } @@ -314,7 +317,7 @@ const modalHandler: ModalSubmitInteraction = { content: '✅ Showcase updated successfully!', }); } catch (error) { - console.error('Error updating showcase:', error); + logger.error('Error updating showcase:', error); await interaction.reply({ content: '❌ An error occurred while trying to update the showcase.', flags: MessageFlags.Ephemeral, diff --git a/src/features/spam-detection/actions.ts b/src/features/spam-detection/actions.ts index 693822e..2ff6896 100644 --- a/src/features/spam-detection/actions.ts +++ b/src/features/spam-detection/actions.ts @@ -4,6 +4,9 @@ import { DAY, HOUR, SECOND } from '../../constants/time.js'; import { defaultLogFunction, type LogFunction } from './logs.js'; import { finishModeration, startModeration } from './moderation-state.js'; import type { Rule } from './rules-config.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('spam-detection'); type ActionConfig = { reason: string; @@ -79,7 +82,7 @@ const handleAction = (config: ActionConfig) => { muted = true; } } catch (error) { - console.error('Failed to mute user:', error); + logger.error('Failed to mute user:', error); } } diff --git a/src/features/tags/delete-tag.ts b/src/features/tags/delete-tag.ts index f292a4a..2e75681 100644 --- a/src/features/tags/delete-tag.ts +++ b/src/features/tags/delete-tag.ts @@ -8,6 +8,9 @@ import { import { getTagPrimaryAlias } from '@/util/tags.js'; import { getCommandUser } from '@/util/member.js'; import { canAccessTags } from './permissions.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('tags'); export const deleteTagCommandHandler = async ( interaction: ChatInputCommandInteraction @@ -43,7 +46,7 @@ export const deleteTagCommandHandler = async ( flags: MessageFlags.IsComponentsV2, }); } catch (error) { - console.error('Error deleting tag:', error); + logger.error('Error deleting tag:', error); if (!interaction.replied) { await interaction.editReply({ components: [ diff --git a/src/features/tags/edit-tag.ts b/src/features/tags/edit-tag.ts index 026d5de..85dcd65 100644 --- a/src/features/tags/edit-tag.ts +++ b/src/features/tags/edit-tag.ts @@ -22,6 +22,9 @@ import { customId, parseCustomId } from '@/util/custom-id.js'; import { isValidTagName, getTagPrimaryAlias } from '@/util/tags.js'; import { getCommandUser } from '@/util/member.js'; import { canAccessTags } from './permissions.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('tags'); const BASE_NAME = 'tags-edit'; @@ -141,7 +144,7 @@ const modalHandler: ModalSubmitInteraction = { flags: MessageFlags.Ephemeral | MessageFlags.IsComponentsV2, }); } catch (error) { - console.error(error); + logger.error(error); if ( error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002' diff --git a/src/loadEnvFile.ts b/src/loadEnvFile.ts index 54788d8..d341679 100644 --- a/src/loadEnvFile.ts +++ b/src/loadEnvFile.ts @@ -1,6 +1,6 @@ import { existsSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; -import { createLogger } from '@/util/logger.js'; +import { createLogger } from './util/logger.js'; const logger = createLogger('env'); diff --git a/src/scripts/deploy-commands.ts b/src/scripts/deploy-commands.ts index a20cf3e..c0cbd90 100644 --- a/src/scripts/deploy-commands.ts +++ b/src/scripts/deploy-commands.ts @@ -6,9 +6,12 @@ import { import { commands } from '@/common/commands/index.js'; import { config } from '@/env.js'; import { pathToFileURL } from 'node:url'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('deploy-commands'); export async function deployCommands() { - console.log('Deploying commands...'); + logger.log('Deploying commands...'); const commandData = [...commands.values()].map((command) => command.data); const rest = new REST({ version: '10' }).setToken(config.discord.token); @@ -23,11 +26,11 @@ export async function deployCommands() { body: commandData, } )) as RESTPutAPIApplicationCommandsResult; - console.log( + logger.log( `✅ Successfully deployed ${result.length} commands to guild ${config.discord.serverId}` ); } catch (error) { - console.error('❌ Error deploying commands:', error); + logger.error('❌ Error deploying commands:', error); } } diff --git a/src/scripts/sync-guides.ts b/src/scripts/sync-guides.ts index 9674326..94b4459 100644 --- a/src/scripts/sync-guides.ts +++ b/src/scripts/sync-guides.ts @@ -11,18 +11,21 @@ import { initializeGuidesChannel, syncGuidesToChannel, } from '@/util/post-guides.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('guides'); async function main() { const args = process.argv.slice(2); const shouldInitialize = args.includes('--initialize'); if (!config.channelIds.guides) { - console.error('❌ GUIDES_CHANNEL_ID environment variable is required'); - console.error('Please set it in your environment variables'); + logger.error('❌ GUIDES_CHANNEL_ID environment variable is required'); + logger.error('Please set it in your environment variables'); process.exit(1); } - console.log(`🤖 Starting Discord client for guide sync...`); + logger.log(`🤖 Starting Discord client for guide sync...`); const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages], @@ -30,29 +33,29 @@ async function main() { try { await client.login(config.discord.token); - console.log(`✅ Logged in as ${client.user?.tag}`); + logger.log(`✅ Logged in as ${client.user?.tag}`); if (shouldInitialize) { - console.log( + logger.log( '🚀 Initializing guides channel (will post all guides fresh)...' ); await initializeGuidesChannel(client, config.channelIds.guides); } else { - console.log('🔄 Synchronizing guides...'); + logger.log('🔄 Synchronizing guides...'); await syncGuidesToChannel(client, config.channelIds.guides); } - console.log('✅ Guide synchronization completed successfully'); + logger.log('✅ Guide synchronization completed successfully'); } catch (error) { - console.error('❌ Guide synchronization failed:', error); + logger.error('❌ Guide synchronization failed:', error); process.exit(1); } finally { await client.destroy(); - console.log('👋 Discord client disconnected'); + logger.log('👋 Discord client disconnected'); } } main().catch((error) => { - console.error('❌ Unexpected error:', error); + logger.error('❌ Unexpected error:', error); process.exit(1); }); diff --git a/src/services/user-bot-messages/user-bot-messages-service.ts b/src/services/user-bot-messages/user-bot-messages-service.ts index 3a6bb60..fb91c6f 100644 --- a/src/services/user-bot-messages/user-bot-messages-service.ts +++ b/src/services/user-bot-messages/user-bot-messages-service.ts @@ -4,6 +4,9 @@ import { isStaff } from '@/util/permissions.js'; import { DAY } from '@/constants/time.js'; import { getBotOption } from '@/options.js'; import { OptionKey } from '@/generated/prisma/enums.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('user-bot-messages'); export const UserBotMessagesService = { async deleteUserBotMessage({ @@ -60,7 +63,7 @@ export const UserBotMessagesService = { where: { expiresAt: { lte: new Date() } }, }); if (count > 0) { - console.log(`Cleaned up ${count} expired user bot messages.`); + logger.log(`Cleaned up ${count} expired user bot messages.`); } }; diff --git a/src/util/advent-scheduler.ts b/src/util/advent-scheduler.ts index aa942ad..9c6e4db 100644 --- a/src/util/advent-scheduler.ts +++ b/src/util/advent-scheduler.ts @@ -2,6 +2,9 @@ import { promises as fs } from 'node:fs'; import { ChannelType, type Client } from 'discord.js'; import * as cron from 'node-cron'; import { config } from '@/env.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('advent-of-code'); const TRACKER_FILE = config.adventOfCodeTrackerPath; @@ -54,12 +57,12 @@ async function createAdventPost( const channel = await client.channels.fetch(channelId); if (!channel) { - console.error(`❌ Advent of Code channel not found: ${channelId}`); + logger.error(`❌ Advent of Code channel not found: ${channelId}`); return false; } if (channel.type !== ChannelType.GuildForum) { - console.error( + logger.error( `❌ Advent of Code channel is not a forum channel. Type: ${channel.type}` ); return false; @@ -76,10 +79,10 @@ async function createAdventPost( }, }); - console.log(`✅ Created Advent of Code post: ${title}`); + logger.log(`✅ Created Advent of Code post: ${title}`); return true; } catch (error) { - console.error( + logger.error( `❌ Failed to create Advent of Code post for day ${day}:`, error ); @@ -106,7 +109,7 @@ async function checkAndCreateTodaysPost( const alreadyPosted = await isDayPosted(year, day); if (alreadyPosted) { - console.log(`â„šī¸ Advent of Code post for ${year} day ${day} already exists`); + logger.log(`â„šī¸ Advent of Code post for ${year} day ${day} already exists`); return; } @@ -125,10 +128,10 @@ export function initializeAdventScheduler( client: Client, channelId: string ): void { - console.log('🎄 Initializing Advent of Code scheduler...'); + logger.log('🎄 Initializing Advent of Code scheduler...'); checkAndCreateTodaysPost(client, channelId).catch((error) => { - console.error( + logger.error( '❌ Error checking for Advent of Code post on startup:', error ); @@ -137,13 +140,13 @@ export function initializeAdventScheduler( // Schedule to run every day at midnight UTC-5 // https://github.com/node-cron/node-cron?tab=readme-ov-file#cron-syntax cron.schedule('0 5 * * *', () => { - console.log('⏰ Running scheduled Advent of Code check...'); + logger.log('⏰ Running scheduled Advent of Code check...'); checkAndCreateTodaysPost(client, channelId).catch((error) => { - console.error('❌ Error in scheduled Advent of Code check:', error); + logger.error('❌ Error in scheduled Advent of Code check:', error); }); }); - console.log( + logger.log( '✅ Advent of Code scheduler initialized (runs daily at midnight UTC)' ); } diff --git a/src/util/cache/recent-message-store.ts b/src/util/cache/recent-message-store.ts index 2ad401f..5021ca5 100644 --- a/src/util/cache/recent-message-store.ts +++ b/src/util/cache/recent-message-store.ts @@ -1,5 +1,13 @@ import type { Message } from 'discord.js'; import { MAX_RULE_TIMEFRAME } from '@/features/spam-detection/constants.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('spam-detection'); + +function throwLoggedError(message: string): never { + logger.error(message); + throw new Error(message); +} // O(1) Priority Queue implementation for LRU eviction class MinHeap { @@ -123,10 +131,10 @@ export class MessageCache { constructor(maxSize: number = 1000, cleanupInterval: number = 100) { if (maxSize <= 0) { - throw new Error('maxSize must be positive'); + throwLoggedError('maxSize must be positive'); } if (cleanupInterval <= 0) { - throw new Error('cleanupInterval must be positive'); + throwLoggedError('cleanupInterval must be positive'); } this.maxSize = maxSize; this.cleanupInterval = cleanupInterval; @@ -134,7 +142,7 @@ export class MessageCache { add(message: Message): void { if (!message || !message.id || !message.author || !message.channelId) { - throw new Error( + throwLoggedError( 'Invalid message: must be a valid Discord.js Message object' ); } @@ -219,7 +227,7 @@ export class MessageCache { // Bulk delete old messages if (messagesToDelete.length > 0) { - console.log( + logger.log( `Cleaning up ${messagesToDelete.length} old messages from cache (older than ${maxRuleTimeframe}ms)` ); this.bulkDeleteByIds(messagesToDelete); @@ -233,14 +241,14 @@ export class MessageCache { maxRuleTimeframe <= 0 || Number.isNaN(maxRuleTimeframe) ) { - throw new Error('Invalid maxRuleTimeframe: must be a positive number'); + throwLoggedError('Invalid maxRuleTimeframe: must be a positive number'); } this.cleanupOldMessages(maxRuleTimeframe); } get(messageId: string): Message | undefined { if (!messageId || typeof messageId !== 'string') { - throw new Error('Invalid messageId: must be a non-empty string'); + throwLoggedError('Invalid messageId: must be a non-empty string'); } // Update LRU on access - O(log n) for heap operations @@ -255,14 +263,14 @@ export class MessageCache { has(messageId: string): boolean { if (!messageId || typeof messageId !== 'string') { - throw new Error('Invalid messageId: must be a non-empty string'); + throwLoggedError('Invalid messageId: must be a non-empty string'); } return this.cache.has(messageId); } delete(messageId: string): boolean { if (!messageId || typeof messageId !== 'string') { - throw new Error('Invalid messageId: must be a non-empty string'); + throwLoggedError('Invalid messageId: must be a non-empty string'); } if (!this.cache.has(messageId)) { @@ -312,7 +320,7 @@ export class MessageCache { // O(1) user message lookup using secondary index getUserMessages(userId: string): Message[] { if (!userId || typeof userId !== 'string') { - throw new Error('Invalid userId: must be a non-empty string'); + throwLoggedError('Invalid userId: must be a non-empty string'); } const messageIds = this.userMessages.get(userId); @@ -328,7 +336,7 @@ export class MessageCache { // O(1) channel message lookup using secondary index getChannelMessages(channelId: string): Message[] { if (!channelId || typeof channelId !== 'string') { - throw new Error('Invalid channelId: must be a non-empty string'); + throwLoggedError('Invalid channelId: must be a non-empty string'); } const messageIds = this.channelMessages.get(channelId); @@ -348,19 +356,19 @@ export class MessageCache { endTime?: number ): Message[] { if (!userId || typeof userId !== 'string') { - throw new Error('Invalid userId: must be a non-empty string'); + throwLoggedError('Invalid userId: must be a non-empty string'); } if (typeof startTime !== 'number' || Number.isNaN(startTime)) { - throw new Error('Invalid startTime: must be a valid number'); + throwLoggedError('Invalid startTime: must be a valid number'); } if ( endTime !== undefined && (typeof endTime !== 'number' || Number.isNaN(endTime)) ) { - throw new Error('Invalid endTime: must be a valid number or undefined'); + throwLoggedError('Invalid endTime: must be a valid number or undefined'); } if (endTime !== undefined && endTime < startTime) { - throw new Error( + throwLoggedError( 'Invalid time range: endTime must be greater than or equal to startTime' ); } @@ -382,12 +390,12 @@ export class MessageCache { bulkDeleteByIds(messageIds: string[]): void { if (!Array.isArray(messageIds)) { - throw new Error('Invalid messageIds: must be an array'); + throwLoggedError('Invalid messageIds: must be an array'); } for (const id of messageIds) { if (typeof id !== 'string' || !id) { - throw new Error( + throwLoggedError( 'Invalid messageId in array: must be non-empty strings' ); } diff --git a/src/util/channel-logging.ts b/src/util/channel-logging.ts index e6a944a..9bd870c 100644 --- a/src/util/channel-logging.ts +++ b/src/util/channel-logging.ts @@ -4,6 +4,9 @@ import type { SendableChannels, TextBasedChannel, } from 'discord.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('channel-logging'); export type SimpleLogContent = { type: 'simple'; @@ -58,7 +61,7 @@ const sendMessage = async ( await channel.send(options); return true; } catch (error) { - console.error('Failed to send log message:', error); + logger.error('Failed to send log message:', error); return false; } }; @@ -78,7 +81,7 @@ export const logToChannel = async ( return true; } catch (error) { if (!options.silent) { - console.error('Logging error:', error); + logger.error('Logging error:', error); } if (options.fallbackChannelId && options.channel?.client) { const fallbackChannel = await options.channel.client.channels.fetch( @@ -88,7 +91,7 @@ export const logToChannel = async ( return sendMessage(fallbackChannel, options.content); } else { if (!options.silent) { - console.error( + logger.error( 'Fallback channel is not a text-based channel or could not be fetched' ); } diff --git a/src/util/channel-prefetch.ts b/src/util/channel-prefetch.ts index 17f85d7..d7f8d2b 100644 --- a/src/util/channel-prefetch.ts +++ b/src/util/channel-prefetch.ts @@ -1,5 +1,8 @@ import type { Guild } from 'discord.js'; import { getPublicChannels } from './channel.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('cache-messages'); const PER_CHANNEL_CACHE_LIMIT = 100; const cachedChannelsMap = new Set(); @@ -20,13 +23,13 @@ export const fetchAndCachePublicChannelsMessages = async ( const messages = await channel.messages.fetch({ limit: PER_CHANNEL_CACHE_LIMIT, }); - console.log( + logger.log( `Fetched and cached ${messages.size} messages from channel ${channel.name} (${channel.id})` ); cachedChannelsMap.add(channel.id); cachedChannels++; } catch (error) { - console.error( + logger.error( `Failed to fetch messages from channel ${channel.name} (${channel.id}):`, error ); diff --git a/src/util/post-guides.ts b/src/util/post-guides.ts index e5412b7..759985e 100644 --- a/src/util/post-guides.ts +++ b/src/util/post-guides.ts @@ -9,6 +9,9 @@ import { } from 'discord.js'; import { config } from '@/env.js'; import { parseMarkdown } from './markdown.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('guides'); export type GuideInfo = { name: string; @@ -52,7 +55,7 @@ const loadTracker = async (): Promise => { const content = await readFile(TRACKER_FILE, 'utf8'); return JSON.parse(content); } catch { - console.log('No existing tracker file found, starting fresh'); + logger.log('No existing tracker file found, starting fresh'); return {}; } }; @@ -98,7 +101,7 @@ const postGuideToChannel = async ( embeds: [createGuideEmbed(guide)], }); - console.log(`✅ Posted guide "${guide.name}" (${guide.filename})`); + logger.log(`✅ Posted guide "${guide.name}" (${guide.filename})`); return message.id; }; @@ -113,9 +116,9 @@ const editGuideMessage = async ( embeds: [createGuideEmbed(guide)], }); - console.log(`📝 Updated guide "${guide.name}" (${guide.filename})`); + logger.log(`📝 Updated guide "${guide.name}" (${guide.filename})`); } catch (error) { - console.error( + logger.error( `Failed to edit message ${messageId} for guide "${guide.name}":`, error ); @@ -132,9 +135,9 @@ const deleteGuideMessage = async ( const message = await channel.messages.fetch(messageId); await message.delete(); - console.log(`đŸ—‘ī¸ Deleted guide "${guideName}"`); + logger.log(`đŸ—‘ī¸ Deleted guide "${guideName}"`); } catch (error) { - console.error( + logger.error( `Failed to delete message ${messageId} for guide "${guideName}":`, error ); @@ -145,7 +148,7 @@ export const syncGuidesToChannel = async ( client: Client, channelId: string ): Promise => { - console.log('🔄 Starting guide synchronization...'); + logger.log('🔄 Starting guide synchronization...'); try { const channel = await client.channels.fetch(channelId); @@ -180,7 +183,7 @@ export const syncGuidesToChannel = async ( ); }); - console.log( + logger.log( `📊 Found: ${newFiles.length} new, ${modifiedFiles.length} modified, ${deletedFiles.length} deleted` ); @@ -225,14 +228,14 @@ export const syncGuidesToChannel = async ( const totalChanges = newFiles.length + modifiedFiles.length + deletedFiles.length; if (totalChanges === 0) { - console.log('✨ All guides are up to date!'); + logger.log('✨ All guides are up to date!'); } else { - console.log( + logger.log( `✅ Guide synchronization complete! Made ${totalChanges} changes.` ); } } catch (error) { - console.error('❌ Guide synchronization failed:', error); + logger.error('❌ Guide synchronization failed:', error); throw error; } }; @@ -241,7 +244,7 @@ export const initializeGuidesChannel = async ( client: Client, channelId: string ): Promise => { - console.log('🚀 Initializing guides channel...'); + logger.log('🚀 Initializing guides channel...'); // Clear existing tracker await saveTracker({}); diff --git a/src/util/server-guard.ts b/src/util/server-guard.ts index 6ccd6ce..75527cf 100644 --- a/src/util/server-guard.ts +++ b/src/util/server-guard.ts @@ -1,5 +1,8 @@ import type { Guild } from 'discord.js'; import { config } from '@/env.js'; +import { createLogger } from '@/util/logger.js'; + +const logger = createLogger('server-guard'); /** * Checks if a guild is the allowed server @@ -14,12 +17,12 @@ export function isAllowedServer(guildId: string): boolean { */ export async function leaveIfNotAllowedServer(guild: Guild): Promise { if (!isAllowedServer(guild.id)) { - console.log( + logger.log( `âš ī¸ Bot added to unauthorized server: ${guild.name} (${guild.id})` ); - console.log(`đŸšĒ Leaving server...`); + logger.log(`đŸšĒ Leaving server...`); await guild.leave(); - console.log(`✅ Left unauthorized server: ${guild.name}`); + logger.log(`✅ Left unauthorized server: ${guild.name}`); return true; } return false; From 040a8d842931a87d20be7e56b802a5e1ad728326 Mon Sep 17 00:00:00 2001 From: Wiktoria Van Harneveldt Date: Sat, 14 Nov 2026 16:05:30 +0100 Subject: [PATCH 4/4] chore: remove unused imports --- src/features/showcase/util.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/features/showcase/util.ts b/src/features/showcase/util.ts index 417829b..0ef8d95 100644 --- a/src/features/showcase/util.ts +++ b/src/features/showcase/util.ts @@ -8,8 +8,6 @@ import { StringSelectMenuOptionBuilder, TextInputBuilder, TextInputStyle, - ActionRowBuilder, - type ModalActionRowComponentBuilder, } from 'discord.js'; export type ShowcaseMessageData = {