Skip to content

Instantly share code, notes, and snippets.

@kraftwerk28
Created May 27, 2021 20:25
Show Gist options
  • Save kraftwerk28/893f59d46fecdf15784648c95027859a to your computer and use it in GitHub Desktop.
Save kraftwerk28/893f59d46fecdf15784648c95027859a to your computer and use it in GitHub Desktop.
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"gopkg.in/tucnak/telebot.v2"
)
type WebhookPoller struct {
updatesChan chan telebot.Update
}
func (p *WebhookPoller) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var update telebot.Update
err := json.NewDecoder(r.Body).Decode(&update)
if err != nil {
return
}
p.updatesChan <- update
}
func (h *WebhookPoller) Poll(
b *telebot.Bot,
dest chan telebot.Update,
stop chan struct{},
) {
whUrl := fmt.Sprintf(
"https://%s:%s/%s",
getEnvPanic("WEBHOOK_DOMAIN"),
getEnvPanic("WEBHOOK_PORT"),
getEnvPanic("WEBHOOK_SECRET_PATH"),
)
h.updatesChan = dest
webhookResult, err := b.Raw("setWebhook", map[string]string{
"url": whUrl,
"drop_pending_updates": "true",
})
log.Printf("Set webhook: %s", string(webhookResult))
if err != nil {
close(stop)
log.Fatal(err)
}
s := &http.Server{
Addr: ":" + getEnvPanic("SERVER_PORT"),
Handler: h,
}
go func(stop chan struct{}, s *http.Server) {
<-stop
close(stop)
s.Shutdown(context.Background())
}(stop, s)
s.ListenAndServe()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment