diff --git a/lib/Discord/Client.js b/lib/Discord/Client.js index 86ca81d..adda56e 100644 --- a/lib/Discord/Client.js +++ b/lib/Discord/Client.js @@ -185,8 +185,8 @@ class Client extends DiscordClient { */ async execute(msg) { if (msg.author.equals(this.user) || msg.author.bot) return; - const serverConf = msg.guild && msg.guild.available ? ServerConfig.get(msg.guild.id) || await ServerConfig.add(msg.guild) : null; - const prefix = serverConf ? serverConf.prefix : Math.random(); + const serverConf = msg.guild && msg.guild.available ? await ServerConfig.forServer(msg.guild) : null; + const prefix = serverConf ? serverConf.prefix : this.prefix; if (msg.channel.type !== 'dm' && !msg.content.startsWith(this.user.toString()) && !msg.content.startsWith(prefix) && !msg.content.startsWith(this.prefix)) return false; const content = (msg.content.startsWith(prefix) && msg.content.replace(prefix, '')) || (msg.content.startsWith(this.user.toString()) && msg.content.replace(`${this.user.toString()} `, '')) || (msg.content.startsWith(this.prefix) && msg.content.replace(this.prefix, '')) || msg.content; diff --git a/lib/Discord/Commands/GitlabInit.js b/lib/Discord/Commands/GitlabInit.js index e80e2ec..eb1058e 100644 --- a/lib/Discord/Commands/GitlabInit.js +++ b/lib/Discord/Commands/GitlabInit.js @@ -53,7 +53,7 @@ class GitlabInitCommand extends Command { if (exists) return this.commandError(msg, `Repository \`${repository.repo}\` is already initialized in this channel`); return ChannelConfig.addRepoToChannel(channelid, repoFullName) .then(() => { - let embed = this._successMessage(repository.repo); + let embed = this._successMessage(repository.repo, conf.embed); return workingMsg.edit({ embed }); }); } @@ -63,7 +63,7 @@ class GitlabInitCommand extends Command { if (exists) return this.commandError(msg, `Repository \`${repository.repo}\` is already initialized in this channel`); return ChannelConfig.addRepoToChannel(channelid, repoFullName) .then(() => { - let embed = this._successMessage(repository.repo); + let embed = this._successMessage(repository.repo, conf.embed); return workingMsg.edit({ embed }); }); }).catch(err => { @@ -72,7 +72,7 @@ class GitlabInitCommand extends Command { return this.commandError(msg, `Unable to initialize! The repository \`${repository.repo}\` could not be found!\nIf it's private, please add \`private\` after the command as a separate argument`); }); } - _successMessage(repo) { + _successMessage(repo, hasEmbed) { return { color: 0x84F139, footer: { @@ -81,7 +81,7 @@ class GitlabInitCommand extends Command { title: `\`${repo}\`: Successfully initialized repository events`, description: [ 'The repository must a webhook pointing to ', - 'To use embeds to have a nicer GitLab log, say `GL! conf set embed true` in this channel to enable embeds for the current channel.', + !hasEmbed && 'To use embeds to have a nicer GitLab log, say `GL! conf set embed true` in this channel to enable embeds for the current channel.', ].join('\n'), }; } diff --git a/lib/Discord/Commands/GitlabInitOrg.js b/lib/Discord/Commands/GitlabInitOrg.js index 696bc78..6f47ab2 100644 --- a/lib/Discord/Commands/GitlabInitOrg.js +++ b/lib/Discord/Commands/GitlabInitOrg.js @@ -40,7 +40,7 @@ class GitlabInitOrgCommand extends Command { let conf; return Gitlab.getGroupProjects(orgName).then(async data => { - conf = ChannelConfig.get(channelid) || await ChannelConfig.add(msg.channel); + conf = await ChannelConfig.get(channelid); const repos = data.body.filter(e => !conf.repos.includes(e.path_with_namespace.toLowerCase())).map(e => e.path_with_namespace); return Promise.all(repos.map(repo => ChannelConfig.addRepoToChannel(channelid, repo))).then(() => repos); diff --git a/lib/Discord/Module.js b/lib/Discord/Module.js index fefcb75..06759a7 100644 --- a/lib/Discord/Module.js +++ b/lib/Discord/Module.js @@ -46,7 +46,7 @@ class Module { * @return {Promise} */ moduleError(msg, str) { - return msg.channel.sendMessage(`❌ ${str}`); + return msg.channel.send(`❌ ${str}`); } /** diff --git a/lib/Discord/Modules/CasualHelp.js b/lib/Discord/Modules/CasualHelp.js index 7b489d2..6948c50 100644 --- a/lib/Discord/Modules/CasualHelp.js +++ b/lib/Discord/Modules/CasualHelp.js @@ -46,8 +46,8 @@ class CasualHelpModule extends Module { domain: this.textToEmbed('Yappy Bots domain has expired', [ 'Our domain https://www.yappybots.tk expired recently, and we did not get a notice.', 'The new domain is https://www.yappybots.tk, which will hopefully be temporary until we are able to get our old one back.', - 'We apologize for the inconvinience.' - ]) + 'We apologize for the inconvinience.', + ]), }; } diff --git a/lib/Discord/index.js b/lib/Discord/index.js index 98f55d2..bb64110 100644 --- a/lib/Discord/index.js +++ b/lib/Discord/index.js @@ -52,7 +52,7 @@ bot.on('ready', () => { ServerConfig.init(bot); }); bot.on('disconnect', (e) => { - Log.warn(`Bot | Disconnected (${e.code}).`) + Log.warn(`Bot | Disconnected (${e.code}).`); logger.log('Disconnected', e.code, 'ORANGE'); }); bot.on('error', (e) => { diff --git a/lib/Gitlab/Events/wiki_page-create.js b/lib/Gitlab/Events/wiki_page-create.js index 43e39a9..cf72b2f 100644 --- a/lib/Gitlab/Events/wiki_page-create.js +++ b/lib/Gitlab/Events/wiki_page-create.js @@ -21,7 +21,7 @@ class WikiPageCreate extends EventResponse { const page = data.object_attributes; return [ `📰 **${actor}** created wiki page **${page.title}**`, - (page.content ? ` ${page.content.slice(0, 100).replace(/\n/g, ' ')}\n` : '') + `<${page.url}>`, + (page.content ? ` ${page.content.slice(0, 100).replace(/\n/g, ' ')}\n` : '') + `<${page.url}>`, // eslint-disable-line prefer-template ].join('\n'); } } diff --git a/lib/Models/ChannelConfig.js b/lib/Models/ChannelConfig.js index d37139a..468a992 100644 --- a/lib/Models/ChannelConfig.js +++ b/lib/Models/ChannelConfig.js @@ -57,7 +57,7 @@ class ChannelConfigItem { } } - this.repos = this.repos || []; + this.repos = [...this.repos]; } /** * Set a specific config property to a value for this config item @@ -153,7 +153,9 @@ class ChannelConfig { if (!channel.name || !channel.guild.name || !channel.id) { Log.warning('ChannelConf | Some info for channel not found', channel); logger.log('Error when adding channel config to database', util.inspect(channel, { depth: 2 }), 'YELLOW'); - } else this.add(channel).catch(e => bot.emit('error', e)); + } else { + this.add(channel).catch(e => bot.emit('error', e)); + } }); } } diff --git a/lib/Models/ServerConfig.js b/lib/Models/ServerConfig.js index c02921a..7eb2676 100644 --- a/lib/Models/ServerConfig.js +++ b/lib/Models/ServerConfig.js @@ -1,5 +1,4 @@ const mongoose = require('mongoose'); -const Collection = require('discord.js').Collection; const Schema = mongoose.Schema; const ChannelConfig = require('./ChannelConfig'); @@ -24,8 +23,8 @@ const serverConfig = mongoose.model('ServerConfig', serverConfigSchema); class ServerConfigItem { constructor(client, config) { /** - * The bot client - * @type Client + * The config manager + * @type ServerConfig * @private */ this._client = client; @@ -35,6 +34,7 @@ class ServerConfigItem { } } } + /** * Set a specific config property to a value for this config item * @param {String} prop Property to modify @@ -45,6 +45,7 @@ class ServerConfigItem { set(prop, value) { return this._client.set(this.guildID, prop, value); } + /** * Delete guild config * @see ServerConfig#delete @@ -62,11 +63,10 @@ class ServerConfig { constructor() { /** * All the config - * @type {Collection} + * @type {WeakMap} * @private */ - this._data = new Collection(); - this.setup(); + this._data = new Map(); this.validKeys = [ 'prefix', ]; @@ -78,37 +78,12 @@ class ServerConfig { */ this.loaded = false; } - /** - * Get config from database and add to this._data - */ - setup() { - serverConfig.find({}).then(configs => { - this.loaded = true; - configs.forEach(row => { - if (!row.guildID) return; - this._data.set(row.guildID, new ServerConfigItem(this, row._doc)); - }); - }); - } + /** * Initialize configuration and Discord bot events * @param {external:Client} bot Client instance */ init(bot) { - if (!this.loaded) { - setTimeout(() => this.init(bot), 5000); - return; - } - - for (const g of bot.guilds) { - const guild = g[1]; - if (!guild || !guild.available) continue; - if (!this.has(guild.id)) { - Log.info(`ServerConf | Adding "${guild.name}"`); - this.add(guild).catch(e => bot.emit('error', e)); - } - } - if (!this.setupEvents) { this.setupEvents = true; @@ -139,13 +114,36 @@ class ServerConfig { return serverConfig.findOneAndRemove({ guildID, }).then(() => { - let oldData = this._data; - let newData = oldData.filter(e => e.guildID !== guildID); - this._data = newData; - return Promise.resolve(this); + this._data.delete(guildID); + + return this; }); } + /** + * Get server config for server, retreive from DB if not cached, create if non-existent + * @param {Server} server discord server object + * @return {ServerConfigItem} + */ + async forServer(server) { + return this._data.get(server.id) || this.addToCache(await serverConfig.findOne({ guildID: server.id }) || await this.add(server)); + } + + /** + * Add config item to cache + * @param {Mixed} item item to add to cache + * @return {ServerConfigItem} + */ + addToCache(item) { + if (item._doc) item = item._doc; + if (!(item instanceof ServerConfigItem)) item = new ServerConfigItem(this, item); + if (this._data.has(item.guildID)) return item; + + this._data.set(item.guildID, item); + + return item; + } + /** * Add channel to config * @param {Guild} guild Guild to add config of @@ -159,9 +157,10 @@ class ServerConfig { guildName: guild.name, prefix: `GL! `, }; + return serverConfig.create(conf).then(() => { this._data.set(conf.guildID, new ServerConfigItem(this, conf)); - return Promise.resolve(this); + return this; }); } @@ -175,7 +174,7 @@ class ServerConfig { set(guildID, prop, value) { return new Promise((resolve, reject) => { if (guildID.id) guildID = guildID.id; - let oldConfig = this._data.find('guildID', guildID); + let oldConfig = this._data.get(guildID); let newConfig = oldConfig; newConfig[prop] = value; serverConfig.findOneAndUpdate({