diff --git a/prisma/schema.prisma b/prisma/schema.prisma index aeb4a65..ea0f937 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -17,6 +17,8 @@ model Settings { id Int @id @default(0) @map("_id") allEpisodes Destination[] // channels that get all episode notifications defaultForum String? // default forum to post episode notifications to + logChannel String? // channel that the bot posts log messages to + disabledLogTypes String[] // types of log message that are turned off morningSummaryDestinations Destination[] // channels that get morning summary notifications } diff --git a/src/app.ts b/src/app.ts index 969720a..2c25266 100644 --- a/src/app.ts +++ b/src/app.ts @@ -8,10 +8,15 @@ import { setRandomShowActivity, setTVDBLoadingActivity, } from "lib/discordActivities.ts" +import { setLogClient } from "lib/discordLog.ts" import { getEnv } from "lib/env.ts" import { scheduleCronJobs } from "./cron.ts" import assert from "node:assert" -import { handleChannelDelete, handleThreadDelete } from "./handlers.ts" +import { + handleChannelDelete, + handleThreadDelete, + handleThreadUpdate, +} from "./handlers.ts" const token = getEnv("DISCORD_TOKEN") const clientId = getEnv("DISCORD_CLIENT_ID") @@ -23,6 +28,7 @@ const commandManager = new CommandManager() await commandManager.registerCommands(clientId, token, guildId) const discordClient = new Client({ intents: [GatewayIntentBits.Guilds] }) +setLogClient(discordClient) export const getClient = (): Client => discordClient @@ -44,6 +50,7 @@ discordClient.on(Events.ClientReady, async (client) => { discordClient.on(Events.InteractionCreate, commandManager.interactionHandler) discordClient.on(Events.ThreadDelete, handleThreadDelete) +discordClient.on(Events.ThreadUpdate, handleThreadUpdate) discordClient.on(Events.ChannelDelete, handleChannelDelete) // start the bot diff --git a/src/commands/link.ts b/src/commands/link.ts index 1fa4d1b..8ce00d9 100644 --- a/src/commands/link.ts +++ b/src/commands/link.ts @@ -18,6 +18,7 @@ import { ProgressError } from "interfaces/error.ts" import { buildShowEmbed } from "lib/messages.ts" import { type SeriesExtendedRecord } from "interfaces/tvdb.generated.ts" import { parseIMDBIds } from "lib/util.ts" +import { codeSpan, logCommandUse, reportError } from "lib/discordLog.ts" /** * Standardized slash command option for getting IMDB ID @@ -58,9 +59,11 @@ export const command: CommandV2 = { ], }, async executeCommand(interaction: ChatInputCommandInteraction) { + const log = logCommandUse(interaction) const imdbIds = parseIMDBIds(interaction.options.getString("imdb_id", true)) if (imdbIds.length > 10) { + void log.fail("too many IMDB IDs") return await interaction.editReply({ content: "You can only create 10 links at a time", }) @@ -70,6 +73,7 @@ export const command: CommandV2 = { const subCommand = interaction.options.getSubcommand() if (subCommand === "") { + void log.fail("invalid subcommand") return await interaction.editReply("Invalid subcommand") } @@ -97,6 +101,7 @@ export const command: CommandV2 = { // error if the channel didnt get set for some reason if (channel == null || !channel.isSendable()) { + void log.fail("invalid channel") return await interaction.editReply("Invalid channel") } @@ -119,6 +124,8 @@ export const command: CommandV2 = { await progress.sendNextStep() // start step 2 const messages: string[] = [] + const linked: string[] = [] + const alreadyLinked: string[] = [] for (const [imdbId, tvdbSeries] of seriesList) { const existingSubscription = await checkForExistingSubscription( @@ -129,6 +136,7 @@ export const command: CommandV2 = { messages.push( `Show \`${tvdbSeries.name}\` is already linked to <#${channel.id}>`, ) + alreadyLinked.push(`${codeSpan(tvdbSeries.name)} (${imdbId})`) seriesList.delete(imdbId) } } @@ -154,26 +162,39 @@ export const command: CommandV2 = { }) messages.push(`Linked show \`${tvdbSeries.name}\` (${imdbId})`) + linked.push(`${codeSpan(tvdbSeries.name)} (${imdbId})`) } catch (error) { messages.push( `Failed to link show \`${tvdbSeries.name}\` (${imdbId})`, ) - console.error(error) + reportError(`/link: linking ${tvdbSeries.name} (${imdbId})`, error, { + type: "thread_ops", + }) } } await progress.sendNextStep() // start step 4 + if (linked.length > 0) { + void log.success(`Linked ${linked.join(", ")} to <#${channel.id}>`) + } else if (alreadyLinked.length > 0) { + void log.append("(already linked)") + } else { + void log.fail("no shows could be linked") + } + return await progress.sendNextStep( `Linked show(s) to <#${channel.id}>:\n\n${messages.join("\n")}`, ) } catch (error) { // catch our custom error and display it for the user if (error instanceof ProgressError) { + void log.fail(error.message) const message = `${progress.toString()}\n\nError: ${error.message}` return await interaction.editReply(message) } + void log.fail() throw error } }, diff --git a/src/commands/post.ts b/src/commands/post.ts index 2916447..bf76415 100644 --- a/src/commands/post.ts +++ b/src/commands/post.ts @@ -22,6 +22,7 @@ import { type SeriesExtendedRecord } from "interfaces/tvdb.generated.ts" import { type Destination, type Show } from "prisma-client/client.ts" import { parseIMDBIds } from "lib/util.ts" import { Settings } from "lib/settingsManager.ts" +import { logCommandUse, reportError } from "lib/discordLog.ts" interface SeriesWrapper { series: SeriesExtendedRecord @@ -54,9 +55,11 @@ export const command: CommandV2 = { }, async executeCommand(interaction: ChatInputCommandInteraction) { + const log = logCommandUse(interaction) let imdbIds = parseIMDBIds(interaction.options.getString("imdb_id", true)) if (imdbIds.length > 10) { + void log.fail("too many IMDB IDs") return await interaction.editReply({ content: "You can only create 10 posts at a time", }) @@ -82,6 +85,7 @@ export const command: CommandV2 = { await progress.sendNextStep() // start step 1 const messages: string[] = [] + const created: string[] = [] for (const imdbId of imdbIds) { const existingPosts = await checkForExistingPosts(imdbId, tvForum) ?? [] @@ -92,6 +96,7 @@ export const command: CommandV2 = { } if (imdbIds.length === 0) { + void log.append("(already posted)") throw new ProgressError( `All show(s) already have a post in <#${tvForum}>`, ) @@ -131,7 +136,9 @@ export const command: CommandV2 = { post: newPost, }) } catch (error) { - console.error(`Error creating post for ${imdbId}:`, error) + reportError(`/post: creating post for ${imdbId}`, error, { + type: "thread_ops", + }) messages.push(`Error creating post for \`${imdbId}\``) seriesList.delete(imdbId) } @@ -160,21 +167,30 @@ export const command: CommandV2 = { messages.push( `Created post for \`${tvDBSeries.name}\` (${imdbId}) - <#${post.id}>`, ) + created.push(`<#${post.id}>`) console.info(`Added show ${tvDBSeries.name} (${imdbId})`) } await progress.sendNextStep() // start step 5 + void log.success( + `Show ${ + created.length === 1 ? "thread" : "threads" + } created: ${created.join(", ")}`, + ) + return await progress.sendNextStep( `Creating post(s) in <#${tvForum}>:\n\n${messages.join("\n")}`, ) // finish step 5 } catch (error) { // catch our custom error and display it for the user if (error instanceof ProgressError) { + void log.fail(error.message) const message = `${progress.toString()}\n\nError: ${error.message}` return await interaction.editReply(message) } + void log.fail() throw error } }, @@ -280,7 +296,9 @@ async function saveShowToDB( channel, ) } catch (error) { - console.error(error) + reportError(`/post: saving ${seriesName} (${imdbId})`, error, { + type: "thread_ops", + }) throw new ProgressError("Something went wrong saving the show to the DB") } } diff --git a/src/commands/setting.ts b/src/commands/setting.ts index e11bf9b..329eb07 100644 --- a/src/commands/setting.ts +++ b/src/commands/setting.ts @@ -1,4 +1,6 @@ import { + ActionRowBuilder, + type AnySelectMenuInteraction, type Channel, ChannelType, type ChatInputCommandInteraction, @@ -8,9 +10,11 @@ import { SlashCommandBuilder, SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder, + StringSelectMenuBuilder, } from "discord.js" import { type CommandV2 } from "interfaces/command.ts" import { ProgressMessageBuilder } from "lib/progressMessages.ts" +import { LOG_TYPES } from "lib/discordLog.ts" import { Settings } from "lib/settingsManager.ts" import { type Destination } from "prisma-client/client.ts" @@ -31,6 +35,18 @@ export const command: CommandV2 = { .addChannelTypes(ChannelType.GuildForum) .setRequired(true) ), + new SlashCommandSubcommandBuilder() + .setName("log_channel") + .setDescription("Set the channel that the bot posts log messages to") + .addChannelOption((option) => + option.setName("channel") + .setDescription("The channel to post logs in") + .addChannelTypes(ChannelType.GuildText) + .setRequired(true) + ), + new SlashCommandSubcommandBuilder() + .setName("log_types") + .setDescription("Choose which types of log message get posted"), ], subGroups: [ { @@ -120,6 +136,16 @@ export const command: CommandV2 = { async executeCommand(interaction: ChatInputCommandInteraction) { const subCommand = interaction.options.getSubcommand() const subcommandGroup = interaction.options.getSubcommandGroup() + + /** + * Handle the log types setting, this subcommand has no channel option + */ + if (subcommandGroup === null && subCommand === "log_types") { + return await interaction.editReply( + buildLogTypesReply(Settings.fetch()?.disabledLogTypes ?? []), + ) + } + const channel = interaction.options.getChannel("channel", true) as Channel /** @@ -130,6 +156,13 @@ export const command: CommandV2 = { return } + /** + * Handle the log channel setting + */ + if (subcommandGroup === null && subCommand === "log_channel") { + return await setLogChannel(interaction, channel) + } + /** * Handle adding channels to the all_episodes list */ @@ -148,6 +181,46 @@ export const command: CommandV2 = { return await updateMorningSummaryChannels(interaction) } }, + selectMenuIds: ["log_types_menu"], + async executeSelectMenu(interaction: AnySelectMenuInteraction) { + const disabledLogTypes = LOG_TYPES.map((type) => type.key) + .filter((key) => !interaction.values.includes(key)) + + await Settings.update({ + disabledLogTypes, + }) + + return await interaction.editReply(buildLogTypesReply(disabledLogTypes)) + }, +} + +/** + * Builds the reply containing the multi-select menu of log types + * @param disabled keys of the log types that are currently turned off + */ +function buildLogTypesReply(disabled: string[]) { + const menu = new StringSelectMenuBuilder() + .setCustomId("log_types_menu") + .setPlaceholder("Nothing selected") + .setMinValues(0) + .setMaxValues(LOG_TYPES.length) + .addOptions(LOG_TYPES.map((type) => ({ + label: type.label, + description: type.description, + value: type.key, + default: !disabled.includes(type.key), + }))) + + const noChannelNote = Settings.fetch()?.logChannel == null + ? "\nNo log channel is set yet, use `/setting log_channel`." + : "" + + return { + content: `Select the types of message to post in the log channel.${noChannelNote}`, + components: [ + new ActionRowBuilder().addComponents(menu), + ], + } } /** @@ -176,6 +249,37 @@ async function setTVForum( await interaction.editReply(progressMessage.nextStep()) } +/** + * Sets the channel that the bot posts log messages to + * @param interaction discord command interaction + * @param channel channel to set as the log channel + */ +async function setLogChannel( + interaction: ChatInputCommandInteraction, + channel: Channel, +): Promise | void> { + if (channel.type !== ChannelType.GuildText) { + return await interaction.editReply("Invalid channel type") + } + + try { + await channel.send("The bot will post log messages in this channel.") + } catch (error) { + console.warn(`Could not send to proposed log channel ${channel.id}:`, error) + return await interaction.editReply( + `I can't send messages in <#${channel.id}>. Check my permissions there and try again.`, + ) + } + + await Settings.update({ + logChannel: channel.id, + }) + + return await interaction.editReply( + `Log messages will be posted in <#${channel.id}>`, + ) +} + /** * Update the list of channels that receive all episode notifications * @param interaction discord interaction diff --git a/src/commands/unlink.ts b/src/commands/unlink.ts index 24fb209..4123f47 100644 --- a/src/commands/unlink.ts +++ b/src/commands/unlink.ts @@ -15,6 +15,13 @@ import { type CommandV2 } from "interfaces/command.ts" import { ProgressError } from "interfaces/error.ts" import { ProgressMessageBuilder } from "lib/progressMessages.ts" import { pruneUnsubscribedShows } from "lib/shows.ts" +import { + codeSpan, + type CommandLog, + logCommandUse, + rememberCommandLog, + takeCommandLog, +} from "lib/discordLog.ts" export const command: CommandV2 = { slashCommand: { @@ -42,6 +49,7 @@ export const command: CommandV2 = { }, selectMenuIds: ["unlink_shows_menu"], async executeCommand(interaction: ChatInputCommandInteraction) { + const log = logCommandUse(interaction) const subCommand = interaction.options.getSubcommand() const progress = new ProgressMessageBuilder() @@ -65,6 +73,7 @@ export const command: CommandV2 = { // error if the channel didnt get set for some reason if (channel === undefined) { + void log.fail("invalid channel") return await interaction.editReply("Invalid channel") } @@ -80,6 +89,7 @@ export const command: CommandV2 = { }) if (showsInChannel === null || showsInChannel.length === 0) { + void log.append("(no shows linked)") return await interaction.editReply( "This channel has no shows linked to it.", ) @@ -100,52 +110,87 @@ export const command: CommandV2 = { })), ) - await interaction.editReply({ + const reply = await interaction.editReply({ content: `Select the shows that you'd like to unlink from <#${channel?.id}>`, components: [row], }) + rememberCommandLog(reply.id, log) } catch (error) { // catch our custom error and display it for the user if (error instanceof ProgressError) { + void log.fail(error.message) const message = `${progress.toString()}\n\nError: ${error.message}` return await interaction.editReply(message) } + void log.fail() throw error } }, async executeSelectMenu(interaction: AnySelectMenuInteraction) { + const log = takeCommandLog(interaction.message.id) const channelId = interaction.message.content.match(/<#([0-9]+)>/)?.at(1) if (channelId === undefined) { + void log?.fail("could not find the channel") return await interaction.reply("Failed to find channel") } - const values = interaction.values + try { + return await unlinkShows(interaction, channelId, log) + } catch (error) { + void log?.fail() + throw error + } + }, +} - const s = await client.show.updateMany({ - where: { - imdbId: { - in: values, - }, +/** + * Unlinks the shows chosen in the select menu from a channel + * @param interaction select menu interaction with the chosen shows + * @param channelId channel to unlink the shows from + * @param log log handle for the original /unlink command, if it's still remembered + */ +async function unlinkShows( + interaction: AnySelectMenuInteraction, + channelId: string, + log: CommandLog | undefined, +) { + const values = interaction.values + + const shows = await client.show.findMany({ + where: { imdbId: { in: values } }, + select: { name: true, imdbId: true }, + }) + + const s = await client.show.updateMany({ + where: { + imdbId: { + in: values, }, - data: { - destinations: { - deleteMany: { - where: { - channelId, - }, + }, + data: { + destinations: { + deleteMany: { + where: { + channelId, }, }, }, - }) + }, + }) - await pruneUnsubscribedShows() + await pruneUnsubscribedShows() - return await interaction.editReply({ - content: `Unlinked ${s.count} shows from <#${channelId}>`, - components: [], - }) - }, + void log?.success( + `Unlinked ${ + shows.map((show) => `${codeSpan(show.name)} (${show.imdbId})`).join(", ") + } from <#${channelId}>`, + ) + + return await interaction.editReply({ + content: `Unlinked ${s.count} shows from <#${channelId}>`, + components: [], + }) } diff --git a/src/cron.ts b/src/cron.ts index 61fc034..1922ef0 100644 --- a/src/cron.ts +++ b/src/cron.ts @@ -2,28 +2,53 @@ import { setRandomShowActivity, setTVDBLoadingActivity, } from "lib/discordActivities.ts" +import { logMessage, reportError } from "lib/discordLog.ts" import { getEnv } from "lib/env.ts" import { sendAiringMessages } from "lib/episodeNotifier.ts" import { sendMorningSummary } from "lib/morningSummary.ts" import { Settings } from "lib/settingsManager.ts" import { checkForAiringEpisodes, pruneUnsubscribedShows } from "lib/shows.ts" +async function runJob( + name: string, + job: () => Promise | void, +): Promise { + try { + await job() + } catch (error) { + reportError(`Cron: ${name}`, error, { type: "task_errors" }) + } +} + export function scheduleCronJobs() { Deno.cron("Announcements", { minute: { every: 10, start: 8 } }, () => { - void sendAiringMessages() - void setRandomShowActivity() + void runJob("Announcements", sendAiringMessages) + void runJob("Random activity", setRandomShowActivity) }) Deno.cron("Fetch Episode Data", { hour: { every: 4 } }, async () => { - setTVDBLoadingActivity() - await pruneUnsubscribedShows() - await checkForAiringEpisodes() + await runJob("Fetch Episode Data", async () => { + setTVDBLoadingActivity() + await pruneUnsubscribedShows() + const { checked, failed, upcomingEpisodes } = await checkForAiringEpisodes() + const shows = `${checked} ${checked === 1 ? "show" : "shows"}` + const episodes = `${upcomingEpisodes} upcoming ${ + upcomingEpisodes === 1 ? "episode" : "episodes" + }` + const failures = failed > 0 ? `, ${failed} failed` : "" + logMessage( + `Fetch Episode Data: checked ${shows}, ${episodes}${failures}`, + "tasks", + ) + }) }) Deno.cron("Morning Summary", { hour: 8, minute: 0 }, async () => { - const settings = Settings.fetch() - if (settings == null) throw new Error("Settings not found") - await sendMorningSummary() + await runJob("Morning Summary", async () => { + const settings = Settings.fetch() + if (settings == null) throw new Error("Settings not found") + await sendMorningSummary() + }) }) const healthcheckUrl = getEnv("HEALTHCHECK_URL") diff --git a/src/handlers.ts b/src/handlers.ts index dc26a94..656bb15 100644 --- a/src/handlers.ts +++ b/src/handlers.ts @@ -1,7 +1,20 @@ import { ChannelType, ClientEvents } from "discord.js" +import { escapeLogText, logMessage, reportError } from "lib/discordLog.ts" +import client from "lib/prisma.ts" import { Settings } from "lib/settingsManager.ts" import { pruneUnsubscribedShows, removeAllSubscriptions } from "lib/shows.ts" +/** + * Check if a thread has at least one show linked to it + * @param threadId id of the thread to check + */ +async function isTrackedThread(threadId: string): Promise { + const count = await client.show.count({ + where: { destinations: { some: { channelId: threadId } } }, + }) + return count > 0 +} + /** * When a thread (forum post) is deleted, remove all subscriptions for that post */ @@ -9,10 +22,58 @@ export async function handleThreadDelete( ...args: ClientEvents["threadDelete"] ) { const [thread] = args + + // check before the subscriptions are removed below + try { + if (await isTrackedThread(thread.id)) { + logMessage( + `Show thread deleted: **${escapeLogText(thread.name)}** (<#${thread.parentId}>)`, + "thread_ops", + ) + } + } catch (error) { + reportError(`Checking thread ${thread.id}`, error) + } + await removeAllSubscriptions(thread.id, "channelId") await pruneUnsubscribedShows() } +/** + * Log when a tracked show thread is renamed or locked/unlocked + */ +export async function handleThreadUpdate( + ...args: ClientEvents["threadUpdate"] +): Promise { + const [oldThread, newThread] = args + const renamed = oldThread.name !== newThread.name + const lockChanged = oldThread.locked !== newThread.locked + if (!renamed && !lockChanged) return + + try { + if (!(await isTrackedThread(newThread.id))) return + } catch (error) { + reportError(`Checking thread ${newThread.id}`, error) + return + } + + if (renamed) { + logMessage( + `Show thread renamed: **${escapeLogText(oldThread.name)}** → [**${ + escapeLogText(newThread.name) + }**](${newThread.url})`, + "thread_ops", + ) + } + + if (lockChanged) { + const action = newThread.locked + ? "Show thread locked" + : "Show thread unlocked" + logMessage(`${action}: <#${newThread.id}>`, "thread_ops") + } +} + /** * When a forum is deleted, remove all subscriptions for post in that forum */ @@ -29,5 +90,10 @@ export async function handleChannelDelete( await removeAllSubscriptions(channel.id, "channelId") await pruneUnsubscribedShows() await Settings.removeGlobalDestination(channel.id) + + // stop trying to post logs to a channel that no longer exists + if (Settings.fetch()?.logChannel === channel.id) { + await Settings.update({ logChannel: null }) + } } } diff --git a/src/lib/commandManager.ts b/src/lib/commandManager.ts index 163fa5e..04ec71e 100644 --- a/src/lib/commandManager.ts +++ b/src/lib/commandManager.ts @@ -12,6 +12,7 @@ import { } from "discord.js" import { type CommandV2 } from "interfaces/command.ts" import { getEnv } from "lib/env.ts" +import { reportError } from "lib/discordLog.ts" interface Getter { command: TInput @@ -70,7 +71,9 @@ export class CommandManager { this.commands.map((cmd) => cmd.slashCommand.main.name).join("\n"), ) } catch (error) { - console.error(error) + reportError("Slash command registration", error, { + type: "command_errors", + }) } } @@ -108,7 +111,9 @@ export class CommandManager { try { await command.executeCommand(interaction) } catch (error) { - console.error(error) + reportError(`/${interaction.commandName}`, error, { + type: "command_errors", + }) await interaction.editReply( "There was an error while executing this command!", ) @@ -128,7 +133,9 @@ export class CommandManager { try { await command.executeSelectMenu(interaction) } catch (error) { - console.error(error) + reportError(`Select menu ${interaction.customId}`, error, { + type: "command_errors", + }) await interaction.editReply( "There was an error while executing this command!", ) @@ -144,7 +151,9 @@ export class CommandManager { try { await command.executeAutoComplete(interaction) } catch (e) { - console.error(e) + reportError(`Autocomplete /${interaction.commandName}`, e, { + type: "command_errors", + }) } } diff --git a/src/lib/discordLog.ts b/src/lib/discordLog.ts new file mode 100644 index 0000000..de10314 --- /dev/null +++ b/src/lib/discordLog.ts @@ -0,0 +1,373 @@ +import { + ApplicationCommandOptionType, + type ChatInputCommandInteraction, + type CommandInteractionOption, + DiscordAPIError, + escapeMarkdown, + type Client, + type Message, +} from "discord.js" +import { parseIMDBIds } from "lib/util.ts" +import { Settings } from "lib/settingsManager.ts" + +export const LOG_TYPES = [ + { + key: "thread_ops", + label: "Thread Ops", + description: "/post, /link, /unlink and show thread changes", + }, + { + key: "tasks", + label: "Tasks", + description: "Scheduled jobs that complete", + }, + { + key: "task_errors", + label: "Task Errors", + description: "Scheduled jobs and notifications that fail", + }, + { + key: "api_errors", + label: "API Errors", + description: "Failed Discord and TVDB API requests", + }, + { + key: "command_errors", + label: "Command Errors", + description: "Commands, menus and autocompletes that crash", + }, + { + key: "other", + label: "Other", + description: "Anything else", + }, +] as const + +export type LogType = typeof LOG_TYPES[number]["key"] + +const MAX_MESSAGE_LENGTH = 2000 +const MAX_ERROR_LENGTH = 1900 +const MAX_DETAIL_LENGTH = 300 +const REPEAT_WINDOW_MS = 5 * 60_000 +const MAX_REMEMBERED_COMMANDS = 100 + +export interface ApiFailure { + service: string + url: string + status: number + body?: string +} + +/** + * Handle for finishing a logged command. Only the first call has an effect, + * so a later failure can't overwrite an earlier result + */ +export interface CommandLog { + /** replaces the logged command with `details` (default "Succeeded"), keeping who ran it and where */ + success: (details?: string) => Promise + /** appends text to the end of the logged command line */ + append: (text: string) => Promise + /** appends "(failed)" to the logged command line, with the reason if given */ + fail: (reason?: string) => Promise +} + +interface ErrorSummary { + origin: string + message: string + status?: number + code?: number | string + endpoint?: string +} + +interface LoggedError { + message: Promise + sentAt: number + repeated: boolean +} + +let discordClient: Client | undefined + +/** + * Gives the log module the client to send messages with. This is set from app.ts + * instead of importing the client, because importing app.ts from here would create + * an import cycle that deadlocks on the top level awaits in app.ts and commandManager.ts + */ +export function setLogClient(client: Client): void { + discordClient = client +} + +/** + * Escapes markdown in text that is shown in a log message, including the + * square brackets that would break a masked link + */ +export function escapeLogText(text: string): string { + return escapeMarkdown(text).replace(/[[\]]/g, "\\$&") +} + +/** + * Wraps text in an inline code span. Backticks can't be escaped inside a code + * span, so they are replaced with apostrophes + */ +export function codeSpan(text: string): string { + return `\`${text.replaceAll("`", "'")}\`` +} + +const recentErrors = new Map() +const commandLogs = new Map() + +function isLogTypeEnabled(type: LogType): boolean { + return !(Settings.fetch()?.disabledLogTypes ?? []).includes(type) +} + +async function sendLog( + content: string, + type: LogType, +): Promise { + try { + const channelId = Settings.fetch()?.logChannel + if (channelId == null || !isLogTypeEnabled(type)) return undefined + + if (discordClient == null) return undefined + + const channel = await discordClient.channels.fetch(channelId) + if (channel == null || !channel.isSendable()) { + console.warn(`Log channel ${channelId} is missing or not sendable`) + return undefined + } + + return await channel.send({ + content: content.slice(0, MAX_MESSAGE_LENGTH), + allowedMentions: { parse: [] }, + }) + } catch (error) { + console.warn("Failed to send to the log channel:", error) + } + return undefined +} + +async function editLog( + message: Message | undefined, + content: string, +): Promise { + if (message == null) return + + try { + await message.edit({ + content: content.slice(0, MAX_MESSAGE_LENGTH), + allowedMentions: { parse: [] }, + }) + } catch (error) { + console.warn("Failed to edit the log message:", error) + } +} + +function describeError(error: unknown, origin?: string): ErrorSummary { + if (error instanceof DiscordAPIError) { + return { + origin: "Discord API", + message: error.message, + status: error.status, + code: error.code, + endpoint: `${error.method} ${error.url}`, + } + } + if (error instanceof Error) { + return { + origin: origin != null ? `${origin} (${error.name})` : error.name, + message: error.message, + } + } + return { origin: origin ?? "Unknown error", message: String(error) } +} + +function describeApiFailure(failure: ApiFailure): ErrorSummary { + return { + origin: failure.service, + message: failure.body?.slice(0, MAX_DETAIL_LENGTH) ?? "Request failed", + status: failure.status, + endpoint: failure.url, + } +} + +function formatError(context: string, summary: ErrorSummary): string { + const details = [ + summary.origin, + summary.status != null ? `HTTP ${summary.status}` : undefined, + summary.code != null ? `code ${summary.code}` : undefined, + ].filter((part) => part != null).join(" · ") + + const lines = [ + `⚠️ **${escapeLogText(context)}**`, + `${details}: ${escapeLogText(summary.message)}`, + ] + if (summary.endpoint != null) lines.push(`\`${summary.endpoint}\``) + + return lines.join("\n").slice(0, MAX_ERROR_LENGTH) +} + +/** + * Sends an error to the log channel. If the same error was already sent recently, + * the original message is edited once to say it repeated, and further repeats are ignored + */ +async function logError(content: string, type: LogType): Promise { + if (Settings.fetch()?.logChannel == null || !isLogTypeEnabled(type)) return + + const now = Date.now() + for (const [key, entry] of recentErrors) { + if (now - entry.sentAt > REPEAT_WINDOW_MS) recentErrors.delete(key) + } + + const existing = recentErrors.get(content) + if (existing == null) { + recentErrors.set(content, { + message: sendLog(content, type), + sentAt: now, + repeated: false, + }) + return + } + + if (existing.repeated) return + existing.repeated = true + await editLog(await existing.message, `${content}\n(repeated)`) +} + +/** + * Logs an error to the console and to the configured log channel (if any) + * @param context short description of what was being attempted + * @param error the thrown value + * @param options.origin optional label for where the error came from, shown instead of the bare error class + * @param options.type log type that controls whether this is posted, Discord API errors are always `api_errors` + */ +export function reportError( + context: string, + error: unknown, + options?: { origin?: string; type?: LogType }, +): void { + console.error(`${context}:`, error) + const type = error instanceof DiscordAPIError + ? "api_errors" + : (options?.type ?? "other") + void logError( + formatError(context, describeError(error, options?.origin)), + type, + ) +} + +/** + * Logs a failed API response to the console and to the configured log channel (if any) + * @param context short description of what was being attempted + * @param failure details of the failed response + */ +export function reportApiFailure(context: string, failure: ApiFailure): void { + console.error(`${context}:`, failure) + void logError( + formatError(context, describeApiFailure(failure)), + "api_errors", + ) +} + +/** + * Posts a plain message to the log channel (if one is set) + * @param content message to post + * @param type log type that controls whether this is posted + */ +export function logMessage(content: string, type: LogType = "other"): void { + void sendLog(content, type) +} + +function formatOptions(options: readonly CommandInteractionOption[]): string { + return options.map((option) => { + switch (option.type) { + case ApplicationCommandOptionType.Subcommand: + case ApplicationCommandOptionType.SubcommandGroup: + return `${option.name} ${formatOptions(option.options ?? [])}`.trim() + case ApplicationCommandOptionType.Channel: + return `${option.name}:<#${option.value}>` + case ApplicationCommandOptionType.User: + return `${option.name}:<@${option.value}>` + case ApplicationCommandOptionType.Role: + return `${option.name}:<@&${option.value}>` + default: + // show IMDB ids rather than whatever url or list was typed, + // unless none could be read from it + if (option.name === "imdb_id" && typeof option.value === "string") { + const ids = parseIMDBIds(option.value) + if (ids.length > 0) return `${option.name}:${ids.join(",")}` + } + return `${option.name}:${escapeLogText(String(option.value))}` + } + }).join(" ") +} + +function formatCommand(interaction: ChatInputCommandInteraction): string { + return `/${interaction.commandName} ${formatOptions(interaction.options.data)}` + .replace(/\s+/g, " ") + .trim() +} + +/** + * Logs that a command was used, including who used it, where and with which arguments. + * The log message is sent in the background so the command doesn't wait for it + * @param interaction the command interaction to log + * @returns handle that edits the log message when the command finishes + */ +export function logCommandUse( + interaction: ChatInputCommandInteraction, +): CommandLog { + const who = `(<@${interaction.user.id}> in <#${interaction.channelId}>)` + const content = `> ${formatCommand(interaction)} ${who}` + + const message = sendLog(content, "thread_ops") + let finished = false + + // edits the log message, unless an earlier call already did + const finish = async (newContent: string): Promise => { + if (finished) return + finished = true + await editLog(await message, newContent) + } + + return { + success: async (details?: string) => { + const result = details != null && details !== "" ? details : "Succeeded" + // leave out the channel when the result already mentions it + const suffix = result.includes(`<#${interaction.channelId}>`) + ? `(<@${interaction.user.id}>)` + : who + await finish(`${result} ${suffix}`) + }, + append: async (text: string) => { + await finish(`${content} ${text}`) + }, + fail: async (reason?: string) => { + const text = reason != null && reason !== "" + ? `(failed: ${reason})` + : "(failed)" + await finish(`${content} ${text}`) + }, + } +} + +/** + * Remember a command log for a reply message, for commands that finish in a later interaction + * @param messageId id of the reply message that the later interaction will come from + * @param log the log handle returned from `logCommandUse` + */ +export function rememberCommandLog(messageId: string, log: CommandLog): void { + if (commandLogs.size >= MAX_REMEMBERED_COMMANDS) { + const oldest = commandLogs.keys().next().value + if (oldest != null) commandLogs.delete(oldest) + } + commandLogs.set(messageId, log) +} + +/** + * Retrieve (and forget) a command log remembered with `rememberCommandLog` + * @param messageId id of the reply message + */ +export function takeCommandLog(messageId: string): CommandLog | undefined { + const log = commandLogs.get(messageId) + commandLogs.delete(messageId) + return log +} diff --git a/src/lib/episodeNotifier.ts b/src/lib/episodeNotifier.ts index 555c791..060aefd 100644 --- a/src/lib/episodeNotifier.ts +++ b/src/lib/episodeNotifier.ts @@ -13,6 +13,7 @@ import client from "lib/prisma.ts" import { Settings, type SettingsType } from "lib/settingsManager.ts" import { addLeadingZeros, toRanges } from "lib/util.ts" import { getClient } from "app.ts" +import { reportError } from "lib/discordLog.ts" export function isTextChannel( channel: Channel, @@ -144,7 +145,11 @@ async function sendNotificationPayload( // send message to discord await sendMessage(channel, message) } catch (e) { - console.error("Error sending message to destination", e) + reportError( + `Sending ${payload.showName} notification to ${destination.channelId}`, + e, + { type: "task_errors" }, + ) } } @@ -163,7 +168,11 @@ async function sendNotificationPayload( // send message to discord await sendMessage(channel, globalMessage) } catch (e) { - console.error("Error sending message to global destination", e) + reportError( + `Sending ${payload.showName} notification to global destination ${destination.channelId}`, + e, + { type: "task_errors" }, + ) } } diff --git a/src/lib/shows.ts b/src/lib/shows.ts index 6988a7d..fb27720 100644 --- a/src/lib/shows.ts +++ b/src/lib/shows.ts @@ -5,6 +5,7 @@ import { isThreadChannel } from "interfaces/discord.ts" import client from "lib/prisma.ts" import { getTimezone } from "lib/timezones.ts" import { getSeries } from "lib/tvdb.ts" +import { reportError } from "lib/discordLog.ts" import { type EpisodeBaseRecord, type SeriesExtendedRecord, @@ -41,12 +42,13 @@ function getAirDate( * @param imdbId imdbid of the show to update * @param tvdbId tvdbId of the show to update * @param providedSeries optional series data to use instead of fetching it + * @returns number of upcoming episodes saved for the show */ export async function updateEpisodes( imdbId: string, tvdbId: number, providedSeries?: SeriesExtendedRecord, -): Promise { +): Promise { // if the caller already has series data for whatever reason and provided it, just use that const series: SeriesExtendedRecord | undefined = providedSeries ?? (await getSeries(tvdbId)) @@ -96,12 +98,17 @@ export async function updateEpisodes( console.info( `[Get Episode Data] ${series.name} / Upcoming episodes: ${upcomingEpisodes.length}`, ) + + return upcomingEpisodes.length } /** * Updates all shows in the DB with new episodes + * @returns how many shows were checked, how many failed and how many upcoming episodes were found */ -export async function checkForAiringEpisodes(): Promise { +export async function checkForAiringEpisodes(): Promise< + { checked: number; failed: number; upcomingEpisodes: number } +> { console.info("== Checking all shows for airing episodes ==") const shows = await client.show.findMany({ select: { @@ -114,15 +121,27 @@ export async function checkForAiringEpisodes(): Promise { }, }) + let checked = 0 + let failed = 0 + let upcomingEpisodes = 0 + for (const show of shows) { try { - await updateEpisodes(show.imdbId, show.tvdbId) + upcomingEpisodes += await updateEpisodes(show.imdbId, show.tvdbId) + checked++ } catch (error) { - console.error(`Error updating episodes for ${show.name} (${show.imdbId}):`, error) + failed++ + reportError( + `Updating episodes for ${show.name} (${show.imdbId})`, + error, + { type: "task_errors" }, + ) } } console.info("== Finished checking all shows for airing episodes ==") + + return { checked, failed, upcomingEpisodes } } /** diff --git a/src/lib/tvdb.ts b/src/lib/tvdb.ts index dc1f829..3f5f86b 100644 --- a/src/lib/tvdb.ts +++ b/src/lib/tvdb.ts @@ -4,6 +4,7 @@ import { type SeriesExtendedRecord, } from "interfaces/tvdb.generated.ts" import { getEnv } from "lib/env.ts" +import { reportApiFailure, reportError } from "lib/discordLog.ts" const baseURL = "https://api4.thetvdb.com/v4" as const @@ -22,7 +23,7 @@ async function getAuthToken(): Promise<{ Authorization: string }> { }) if (!response.ok) { - throw new Error("Failed to get TVDB token", { + throw new Error(`Failed to get TVDB token (HTTP ${response.status})`, { cause: await response.text(), }) } @@ -112,10 +113,11 @@ export async function getSeries( ) if (!response.ok) { - console.error(`Error Getting Extended Show Data:`, { + reportApiFailure("TVDB: Getting extended show data", { + service: "TVDB API", url: response.url, status: response.status, - data: await response.text(), + body: await response.text(), }) return undefined } @@ -123,7 +125,11 @@ export async function getSeries( const data: { data?: SeriesExtendedRecord } = await response.json() return data.data } catch (error) { - console.error(`Unexpected Error Getting Extended Show Data:`, error) + reportError( + "TVDB: Getting extended show data", + error, + { origin: "TVDB API request failed", type: "api_errors" }, + ) } return undefined } @@ -140,10 +146,11 @@ async function searchSeriesByImdbId( ) if (!response.ok) { - console.error(`Error Searching Series by IMDB ID:`, { + reportApiFailure("TVDB: Searching series by IMDB ID", { + service: "TVDB API", url: response.url, status: response.status, - data: await response.text(), + body: await response.text(), }) return undefined } @@ -151,7 +158,11 @@ async function searchSeriesByImdbId( const data: { data?: SearchByRemoteIdResult[] } = await response.json() return data.data?.at(0) } catch (error) { - console.error(`Unexpected Error Searching Series by IMDB ID:`, error) + reportError( + "TVDB: Searching series by IMDB ID", + error, + { origin: "TVDB API request failed", type: "api_errors" }, + ) } return undefined } @@ -173,10 +184,11 @@ async function searchSeriesByName( ) if (!response.ok) { - console.error(`Error Searching Series:`, { + reportApiFailure("TVDB: Searching series", { + service: "TVDB API", url: response.url, status: response.status, - data: await response.text(), + body: await response.text(), }) return undefined } @@ -188,7 +200,11 @@ async function searchSeriesByName( } return searchResult } catch (error) { - console.error(`Unexpected Error Searching Series:`, error) + reportError( + "TVDB: Searching series", + error, + { origin: "TVDB API request failed", type: "api_errors" }, + ) } return undefined }