diff --git a/bot.go b/bot.go index f52cc2f..ae92876 100644 --- a/bot.go +++ b/bot.go @@ -9,17 +9,13 @@ type Bot struct { // Bot as `User` on API level. Identity User - - listeners []Listener } -type Listener func(*Bot, Message) - -func (b *Bot) Listen(interval time.Duration) { - updates := make(chan Update, 1000) - var latest_update int - +func (b *Bot) Listen(subscription chan<- Message, interval time.Duration) { + updates := make(chan Update) pulse := time.NewTicker(interval) + latest_update := 0 + go func() { for range pulse.C { go api_getUpdates(b.Token, @@ -28,19 +24,15 @@ func (b *Bot) Listen(interval time.Duration) { } }() - for update := range updates { - if update.Id > latest_update { - latest_update = update.Id - } + go func() { + for update := range updates { + if update.Id > latest_update { + latest_update = update.Id + } - for _, ear := range b.listeners { - go ear(b, update.Payload) + subscription <- update.Payload } - } -} - -func (b *Bot) AddListener(ear Listener) { - b.listeners = append(b.listeners, ear) + }() } func (b *Bot) SendMessage(recipient User, message string) { diff --git a/telebot_test.go b/telebot_test.go index a90c2dc..2fffe60 100644 --- a/telebot_test.go +++ b/telebot_test.go @@ -25,13 +25,15 @@ func TestListen(t *testing.T) { t.Fatal(err) } - bot.AddListener(func(bot *Bot, message Message) { + messages := make(chan Message) + bot.Listen(messages, 1*time.Second) + + log.Println("Listening...") + + for message := range messages { if message.Text == "/hi" { bot.SendMessage(message.Chat, "Hello, "+message.Sender.FirstName+"!") } - }) - - log.Println("Listening...") - bot.Listen(1 * time.Second) + } }