diff --git a/Myriad/Cache/DiscordCacheExtensions.cs b/Myriad/Cache/DiscordCacheExtensions.cs index e50c3453..aa0541fb 100644 --- a/Myriad/Cache/DiscordCacheExtensions.cs +++ b/Myriad/Cache/DiscordCacheExtensions.cs @@ -1,8 +1,6 @@ using System.Threading.Tasks; using Myriad.Gateway; -using Myriad.Rest; -using Myriad.Types; namespace Myriad.Cache { @@ -51,6 +49,11 @@ namespace Myriad.Cache private static async ValueTask SaveMessageCreate(this IDiscordCache cache, MessageCreateEvent evt) { + // DM messages don't get Channel Create events first, so we need to save + // some kind of stub channel object until we get the real one + if (evt.GuildId == null) + await cache.SaveDmChannelStub(evt.ChannelId); + await cache.SaveUser(evt.Author); foreach (var mention in evt.Mentions) await cache.SaveUser(mention); diff --git a/Myriad/Cache/IDiscordCache.cs b/Myriad/Cache/IDiscordCache.cs index c778ed32..34207d74 100644 --- a/Myriad/Cache/IDiscordCache.cs +++ b/Myriad/Cache/IDiscordCache.cs @@ -11,6 +11,7 @@ namespace Myriad.Cache public ValueTask SaveChannel(Channel channel); public ValueTask SaveUser(User user); public ValueTask SaveRole(ulong guildId, Role role); + public ValueTask SaveDmChannelStub(ulong channelId); public ValueTask RemoveGuild(ulong guildId); public ValueTask RemoveChannel(ulong channelId); diff --git a/Myriad/Cache/MemoryDiscordCache.cs b/Myriad/Cache/MemoryDiscordCache.cs index 2dcfde6a..9dc4ca1c 100644 --- a/Myriad/Cache/MemoryDiscordCache.cs +++ b/Myriad/Cache/MemoryDiscordCache.cs @@ -81,6 +81,18 @@ namespace Myriad.Cache return default; } + public ValueTask SaveDmChannelStub(ulong channelId) + { + // Use existing channel object if present, otherwise add a stub + // We may get a message create before channel create and we want to have it saved + _channels.GetOrAdd(channelId, id => new Channel + { + Id = id, + Type = Channel.ChannelType.Dm + }); + return default; + } + public ValueTask RemoveGuild(ulong guildId) { _guilds.TryRemove(guildId, out _); diff --git a/Myriad/Types/Channel.cs b/Myriad/Types/Channel.cs index 841a2e1d..180e992b 100644 --- a/Myriad/Types/Channel.cs +++ b/Myriad/Types/Channel.cs @@ -22,7 +22,7 @@ public bool? Nsfw { get; init; } public ulong? ParentId { get; init; } public Overwrite[]? PermissionOverwrites { get; init; } - public User[]? Recipients { get; init; } + public User[]? Recipients { get; init; } // NOTE: this may be null for stub channel objects public record Overwrite {