package tldr import ( "sort" "github.com/bwmarrin/discordgo" ) type MessageFetcher interface { ChannelMessages(channelID string, limit int, beforeID, afterID, aroundID string, options ...discordgo.RequestOption) ([]*discordgo.Message, error) } // FetchAfter pages forward from afterID and returns up to limit messages, // oldest first. Discord returns the messages immediately following the ID, // so paging with the newest ID of each batch walks toward the present. func FetchAfter(f MessageFetcher, channelID, afterID string, limit int) ([]*discordgo.Message, error) { var all []*discordgo.Message after := afterID for len(all) < limit { want := min(100, limit-len(all)) batch, err := f.ChannelMessages(channelID, want, "", after, "") if err != nil { return nil, err } if len(batch) == 0 { break } newest := batch[0].ID for _, m := range batch { if CompareIDs(m.ID, newest) > 0 { newest = m.ID } } all = append(all, batch...) after = newest if len(batch) < want { break } } sort.Slice(all, func(i, j int) bool { return CompareIDs(all[i].ID, all[j].ID) < 0 }) return all, nil }