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

Implement client for TokenService server

This commit is contained in:
AnxietyisReal 2023-10-05 12:01:36 +11:00
parent c602c7ed3d
commit 51c37a4c8e
8 changed files with 37 additions and 30 deletions

View File

@ -6,9 +6,10 @@ type MPServerCache = Record<string,{
status: 'online' | 'offline' | null, status: 'online' | 'offline' | null,
name: string | null name: string | null
}> }>
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 {Config, FSPlayer} from './typings/interfaces';
import bannedWords from './models/bannedWords.js'; import bannedWords from './models/bannedWords.js';
import userLevels from './models/userLevels.js'; import userLevels from './models/userLevels.js';
import suggestion from './models/suggestion.js'; import suggestion from './models/suggestion.js';
@ -20,8 +21,7 @@ import DatabaseServer from './funcs/DatabaseServer.js';
import CacheServer from './funcs/CacheServer.js'; import CacheServer from './funcs/CacheServer.js';
import xjs from 'xml-js'; import xjs from 'xml-js';
import moment from 'moment'; import moment from 'moment';
const tokens = JSON.parse(readFileSync('src/tokens.json', 'utf8')); import TSClient from './helpers/TSClient.js';
// Import assertion warning workaround yes
let importconfig:Config let importconfig:Config
try{ try{
@ -37,7 +37,6 @@ export default class TClient extends Discord.Client {
commands: Discord.Collection<string, any>; commands: Discord.Collection<string, any>;
registry: Array<Discord.ApplicationCommandDataResolvable>; registry: Array<Discord.ApplicationCommandDataResolvable>;
config: Config; config: Config;
tokens: Tokens;
embed: typeof Discord.EmbedBuilder; embed: typeof Discord.EmbedBuilder;
collection: typeof Discord.Collection; collection: typeof Discord.Collection;
attachmentBuilder: typeof Discord.AttachmentBuilder; attachmentBuilder: typeof Discord.AttachmentBuilder;
@ -70,7 +69,6 @@ export default class TClient extends Discord.Client {
this.commands = new Discord.Collection(); this.commands = new Discord.Collection();
this.registry = []; this.registry = [];
this.config = importconfig as Config; this.config = importconfig as Config;
this.tokens = tokens as Tokens;
this.embed = Discord.EmbedBuilder; this.embed = Discord.EmbedBuilder;
this.collection = Discord.Collection; this.collection = Discord.Collection;
this.attachmentBuilder = Discord.AttachmentBuilder; this.attachmentBuilder = Discord.AttachmentBuilder;
@ -92,7 +90,7 @@ export default class TClient extends Discord.Client {
console.time('Startup'); console.time('Startup');
CacheServer.init(); CacheServer.init();
DatabaseServer.init(); DatabaseServer.init();
this.login(this.tokens.main); this.login((await TSClient.Token()).main);
for (const file of readdirSync('dist/events')){ for (const file of readdirSync('dist/events')){
const eventFile = await import(`./events/${file}`); const eventFile = await import(`./events/${file}`);
this.on(file.replace('.js',''), async(...args)=>eventFile.default.run(this,...args)) this.on(file.replace('.js',''), async(...args)=>eventFile.default.run(this,...args))

View File

@ -5,6 +5,7 @@ import {exec} from 'node:child_process';
import MessageTool from '../helpers/MessageTool.js'; import MessageTool from '../helpers/MessageTool.js';
import UsernameHelper from '../helpers/UsernameHelper.js'; import UsernameHelper from '../helpers/UsernameHelper.js';
import FormatTime from '../helpers/FormatTime.js'; import FormatTime from '../helpers/FormatTime.js';
import TSClient from '../helpers/TSClient.js';
import fs from 'node:fs'; import fs from 'node:fs';
import util from 'node:util'; import util from 'node:util';
import TClient from '../client.js'; import TClient from '../client.js';
@ -18,7 +19,7 @@ export default {
let output = 'error'; let output = 'error';
let error = false; let error = false;
try { try {
output = await eval(code); output = await eval(`(async()=>{${code}})()`);
} catch (err: any) { } catch (err: any) {
error = true error = true
const embed = new client.embed().setColor('#630D12').setTitle('__Eval__').addFields( const embed = new client.embed().setColor('#630D12').setTitle('__Eval__').addFields(
@ -36,10 +37,6 @@ export default {
if (error) return; if (error) return;
if (typeof output === 'object') output = 'js\n'+util.formatWithOptions({depth: 1}, '%O', output) if (typeof output === 'object') output = 'js\n'+util.formatWithOptions({depth: 1}, '%O', output)
else output = '\n' + String(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( const embed = new client.embed().setColor(client.config.embedColor).setTitle('__Eval__').addFields(
{name: 'Input', value: `\`\`\`js\n${code.slice(0,1010)}\n\`\`\``}, {name: 'Input', value: `\`\`\`js\n${code.slice(0,1010)}\n\`\`\``},
{name: 'Output', value: `\`\`\`${UsernameHelper.stripName(output).slice(0,1016)}\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]})); interaction.reply({embeds: [embed]}).catch(()=>(interaction.channel as Discord.TextChannel).send({embeds: [embed]}));
}, },
update: async()=>{ update: async()=>{
const SummonAuthentication = createTokenAuth(client.tokens.octokit); const SummonAuthentication = createTokenAuth((await TSClient.Token()).octokit);
const {token} = await SummonAuthentication(); const {token} = await SummonAuthentication();
var githubRepo = {owner: 'AnxietyisReal', repo: 'Daggerbot-TS', ref: 'HEAD'}; var githubRepo = {owner: 'AnxietyisReal', repo: 'Daggerbot-TS', ref: 'HEAD'};
const hammond = await interaction.reply({content: 'Pulling from repository...', fetchReply: true}); const hammond = await interaction.reply({content: 'Pulling from repository...', fetchReply: true});

View File

@ -2,12 +2,17 @@ import Discord from 'discord.js';
import TClient from '../client.js'; import TClient from '../client.js';
import {Player,useTimeline,useQueue} from 'discord-player'; import {Player,useTimeline,useQueue} from 'discord-player';
import {SpotifyExtractor} from '@discord-player/extractor'; 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 { export default {
async run(client: TClient, interaction: Discord.ChatInputCommandInteraction<'cached'>){ 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.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.'); 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); 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.'); if (!interaction.member.voice.channel) return interaction.reply('Please join a voice channel first to use the command.');
player.nodes.create(interaction.guildId, { player.nodes.create(interaction.guildId, {
metadata: { metadata: {

View File

@ -5,6 +5,7 @@ import FormatBytes from '../helpers/FormatBytes.js';
import FormatTime from '../helpers/FormatTime.js'; import FormatTime from '../helpers/FormatTime.js';
import si from 'systeminformation'; import si from 'systeminformation';
import TClient from '../client.js'; import TClient from '../client.js';
import TSClient from '../helpers/TSClient.js';
import os from 'node:os'; import os from 'node:os';
import {Octokit} from '@octokit/rest'; import {Octokit} from '@octokit/rest';
import {createTokenAuth} from '@octokit/auth-token'; import {createTokenAuth} from '@octokit/auth-token';
@ -53,7 +54,7 @@ export default {
embed.addFields({name: '\u200b', value: `\`\`\`\n${fieldValue}\`\`\``}); embed.addFields({name: '\u200b', value: `\`\`\`\n${fieldValue}\`\`\``});
} else embed.addFields({name: '\u200b', value: `\`\`\`\n${rows.join('')}\`\`\``}); } 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(); const {token} = await SummonAuthentication();
let githubRepo = {owner: 'AnxietyisReal', repo: 'Daggerbot-TS', ref: 'HEAD'}; let githubRepo = {owner: 'AnxietyisReal', repo: 'Daggerbot-TS', ref: 'HEAD'};
const octokit = new Octokit({auth: token, timeZone: 'Australia/NSW', userAgent: 'Daggerbot-TS'}); const octokit = new Octokit({auth: token, timeZone: 'Australia/NSW', userAgent: 'Daggerbot-TS'});

View File

@ -1,12 +1,10 @@
import {createClient, ErrorReply} from 'redis'; import {createClient, ErrorReply} from 'redis';
import Logger from '../helpers/Logger.js'; import Logger from '../helpers/Logger.js';
import {readFileSync} from 'node:fs'; import TSClient from '../helpers/TSClient.js';
import {Tokens} from '../typings/interfaces';
const tokens:Tokens = JSON.parse(readFileSync('src/tokens.json', 'utf-8'));
let Prefix = 'Cache'; let Prefix = 'Cache';
const RedisClient = createClient({ const RedisClient = createClient({
url: tokens.redis_uri, url: (await TSClient.Token()).redis_uri,
database: 0, database: 0,
name: 'Daggerbot', name: 'Daggerbot',
socket: { socket: {

View File

@ -1,8 +1,6 @@
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import Logger from '../helpers/Logger.js'; import Logger from '../helpers/Logger.js';
import {readFileSync} from 'node:fs'; import TSClient from '../helpers/TSClient.js';
import {Tokens} from '../typings/interfaces';
const tokens:Tokens = JSON.parse(readFileSync('src/tokens.json', 'utf-8'));
const connection:mongoose.Connection = mongoose.connection; const connection:mongoose.Connection = mongoose.connection;
export default class DatabaseServer { 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('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}`)) .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.set('strictQuery', true);
connection.openUri(tokens.mongodb_uri, { connection.openUri((await TSClient.Token()).mongodb_uri, {
replicaSet: 'toastyy', replicaSet: 'toastyy',
autoIndex: true, autoIndex: true,
authMechanism: 'SCRAM-SHA-256', authMechanism: 'SCRAM-SHA-256',

17
src/helpers/TSClient.ts Normal file
View File

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

View File

@ -112,17 +112,10 @@ interface XMLText {
_text: string _text: string
} }
export interface Tokens { export interface Tokens {
main: string
beta: string
toast: string
spotify: { spotify: {
client: string, client: string,
secret: string secret: string
} }
octokit: string
mongodb_uri: string
mongodb_uri_dev: string
redis_uri: string
} }
export interface Config { export interface Config {
embedColor: Discord.ColorResolvable, embedColor: Discord.ColorResolvable,