From fa975a622cc00572303c4256e60b35633ee54163 Mon Sep 17 00:00:00 2001 From: "Navy.gif" Date: Mon, 17 Jan 2022 17:43:02 +0200 Subject: [PATCH] webhook helpers --- src/structure/client/wrappers/GuildWrapper.js | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) 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())); }