Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
9 changes: 8 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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<boolean> => discordClient

Expand All @@ -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
Expand Down
23 changes: 22 additions & 1 deletion src/commands/link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
})
Expand All @@ -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")
}

Expand Down Expand Up @@ -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")
}

Expand All @@ -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(
Expand All @@ -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)
}
}
Expand All @@ -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
}
},
Expand Down
22 changes: 20 additions & 2 deletions src/commands/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
})
Expand All @@ -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) ?? []
Expand All @@ -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}>`,
)
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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
}
},
Expand Down Expand Up @@ -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")
}
}
104 changes: 104 additions & 0 deletions src/commands/setting.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import {
ActionRowBuilder,
type AnySelectMenuInteraction,
type Channel,
ChannelType,
type ChatInputCommandInteraction,
Expand All @@ -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"

Expand All @@ -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: [
{
Expand Down Expand Up @@ -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

/**
Expand All @@ -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
*/
Expand All @@ -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<StringSelectMenuBuilder>().addComponents(menu),
],
}
}

/**
Expand Down Expand Up @@ -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<Message<boolean> | 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
Expand Down
Loading
Loading