62 lines
1.5 KiB
Go
62 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
|
|
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
|
|
|
"worktimeBot/internal/bot"
|
|
)
|
|
|
|
// startWebhook configures the Telegram webhook and starts the HTTP(S) listener.
|
|
func startWebhook(botAPI *tgbotapi.BotAPI, handler *bot.Handler, webhookURL string) {
|
|
// Delete any previously set webhook
|
|
if _, err := botAPI.Request(tgbotapi.DeleteWebhookConfig{}); err != nil {
|
|
log.Fatal("DeleteWebhook:", err)
|
|
}
|
|
|
|
// Set the new webhook
|
|
wh, err := tgbotapi.NewWebhook(webhookURL)
|
|
if err != nil {
|
|
log.Fatal("NewWebhook:", err)
|
|
}
|
|
if _, err := botAPI.Request(wh); err != nil {
|
|
log.Fatal("SetWebhook:", err)
|
|
}
|
|
|
|
// Register the webhook endpoint and get the updates channel
|
|
updates := botAPI.ListenForWebhook("/webhook")
|
|
|
|
// Determine where to listen
|
|
listenAddr := getEnvDefault("BOT_LISTEN", ":8080")
|
|
tlsCert := os.Getenv("BOT_TLS_CERT")
|
|
tlsKey := os.Getenv("BOT_TLS_KEY")
|
|
|
|
if tlsCert != "" && tlsKey != "" {
|
|
log.Printf("Starting HTTPS webhook on %s", listenAddr)
|
|
go func() {
|
|
if err := http.ListenAndServeTLS(listenAddr, tlsCert, tlsKey, nil); err != nil {
|
|
log.Fatal("HTTPS server:", err)
|
|
}
|
|
}()
|
|
} else {
|
|
log.Printf("Starting HTTP webhook on %s (TLS handled by reverse proxy)", listenAddr)
|
|
go func() {
|
|
if err := http.ListenAndServe(listenAddr, nil); err != nil {
|
|
log.Fatal("HTTP server:", err)
|
|
}
|
|
}()
|
|
}
|
|
|
|
log.Printf("Webhook registered at %s", webhookURL)
|
|
|
|
// Process incoming updates
|
|
for update := range updates {
|
|
if update.Message != nil {
|
|
handler.HandleMessage(update)
|
|
}
|
|
}
|
|
}
|