From b71db7b2524abd53161b1b9edeb471c1430fb63b Mon Sep 17 00:00:00 2001 From: AnxietyisReal <96593068+AnxietyisReal@users.noreply.github.com> Date: Fri, 1 Sep 2023 14:32:11 +1000 Subject: [PATCH] Optimizations --- .npmrc | 1 - package.json | 1 + src/client.ts | 25 +++++++++----- src/commands/mp.ts | 2 +- src/funcs/DatabaseServer.ts | 51 +++++++++++++++------------- src/funcs/{MPLoop.ts => MPModule.ts} | 10 ++++-- src/funcs/{YTLoop.ts => YTModule.ts} | 0 src/helpers/LogPrefix.ts | 1 + src/index.ts | 12 +++---- src/models/punishments.ts | 2 +- src/typings/interfaces.d.ts | 21 ------------ tsconfig.json | 4 +-- 12 files changed, 62 insertions(+), 68 deletions(-) delete mode 100644 .npmrc rename src/funcs/{MPLoop.ts => MPModule.ts} (95%) rename src/funcs/{YTLoop.ts => YTModule.ts} (100%) create mode 100644 src/helpers/LogPrefix.ts diff --git a/.npmrc b/.npmrc deleted file mode 100644 index d1cdf2f..0000000 --- a/.npmrc +++ /dev/null @@ -1 +0,0 @@ -engine-strict = true \ No newline at end of file diff --git a/package.json b/package.json index 7823b5d..c794609 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "yarn": ">=3.6.1", "npm": "please use yarn instead of npm" }, + "engineStrict": true, "packageManager": "yarn@3.6.3", "dependencies": { "@discord-player/extractor": "4.4.1", diff --git a/src/client.ts b/src/client.ts index 381ebd7..fcafabd 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,6 +1,15 @@ +interface repeatedMessages { + [key: string]: {data: Discord.Collection,timeout: NodeJS.Timeout} +} +type MPServerCache = Record +type YouTubeCache = Record import Discord from 'discord.js'; import {readFileSync, readdirSync} from 'node:fs'; -import {Tokens, Config, repeatedMessages, type MPServerCache} from './typings/interfaces'; +import {Tokens, Config, FSPlayer} from './typings/interfaces'; import bannedWords from './models/bannedWords.js'; import userLevels from './models/userLevels.js'; import suggestion from './models/suggestion.js'; @@ -29,11 +38,10 @@ export default class TClient extends Discord.Client { registry: Array; config: Config; tokens: Tokens; - YTCache: any; + YTCache: YouTubeCache = {}; embed: typeof Discord.EmbedBuilder; - collection: any; - messageCollector: any; - attachmentBuilder: any; + collection: typeof Discord.Collection; + attachmentBuilder: typeof Discord.AttachmentBuilder; moment: typeof moment; xjs: typeof xjs; userLevels: userLevels; @@ -67,10 +75,9 @@ export default class TClient extends Discord.Client { this.YTCache = { 'UCQ8k8yTDLITldfWYKDs3xFg': undefined, // Daggerwin 'UCguI73--UraJpso4NizXNzA': undefined // Machinery Restorer - } + } as YouTubeCache; this.embed = Discord.EmbedBuilder; this.collection = Discord.Collection; - this.messageCollector = Discord.MessageCollector; this.attachmentBuilder = Discord.AttachmentBuilder; this.moment = moment; this.xjs = xjs; @@ -83,12 +90,12 @@ export default class TClient extends Discord.Client { this.suggestion = new suggestion(this); this.tags = new tags(this); this.repeatedMessages = {}; - this.setMaxListeners(45); + this.setMaxListeners(62); this.statsGraph = -120; } async init(){ console.time('Startup'); - await DatabaseServer(this); + DatabaseServer.connect(this); this.login(this.tokens.main); for (const file of readdirSync('dist/events')){ const eventFile = await import(`./events/${file}`); diff --git a/src/commands/mp.ts b/src/commands/mp.ts index 374fe6b..749c3b5 100644 --- a/src/commands/mp.ts +++ b/src/commands/mp.ts @@ -5,7 +5,7 @@ import canvas from 'canvas'; import FormatPlayer from '../helpers/FormatPlayer.js'; import MessageTool from '../helpers/MessageTool.js'; import {readFileSync} from 'node:fs'; -import {FSData} from '../typings/interfaces.js'; +import {FSData} from '../typings/interfaces'; const serverChoices = [ {name: 'Main Server', value: 'mainServer'}, diff --git a/src/funcs/DatabaseServer.ts b/src/funcs/DatabaseServer.ts index 0aaf772..3cf9ca9 100644 --- a/src/funcs/DatabaseServer.ts +++ b/src/funcs/DatabaseServer.ts @@ -1,30 +1,33 @@ import TClient from '../client'; import mongoose from 'mongoose'; +import LogPrefix from '../helpers/LogPrefix.js'; -export default async(client:TClient)=>{ - const LogPrefix = '[DATABASE]'; - mongoose.set('strictQuery', true); +const connection:mongoose.Connection = mongoose.connection; +export default class DatabaseServer { + static connect(client: TClient) { + const Logger = (logType:'log'|'error', msg:string)=>console[logType](client.logTime(), `${LogPrefix('DATABASE')} ${msg}`); - const connection = mongoose.connection; - connection.openUri(client.tokens.mongodb_uri, { - replicaSet: 'toastyy', - autoIndex: true, - authMechanism: 'SCRAM-SHA-256', - authSource: 'admin', - serverSelectionTimeoutMS: 15000, - waitQueueTimeoutMS: 50000, - socketTimeoutMS: 30000, - tls: false, - family: 4 - }); + connection.set('strictQuery', true); + connection.openUri(client.tokens.mongodb_uri, { + replicaSet: 'toastyy', + autoIndex: true, + authMechanism: 'SCRAM-SHA-256', + authSource: 'admin', + serverSelectionTimeoutMS: 15000, + waitQueueTimeoutMS: 50000, + socketTimeoutMS: 30000, + tls: false, + family: 4 + }); - connection - .on('connecting', ()=>console.log(client.logTime(), `${LogPrefix} Establishing connection to MongoDB`)) - .on('connected', ()=>console.log(client.logTime(), `${LogPrefix} Connection to MongoDB has been established`)) - .on('disconnecting', ()=>console.log(client.logTime(), `${LogPrefix} Disconnecting from MongoDB`)) - .on('disconnected', ()=>console.log(client.logTime(), `${LogPrefix} Disconnected from MongoDB`)) - .on('close', ()=>console.log(client.logTime(), `${LogPrefix} MongoDB has closed the connection`)) - .on('all', ()=>console.log(client.logTime(), `${LogPrefix} Successfully established a connection to all members`)) - .on('fullsetup', ()=>console.log(client.logTime(), `${LogPrefix} Successfully established a connection to Primary server & atleast one member`)) - .on('error', (err:mongoose.Error)=>console.error(client.logTime(), `${LogPrefix} Encountered an error in MongoDB: ${err.message}`)); + connection + .on('connecting', ()=>Logger('log','Establishing connection to MongoDB')) + .on('connected', ()=>Logger('log','Connection to MongoDB has been established')) + .on('disconnecting', ()=>Logger('log','Disconnecting from MongoDB')) + .on('disconnected', ()=>Logger('log','Disconnected from MongoDB')) + .on('close', ()=>Logger('log','MongoDB has closed the connection')) + .on('all', ()=>Logger('log','Successfully established a connection to all members')) + .on('fullsetup', ()=>Logger('log','Successfully established a connection to Primary server & atleast one member')) + .on('error', (err:mongoose.Error)=>Logger('error',`Encountered an error in MongoDB: ${err.message}`)); + } } diff --git a/src/funcs/MPLoop.ts b/src/funcs/MPModule.ts similarity index 95% rename from src/funcs/MPLoop.ts rename to src/funcs/MPModule.ts index 44176c4..9ed8c09 100644 --- a/src/funcs/MPLoop.ts +++ b/src/funcs/MPModule.ts @@ -1,11 +1,15 @@ +interface TServer { + ip: string + code: string +} import Discord from 'discord.js'; import TClient from '../client'; import FormatPlayer from '../helpers/FormatPlayer.js'; +import LogPrefix from '../helpers/LogPrefix.js'; import {writeFileSync, readFileSync} from 'node:fs'; -import {FSPlayer, FSData, FSCareerSavegame, TServer} from '../typings/interfaces'; +import {FSPlayer, FSData, FSCareerSavegame} from '../typings/interfaces'; export default async(client:TClient, Channel:string, Message:string, Server:TServer, ServerName:string)=>{ - let MPLoopPrefix = '[MPLoop] '; let isServerOnline = false; let playerData:Array = []; let noContentImage = 'https://cdn.discordapp.com/attachments/1118960531135541318/1140906691236479036/68efx1.png'; @@ -20,7 +24,7 @@ export default async(client:TClient, Channel:string, Message:string, Server:TSer const hitCSG = await fetch(Server.ip+'/feed/dedicated-server-savegame.html?code='+Server.code+'&file=careerSavegame', sessionInit).then(async r=>(client.xjs.xml2js(await r.text(), {compact: true}) as any).careerSavegame as FSCareerSavegame); if (!hitDSS ?? !hitCSG){ - if (hitDSS && !hitDSS.slots) return new Error(`${MPLoopPrefix}DSS failed with unknown slots table for ${client.MPServerCache[ServerName].name}`); + if (hitDSS && !hitDSS.slots) return new Error(`${LogPrefix('MPLoop')} DSS failed with unknown slots table for ${client.MPServerCache[ServerName].name}`); if (hitDSS && !hitCSG) return msg.edit({content: 'No savegame found or autosave has ran.', embeds: [genericEmbed.setColor(client.config.embedColorOrange).setImage(noContentImage)]}); else return msg.edit({embeds: [serverErrorEmbed]}); } diff --git a/src/funcs/YTLoop.ts b/src/funcs/YTModule.ts similarity index 100% rename from src/funcs/YTLoop.ts rename to src/funcs/YTModule.ts diff --git a/src/helpers/LogPrefix.ts b/src/helpers/LogPrefix.ts new file mode 100644 index 0000000..5319190 --- /dev/null +++ b/src/helpers/LogPrefix.ts @@ -0,0 +1 @@ +export default (prefix:string)=>{ return `[${prefix}]` }; \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 6ac59d5..99b498c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,8 +2,8 @@ import Discord from 'discord.js'; import TClient from './client.js'; const client = new TClient; client.init(); -import YTLoop from './funcs/YTLoop.js'; -import MPLoop from './funcs/MPLoop.js'; +import YTModule from './funcs/YTModule.js'; +import MPModule from './funcs/MPModule.js'; import {Player} from 'discord-player'; const player = Player.singleton(client); import MessageTool from './helpers/MessageTool.js'; @@ -36,18 +36,18 @@ if (client.config.botSwitches.music){ // YouTube Upload notification and MP loop if (client.config.botSwitches.mpstats) setInterval(async()=>{ const serverlake = (await client.MPServer._content.findById(client.config.mainServer.id)); - for await (const [locName, locArea] of Object.entries(client.config.MPStatsLocation)) await MPLoop(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); 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. - YTLoop(client, 'UCQ8k8yTDLITldfWYKDs3xFg', 'Daggerwin', '528967918772551702', '1011341005389307925'); // 528967918772551702 = #videos-and-streams; 1011341005389307925 = Bot Tech; - YTLoop(client, 'UCguI73--UraJpso4NizXNzA', 'Machinery Restorer', '767444045520961567', '989591094524276796') // 767444045520961567 = #machinery-restorer; 989591094524276796 = Temp; + YTModule(client, 'UCQ8k8yTDLITldfWYKDs3xFg', 'Daggerwin', '528967918772551702', '1011341005389307925'); // 528967918772551702 = #videos-and-streams; 1011341005389307925 = Bot Tech; + YTModule(client, 'UCguI73--UraJpso4NizXNzA', 'Machinery Restorer', '767444045520961567', '989591094524276796') // 767444045520961567 = #machinery-restorer; 989591094524276796 = Temp; }, 300000) // Event loop for punishments and daily msgs setInterval(async()=>{ const now = Date.now(); - const punishments = await client.punishments._content.find({}); + const punishments = await client.punishments._content.find(); punishments.filter(x=>x.endTime && x.endTime<= now && !x.expired).forEach(async punishment=>{ console.log(client.logTime(), `${punishment.member}\'s ${punishment.type} should expire now`); console.log(client.logTime(), await client.punishments.removePunishment(punishment._id, client.user.id, 'Time\'s up!')); diff --git a/src/models/punishments.ts b/src/models/punishments.ts index 6fb7afe..e3f043c 100644 --- a/src/models/punishments.ts +++ b/src/models/punishments.ts @@ -3,7 +3,7 @@ import TClient from '../client.js'; import mongoose from 'mongoose'; import ms from 'ms'; import FormatTime from '../helpers/FormatTime.js'; -import {Punishment} from '../typings/interfaces.js'; +import {Punishment} from '../typings/interfaces'; const Schema = mongoose.model('punishments', new mongoose.Schema({ _id: {type: Number, required: true}, diff --git a/src/typings/interfaces.d.ts b/src/typings/interfaces.d.ts index 8a1ff81..cd06a03 100644 --- a/src/typings/interfaces.d.ts +++ b/src/typings/interfaces.d.ts @@ -1,17 +1,5 @@ import Discord from 'discord.js'; -export interface UserLevels { - messages: number, - level: number -} -export interface punOpt { - time?: string, - reason?: string, - interaction?: Discord.ChatInputCommandInteraction<"cached"> -} -export interface repeatedMessages { - [key:string]: {data: Discord.Collection, timeout: NodeJS.Timeout} -} export interface Punishment { _id: number; type: string; @@ -186,13 +174,4 @@ export interface Config { dcmod_chat: string } } -} -export type MPServerCache = Record -export interface TServer { - ip: string - code: string } \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index 4d5971f..9aba5b7 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -12,8 +12,8 @@ "rootDir": "src/", "outDir": "dist/", "moduleResolution": "bundler", - "typeRoots": [ "./src/typings" ], + "typeRoots": [ "./src/typings" ] }, "include": [ "src/" ], - "exclude": [ ".yarn/cache", ".yarn/unplugged",".git", "src/config.json", "src/DB-Beta.config.json", "src/Toast-Testbot.config.json" ] + "exclude": [ ".yarn/cache", ".yarn/unplugged", ".git", "src/config.json", "src/DB-Beta.config.json", "src/Toast-Testbot.config.json" ] }