Merge pull request #5 from Ronmi/issue

Doing long polling in Bot.Listen to ensure message order
pull/8/head
llya Kowalewski 9 years ago
commit 4a633dc640

@ -126,12 +126,13 @@ func getMe(token string) (User, error) {
return User{}, AuthError{botInfo.Description} return User{}, AuthError{botInfo.Description}
} }
func getUpdates(token string, offset int, updates chan<- Update) error { func getUpdates(token string, offset int, timeout int) (updates []Update, err error) {
params := url.Values{} params := url.Values{}
params.Set("offset", strconv.Itoa(offset)) params.Set("offset", strconv.Itoa(offset))
params.Set("timeout", strconv.Itoa(timeout))
updatesJSON, err := sendCommand("getUpdates", token, params) updatesJSON, err := sendCommand("getUpdates", token, params)
if err != nil { if err != nil {
return err return
} }
var updatesRecieved struct { var updatesRecieved struct {
@ -142,16 +143,14 @@ func getUpdates(token string, offset int, updates chan<- Update) error {
err = json.Unmarshal(updatesJSON, &updatesRecieved) err = json.Unmarshal(updatesJSON, &updatesRecieved)
if err != nil { if err != nil {
return err return
} }
if !updatesRecieved.Ok { if !updatesRecieved.Ok {
return FetchError{updatesRecieved.Description} err = FetchError{updatesRecieved.Description}
} return
for _, update := range updatesRecieved.Result {
updates <- update
} }
return nil updates = updatesRecieved.Result
return
} }

@ -32,27 +32,18 @@ func NewBot(token string) (*Bot, error) {
// Listen periodically looks for updates and delivers new messages // Listen periodically looks for updates and delivers new messages
// to subscription channel. // to subscription channel.
func (b Bot) Listen(subscription chan<- Message, interval time.Duration) { func (b Bot) Listen(subscription chan<- Message, timeout time.Duration) {
updates := make(chan Update)
pulse := time.NewTicker(interval)
latestUpdate := 0
go func() {
for _ = range pulse.C {
go getUpdates(b.Token,
latestUpdate+1,
updates)
}
}()
go func() { go func() {
for update := range updates { latestUpdate := 0
if update.ID > latestUpdate { for {
if updates, err := getUpdates(b.Token, latestUpdate+1, int(timeout / time.Second)); err == nil {
for _, update := range updates {
latestUpdate = update.ID latestUpdate = update.ID
}
subscription <- update.Payload subscription <- update.Payload
} }
}
}
}() }()
} }

Loading…
Cancel
Save