From 8d136faf87662a771603dce9d3d6aeef77aaef49 Mon Sep 17 00:00:00 2001 From: Ayfri Date: Sun, 24 Jan 2021 15:30:09 +0100 Subject: [PATCH] Formatted Fetcher class. --- src/Fetcher.ts | 58 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/src/Fetcher.ts b/src/Fetcher.ts index 846b624..a4caa39 100644 --- a/src/Fetcher.ts +++ b/src/Fetcher.ts @@ -1,4 +1,58 @@ -export default class Fetcher { - public constructor() { +import { Client, Message, Collection, Snowflake, TextChannel, Guild } from 'discord.js'; +import { EventEmitter } from 'events'; + +export class Fetcher extends EventEmitter { + public totalMessages: Collection; + public fetching: boolean; + + public constructor(public readonly client: Client) { + super(); + this.totalMessages = new Collection(); + this.fetching = false; + } + + public async fetchChannel(channelID: Snowflake | TextChannel): Promise> { + const channel = channelID instanceof TextChannel ? channelID : await this.client.channels.fetch(channelID); + let messages = new Collection(); + + if (channel.isText()) { + this.emit('fetchChannel', channel); + this.fetching = true; + let channelMessages = await channel.messages.fetch({ + limit: 100, + }); + this.emit('fetch', channelMessages.size, channelMessages); + + while (channelMessages.size > 0) { + messages = messages.concat(channelMessages); + channelMessages = await channel.messages.fetch({ + limit: 100, + before: channelMessages.last()!.id, + }); + this.emit('fetch', channelMessages.size, channelMessages); + } + + this.fetching = false; + } + return messages; + } + + public async fetchGuild(guildID: Snowflake | Guild): Promise> { + const guild = guildID instanceof Guild ? guildID : await this.client.guilds.fetch(guildID); + let messages = new Collection(); + if (guild) { + this.fetching = true; + const channels = guild.channels.cache.filter(c => c.isText()) as Collection; + this.emit('fetchGuild', guild); + + for (const channel of channels.array()) { + const channelMessages = await this.fetchChannel(channel); + messages = messages.concat(channelMessages); + } + + this.fetching = false; + } + + return messages; } }