1
0
mirror of https://github.com/toast-ts/Daggerbot-TS.git synced 2024-11-17 12:21:00 -05:00

Optimizations

This commit is contained in:
AnxietyisReal 2023-09-01 14:32:11 +10:00
parent 1dba2cc572
commit 7e1203b708
12 changed files with 62 additions and 68 deletions

1
.npmrc
View File

@ -1 +0,0 @@
engine-strict = true

View File

@ -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",

View File

@ -1,6 +1,15 @@
interface repeatedMessages {
[key: string]: {data: Discord.Collection<number,{type:string,channel:string}>,timeout: NodeJS.Timeout}
}
type MPServerCache = Record<string,{
players: FSPlayer[],
status: 'online' | 'offline' | null,
name: string | null
}>
type YouTubeCache = Record<string,string>
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<Discord.ApplicationCommandDataResolvable>;
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}`);

View File

@ -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'},

View File

@ -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}`));
}
}

View File

@ -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<string> = [];
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]});
}

1
src/helpers/LogPrefix.ts Normal file
View File

@ -0,0 +1 @@
export default (prefix:string)=>{ return `[${prefix}]` };

View File

@ -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!'));

View File

@ -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},

View File

@ -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<number,{type:string,channel:string}>, timeout: NodeJS.Timeout}
}
export interface Punishment {
_id: number;
type: string;
@ -187,12 +175,3 @@ export interface Config {
}
}
}
export type MPServerCache = Record<string,{
players: FSPlayer[],
status: 'online' | 'offline' | null,
name: string | null
}>
export interface TServer {
ip: string
code: string
}

View File

@ -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" ]
}