State: Fixed incoming messages being backwards in order

This commit is contained in:
diamondburned (Forefront) 2020-05-16 13:04:54 -07:00
parent 1ca7d1c62c
commit 5aec467779
3 changed files with 19 additions and 10 deletions

View File

@ -449,7 +449,9 @@ func (s *State) Messages(channelID discord.Snowflake) ([]discord.Message, error)
guildID = c.GuildID
}
for i := range ms {
// Iterate in reverse, since the store is expected to prepend the latest
// messages.
for i := len(ms) - 1; i >= 0; i-- {
// Set the guild ID, fine if it's 0 (it's already 0 anyway).
ms[i].GuildID = guildID

View File

@ -42,6 +42,7 @@ type StoreGetter interface {
Members(guildID discord.Snowflake) ([]discord.Member, error)
Message(channelID, messageID discord.Snowflake) (*discord.Message, error)
// Messages should return messages ordered from latest to earliest.
Messages(channelID discord.Snowflake) ([]discord.Message, error)
MaxMessages() int // used to know if the state is filled or not.
@ -73,6 +74,8 @@ type StoreModifier interface {
MemberSet(guildID discord.Snowflake, member *discord.Member) error
MemberRemove(guildID, userID discord.Snowflake) error
// MessageSet should prepend messages into the slice, the latest being in
// front.
MessageSet(*discord.Message) error
MessageRemove(channelID, messageID discord.Snowflake) error

View File

@ -463,19 +463,23 @@ func (s *DefaultStore) MessageSet(message *discord.Message) error {
}
}
// Prepend the latest message at the end
if end := s.MaxMessages(); len(ms) >= end {
// Copy hack to prepend. This copies the 0th-(end-1)th entries to
// 1st-endth.
copy(ms[1:end], ms[0:end-1])
// Then, set the 0th entry.
ms[0] = *message
// Order: latest to earliest, similar to the API.
var end = len(ms)
if max := s.MaxMessages(); end >= max {
// If the end (length) is larger than the maximum amount, then cap it.
end = max
} else {
ms = append(ms, *message)
// Else, append an empty message to the end.
ms = append(ms, discord.Message{})
}
// Copy hack to prepend. This copies the 0th-(end-1)th entries to
// 1st-endth.
copy(ms[1:end], ms[0:end-1])
// Then, set the 0th entry.
ms[0] = *message
s.messages[message.ChannelID] = ms
return nil
}