abourget / slick

Slick, a Slack bot in Go
150 stars 27 forks source link

Set listeners in a loop #7

Open kiliankoe opened 8 years ago

kiliankoe commented 8 years ago

I have a bot that has a few very simple responses. I tried doing the following to register multiple listeners on the bot calling initSimple from within a InitPlugin func and passing it the reference to the bot.

var simpleResponses = map[string]string {
    "listenfor1": "response1",
    "listenfor2": "response2",
}

func initSimple(bot *slick.Bot) {
    for listen, response := range simpleResponses {
        bot.Listen(&slick.Listener{
            Contains:           listen,
            MessageHandlerFunc: func(l *slick.Listener, m *slick.Message) {
                m.Reply(response)
            },
        })
    }
}

The problem is that every "query" into simpleResponses returns the response from the last response, e.g. "response2" in this case. I've also tried generating a listener for every case and handing them to the bot one for one, but that leads to the same result.

Any help on how to achieve this would be much appreciated 😊

kiliankoe commented 8 years ago

I currently implemented this in my bot by using the same handler and checking msg.Match[0] inside the handler. This requires a regex match though, which is only a minor tradeoff.

I'm still unsure why the loop with closures didn't work and would love to figure that out.

abourget commented 7 years ago

That is weird indeed. Do you have a more complete example? This code seems fine, you're not even passing pointers, only copies of strings, and you create a new Listener on each iteration. Hmm.