From c92249702b3e966f51493ee233bbddeda294d486 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Santos=20Garrido?= Date: Thu, 10 Aug 2023 15:33:56 +0200 Subject: [PATCH] [Fix] GetMessagesAsync with Direction.After not working as expected #2744 (#2745) * Fixed GetMessagesAsync with Direction.After issue #2744 * Fixed GetMessagesAsync with Direction.After issue #2744 --- .../Entities/Channels/SocketChannelHelper.cs | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/src/Discord.Net.WebSocket/Entities/Channels/SocketChannelHelper.cs b/src/Discord.Net.WebSocket/Entities/Channels/SocketChannelHelper.cs index c977993d..032afb60 100644 --- a/src/Discord.Net.WebSocket/Entities/Channels/SocketChannelHelper.cs +++ b/src/Discord.Net.WebSocket/Entities/Channels/SocketChannelHelper.cs @@ -33,14 +33,31 @@ namespace Discord.WebSocket } else if (dir == Direction.After) { - limit -= cachedMessages.Count; - if (mode == CacheMode.CacheOnly || limit <= 0) + if (mode == CacheMode.CacheOnly) return result; + bool ignoreCache = false; + + // We can find two cases: + // 1. fromMessageId is not null and corresponds to a message that is not in the cache, + // so we have to make a request and ignore the cache + if (fromMessageId.HasValue && messages?.Get(fromMessageId.Value) == null) + { + ignoreCache = true; + } + // 2. fromMessageId is null or already in the cache, so we start from the cache + else if (cachedMessages.Count > 0) + { + fromMessageId = cachedMessages.Max(x => x.Id); + limit -= cachedMessages.Count; + + if (limit <= 0) + return result; + } + //Download remaining messages - ulong maxId = cachedMessages.Count > 0 ? cachedMessages.Max(x => x.Id) : fromMessageId.Value; - var downloadedMessages = ChannelHelper.GetMessagesAsync(channel, discord, maxId, dir, limit, options); - if (cachedMessages.Count != 0) + var downloadedMessages = ChannelHelper.GetMessagesAsync(channel, discord, fromMessageId, dir, limit, options); + if (!ignoreCache && cachedMessages.Count != 0) return result.Concat(downloadedMessages); else return downloadedMessages;