I want to user the ippy04/messengerbot library to build a bot for the facebook messenger.
For receiving a new message the library uses a construct I can´t wrap my head around. The following function type is defined (but without body) in the relevant library source file:
type MessageReceivedHandler func(*MessengerBot, Event, MessageOpts, ReceivedMessage)
This type then gets attached to the actual bot:
type MessengerBot struct {
MessageReceived MessageReceivedHandler
}
Later in the code it gets called like this:
if bot.MessageReceived != nil {
go bot.MessageReceived(bot, entry.Event, message.MessageOpts, *message.Message)
}
Now it seems I need to extend MessageReceivedHandler
with an actual body implementation in my own package. I tried a few thing.
Following another SO thread I did this:
import "github.com/ippy04/messengerbot"
type myMRH messengerbot.MessageReceivedHandler
func (mr myMRH) HRM() {
log.Println("works!")
}
... but that code never gets called.
Also I tried to extend bot.MessageReceived
like this (I´m using GinGonic)
router.POST("/webhook", func(c *gin.Context) {
bot := messengerbot.NewMessengerBot(os.Getenv("FB_PAGE_ACCESS_TOKEN"), os.Getenv("FB_MESSENGER_VERIFY_TOKEN"))
bot.Debug = true
bot.MessageReceived = func(*MessengerBot, Event, MessageOpts, ReceivedMessage) {
log.Println("works!")
}
bot.Handler(c.Writer, c.Request)
})
but then I have no idea where to get the necessary function variables from since they ar enot exposed by the library.
Any idea on how to implement that MessageReceivedHandler
?
Based on the answer from @mykola here is the complete solution to my problem:
router.POST("/webhook", func(c *gin.Context) {
bot := messengerbot.NewMessengerBot(os.Getenv("FB_PAGE_ACCESS_TOKEN"), os.Getenv("FB_MESSENGER_VERIFY_TOKEN"))
bot.Debug = true
bot.MessageReceived = func(bot *messengerbot.MessengerBot, evt messengerbot.Event, opts messengerbot.MessageOpts, msg messengerbot.ReceivedMessage) {
log.Println(msg.Message.Text)
}
bot.Handler(c.Writer, c.Request)
})
The fact that someone somewhere has declared a new type derived from messengerbot.MessageReceivedHandler
doesn't and shouldn't have any effect on the bot library itself.
What you need is to set the handler of the bot either at the construction point, by instantiating it yourself, or later by doing
bot.MessageReceived = func(bot *MessengerBot, evt Event, opts MessageOpts, msg ReceivedMessage) {
log.Println("works!", msg)
}
P.S. You might want to check the tour of go if you haven't yet, as you seem to miss some basic concepts of working with go.