diff --git a/src/cool-links-management.ts b/src/cool-links-management.ts index dacf7ee..0e42864 100644 --- a/src/cool-links-management.ts +++ b/src/cool-links-management.ts @@ -1,5 +1,6 @@ import { type Message, ThreadAutoArchiveDuration } from 'discord.js'; import ogs from 'open-graph-scraper'; +import { getVideoSummary } from './summarize-cool-videos'; const getThreadNameFromOpenGraph = async (url: string): Promise => { try { @@ -24,6 +25,8 @@ const getThreadNameFromOpenGraph = async (url: string): Promise = return null; }; +const youtubeUrlRegex = new RegExp('^(https?)?(://)?(www.)?(m.)?((youtube.com)|(youtu.be))'); + export const coolLinksManagement = async (message: Message) => { const urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g; const detectedURLs = message.content.match(urlRegex); @@ -36,9 +39,18 @@ export const coolLinksManagement = async (message: Message) => { await message.react('✅'); await message.react('❌'); - const threadName = await getThreadNameFromOpenGraph(detectedURLs[0]); - await message.startThread({ + const url = detectedURLs[0]; + const threadName = await getThreadNameFromOpenGraph(url); + const thread = await message.startThread({ name: threadName ?? message.content, autoArchiveDuration: ThreadAutoArchiveDuration.ThreeDays, }); + if (thread.joinable) await thread.join(); + + if (youtubeUrlRegex.test(url)) { + const summary = await getVideoSummary(url); + if (!summary) return; + + await thread.send(summary); + } }; diff --git a/src/summarize-cool-videos.ts b/src/summarize-cool-videos.ts new file mode 100644 index 0000000..a844747 --- /dev/null +++ b/src/summarize-cool-videos.ts @@ -0,0 +1,43 @@ +const baseUrl = 'https://www.summarize.tech/api/summary'; + +export const getVideoSummary = async (videoUrl: string) => { + const summary = await fetch(baseUrl, { + method: 'POST', + body: JSON.stringify({ url: videoUrl, deviceId: makeId(21) }), + headers: { 'content-type': 'application/json' }, + }) + .then((res) => res.json()) + .then((res) => + (Object.values((res as SummaryResponse).rollups) ?? []) + .map((chunk) => chunk.summary) + .join(' '), + ); + + return summary; +}; + +const makeId = (length: number) => { + let result = ''; + const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_'; + const charactersLength = characters.length; + + for (let i = 0; i < length; i++) + result += characters.charAt(Math.floor(Math.random() * charactersLength)); + + return result; +}; + +// Example usage: +// const videoUrl = 'https://www.youtube.com/watch?v=ruUlK6zRwS8'; +// const summary = await getVideoSummary(videoUrl); +// console.log({ summary }); + +type SummaryResponse = { + rollups: Record; + title: string; +}; + +type SummaryChunk = { + children: Record; + summary: string; +};