I use this library tucnak/telebot to build a telegram bot.
Method b.Handle()
have two parameters such as Handle(endpoint interface{}, handler
interface{})`.
Here is the code i use for a starter
func main() {
b, err := tb.NewBot(tb.Settings{
Token: "TOKEN_HERE",
Poller: &tb.LongPoller{Timeout: 10 * time.Second},
})
if err != nil {
log.Fatal(err)
return
}
// i want to split this(interface)
b.Handle("/hello", func(m *tb.Message) {
b.Send(m.Sender, "Hello World!")
})
b.Start()
}
Here is what I have tried to compile :
func main() {
b, err := tb.NewBot(tb.Settings{
Token: "TOKEN_HERE",
Poller: &tb.LongPoller{Timeout: 10 * time.Second},
})
if err != nil {
log.Fatal(err)
return
}
b.Handle("/hello", handleHello(b))
b.Start()
}
func handleHello(b *tb.Bot) {
b.Send(m.Sender, "Hello World!")
}
I have an error with this code : undefined m
, in m.Sender()
and I can’t use m
as a parameter for that function call, because of the same error. I don’t understand where that m
comes from.
2
Answers
As you can see hello handler takes a parameter called m here.
so you should return a function that takes the same parameter.
The bot responsibility is to listen some sockets, whatever, and calls your
function handlers
when a message arrives on the associatedpath handler
.Thus, you should not try to call your handlers like in
b.Handle("/hello", handleHello(b))
. Instead pass the function handler to the botb.Handle("/hello", handleHello)
. Let the bot call that function with the new message as a parameter like infunc(m *tb.Message)
.To retain a reference to
b
, you can proceed as described by Sinan Coment. Write a function that takes in parameter the bot and returns a function that receives the message as a parameter.The bot instance
b
acts as a muxer, you can re use that terminology to improve the meaning of your code.A muxer is defined as
[...] a request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.
Though, I want to suggest you to wrap that instance of telebot.Bot into a type that defines message handlers as methods.
https://play.golang.org/p/6ng6WSIp8Er