mirror of
https://github.com/toast-ts/Daggerbot-TS.git
synced 2024-11-17 12:21:00 -05:00
Rework the YTModule and CacheServer
This commit is contained in:
parent
9719fce92f
commit
555a3e4930
@ -6,7 +6,6 @@ type MPServerCache = Record<string,{
|
|||||||
status: 'online' | 'offline' | null,
|
status: 'online' | 'offline' | null,
|
||||||
name: string | null
|
name: string | null
|
||||||
}>
|
}>
|
||||||
type YouTubeCache = Record<string,string>
|
|
||||||
import Discord from 'discord.js';
|
import Discord from 'discord.js';
|
||||||
import {readFileSync, readdirSync} from 'node:fs';
|
import {readFileSync, readdirSync} from 'node:fs';
|
||||||
import {Tokens, Config, FSPlayer} from './typings/interfaces';
|
import {Tokens, Config, FSPlayer} from './typings/interfaces';
|
||||||
@ -39,7 +38,6 @@ export default class TClient extends Discord.Client {
|
|||||||
registry: Array<Discord.ApplicationCommandDataResolvable>;
|
registry: Array<Discord.ApplicationCommandDataResolvable>;
|
||||||
config: Config;
|
config: Config;
|
||||||
tokens: Tokens;
|
tokens: Tokens;
|
||||||
YTCache: YouTubeCache = {};
|
|
||||||
embed: typeof Discord.EmbedBuilder;
|
embed: typeof Discord.EmbedBuilder;
|
||||||
collection: typeof Discord.Collection;
|
collection: typeof Discord.Collection;
|
||||||
attachmentBuilder: typeof Discord.AttachmentBuilder;
|
attachmentBuilder: typeof Discord.AttachmentBuilder;
|
||||||
@ -73,10 +71,6 @@ export default class TClient extends Discord.Client {
|
|||||||
this.registry = [];
|
this.registry = [];
|
||||||
this.config = importconfig as Config;
|
this.config = importconfig as Config;
|
||||||
this.tokens = tokens as Tokens;
|
this.tokens = tokens as Tokens;
|
||||||
this.YTCache = {
|
|
||||||
'UCQ8k8yTDLITldfWYKDs3xFg': undefined, // Daggerwin
|
|
||||||
'UCguI73--UraJpso4NizXNzA': undefined // Machinery Restorer
|
|
||||||
} as YouTubeCache;
|
|
||||||
this.embed = Discord.EmbedBuilder;
|
this.embed = Discord.EmbedBuilder;
|
||||||
this.collection = Discord.Collection;
|
this.collection = Discord.Collection;
|
||||||
this.attachmentBuilder = Discord.AttachmentBuilder;
|
this.attachmentBuilder = Discord.AttachmentBuilder;
|
||||||
|
@ -19,30 +19,33 @@ export default class CacheServer {
|
|||||||
protected static eventManager() {
|
protected static eventManager() {
|
||||||
RedisClient
|
RedisClient
|
||||||
.on('connect', ()=>Logger.forwardToConsole('log', Prefix, 'Connection to Redis has been established'))
|
.on('connect', ()=>Logger.forwardToConsole('log', Prefix, 'Connection to Redis has been established'))
|
||||||
.on('error', (err:ErrorReply)=>Logger.forwardToConsole('error', Prefix, `Encountered an error in Redis: ${err.message}`))
|
.on('error', (err:ErrorReply)=>{
|
||||||
}
|
Logger.forwardToConsole('error', Prefix, `Encountered an error in Redis: ${err.message}`)
|
||||||
protected static async connect() {
|
setTimeout(async()=>{
|
||||||
|
if (!RedisClient.isReady) {
|
||||||
|
Logger.forwardToConsole('log', Prefix, 'Client is zombified, starting a fresh connection...');
|
||||||
|
RedisClient.quit();
|
||||||
await RedisClient.connect();
|
await RedisClient.connect();
|
||||||
}
|
}
|
||||||
|
}, 1500)
|
||||||
|
})
|
||||||
|
}
|
||||||
static async get(key:any) {
|
static async get(key:any) {
|
||||||
const cachedResult = await RedisClient.get(key);
|
const cachedResult = await RedisClient.get(key);
|
||||||
if (cachedResult) return JSON.parse(cachedResult);
|
if (cachedResult) return JSON.parse(cachedResult);
|
||||||
else return null
|
else return null
|
||||||
}
|
}
|
||||||
static async set(key:any, value:any) {
|
static async set(key:any, value:any) {
|
||||||
Logger.forwardToConsole('log', Prefix, `Building cache for ${key}`);
|
|
||||||
return await RedisClient.set(key, JSON.stringify(value));
|
return await RedisClient.set(key, JSON.stringify(value));
|
||||||
}
|
}
|
||||||
static async expiry(key:any, time:number) {
|
static async expiry(key:any, time:number) {
|
||||||
Logger.forwardToConsole('log', Prefix, `Setting expiration for ${key} to ${time} seconds`);
|
return await RedisClient.expire(key, time); // NOTE: time is in seconds, not milliseconds -- you know what you did wrong
|
||||||
return await RedisClient.expire(key, time);
|
|
||||||
}
|
}
|
||||||
static async delete(key:any) {
|
static async delete(key:any) {
|
||||||
Logger.forwardToConsole('log', Prefix, `Deleting cache for ${key}`);
|
|
||||||
return await RedisClient.del(key);
|
return await RedisClient.del(key);
|
||||||
}
|
}
|
||||||
static init() {
|
static init() {
|
||||||
this.connect();
|
RedisClient.connect();
|
||||||
this.eventManager();
|
this.eventManager();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,20 +1,38 @@
|
|||||||
import {TextChannel} from 'discord.js';
|
import {TextChannel} from 'discord.js';
|
||||||
import TClient from '../client.js';
|
import TClient from '../client.js';
|
||||||
import Logger from '../helpers/Logger.js';
|
import Logger from '../helpers/Logger.js';
|
||||||
|
import CacheServer from './CacheServer.js';
|
||||||
import MessageTool from '../helpers/MessageTool.js';
|
import MessageTool from '../helpers/MessageTool.js';
|
||||||
|
|
||||||
export default async(client:TClient, YTChannelID:string, YTChannelName:string, DiscordChannelID:string, DiscordRoleID:string)=>{
|
export default async(client:TClient, YTChannelID:string, YTChannelName:string, DiscordChannelID:string, DiscordRoleID:string)=>{
|
||||||
let Data: any;
|
let Data: any;
|
||||||
|
let cacheExpiry: number = 14400; // Invalidate cache after sitting in Redis for 4 hours
|
||||||
try {
|
try {
|
||||||
await fetch(`https://www.youtube.com/feeds/videos.xml?channel_id=${YTChannelID}`, {signal: AbortSignal.timeout(8000), headers: {'User-Agent': 'Daggerbot - Notification/undici'}}).then(async xml=>Data = client.xjs.xml2js(await xml.text(), {compact: true}))
|
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) {
|
} catch (err) {
|
||||||
Logger.forwardToConsole('log', 'YTModule', `Failed to fetch "${YTChannelName}" from YouTube`)
|
Logger.forwardToConsole('log', 'YTModule', `Failed to fetch "${YTChannelName}" from YouTube`);
|
||||||
|
}
|
||||||
|
if (!Data) return;
|
||||||
|
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) return;
|
if (Data.feed.entry[1]['yt:videoId']._text === cachedVideoId) {
|
||||||
if (!client.YTCache[YTChannelID]) return client.YTCache[YTChannelID] = Data.feed.entry[0]['yt:videoId']._text;
|
const videoId = Data.feed.entry[0]['yt:videoId']._text;
|
||||||
if (Data.feed.entry[1]['yt:videoId']._text === client.YTCache[YTChannelID]){
|
await CacheServer.delete(cacheKey).then(async()=>{
|
||||||
client.YTCache[YTChannelID] = Data.feed.entry[0]['yt:videoId']._text;
|
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']}})
|
});
|
||||||
|
|
||||||
|
(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']},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -38,11 +38,11 @@ if (client.config.botSwitches.music){
|
|||||||
if (client.config.botSwitches.mpstats) setInterval(async()=>{
|
if (client.config.botSwitches.mpstats) setInterval(async()=>{
|
||||||
const serverlake = (await client.MPServer.findInCache(client.config.mainServer.id));
|
const serverlake = (await client.MPServer.findInCache(client.config.mainServer.id));
|
||||||
for await (const [locName, locArea] of Object.entries(client.config.MPStatsLocation)) await MPModule(client, locArea.channel, locArea.message, serverlake[locName], locName)
|
for await (const [locName, locArea] of Object.entries(client.config.MPStatsLocation)) await MPModule(client, locArea.channel, locArea.message, serverlake[locName], locName)
|
||||||
}, 35000);
|
}, 35000); // 35 seconds
|
||||||
setInterval(async()=>{// Ping notification is currently WIP, it might be active in production but I want to see how it goes with role mentions first so I can make any further changes.
|
setInterval(async()=>{
|
||||||
YTModule(client, 'UCQ8k8yTDLITldfWYKDs3xFg', 'Daggerwin', '528967918772551702', '1155760735612305408'); // 528967918772551702 = #videos-and-streams; 1155760735612305408 = YT Upload Ping;
|
YTModule(client, 'UCQ8k8yTDLITldfWYKDs3xFg', 'Daggerwin', '528967918772551702', '1155760735612305408'); // 528967918772551702 = #videos-and-streams; 1155760735612305408 = YT Upload Ping;
|
||||||
YTModule(client, 'UCguI73--UraJpso4NizXNzA', 'Machinery Restorer', '767444045520961567', '1155760735612305408') // 767444045520961567 = #machinery-restorer; ^^
|
YTModule(client, 'UCguI73--UraJpso4NizXNzA', 'Machinery Restorer', '767444045520961567', '1155760735612305408') // 767444045520961567 = #machinery-restorer; ^^
|
||||||
}, 300000)
|
}, 300000); // 5 minutes
|
||||||
|
|
||||||
// Event loop for punishments and daily msgs
|
// Event loop for punishments and daily msgs
|
||||||
setInterval(async()=>{
|
setInterval(async()=>{
|
||||||
|
Loading…
Reference in New Issue
Block a user