From e0ad0dadb871eb93874adeff63adc37ef270d985 Mon Sep 17 00:00:00 2001 From: SpackledJim Date: Sat, 10 Oct 2026 13:16:02 +0000 Subject: [PATCH 1/9] fix(search): clean up autocomplete labels and command description Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H6X9gSzpaW1Z5cEET9L1pt --- src/commands/search.ts | 2 +- src/lib/autocomplete.ts | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/commands/search.ts b/src/commands/search.ts index d52d402..8762fdf 100644 --- a/src/commands/search.ts +++ b/src/commands/search.ts @@ -14,7 +14,7 @@ export const command: CommandV2 = { slashCommand: { main: new SlashCommandBuilder() .setName("search") - .setDescription("Link a show to a channel for notifications.") + .setDescription("Look up a show and see its details and linked channels.") .setContexts(InteractionContextType.Guild) .addStringOption((option) => option.setName("query") diff --git a/src/lib/autocomplete.ts b/src/lib/autocomplete.ts index b84b202..0a99aa1 100644 --- a/src/lib/autocomplete.ts +++ b/src/lib/autocomplete.ts @@ -42,7 +42,11 @@ export async function showSearchAutocomplete( const choices = data.map( (item): ApplicationCommandOptionChoiceData => { const { name, imdbId } = item - return ({ name: `${name} - (${name})`, value: imdbId }) + return ({ + // Discord caps choice names at 100 characters + name: `${name} (${imdbId})`.slice(0, 100), + value: imdbId, + }) }, ) From ae5bd1fc18c309ac498945367d612c61056d6b35 Mon Sep 17 00:00:00 2001 From: SpackledJim Date: Sat, 10 Oct 2026 13:24:30 +0000 Subject: [PATCH 2/9] fix(search): handle empty TVDB name search results Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H6X9gSzpaW1Z5cEET9L1pt --- src/lib/tvdb.ts | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/lib/tvdb.ts b/src/lib/tvdb.ts index dc1f829..dcf7ae6 100644 --- a/src/lib/tvdb.ts +++ b/src/lib/tvdb.ts @@ -183,9 +183,8 @@ async function searchSeriesByName( const data: { data: SearchResult[] } = await response.json() const searchResult = data?.data - if (searchResult == null || searchResult[0].tvdb_id == null) { - return undefined - } + // an unknown show gives an empty array, so guard before indexing + if (searchResult?.[0]?.tvdb_id == null) return undefined return searchResult } catch (error) { console.error(`Unexpected Error Searching Series:`, error) @@ -197,7 +196,7 @@ export async function getSeriesByName( query: string, ): Promise { const searchResult = await searchSeriesByName(query) - if (searchResult == null || searchResult[0].tvdb_id == null) return undefined - const series = await getSeries(parseInt(searchResult[0].tvdb_id)) - return series + const tvdbId = searchResult?.[0]?.tvdb_id + if (tvdbId == null) return undefined + return await getSeries(parseInt(tvdbId)) } From a3b584fb95ae85ea301b9adbb07be38f6d84b7cd Mon Sep 17 00:00:00 2001 From: SpackledJim Date: Sat, 10 Oct 2026 13:37:20 +0000 Subject: [PATCH 3/9] fix(search): show linked channels for name searches Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H6X9gSzpaW1Z5cEET9L1pt --- src/commands/search.ts | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/src/commands/search.ts b/src/commands/search.ts index 8762fdf..54496f2 100644 --- a/src/commands/search.ts +++ b/src/commands/search.ts @@ -5,11 +5,21 @@ import { SlashCommandBuilder, } from "discord.js" import client from "lib/prisma.ts" +import { type Destination } from "prisma-client/client.ts" import { type CommandV2 } from "interfaces/command.ts" import { getSeriesByImdbId, getSeriesByName } from "lib/tvdb.ts" import { buildShowEmbed } from "lib/messages.ts" import { showSearchAutocomplete } from "lib/autocomplete.ts" +/** Channels a show is linked to, or none if the show isn't tracked. */ +async function getDestinations(imdbId: string): Promise { + const show = await client.show.findUnique({ + where: { imdbId }, + select: { destinations: true }, + }) + return show?.destinations ?? [] +} + export const command: CommandV2 = { slashCommand: { main: new SlashCommandBuilder() @@ -40,17 +50,10 @@ export const command: CommandV2 = { ) } - const show = await client.show.findUnique({ - where: { - imdbId, - }, - select: { - destinations: true, - }, - }) - return await interaction.editReply({ - embeds: [buildShowEmbed(imdbId, series, show?.destinations ?? [])], + embeds: [ + buildShowEmbed(imdbId, series, await getDestinations(imdbId)), + ], }) } @@ -63,7 +66,7 @@ export const command: CommandV2 = { if (imdbId == null) return await interaction.editReply("Show not found") return await interaction.editReply({ - embeds: [buildShowEmbed(imdbId, series, [])], + embeds: [buildShowEmbed(imdbId, series, await getDestinations(imdbId))], }) }, async executeAutoComplete(interaction: AutocompleteInteraction) { From 8d459212cce79d65f1a3b1271025c9b4919c4553 Mon Sep 17 00:00:00 2001 From: SpackledJim Date: Sat, 10 Oct 2026 13:47:22 +0000 Subject: [PATCH 4/9] fix(search): translate name search results to English Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H6X9gSzpaW1Z5cEET9L1pt --- src/lib/tvdb.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/lib/tvdb.ts b/src/lib/tvdb.ts index dcf7ae6..d1a81b4 100644 --- a/src/lib/tvdb.ts +++ b/src/lib/tvdb.ts @@ -58,6 +58,13 @@ export async function getSeriesByImdbId( series = await getSeries(data?.season?.seriesId) } + return withEnglishTranslation(series) +} + +/** Swaps in the English name/overview for shows not originally in English. */ +function withEnglishTranslation( + series: SeriesExtendedRecord | undefined, +): SeriesExtendedRecord | undefined { if ( series?.originalLanguage == null || series.originalLanguage === "eng" ) return series @@ -198,5 +205,5 @@ export async function getSeriesByName( const searchResult = await searchSeriesByName(query) const tvdbId = searchResult?.[0]?.tvdb_id if (tvdbId == null) return undefined - return await getSeries(parseInt(tvdbId)) + return withEnglishTranslation(await getSeries(parseInt(tvdbId))) } From 483a91dd8a71d09a6bed10b762c5b3415c540cc2 Mon Sep 17 00:00:00 2001 From: SpackledJim Date: Sat, 10 Oct 2026 13:55:26 +0000 Subject: [PATCH 5/9] feat(search): accept IMDB links as the query Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H6X9gSzpaW1Z5cEET9L1pt --- src/commands/search.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/commands/search.ts b/src/commands/search.ts index 54496f2..414d4ac 100644 --- a/src/commands/search.ts +++ b/src/commands/search.ts @@ -10,6 +10,7 @@ import { type CommandV2 } from "interfaces/command.ts" import { getSeriesByImdbId, getSeriesByName } from "lib/tvdb.ts" import { buildShowEmbed } from "lib/messages.ts" import { showSearchAutocomplete } from "lib/autocomplete.ts" +import { parseIMDBIds } from "lib/util.ts" /** Channels a show is linked to, or none if the show isn't tracked. */ async function getDestinations(imdbId: string): Promise { @@ -29,7 +30,7 @@ export const command: CommandV2 = { .addStringOption((option) => option.setName("query") .setDescription( - "Query to search for. Can be an IMDB ID or a show name", + "Query to search for. Can be an IMDB ID, an IMDB link or a show name", ) .setMinLength(1) .setAutocomplete(true) @@ -37,9 +38,10 @@ export const command: CommandV2 = { ), }, async executeCommand(interaction: ChatInputCommandInteraction) { - const query = interaction.options.getString("query", true) + const query = interaction.options.getString("query", true).trim() - let imdbId = query.toLowerCase().startsWith("tt") ? query : undefined + // the query may be an IMDB ID or an IMDB link; anything else is a show name + let imdbId: string | undefined = parseIMDBIds(query.toLowerCase())[0] if (imdbId !== undefined) { const series = await getSeriesByImdbId(imdbId) From b48b8070202ada2a3bcf904cb0ad3708d6074a69 Mon Sep 17 00:00:00 2001 From: SpackledJim Date: Sat, 10 Oct 2026 14:02:30 +0000 Subject: [PATCH 6/9] feat(search): understand IMDB links in autocomplete Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H6X9gSzpaW1Z5cEET9L1pt --- src/lib/autocomplete.ts | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/src/lib/autocomplete.ts b/src/lib/autocomplete.ts index 0a99aa1..60bffa6 100644 --- a/src/lib/autocomplete.ts +++ b/src/lib/autocomplete.ts @@ -4,6 +4,7 @@ import { type AutocompleteInteraction, } from "discord.js" import client from "lib/prisma.ts" +import { parseIMDBIds } from "lib/util.ts" export async function showSearchAutocomplete( interaction: AutocompleteInteraction, @@ -12,20 +13,22 @@ export async function showSearchAutocomplete( if (focusedValue === undefined) return - const where: Prisma.ShowWhereInput = - focusedValue.toLocaleLowerCase().startsWith("tt") - ? { - imdbId: { - startsWith: focusedValue, - mode: "insensitive", - }, - } - : { - name: { - startsWith: focusedValue, - mode: "insensitive", - }, - } + // the input may be a (partial) IMDB ID or IMDB link; otherwise match by name + const [parsedId] = parseIMDBIds(focusedValue.trim().toLowerCase()) + + const where: Prisma.ShowWhereInput = parsedId != null && parsedId !== "" + ? { + imdbId: { + startsWith: parsedId, + mode: "insensitive", + }, + } + : { + name: { + startsWith: focusedValue, + mode: "insensitive", + }, + } const data = await client.show.findMany({ where, From be79586eefe962303e74dbc29b1699b34b77e73a Mon Sep 17 00:00:00 2001 From: SpackledJim Date: Sat, 10 Oct 2026 17:31:54 +0000 Subject: [PATCH 7/9] feat(search): browse name search matches in a carousel Name searches now load every match and show them one at a time in a private message, with a dropdown to jump to any match and previous/next buttons that wrap around. Matches without an IMDB id are dropped. Titles show the year, unless the TVDB name already ends in one. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H6X9gSzpaW1Z5cEET9L1pt --- src/commands/search.ts | 74 ++++++++++++-- src/lib/carousel.ts | 221 +++++++++++++++++++++++++++++++++++++++++ src/lib/tvdb.ts | 31 ++++-- 3 files changed, 310 insertions(+), 16 deletions(-) create mode 100644 src/lib/carousel.ts diff --git a/src/commands/search.ts b/src/commands/search.ts index 414d4ac..ffcadac 100644 --- a/src/commands/search.ts +++ b/src/commands/search.ts @@ -7,10 +7,17 @@ import { import client from "lib/prisma.ts" import { type Destination } from "prisma-client/client.ts" import { type CommandV2 } from "interfaces/command.ts" -import { getSeriesByImdbId, getSeriesByName } from "lib/tvdb.ts" +import { + getSeriesByImdbId, + getSeriesByTvdbId, + getSeriesCandidates, + type SeriesCandidate, +} from "lib/tvdb.ts" import { buildShowEmbed } from "lib/messages.ts" import { showSearchAutocomplete } from "lib/autocomplete.ts" import { parseIMDBIds } from "lib/util.ts" +import { type CarouselPage, sendCarousel } from "lib/carousel.ts" +import { type SeriesExtendedRecord } from "interfaces/tvdb.generated.ts" /** Channels a show is linked to, or none if the show isn't tracked. */ async function getDestinations(imdbId: string): Promise { @@ -21,6 +28,50 @@ async function getDestinations(imdbId: string): Promise { return show?.destinations ?? [] } +/** + * Builds the page shown for a show, with the channels it is linked to + * @param fallbackYear year to use if the show record doesn't have one + */ +async function buildSeriesPage( + imdbId: string, + series: SeriesExtendedRecord, + fallbackYear?: string, +): Promise { + const year = [series.year, series.firstAired?.slice(0, 4), fallbackYear] + .find((y) => y != null && y !== "") + + // some TVDB names already end in a year, like "The Count of Monte Cristo (1965)" + const nameHasYear = /\(\d{4}\)\s*$/.test(series.name) + const title = year != null && !nameHasYear + ? `${series.name} (${year})` + : series.name + const embed = buildShowEmbed(imdbId, series, await getDestinations(imdbId)) + + return { + label: title, + // tells apart shows with the same name and year + description: series.latestNetwork?.name, + // the year is only added here so /link and /post embeds stay as they are + embed: { ...embed, title }, + } +} + +/** + * Builds the carousel page for one name search match + * @returns the page, or undefined if the show can't be loaded or has no IMDB id + */ +async function buildCandidatePage( + candidate: SeriesCandidate, +): Promise { + const series = await getSeriesByTvdbId(parseInt(candidate.tvdb_id)) + if (series == null) return undefined + + const imdbId = series.remoteIds?.find((r) => r.type === 2)?.id + if (imdbId == null) return undefined + + return await buildSeriesPage(imdbId, series, candidate.year) +} + export const command: CommandV2 = { slashCommand: { main: new SlashCommandBuilder() @@ -41,7 +92,7 @@ export const command: CommandV2 = { const query = interaction.options.getString("query", true).trim() // the query may be an IMDB ID or an IMDB link; anything else is a show name - let imdbId: string | undefined = parseIMDBIds(query.toLowerCase())[0] + const imdbId: string | undefined = parseIMDBIds(query.toLowerCase())[0] if (imdbId !== undefined) { const series = await getSeriesByImdbId(imdbId) @@ -59,17 +110,22 @@ export const command: CommandV2 = { }) } - const series = await getSeriesByName(query) + const candidates = await getSeriesCandidates(query) - if (series == null) return await interaction.editReply("Show not found") + if (candidates.length === 0) { + return await interaction.editReply("Show not found") + } - imdbId = series.remoteIds.find((r) => r.type === 2)?.id + // the search results don't reliably say which shows have an IMDB id, so + // load every match now and drop the ones without, keeping the page count right + const pages = (await Promise.all(candidates.map(buildCandidatePage))) + .filter((page) => page != null) - if (imdbId == null) return await interaction.editReply("Show not found") + if (pages.length === 0) { + return await interaction.editReply("Show not found") + } - return await interaction.editReply({ - embeds: [buildShowEmbed(imdbId, series, await getDestinations(imdbId))], - }) + return await sendCarousel(interaction, pages) }, async executeAutoComplete(interaction: AutocompleteInteraction) { await showSearchAutocomplete(interaction) diff --git a/src/lib/carousel.ts b/src/lib/carousel.ts new file mode 100644 index 0000000..93dbff7 --- /dev/null +++ b/src/lib/carousel.ts @@ -0,0 +1,221 @@ +import { + ActionRowBuilder, + type APIEmbed, + ButtonBuilder, + ButtonStyle, + type ChatInputCommandInteraction, + ContainerBuilder, + type Message, + MessageFlags, + SectionBuilder, + SeparatorBuilder, + SeparatorSpacingSize, + StringSelectMenuBuilder, + StringSelectMenuOptionBuilder, + TextDisplayBuilder, + ThumbnailBuilder, +} from "discord.js" + +const PREVIOUS_ID = "carousel_previous" +const NEXT_ID = "carousel_next" +const SELECT_ID = "carousel_select" + +/** how long the controls keep working after the reply is sent */ +const TIMEOUT_MS = 10 * 60 * 1000 + +/** discord allows at most 25 options in a select menu */ +const MAX_PAGES = 25 + +/** discord allows 4000 characters of text per message, this leaves room for the rest */ +const MAX_DESCRIPTION_LENGTH = 2000 + +export interface CarouselPage { + /** shown in the dropdown, discord limits this to 100 characters */ + label: string + /** shown under the label in the dropdown, discord limits this to 100 characters */ + description?: string + embed: APIEmbed +} + +function buildSelect( + pages: CarouselPage[], + index: number, + disabled: boolean, +): ActionRowBuilder { + return new ActionRowBuilder().addComponents( + new StringSelectMenuBuilder() + .setCustomId(SELECT_ID) + .setPlaceholder("Choose a result") + .setDisabled(disabled) + .addOptions( + pages.map((page, i) => { + const option = new StringSelectMenuOptionBuilder() + .setLabel(page.label.slice(0, 100)) + .setValue(String(i)) + // the selected option is what the dropdown displays + .setDefault(i === index) + if (page.description != null && page.description !== "") { + option.setDescription(page.description.slice(0, 100)) + } + return option + }), + ), + ) +} + +function buildButtons( + index: number, + count: number, + disabled: boolean, +): ActionRowBuilder { + return new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId(PREVIOUS_ID) + .setLabel("◀ Previous") + .setStyle(ButtonStyle.Secondary) + .setDisabled(disabled), + // not clickable, only shows the position + new ButtonBuilder() + .setCustomId("carousel_position") + .setLabel(`${index + 1} / ${count}`) + .setStyle(ButtonStyle.Secondary) + .setDisabled(true), + new ButtonBuilder() + .setCustomId(NEXT_ID) + .setLabel("Next ▶") + .setStyle(ButtonStyle.Secondary) + .setDisabled(disabled), + ) +} + +/** + * Lays an embed out as a container, with the dropdown above it where the title was + * Embeds can't be combined with the layout components needed to put the dropdown on top + * The embed title is dropped, the dropdown shows it instead + */ +function buildContainer( + pages: CarouselPage[], + index: number, + disabled: boolean, +): ContainerBuilder { + const { embed } = pages[index] + const container = new ContainerBuilder() + + if (embed.color != null) container.setAccentColor(embed.color) + + container.addActionRowComponents(buildSelect(pages, index, disabled)) + + if (embed.description != null && embed.description !== "") { + const description = embed.description.length > MAX_DESCRIPTION_LENGTH + ? embed.description.slice(0, MAX_DESCRIPTION_LENGTH - 1) + "…" + : embed.description + const text = new TextDisplayBuilder().setContent(description) + + if (embed.thumbnail?.url != null) { + container.addSectionComponents( + new SectionBuilder() + .addTextDisplayComponents(text) + .setThumbnailAccessory( + new ThumbnailBuilder().setURL(embed.thumbnail.url), + ), + ) + } else { + container.addTextDisplayComponents(text) + } + } + + if (embed.fields != null && embed.fields.length > 0) { + container + .addSeparatorComponents( + new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small), + ) + .addTextDisplayComponents( + new TextDisplayBuilder().setContent( + embed.fields + .map((f) => `**${f.name}**: ${f.value.replaceAll("\n", " • ")}`) + .join("\n"), + ), + ) + } + + container + .addSeparatorComponents( + new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small), + ) + .addActionRowComponents(buildButtons(index, pages.length, disabled)) + + if (embed.footer?.text != null) { + container.addTextDisplayComponents( + // small text, like an embed footer + new TextDisplayBuilder().setContent(`-# ${embed.footer.text}`), + ) + } + + return container +} + +/** + * Replies to a deferred command with a private card: one show at a time + * with a dropdown above it to jump to any page, and previous and next buttons + * that wrap around at either end + * The controls stop working after TIMEOUT_MS or when the bot restarts + * With a single page the embed is sent as it is, without controls + * @param interaction deferred command interaction to reply to + * @param allPages the pages in order, only the first MAX_PAGES are used + */ +export async function sendCarousel( + interaction: ChatInputCommandInteraction, + allPages: CarouselPage[], +): Promise { + const pages = allPages.slice(0, MAX_PAGES) + const count = pages.length + + if (count === 1) { + return await interaction.editReply({ embeds: [pages[0].embed] }) + } + + let index = 0 + + // a message with layout components can't have embeds or content + const buildPage = (disabled = false) => ({ + components: [buildContainer(pages, index, disabled)], + flags: MessageFlags.IsComponentsV2 as const, + }) + + const message = await interaction.editReply(buildPage()) + + const collector = message.createMessageComponentCollector({ + time: TIMEOUT_MS, + filter: (i) => i.user.id === interaction.user.id, + }) + + collector.on("collect", async (componentInteraction) => { + try { + if (componentInteraction.isStringSelectMenu()) { + const selected = Number(componentInteraction.values[0]) + if (Number.isInteger(selected) && selected >= 0 && selected < count) { + index = selected + } + } else if (componentInteraction.customId === NEXT_ID) { + index = (index + 1) % count + } else if (componentInteraction.customId === PREVIOUS_ID) { + index = (index - 1 + count) % count + } + + await componentInteraction.update(buildPage()) + } catch (error) { + console.error("Error changing carousel page:", error) + } + }) + + collector.on("end", async () => { + try { + await interaction.editReply(buildPage(true)) + } catch (error) { + // the reply may have been dismissed or the interaction token expired + console.debug("Could not disable carousel controls:", error) + } + }) + + return message +} diff --git a/src/lib/tvdb.ts b/src/lib/tvdb.ts index d1a81b4..e69f712 100644 --- a/src/lib/tvdb.ts +++ b/src/lib/tvdb.ts @@ -190,8 +190,8 @@ async function searchSeriesByName( const data: { data: SearchResult[] } = await response.json() const searchResult = data?.data - // an unknown show gives an empty array, so guard before indexing - if (searchResult?.[0]?.tvdb_id == null) return undefined + // an unknown show gives an empty array + if (searchResult == null || searchResult.length === 0) return undefined return searchResult } catch (error) { console.error(`Unexpected Error Searching Series:`, error) @@ -199,11 +199,28 @@ async function searchSeriesByName( return undefined } -export async function getSeriesByName( +export type SeriesCandidate = SearchResult & { tvdb_id: string } + +/** + * Searches TVDB for series matching a name + * Results without a TVDB id, or known to have no IMDB id, are left out + * The search results don't always list IMDB ids, so callers should still + * check the full record from getSeriesByTvdbId + * @returns matching series, best match first + */ +export async function getSeriesCandidates( query: string, +): Promise { + const results = await searchSeriesByName(query) + + return (results ?? []).filter((r): r is SeriesCandidate => + r.tvdb_id != null && + (r.remote_ids == null || r.remote_ids.some((id) => id.type === 2)) + ) +} + +export async function getSeriesByTvdbId( + tvdbId: number, ): Promise { - const searchResult = await searchSeriesByName(query) - const tvdbId = searchResult?.[0]?.tvdb_id - if (tvdbId == null) return undefined - return withEnglishTranslation(await getSeries(parseInt(tvdbId))) + return withEnglishTranslation(await getSeries(tvdbId)) } From b9d87a5ae877e0444f4d74a22bcf2139fbc4a16e Mon Sep 17 00:00:00 2001 From: SpackledJim Date: Sat, 10 Oct 2026 17:32:09 +0000 Subject: [PATCH 8/9] feat(search): send a chosen match to the channel Every successful search now shows a private card first. Its green Send button posts the current match to the channel as a public embed, with a small "user used search" line that doesn't mention anyone, then deletes the private card. If the post fails the card stays so Send can be retried. Searches by IMDB id or link, and name searches with one match, show the same card without the dropdown and previous/next buttons. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H6X9gSzpaW1Z5cEET9L1pt --- src/commands/search.ts | 8 ++--- src/lib/carousel.ts | 74 ++++++++++++++++++++++++++++++++++++++---- 2 files changed, 70 insertions(+), 12 deletions(-) diff --git a/src/commands/search.ts b/src/commands/search.ts index ffcadac..f149ef1 100644 --- a/src/commands/search.ts +++ b/src/commands/search.ts @@ -103,11 +103,9 @@ export const command: CommandV2 = { ) } - return await interaction.editReply({ - embeds: [ - buildShowEmbed(imdbId, series, await getDestinations(imdbId)), - ], - }) + return await sendCarousel(interaction, [ + await buildSeriesPage(imdbId, series), + ]) } const candidates = await getSeriesCandidates(query) diff --git a/src/lib/carousel.ts b/src/lib/carousel.ts index 93dbff7..6be20cd 100644 --- a/src/lib/carousel.ts +++ b/src/lib/carousel.ts @@ -19,6 +19,10 @@ import { const PREVIOUS_ID = "carousel_previous" const NEXT_ID = "carousel_next" const SELECT_ID = "carousel_select" +const SEND_ID = "carousel_send" + +/** why the collector stopped when a result was sent */ +const SENT_REASON = "sent" /** how long the controls keep working after the reply is sent */ const TIMEOUT_MS = 10 * 60 * 1000 @@ -68,6 +72,17 @@ function buildButtons( count: number, disabled: boolean, ): ActionRowBuilder { + const send = new ButtonBuilder() + .setCustomId(SEND_ID) + .setLabel("Send") + .setStyle(ButtonStyle.Success) + .setDisabled(disabled) + + // there is nothing to browse with a single page + if (count === 1) { + return new ActionRowBuilder().addComponents(send) + } + return new ActionRowBuilder().addComponents( new ButtonBuilder() .setCustomId(PREVIOUS_ID) @@ -85,6 +100,7 @@ function buildButtons( .setLabel("Next ▶") .setStyle(ButtonStyle.Secondary) .setDisabled(disabled), + send, ) } @@ -103,7 +119,17 @@ function buildContainer( if (embed.color != null) container.setAccentColor(embed.color) - container.addActionRowComponents(buildSelect(pages, index, disabled)) + if (pages.length > 1) { + container.addActionRowComponents(buildSelect(pages, index, disabled)) + } else { + // with one page the title isn't in a dropdown, so show it as a heading + const { label } = pages[index] + container.addTextDisplayComponents( + new TextDisplayBuilder().setContent( + `## ${embed.url != null ? `[${label}](${embed.url})` : label}`, + ), + ) + } if (embed.description != null && embed.description !== "") { const description = embed.description.length > MAX_DESCRIPTION_LENGTH @@ -158,8 +184,10 @@ function buildContainer( * Replies to a deferred command with a private card: one show at a time * with a dropdown above it to jump to any page, and previous and next buttons * that wrap around at either end + * A single page has just its title and the Send button + * The Send button posts the current page's embed publicly to the channel + * then deletes the carousel reply * The controls stop working after TIMEOUT_MS or when the bot restarts - * With a single page the embed is sent as it is, without controls * @param interaction deferred command interaction to reply to * @param allPages the pages in order, only the first MAX_PAGES are used */ @@ -170,10 +198,6 @@ export async function sendCarousel( const pages = allPages.slice(0, MAX_PAGES) const count = pages.length - if (count === 1) { - return await interaction.editReply({ embeds: [pages[0].embed] }) - } - let index = 0 // a message with layout components can't have embeds or content @@ -191,6 +215,39 @@ export async function sendCarousel( collector.on("collect", async (componentInteraction) => { try { + if (componentInteraction.customId === SEND_ID) { + await componentInteraction.deferUpdate() + + // the embed is sent as built, with its title, columns and footer logo + // the user is shown as a name but not pinged + const publicMessage = { + content: + `-# <@${interaction.user.id}> used ${interaction.commandName}`, + embeds: [pages[index].embed], + allowedMentions: { parse: [] }, + } + try { + const channel = componentInteraction.channel + if (channel?.isSendable()) { + await channel.send(publicMessage) + } else { + await componentInteraction.followUp(publicMessage) + } + } catch (error) { + console.error("Error sending carousel page to the channel:", error) + await componentInteraction.followUp({ + content: "Couldn't send that to the channel.", + flags: MessageFlags.Ephemeral, + }) + return + } + + // only remove the carousel once the result has been sent + collector.stop(SENT_REASON) + await interaction.deleteReply() + return + } + if (componentInteraction.isStringSelectMenu()) { const selected = Number(componentInteraction.values[0]) if (Number.isInteger(selected) && selected >= 0 && selected < count) { @@ -208,7 +265,10 @@ export async function sendCarousel( } }) - collector.on("end", async () => { + collector.on("end", async (_collected, reason) => { + // the reply was deleted, so there are no controls left to disable + if (reason === SENT_REASON) return + try { await interaction.editReply(buildPage(true)) } catch (error) { From 4b9c1937431791fcedb451a2e9c3bb753f4bcbd3 Mon Sep 17 00:00:00 2001 From: SpackledJim Date: Sat, 10 Oct 2026 17:32:15 +0000 Subject: [PATCH 9/9] feat(search): add optional year filter Name searches can be narrowed to shows first aired in a given year. The year is ignored for IMDB ids and links, which already identify one show. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01H6X9gSzpaW1Z5cEET9L1pt --- src/commands/search.ts | 10 +++++++++- src/lib/tvdb.ts | 6 +++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/commands/search.ts b/src/commands/search.ts index f149ef1..4f52756 100644 --- a/src/commands/search.ts +++ b/src/commands/search.ts @@ -86,6 +86,12 @@ export const command: CommandV2 = { .setMinLength(1) .setAutocomplete(true) .setRequired(true) + ) + .addIntegerOption((option) => + option.setName("year") + .setDescription("Only show matches first aired in this year") + .setMinValue(1900) + .setMaxValue(2100) ), }, async executeCommand(interaction: ChatInputCommandInteraction) { @@ -108,7 +114,9 @@ export const command: CommandV2 = { ]) } - const candidates = await getSeriesCandidates(query) + // an IMDB id or link already points at one show, so the year only narrows name searches + const year = interaction.options.getInteger("year") ?? undefined + const candidates = await getSeriesCandidates(query, year) if (candidates.length === 0) { return await interaction.editReply("Show not found") diff --git a/src/lib/tvdb.ts b/src/lib/tvdb.ts index e69f712..0888fcd 100644 --- a/src/lib/tvdb.ts +++ b/src/lib/tvdb.ts @@ -165,6 +165,7 @@ async function searchSeriesByImdbId( async function searchSeriesByName( query: string, + year?: number, ): Promise { try { const params = new URLSearchParams({ @@ -172,6 +173,7 @@ async function searchSeriesByName( limit: "10", q: query, }) + if (year != null) params.set("year", String(year)) const response = await fetch( `${baseURL}/search?${params}`, { @@ -206,12 +208,14 @@ export type SeriesCandidate = SearchResult & { tvdb_id: string } * Results without a TVDB id, or known to have no IMDB id, are left out * The search results don't always list IMDB ids, so callers should still * check the full record from getSeriesByTvdbId + * @param year only return series first aired in this year * @returns matching series, best match first */ export async function getSeriesCandidates( query: string, + year?: number, ): Promise { - const results = await searchSeriesByName(query) + const results = await searchSeriesByName(query, year) return (results ?? []).filter((r): r is SeriesCandidate => r.tvdb_id != null &&