Skip to content
This repository was archived by the owner on Jan 3, 2024. It is now read-only.

Commit 5842692

Browse files
committed
Fix potential member replacement
1 parent f057669 commit 5842692

File tree

1 file changed

+38
-9
lines changed

1 file changed

+38
-9
lines changed

Sources/Discord/Gateway.swift

Lines changed: 38 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -614,15 +614,44 @@ class Gateway {
614614
}
615615

616616
case .guildCreate:
617-
let guild = Guild(bot: bot, guildData: data, fromGateway: true)
618-
initialState!.guildsCreated += 1
619-
bot.cacheGuild(guild)
620-
dispatch({ await $0.onGuildCreate(guild: guild) })
621-
dispatch({ await $0.onGuildAvailable(guild: guild) })
622-
623-
if initialState!.expectedGuilds == initialState!.guildsCreated {
624-
initialState!.dispatched = true
625-
dispatch({ await $0.onReady(user: self.bot.user!) })
617+
// Since this is the raw guild, the key is "id" instead of "guild_id"
618+
let insertedKey: JSON = ["guild_id": data["id"] as Any]
619+
let guildId = getGuildId(insertedKey)
620+
621+
// When this is dispatched and the `if let` executes (found in cache), that means the guild is now
622+
// available from a recent .onUnavailable(). Since it's already cached, there's no need to replace
623+
// it because Bot.cacheGuild() uses Dictionary.updateValue(). Instead, just update the guild data and
624+
// merge the members together. If the new (available) guild replaced the old one, that would also replace its
625+
// members which could significantly reduce the amount of members in the members cache, especially
626+
// if that guild was chunked.
627+
if let guild = bot.getGuild(guildId) {
628+
guild.update(data)
629+
630+
let incomingMembers = {
631+
var members = [Snowflake: Member]()
632+
for obj in data["members"] as! [JSON] {
633+
let member = Member(bot: bot, memberData: obj, guildId: guildId)
634+
members[member.id] = member
635+
}
636+
return members
637+
}()
638+
639+
guild.membersCache.merge(incomingMembers) { (_, new) in new }
640+
dispatch({ await $0.onGuildAvailable(guild: guild) })
641+
642+
} else {
643+
let guild = Guild(bot: bot, guildData: data, fromGateway: true)
644+
645+
bot.cacheGuild(guild)
646+
initialState!.guildsCreated += 1
647+
648+
dispatch({ await $0.onGuildCreate(guild: guild) })
649+
dispatch({ await $0.onGuildAvailable(guild: guild) })
650+
651+
if initialState!.expectedGuilds == initialState!.guildsCreated {
652+
initialState!.dispatched = true
653+
dispatch({ await $0.onReady(user: self.bot.user!) })
654+
}
626655
}
627656

628657
case .guildUpdate:

0 commit comments

Comments
 (0)