harmony/src/gateway/handlers/guildEmojiUpdate.ts

62 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-12-02 12:29:52 +00:00
import { Emoji } from '../../structures/emoji.ts'
import { Guild } from '../../structures/guild.ts'
import { EmojiPayload } from '../../types/emoji.ts'
import { GuildEmojiUpdatePayload } from '../../types/gateway.ts'
2021-04-04 05:42:15 +00:00
import type { Gateway, GatewayEventHandler } from '../mod.ts'
2020-12-02 12:29:52 +00:00
export const guildEmojiUpdate: GatewayEventHandler = async (
gateway: Gateway,
d: GuildEmojiUpdatePayload
) => {
const guild: Guild | undefined = await gateway.client.guilds.get(d.guild_id)
if (guild !== undefined) {
const emojis = await guild.emojis.collection()
const deleted: Emoji[] = []
const added: Emoji[] = []
const updated: Array<{ before: Emoji; after: Emoji }> = []
const _updated: EmojiPayload[] = []
for (const raw of d.emojis) {
2020-12-26 06:49:52 +00:00
const emojiID = (raw.id !== null ? raw.id : raw.name) as string
2020-12-24 00:59:32 +00:00
const has = emojis.get(emojiID)
2020-12-02 12:29:52 +00:00
if (has === undefined) {
2020-12-24 00:59:32 +00:00
await guild.emojis.set(emojiID, raw)
const emoji = (await guild.emojis.get(emojiID)) as Emoji
2020-12-02 12:29:52 +00:00
added.push(emoji)
} else _updated.push(raw)
}
for (const emoji of emojis.values()) {
2020-12-26 06:49:52 +00:00
const emojiID = (emoji.id !== null ? emoji.id : emoji.name) as string
2020-12-24 00:59:32 +00:00
const find = _updated.find((e) => {
const eID = e.id !== null ? e.id : e.name
return emojiID === eID
})
2020-12-02 12:29:52 +00:00
if (find === undefined) {
2020-12-24 00:59:32 +00:00
await guild.emojis.delete(emojiID)
2020-12-02 12:29:52 +00:00
deleted.push(emoji)
} else {
2020-12-26 06:49:52 +00:00
const foundID = (find.id !== null ? find.id : find.name) as string
2020-12-24 00:59:32 +00:00
const before = (await guild.emojis.get(foundID)) as Emoji
await guild.emojis.set(foundID, find)
const after = (await guild.emojis.get(foundID)) as Emoji
2020-12-02 12:29:52 +00:00
updated.push({ before, after })
}
}
2021-01-25 11:34:43 +00:00
gateway.client.emit('guildEmojisUpdate', guild)
2020-12-02 12:29:52 +00:00
for (const emoji of deleted) {
2021-01-25 11:34:43 +00:00
gateway.client.emit('guildEmojiDelete', emoji)
2020-12-02 12:29:52 +00:00
}
for (const emoji of added) {
2021-01-25 11:34:43 +00:00
gateway.client.emit('guildEmojiAdd', emoji)
2020-12-02 12:29:52 +00:00
}
for (const emoji of updated) {
2021-01-25 11:34:43 +00:00
gateway.client.emit('guildEmojiUpdate', emoji.before, emoji.after)
2020-12-02 12:29:52 +00:00
}
}
}