2023-08-30 04:34:59 -04:00
import { TextChannel } from 'discord.js' ;
import TClient from '../client.js' ;
2023-09-29 17:27:32 -04:00
import Logger from '../helpers/Logger.js' ;
2023-10-03 03:07:19 -04:00
import CacheServer from './CacheServer.js' ;
2023-09-26 06:03:27 -04:00
import MessageTool from '../helpers/MessageTool.js' ;
2023-08-30 04:34:59 -04:00
2023-10-03 03:07:19 -04:00
export default async ( client :TClient , YTChannelID :string , YTChannelName :string , DiscordChannelID :string , DiscordRoleID :string ) = > {
2023-08-30 04:34:59 -04:00
let Data : any ;
2023-10-03 03:07:19 -04:00
let cacheExpiry : number = 14400 ; // Invalidate cache after sitting in Redis for 4 hours
2023-08-30 04:34:59 -04:00
try {
2023-10-03 03:07:19 -04:00
await fetch ( ` https://www.youtube.com/feeds/videos.xml?channel_id= ${ YTChannelID } ` , {
signal : AbortSignal.timeout ( 10000 ) ,
headers : { 'User-Agent' : 'Daggerbot - Notification/undici' } ,
} ) . then ( async xml = > ( Data = client . xjs . xml2js ( await xml . text ( ) , { compact : true } ) ) ) ;
} catch ( err ) {
Logger . forwardToConsole ( 'log' , 'YTModule' , ` Failed to fetch " ${ YTChannelName } " from YouTube ` ) ;
2023-08-30 04:34:59 -04:00
}
if ( ! Data ) return ;
2023-10-03 03:07:19 -04:00
const cacheKey = ` YTCache: ${ YTChannelID } ` ;
const cachedVideoId = await CacheServer . get ( cacheKey ) ;
if ( ! cachedVideoId ) {
const videoId = Data . feed . entry [ 0 ] [ 'yt:videoId' ] . _text ;
await CacheServer . set ( cacheKey , videoId ) . then ( async ( ) = > await CacheServer . expiry ( cacheKey , cacheExpiry ) ) ;
return ;
}
if ( Data . feed . entry [ 1 ] [ 'yt:videoId' ] . _text === cachedVideoId ) {
const videoId = Data . feed . entry [ 0 ] [ 'yt:videoId' ] . _text ;
await CacheServer . delete ( cacheKey ) . then ( async ( ) = > {
await CacheServer . set ( cacheKey , videoId ) . 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 . _attributes . href } ` ,
allowedMentions : { parse : [ 'roles' ] } ,
} ) ;
2023-08-30 04:34:59 -04:00
}
}