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,26 +32,17 @@ 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() { go func() {
for _ = range pulse.C { latestUpdate := 0
go getUpdates(b.Token, for {
latestUpdate+1, if updates, err := getUpdates(b.Token, latestUpdate+1, int(timeout / time.Second)); err == nil {
updates) for _, update := range updates {
} latestUpdate = update.ID
}() subscription <- update.Payload
}
go func() {
for update := range updates {
if update.ID > latestUpdate {
latestUpdate = update.ID
} }
subscription <- update.Payload
} }
}() }()
} }

Loading…
Cancel
Save