diff --git a/src/structure/client/wrappers/GuildWrapper.js b/src/structure/client/wrappers/GuildWrapper.js index 04e02cc..a70a42d 100644 --- a/src/structure/client/wrappers/GuildWrapper.js +++ b/src/structure/client/wrappers/GuildWrapper.js @@ -1,9 +1,12 @@ +const { default: Collection } = require("@discordjs/collection"); + class GuildWrapper { constructor(client, guild) { this.client = client; this.guild = guild; + this.webhooks = new Collection(); this._settings = null; this._permissions = null; @@ -36,6 +39,58 @@ class GuildWrapper { } } + /** + * 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) throw new Error('Missing feature name'); + + 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.storageManager.mongodb.webhooks.deleteOne({ feature, guild: this.id }); + } + + this.webhooks.set(feature, hook); + return this.client.storageManager.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 The name of the feature, ex. messageLogs + * @returns {Webhook} + * @memberof ExtendedGuild + */ + async getWebhook(feature) { + + if (!feature) return null; + if (this.webhooks.has(feature)) return this.webhooks.get(feature); + + const result = await this.client.storageManager.mongodb.webhooks.findOne({ feature, guild: this.id }); + if (!result) return null; + if (!this.me.permissions.has('MANAGE_WEBHOOKS')) throw new Error('Missing MANAGE_WEBHOOKS'); + const hooks = await this.guild.fetchWebhooks(); + const hook = hooks.get(result.hookID); + if (!hook) return null; + // const hook = new WebhookClient(result.hookID, result.token, { + // disableMentions: 'everyone' + // }); + this.webhooks.set(feature, hook); + return hook; + + } + get defaultConfig() { return JSON.parse(JSON.stringify(this.client.defaultConfig())); }