Added HandleUpdate method for serverless deploy (cherry picked from commit d4b2e3c2136aa63ffce72c297c97a9c3e0a06cc8)
gropher grophen@gmail.com
Wed, 18 Sep 2019 03:34:37 +0300
2 files changed,
41 insertions(+),
7 deletions(-)
M
bot.go
→
bot.go
@@ -451,16 +451,21 @@ func (bot *BotAPI) ListenForWebhook(pattern string) UpdatesChannel {
ch := make(chan Update, bot.Buffer) http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { - bytes, _ := ioutil.ReadAll(r.Body) - r.Body.Close() + ch <- bot.HandleUpdate(w, r) + }) - var update Update - json.Unmarshal(bytes, &update) + return ch +} + +// HandleUpdate parses and returns update received via webhook +func (bot *BotAPI) HandleUpdate(res http.ResponseWriter, req *http.Request) Update { + bytes, _ := ioutil.ReadAll(req.Body) + req.Body.Close() - ch <- update - }) + var update Update + json.Unmarshal(bytes, &update) - return ch + return update } // WriteToHTTPResponse writes the request to the HTTP ResponseWriter.
M
bot_test.go
→
bot_test.go
@@ -599,6 +599,35 @@ log.Printf("%+v\n", update)
} } +func ExampleWebhookHandler() { + bot, err := NewBotAPI("MyAwesomeBotToken") + if err != nil { + panic(err) + } + + bot.Debug = true + + log.Printf("Authorized on account %s", bot.Self.UserName) + + _, err = bot.Request(NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem")) + if err != nil { + panic(err) + } + info, err := bot.GetWebhookInfo() + if err != nil { + panic(err) + } + if info.LastErrorDate != 0 { + log.Printf("[Telegram callback failed]%s", info.LastErrorMessage) + } + + http.HandleFunc("/"+bot.Token, func(w http.ResponseWriter, r *http.Request) { + log.Printf("%+v\n", bot.HandleUpdate(w, r)) + }) + + go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil) +} + func ExampleInlineConfig() { bot, err := NewBotAPI("MyAwesomeBotToken") // create new bot if err != nil {