diff --git a/api.go b/api.go index c42a6a3..f93fdbe 100644 --- a/api.go +++ b/api.go @@ -126,12 +126,13 @@ func getMe(token string) (User, error) { 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.Set("offset", strconv.Itoa(offset)) + params.Set("timeout", strconv.Itoa(timeout)) updatesJSON, err := sendCommand("getUpdates", token, params) if err != nil { - return err + return } var updatesRecieved struct { @@ -142,16 +143,14 @@ func getUpdates(token string, offset int, updates chan<- Update) error { err = json.Unmarshal(updatesJSON, &updatesRecieved) if err != nil { - return err + return } if !updatesRecieved.Ok { - return FetchError{updatesRecieved.Description} - } - - for _, update := range updatesRecieved.Result { - updates <- update + err = FetchError{updatesRecieved.Description} + return } - return nil + updates = updatesRecieved.Result + return } diff --git a/bot.go b/bot.go index 482ad9b..49f7bac 100644 --- a/bot.go +++ b/bot.go @@ -32,26 +32,17 @@ func NewBot(token string) (*Bot, error) { // Listen periodically looks for updates and delivers new messages // to subscription channel. -func (b Bot) Listen(subscription chan<- Message, interval time.Duration) { - updates := make(chan Update) - pulse := time.NewTicker(interval) - latestUpdate := 0 +func (b Bot) Listen(subscription chan<- Message, timeout time.Duration) { go func() { - for _ = range pulse.C { - go getUpdates(b.Token, - latestUpdate+1, - updates) - } - }() - - go func() { - for update := range updates { - if update.ID > latestUpdate { - latestUpdate = update.ID + latestUpdate := 0 + for { + if updates, err := getUpdates(b.Token, latestUpdate+1, int(timeout / time.Second)); err == nil { + for _, update := range updates { + latestUpdate = update.ID + subscription <- update.Payload + } } - - subscription <- update.Payload } }() }