From e798fb720ee5ced008471fe899337f6817936770 Mon Sep 17 00:00:00 2001 From: Ishmaam Khan Date: Wed, 9 Jun 2021 18:12:33 +0600 Subject: [PATCH] feat(GuildChannelManager): add 'fetch' method (#4966) Co-authored-by: Sugden <28943913+NotSugden@users.noreply.github.com> Co-authored-by: Avocado <43632131+Awoocado@users.noreply.github.com> --- src/managers/GuildChannelManager.js | 31 +++++++++++++++++++++++++++++ typings/index.d.ts | 2 ++ 2 files changed, 33 insertions(+) diff --git a/src/managers/GuildChannelManager.js b/src/managers/GuildChannelManager.js index 12ecafe245ff..89aeaa052c23 100644 --- a/src/managers/GuildChannelManager.js +++ b/src/managers/GuildChannelManager.js @@ -3,6 +3,7 @@ const BaseManager = require('./BaseManager'); const GuildChannel = require('../structures/GuildChannel'); const PermissionOverwrites = require('../structures/PermissionOverwrites'); +const Collection = require('../util/Collection'); const { ChannelTypes } = require('../util/Constants'); /** @@ -117,6 +118,36 @@ class GuildChannelManager extends BaseManager { }); return this.client.actions.ChannelCreate.handle(data).channel; } + + /** + * Obtains one or more guild channels from Discord, or the channel cache if they're already available. + * @param {Snowflake} [id] ID of the channel + * @param {boolean} [cache=true] Whether to cache the new channel objects if it weren't already + * @param {boolean} [force=false] Whether to skip the cache check and request the API + * @returns {Promise>} + * @example + * // Fetch all channels from the guild + * message.guild.channels.fetch() + * .then(channels => console.log(`There are ${channels.size} channels.`)) + * .catch(console.error); + * @example + * // Fetch a single channel + * message.guild.channels.fetch('222197033908436994') + * .then(channel => console.log(`The channel name is: ${channel.name}`)) + * .catch(console.error); + */ + async fetch(id, cache = true, force = false) { + if (id && !force) { + const existing = this.cache.get(id); + if (existing) return existing; + } + + // We cannot fetch a single guild channel, as of this commit's date, Discord API throws with 404 + const data = await this.client.api.guilds(this.guild.id).channels.get(); + const channels = new Collection(); + for (const channel of data) channels.set(channel.id, this.client.channels.add(channel, this.guild, cache)); + return id ? channels.get(id) ?? null : channels; + } } module.exports = GuildChannelManager; diff --git a/typings/index.d.ts b/typings/index.d.ts index aea36bf661fa..a9710cd10ac0 100644 --- a/typings/index.d.ts +++ b/typings/index.d.ts @@ -2256,6 +2256,8 @@ declare module 'discord.js' { name: string, options: GuildCreateChannelOptions, ): Promise; + public fetch(id: Snowflake, cache?: boolean, force?: boolean): Promise; + public fetch(id?: Snowflake, cache?: boolean, force?: boolean): Promise>; } export class GuildEmojiManager extends BaseGuildEmojiManager {