diff --git a/structure/extensions/Guild.js b/structure/extensions/Guild.js index d983a2c..6340e09 100644 --- a/structure/extensions/Guild.js +++ b/structure/extensions/Guild.js @@ -1,5 +1,5 @@ const escapeRegex = require('escape-string-regexp'); -const { Structures } = require('discord.js'); +const { Structures, WebhookClient } = require('discord.js'); const { Collection, Emojis } = require('../../util'); const safeCommands = ['command:settings', 'command:grant', 'command:revoke']; @@ -43,6 +43,54 @@ const Guild = Structures.extend('Guild', (Guild) => { return this._caseId = this._settings.caseId; //eslint-disable-line no-return-assign } + /** + * Update a webhook entry in the database + * + * @param {string} feature Which feature webhook to update, e.g. messagelog + * @param {Webhook} hook The webhook object, omitting this will nullify the hook data + * @memberof ExtendedGuild + */ + async updateWebhook(feature, hook) { + + if (!feature) return false; + + if (!hook) { + this.client.logger.debug(`Removing webhook in ${this.name} (${this.id})`); + const hook = this.webhooks.get(feature); + if (hook) await hook.delete('Removing old webhook').catch((err) => { + if(err.code !== 10015) this.client.logger.error(err.stack); + }); + this.webhooks.delete(feature); + return this.client.storage.mongodb.webhooks.deleteOne({ feature, guild: this.id }); + } + + this.webhooks.set(feature, hook); + return this.client.storage.mongodb.webhooks.updateOne({ feature, guild: this.id }, { hookID: hook.id, token: hook.token }); + + } + + /** + * Retrieves a cached webhook for a feature if it exists, gets it from the database if not cached + * + * @param {string} feature + * @returns {Webhook} + * @memberof ExtendedGuild + */ + async getWebhook(feature) { + + if (!feature) return false; + if (this.webhooks.has(feature)) return this.webhooks.get(feature); + + const result = await this.client.storage.mongodb.webhooks.findOne({ feature, guild: this.id }); + if (!result) return false; + const hook = new WebhookClient(result.hookID, result.token, { + disableMentions: 'everyone' + }); + this.webhooks.set(feature, hook); + return hook; + + } + /* Settings Wrapper */ async _deleteSettings() { //Delete whole entry - remove