# How to Set Up a Webhook for a Telego Bot: Complete Guide with Examples

> Learn to set up a webhook for your Telego bot with this complete guide. Follow simple steps to register your URL, start an HTTP server, and handle updates efficiently.

- Repository: [Artem Yadelskyi/telego](https://github.com/mymmrac/telego)
- Tags: how-to-guide
- Published: 2026-03-07

---

**To set up a webhook for a Telego bot, create a `Bot` instance, register your webhook URL with Telegram using `SetWebhook` or the `WithWebhookSet` option, start an HTTP server with one of Telego’s adapter helpers (`WebhookFastHTTP`, `WebhookHTTPServer`, or `WebhookHTTPServeMux`), and consume updates from the channel returned by `UpdatesViaWebhook`.**

The [mymmrac/telego](https://github.com/mymmrac/telego) library provides a robust, type-safe Go implementation for the Telegram Bot API. Unlike long-polling, which requires your bot to constantly request updates, webhook mode allows Telegram to push updates directly to your HTTP server, reducing latency and resource consumption.

## What Is a Webhook and Why Use It?

A webhook is an HTTP callback mechanism where Telegram sends a POST request to your server whenever a new update (message, callback query, etc.) occurs. In `telego`, the `UpdatesViaWebhook` method in [`webhook.go`](https://github.com/mymmrac/telego/blob/main/webhook.go) manages this flow by registering a `WebhookHandler` and returning a buffered Go channel of `Update` objects.

**Key advantages:**
- **Immediate delivery**: Updates arrive as soon as they are created.
- **Lower resource usage**: No persistent HTTP connections required for polling.
- **Scalability**: Easier to distribute across multiple server instances.

## Prerequisites for Telego Webhook Setup

Before implementing the webhook in `telego`, ensure you have:

1. **A publicly accessible HTTPS URL** (Telegram requires HTTPS for webhooks).
2. **Go 1.18+** installed in your environment.
3. **Your bot token** from [@BotFather](https://t.me/botfather).
4. **TLS certificate** (if using a self-signed certificate, you must provide the public key to Telegram).

## Setting Up the Webhook in Telego

Telego provides two approaches to register your webhook with Telegram: manual configuration via `SetWebhook` or automatic registration using the `WithWebhookSet` option.

### Option 1: Manual Webhook Registration with SetWebhook

Use the `SetWebhook` method defined in [`methods.go`](https://github.com/mymmrac/telego/blob/main/methods.go) to explicitly configure the webhook URL and security parameters.

```go
ctx := context.Background()
bot, _ := telego.NewBot(os.Getenv("TOKEN"))

err := bot.SetWebhook(ctx, &telego.SetWebhookParams{
    URL:         "https://your-domain.com/bot",
    SecretToken: bot.SecretToken(), // Verifies requests originate from Telegram
})

```

The `SetWebhookParams` struct allows you to specify:
- `URL`: Your HTTPS endpoint.
- `SecretToken`: Optional token for request verification (stored in `WebhookSecretTokenHeader`).
- `Certificate`: Public key for self-signed TLS certificates.

### Option 2: Automatic Registration with WithWebhookSet

The `WithWebhookSet` option in [`webhook.go`](https://github.com/mymmrac/telego/blob/main/webhook.go) automatically calls `SetWebhook` when the webhook runner starts, reducing boilerplate.

```go
updates, _ := bot.UpdatesViaWebhook(
    ctx,
    telego.WebhookFastHTTP(srv, "/bot", bot.SecretToken()),
    telego.WithWebhookSet(ctx, &telego.SetWebhookParams{
        URL:         "https://your-domain.com/bot",
        SecretToken: bot.SecretToken(),
    }),
)

```

## HTTP Server Integration Options

Telego abstracts HTTP server integration through adapter functions in [`webhook_handler.go`](https://github.com/mymmrac/telego/blob/main/webhook_handler.go). These adapters validate incoming requests and forward the JSON payload to the internal `WebhookHandler`.

### Using FastHTTP (High Performance)

For high-throughput scenarios, use `WebhookFastHTTP` which integrates with [valyala/fasthttp](https://github.com/valyala/fasthttp).

```go
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/valyala/fasthttp"
	"github.com/mymmrac/telego"
)

func main() {
	ctx := context.Background()
	bot, _ := telego.NewBot(os.Getenv("TOKEN"), telego.WithDefaultDebugLogger())

	// Register webhook with Telegram
	_ = bot.SetWebhook(ctx, &telego.SetWebhookParams{
		URL:         "https://YOUR_PUBLIC_URL/bot",
		SecretToken: bot.SecretToken(),
	})

	// Create FastHTTP server
	srv := &fasthttp.Server{}

	// Obtain update channel using the FastHTTP adapter
	updates, _ := bot.UpdatesViaWebhook(
		ctx,
		telego.WebhookFastHTTP(srv, "/bot", bot.SecretToken()),
		telego.WithWebhookBuffer(128), // Optional: set channel buffer size
	)

	// Start server in background
	go srv.ListenAndServe(":443")

	// Consume updates
	for upd := range updates {
		fmt.Printf("Got update: %+v\n", upd)
	}
}

```

The `WebhookFastHTTP` adapter validates the `X-Telegram-Bot-Api-Secret-Token` header against your configured secret before processing the request body.

### Using Standard net/http

For standard library compatibility, use `WebhookHTTPServer` which works with `*http.Server`.

```go
package main

import (
	"context"
	"fmt"
	"net/http"
	"os"

	"github.com/mymmrac/telego"
)

func main() {
	ctx := context.Background()
	bot, _ := telego.NewBot(os.Getenv("TOKEN"))

	// Configure webhook and start listening
	updates, _ := bot.UpdatesViaWebhook(
		ctx,
		telego.WebhookHTTPServer(&http.Server{}, "/bot", bot.SecretToken()),
		telego.WithWebhookSet(ctx, &telego.SetWebhookParams{
			URL:         "https://YOUR_PUBLIC_URL/bot",
			SecretToken: bot.SecretToken(),
		}),
	)

	go http.ListenAndServe(":8080", nil)

	for upd := range updates {
		fmt.Println("Update:", upd.UpdateID)
	}
}

```

### Using http.ServeMux

For routing flexibility with `ServeMux`, use `WebhookHTTPServeMux`.

```go
package main

import (
	"context"
	"fmt"
	"net/http"
	"os"

	"github.com/mymmrac/telego"
)

func main() {
	ctx := context.Background()
	bot, _ := telego.NewBot(os.Getenv("TOKEN"))

	mux := http.NewServeMux()
	updates, _ := bot.UpdatesViaWebhook(
		ctx,
		telego.WebhookHTTPServeMux(mux, "POST /bot", bot.SecretToken()),
		telego.WithWebhookSet(ctx, &telego.SetWebhookParams{
			URL:         "https://YOUR_PUBLIC_URL/bot",
			SecretToken: bot.SecretToken(),
		}),
	)

	go http.ListenAndServe(":8080", mux)

	for upd := range updates {
		fmt.Printf("Message from %s: %s\n", upd.Message.From.FirstName, upd.Message.Text)
	}
}

```

## Security Considerations

When configuring your Telego webhook, implement these security measures defined in [`webhook_handler.go`](https://github.com/mymmrac/telego/blob/main/webhook_handler.go):

1. **Secret Token Validation**: Always set `SecretToken` in `SetWebhookParams`. Telego automatically validates the `X-Telegram-Bot-Api-Secret-Token` header against this value in all webhook adapter functions.

2. **TLS Encryption**: Telegram requires HTTPS for webhook endpoints. Use valid certificates from providers like Let's Encrypt, or provide your public certificate via `SetWebhookParams.Certificate` for self-signed TLS.

3. **IP Allowlisting**: Restrict incoming requests to Telegram's IP ranges (149.154.160.0/20 and 91.108.4.0/22) at your firewall or reverse proxy level for additional protection.

## Summary

- **Webhook mode** pushes updates from Telegram to your HTTP server, eliminating the need for long-polling loops.
- **Registration options**: Use `Bot.SetWebhook` for manual control or `WithWebhookSet` for automatic registration when starting the webhook runner.
- **Server adapters**: Choose `WebhookFastHTTP` for high performance, `WebhookHTTPServer` for standard library compatibility, or `WebhookHTTPServeMux` for custom routing.
- **Security**: Always configure `SecretToken` to verify requests via the `X-Telegram-Bot-Api-Secret-Token` header, and ensure HTTPS endpoints.

## Frequently Asked Questions

### How do I choose between long-polling and webhooks in Telego?

Use **long-polling** (via `Bot.UpdatesViaLongPolling`) when developing locally or behind NAT/firewalls where you cannot expose a public HTTPS endpoint. Use **webhooks** (via `Bot.UpdatesViaWebhook`) in production environments with public IPs, as they provide lower latency and better resource efficiency by pushing updates only when they occur.

### Can I use a self-signed certificate with Telego webhooks?

Yes. Generate your self-signed certificate and provide the public key via the `Certificate` field in `telego.SetWebhookParams`. According to the Telegram Bot API, you must upload the certificate as part of the `setWebhook` call so Telegram can validate your server's identity during the TLS handshake.

### What happens if my webhook server is temporarily offline?

If your server is unreachable, Telegram will retry delivery with an exponential backoff for a short period, but updates may be lost if the outage persists. Implement a reverse proxy or load balancer to ensure high availability. For critical bots, consider implementing a fallback mechanism or using `drop_pending_updates` in `SetWebhookParams` to clear the queue when restarting.

### How does Telego verify that requests come from Telegram?

When you configure `SecretToken` in `SetWebhookParams`, Telego stores this value and compares it against the `X-Telegram-Bot-Api-Secret-Token` header in every incoming request. The adapter functions (`WebhookFastHTTP`, `WebhookHTTPServer`, etc.) perform this validation automatically and reject requests with missing or incorrect tokens before processing the JSON payload.