Skip to content

Commit c922497

Browse files
authored
[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
1 parent 6bb3777 commit c922497

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

src/Discord.Net.WebSocket/Entities/Channels/SocketChannelHelper.cs

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,31 @@ public static IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(I
3333
}
3434
else if (dir == Direction.After)
3535
{
36-
limit -= cachedMessages.Count;
37-
if (mode == CacheMode.CacheOnly || limit <= 0)
36+
if (mode == CacheMode.CacheOnly)
3837
return result;
3938

39+
bool ignoreCache = false;
40+
41+
// We can find two cases:
42+
// 1. fromMessageId is not null and corresponds to a message that is not in the cache,
43+
// so we have to make a request and ignore the cache
44+
if (fromMessageId.HasValue && messages?.Get(fromMessageId.Value) == null)
45+
{
46+
ignoreCache = true;
47+
}
48+
// 2. fromMessageId is null or already in the cache, so we start from the cache
49+
else if (cachedMessages.Count > 0)
50+
{
51+
fromMessageId = cachedMessages.Max(x => x.Id);
52+
limit -= cachedMessages.Count;
53+
54+
if (limit <= 0)
55+
return result;
56+
}
57+
4058
//Download remaining messages
41-
ulong maxId = cachedMessages.Count > 0 ? cachedMessages.Max(x => x.Id) : fromMessageId.Value;
42-
var downloadedMessages = ChannelHelper.GetMessagesAsync(channel, discord, maxId, dir, limit, options);
43-
if (cachedMessages.Count != 0)
59+
var downloadedMessages = ChannelHelper.GetMessagesAsync(channel, discord, fromMessageId, dir, limit, options);
60+
if (!ignoreCache && cachedMessages.Count != 0)
4461
return result.Concat(downloadedMessages);
4562
else
4663
return downloadedMessages;

0 commit comments

Comments
 (0)