From 2022dd6adf14c3d1dbf68d3613fb3d5bfede8826 Mon Sep 17 00:00:00 2001 From: toast-ts <96593068+toast-ts@users.noreply.github.com> Date: Fri, 13 Oct 2023 09:11:17 +1100 Subject: [PATCH] YouTube no longer has `videos.xml` page --- src/funcs/YTModule.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/funcs/YTModule.ts b/src/funcs/YTModule.ts index 111ce92..3ba2d49 100644 --- a/src/funcs/YTModule.ts +++ b/src/funcs/YTModule.ts @@ -1,5 +1,6 @@ import {TextChannel} from 'discord.js'; import TClient from '../client.js'; +import TSClient from '../helpers/TSClient.js'; import Logger from '../helpers/Logger.js'; import CacheServer from './CacheServer.js'; import MessageTool from '../helpers/MessageTool.js'; @@ -8,27 +9,29 @@ export default async(client:TClient, YTChannelID:string, YTChannelName:string, D let Data: any; let cacheExpiry: number = 7200; // Invalidate cache after sitting in Redis for 2 hours try { - await fetch(`https://www.youtube.com/feeds/videos.xml?channel_id=${YTChannelID}`, { + await fetch(`https://youtube.googleapis.com/youtube/v3/activities?part=snippet&channelId=${YTChannelID}&maxResults=2&key=${(await TSClient.Token()).youtube}`, { signal: AbortSignal.timeout(10000), headers: {'User-Agent':'Daggerbot - Notification/undici'}, - }).then(async xml=>(Data = new client.fxp.XMLParser({ignoreAttributes: false, transformAttributeName(attributeName){return attributeName.replaceAll('@_','')}}).parse(await xml.text()) as any)); + }).then(async json=>Data = await json.json()); } catch (err) { Logger.forwardToConsole('log', 'YTModule', `Failed to fetch "${YTChannelName}" from YouTube`); } if (!Data) return; + const getVideoId = (index:number)=>Data.items[index].snippet.thumbnails.default.url.split('/')[4]; + const videoUrl = `https://www.youtube.com/watch?v=${getVideoId(0)}`; const cacheKey = `YTCache:${YTChannelID}`; const cachedVideoId = await CacheServer.get(cacheKey); if (!cachedVideoId) { - await CacheServer.set(cacheKey, Data.feed.entry[0]['yt:videoId']).then(async()=>await CacheServer.expiry(cacheKey, cacheExpiry)); + await CacheServer.set(cacheKey, getVideoId(0)).then(async()=>await CacheServer.expiry(cacheKey, cacheExpiry)); return; } - if (Data.feed.entry[1]['yt:videoId'] === cachedVideoId) { + if (getVideoId(1) === cachedVideoId) { await CacheServer.delete(cacheKey).then(async()=>{ - await CacheServer.set(cacheKey, Data.feed.entry[0]['yt:videoId']).then(async()=>await CacheServer.expiry(cacheKey, cacheExpiry)) + await CacheServer.set(cacheKey, getVideoId(0)).then(async()=>await CacheServer.expiry(cacheKey, cacheExpiry)) }); (client.channels.resolve(DiscordChannelID) as TextChannel).send({ - content: `${MessageTool.formatMention(DiscordRoleID, 'role')}\n**${YTChannelName}** just uploaded a video!\n${Data.feed.entry[0].link.href}`, + content: `${MessageTool.formatMention(DiscordRoleID, 'role')}\n**${YTChannelName}** just uploaded a video!\n${videoUrl}`, allowedMentions: {parse:['roles']}, }); }