Webhooks are the recommended way to receive updates in production. This involves:
- Setting the webhook on the Telegram side using
bot.SetWebhook with a SetWebhookParams object containing your URL and SecretToken. - Creating an HTTP server (e.g., using
http.NewServeMux). - Using
bot.UpdatesViaWebhook with telego.WebhookHTTPServeMux to link the Telegram webhook to your HTTP mux.
For local testing, tools like Ngrok can be used to tunnel your localhost to a public URL.
package main
import (
"context"
"net/http"
"os"
"github.com/mymmrac/telego"
)
func main() {
ctx := context.Background()
botToken := os.Getenv("TOKEN")
bot, err := telego.NewBot(botToken)
if err != nil {
os.Exit(1)
}
// Set up a webhook on Telegram side
_ = bot.SetWebhook(ctx, &telego.SetWebhookParams{
URL: "https://example.com/bot",
SecretToken: bot.SecretToken(),
})
// Create http serve mux
mux := http.NewServeMux()
// Get an update channel from webhook
updates, _ := bot.UpdatesViaWebhook(ctx, telego.WebhookHTTPServeMux(mux, "/bot", bot.SecretToken()))
// Start server for receiving requests
go func() {
_ = http.ListenAndServe(":443", mux)
}()
for update := range updates {
// Process update
}
}