From 5cb2ab317238c1c28d7b3d5dd66d1c9c63bfd3aa Mon Sep 17 00:00:00 2001 From: toast-ts <96593068+toast-ts@users.noreply.github.com> Date: Thu, 5 Oct 2023 12:01:36 +1100 Subject: [PATCH] Implement client for TokenService server --- src/client.ts | 10 ++++------ src/commands/dev.ts | 9 +++------ src/commands/music.ts | 7 ++++++- src/commands/statistics.ts | 3 ++- src/funcs/CacheServer.ts | 6 ++---- src/funcs/DatabaseServer.ts | 8 +++----- src/helpers/TSClient.ts | 17 +++++++++++++++++ src/typings/interfaces.d.ts | 7 ------- 8 files changed, 37 insertions(+), 30 deletions(-) create mode 100644 src/helpers/TSClient.ts diff --git a/src/client.ts b/src/client.ts index e972c75..7f6008a 100644 --- a/src/client.ts +++ b/src/client.ts @@ -6,9 +6,10 @@ type MPServerCache = Record + import Discord from 'discord.js'; import {readFileSync, readdirSync} from 'node:fs'; -import {Tokens, Config, FSPlayer} from './typings/interfaces'; +import {Config, FSPlayer} from './typings/interfaces'; import bannedWords from './models/bannedWords.js'; import userLevels from './models/userLevels.js'; import suggestion from './models/suggestion.js'; @@ -20,8 +21,7 @@ import DatabaseServer from './funcs/DatabaseServer.js'; import CacheServer from './funcs/CacheServer.js'; import xjs from 'xml-js'; import moment from 'moment'; -const tokens = JSON.parse(readFileSync('src/tokens.json', 'utf8')); -// Import assertion warning workaround yes +import TSClient from './helpers/TSClient.js'; let importconfig:Config try{ @@ -37,7 +37,6 @@ export default class TClient extends Discord.Client { commands: Discord.Collection; registry: Array; config: Config; - tokens: Tokens; embed: typeof Discord.EmbedBuilder; collection: typeof Discord.Collection; attachmentBuilder: typeof Discord.AttachmentBuilder; @@ -70,7 +69,6 @@ export default class TClient extends Discord.Client { this.commands = new Discord.Collection(); this.registry = []; this.config = importconfig as Config; - this.tokens = tokens as Tokens; this.embed = Discord.EmbedBuilder; this.collection = Discord.Collection; this.attachmentBuilder = Discord.AttachmentBuilder; @@ -92,7 +90,7 @@ export default class TClient extends Discord.Client { console.time('Startup'); CacheServer.init(); DatabaseServer.init(); - this.login(this.tokens.main); + this.login((await TSClient.Token()).main); for (const file of readdirSync('dist/events')){ const eventFile = await import(`./events/${file}`); this.on(file.replace('.js',''), async(...args)=>eventFile.default.run(this,...args)) diff --git a/src/commands/dev.ts b/src/commands/dev.ts index a6aacaf..e333a7c 100644 --- a/src/commands/dev.ts +++ b/src/commands/dev.ts @@ -5,6 +5,7 @@ import {exec} from 'node:child_process'; import MessageTool from '../helpers/MessageTool.js'; import UsernameHelper from '../helpers/UsernameHelper.js'; import FormatTime from '../helpers/FormatTime.js'; +import TSClient from '../helpers/TSClient.js'; import fs from 'node:fs'; import util from 'node:util'; import TClient from '../client.js'; @@ -18,7 +19,7 @@ export default { let output = 'error'; let error = false; try { - output = await eval(code); + output = await eval(`(async()=>{${code}})()`); } catch (err: any) { error = true const embed = new client.embed().setColor('#630D12').setTitle('__Eval__').addFields( @@ -36,10 +37,6 @@ export default { if (error) return; if (typeof output === 'object') output = 'js\n'+util.formatWithOptions({depth: 1}, '%O', output) else output = '\n' + String(output); - [ - client.tokens.main,client.tokens.beta,client.tokens.toast,client.tokens.spotify.client,client.tokens.spotify.secret, - client.tokens.mongodb_uri,client.tokens.mongodb_uri_dev,client.tokens.octokit,client.tokens.redis_uri - ].forEach(x=>output = output.replace(new RegExp(x as string,'g'),':noblank: No token?')); const embed = new client.embed().setColor(client.config.embedColor).setTitle('__Eval__').addFields( {name: 'Input', value: `\`\`\`js\n${code.slice(0,1010)}\n\`\`\``}, {name: 'Output', value: `\`\`\`${UsernameHelper.stripName(output).slice(0,1016)}\n\`\`\``} @@ -47,7 +44,7 @@ export default { interaction.reply({embeds: [embed]}).catch(()=>(interaction.channel as Discord.TextChannel).send({embeds: [embed]})); }, update: async()=>{ - const SummonAuthentication = createTokenAuth(client.tokens.octokit); + const SummonAuthentication = createTokenAuth((await TSClient.Token()).octokit); const {token} = await SummonAuthentication(); var githubRepo = {owner: 'AnxietyisReal', repo: 'Daggerbot-TS', ref: 'HEAD'}; const hammond = await interaction.reply({content: 'Pulling from repository...', fetchReply: true}); diff --git a/src/commands/music.ts b/src/commands/music.ts index 6f01c46..a360b08 100644 --- a/src/commands/music.ts +++ b/src/commands/music.ts @@ -2,12 +2,17 @@ import Discord from 'discord.js'; import TClient from '../client.js'; import {Player,useTimeline,useQueue} from 'discord-player'; import {SpotifyExtractor} from '@discord-player/extractor'; +import {readFileSync} from 'node:fs'; +import {Tokens} from 'src/typings/interfaces'; +const token:Tokens = JSON.parse(readFileSync('src/tokens.json', 'utf8')); +// TODO: Fix above. + export default { async run(client: TClient, interaction: Discord.ChatInputCommandInteraction<'cached'>){ if (!client.config.botSwitches.music && !client.config.whitelist.includes(interaction.user.id)) return interaction.reply({content:'Music module is currently disabled.',ephemeral:true}); if (!client.isStaff(interaction.member) && !client.config.whitelist.includes(interaction.member.id)) return interaction.reply('Music module is close to being completed, some parts may be incomplete or broken, so it has been restricted to staff for time-being.'); const player = Player.singleton(client); - await player.extractors.register(SpotifyExtractor,{clientId: client.tokens.spotify.client, clientSecret: client.tokens.spotify.secret}); + await player.extractors.register(SpotifyExtractor,{clientId: token.spotify.client, clientSecret: token.spotify.secret}); if (!interaction.member.voice.channel) return interaction.reply('Please join a voice channel first to use the command.'); player.nodes.create(interaction.guildId, { metadata: { diff --git a/src/commands/statistics.ts b/src/commands/statistics.ts index 7649e88..552f912 100644 --- a/src/commands/statistics.ts +++ b/src/commands/statistics.ts @@ -5,6 +5,7 @@ import FormatBytes from '../helpers/FormatBytes.js'; import FormatTime from '../helpers/FormatTime.js'; import si from 'systeminformation'; import TClient from '../client.js'; +import TSClient from '../helpers/TSClient.js'; import os from 'node:os'; import {Octokit} from '@octokit/rest'; import {createTokenAuth} from '@octokit/auth-token'; @@ -53,7 +54,7 @@ export default { embed.addFields({name: '\u200b', value: `\`\`\`\n${fieldValue}\`\`\``}); } else embed.addFields({name: '\u200b', value: `\`\`\`\n${rows.join('')}\`\`\``}); - const SummonAuthentication = createTokenAuth(client.tokens.octokit); + const SummonAuthentication = createTokenAuth((await TSClient.Token()).octokit); const {token} = await SummonAuthentication(); let githubRepo = {owner: 'AnxietyisReal', repo: 'Daggerbot-TS', ref: 'HEAD'}; const octokit = new Octokit({auth: token, timeZone: 'Australia/NSW', userAgent: 'Daggerbot-TS'}); diff --git a/src/funcs/CacheServer.ts b/src/funcs/CacheServer.ts index 31f096d..f8f53a2 100644 --- a/src/funcs/CacheServer.ts +++ b/src/funcs/CacheServer.ts @@ -1,12 +1,10 @@ import {createClient, ErrorReply} from 'redis'; import Logger from '../helpers/Logger.js'; -import {readFileSync} from 'node:fs'; -import {Tokens} from '../typings/interfaces'; -const tokens:Tokens = JSON.parse(readFileSync('src/tokens.json', 'utf-8')); +import TSClient from '../helpers/TSClient.js'; let Prefix = 'Cache'; const RedisClient = createClient({ - url: tokens.redis_uri, + url: (await TSClient.Token()).redis_uri, database: 0, name: 'Daggerbot', socket: { diff --git a/src/funcs/DatabaseServer.ts b/src/funcs/DatabaseServer.ts index e131aa7..3e312b6 100644 --- a/src/funcs/DatabaseServer.ts +++ b/src/funcs/DatabaseServer.ts @@ -1,8 +1,6 @@ import mongoose from 'mongoose'; import Logger from '../helpers/Logger.js'; -import {readFileSync} from 'node:fs'; -import {Tokens} from '../typings/interfaces'; -const tokens:Tokens = JSON.parse(readFileSync('src/tokens.json', 'utf-8')); +import TSClient from '../helpers/TSClient.js'; const connection:mongoose.Connection = mongoose.connection; export default class DatabaseServer { @@ -16,9 +14,9 @@ export default class DatabaseServer { .on('fullsetup', ()=>Logger.forwardToConsole('log', dbPrefix, 'Successfully established a connection to Primary server & atleast one member')) .on('error', (err:mongoose.Error)=>Logger.forwardToConsole('error', dbPrefix, `Encountered an error in MongoDB: ${err.message}`)) } - protected static connect() { + protected static async connect() { connection.set('strictQuery', true); - connection.openUri(tokens.mongodb_uri, { + connection.openUri((await TSClient.Token()).mongodb_uri, { replicaSet: 'toastyy', autoIndex: true, authMechanism: 'SCRAM-SHA-256', diff --git a/src/helpers/TSClient.ts b/src/helpers/TSClient.ts new file mode 100644 index 0000000..8f4bdd4 --- /dev/null +++ b/src/helpers/TSClient.ts @@ -0,0 +1,17 @@ +interface TokenService_API { + main: string, + beta: string, + mongodb_uri: string, + redis_uri: string, + octokit: string, + spotify: { + client: string, + secret: string + } +} + +export default class TSClient { + static async Token() { + return await fetch('http://localhost:36961/daggerbot').then(x=>x.json()) as Promise + } +} diff --git a/src/typings/interfaces.d.ts b/src/typings/interfaces.d.ts index d43204f..12573eb 100644 --- a/src/typings/interfaces.d.ts +++ b/src/typings/interfaces.d.ts @@ -112,17 +112,10 @@ interface XMLText { _text: string } export interface Tokens { - main: string - beta: string - toast: string spotify: { client: string, secret: string } - octokit: string - mongodb_uri: string - mongodb_uri_dev: string - redis_uri: string } export interface Config { embedColor: Discord.ColorResolvable,