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}
}
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
}

@ -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
}
}()
}

Loading…
Cancel
Save