UNPKG

disco-bot-framework

Version:

Integrating this framework into a Discord bot will allow it to be configured using Disco

109 lines (83 loc) 2.57 kB
const axios = require('axios'); // TODO write docstrings for these functions class DiscoBot { static APIBaseURL = 'https://disco-express-z7kpx.ondigitalocean.app/api/db/config'; constructor(parameters) { this.parameters = parameters; this._client = null; } set client(client) { this._client = client; client.on('guildCreate', async guild => { await this.createConfigInDatabase(guild.id); }); } async createConfigInDatabase(guildID) { if (await this.doesConfigExist(guildID)) { return; } const botID = this._client.user.id; DiscoBot.log(`Creating config with botID=${botID} and guildID=${guildID}`); const configID = this._client.user.id + 'x' + guildID; try { await axios.post(`${DiscoBot.APIBaseURL}/${configID}`, { botID: botID, guildID: guildID, botName: this._client.user.username, parameters: this.parameters }); DiscoBot.log(`Successfully created config.`); } catch (e) { DiscoBot.log(e, true); DiscoBot.log('Could not create config in database.'); } } async doesConfigExist(guildID) { try { const URL = `${DiscoBot.APIBaseURL}/${this._client.user.id}x${guildID}`; await axios.get(URL); return true; } catch { return false; } } async loadConfig(guildID) { try { return await this.loadConfigFromDatabase(guildID); } catch (e) { DiscoBot.log(e, true); DiscoBot.log('Could not load config from database. Loaded default config.', true); return DiscoBot.createConfigObject(this.parameters); } } async loadConfigFromDatabase(guildID) { const URL = `${DiscoBot.APIBaseURL}/${this._client.user.id}x${guildID}`; DiscoBot.log(`Loading config from ${URL}.`); const response = await axios.get(URL); return DiscoBot.createConfigObject(response.data.config); } static createConfigObject(parameters) { // reference https://stackoverflow.com/a/53508215/15394129 accessed 24 august return Object.fromEntries( parameters.map(parameter => [parameter.name, parameter.value]) ); } static log(msg, error = false) { const date = new Date(); const time = Object.fromEntries( [ ['hours', date.getHours()], ['minutes', date.getMinutes()], ['seconds', date.getSeconds()] ].map(pair => [pair[0], DiscoBot.formatTime(pair[1])]) ); const prefix = `[${time.hours}:${time.minutes}:${time.seconds}] disco: `; const message = prefix + msg; const func = error ? console.error : console.log; func(message); } static formatTime(time) { return time.toString().padStart(2, '0'); } } module.exports = DiscoBot;