Telego Health Check During Bot Initialization: Validating Tokens with WithHealthCheck

Use telego.WithHealthCheck() during NewBot() to synchronously validate your Telegram bot token via the getMe API call before the bot instance is returned, ensuring immediate feedback on authentication or network failures.

When building Telegram bots with the Telego library, verifying that your bot token is valid and the Telegram API is reachable before starting message processing is critical. The Telego health check during bot initialization feature provides exactly this capability through the functional options pattern, allowing developers to catch configuration errors early in the application lifecycle.

How the Telego Health Check Validates Bot Tokens

The WithHealthCheck Option Implementation

Located in bot_options.go (lines 33-46), the WithHealthCheck function implements the BotOption functional option type. When passed to NewBot(), it executes a synchronous validation sequence:

  • Calls the Telegram getMe method using the provided context
  • Caches the bot's identity fields (myID, myUsername) in the Bot struct
  • Primes the sync.Once guard (myOnce) to prevent redundant API calls during subsequent ID() or Username() method invocations

Error Handling and Initialization Flow

If the getMe request fails—whether due to an invalid token, network connectivity issues, or Telegram API errors—the error propagates immediately from WithHealthCheck to NewBot(), causing bot creation to fail. This prevents the instantiation of non-functional bot objects and ensures that downstream code never operates with invalid credentials.

Implementing Health Check in Telego Bot Initialization

Basic Health Check During Bot Creation

The most common implementation passes WithHealthCheck with a background context during NewBot():

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/mymmrac/telego"
)

func main() {
	botToken := os.Getenv("TOKEN")

	bot, err := telego.NewBot(
		botToken,
		telego.WithHealthCheck(context.Background()),
	)
	if err != nil {
		fmt.Printf("Failed to create bot: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("Bot initialized: ID=%d, Username=%s\n", bot.ID(), bot.Username())
}

This example, adapted from examples/configuration/main.go (lines 31-33), demonstrates how the health check validates the token before the bot enters the main execution loop.

Health Check with Custom Context and Timeouts

For production environments where API latency must be bounded, pass a context with timeout:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

bot, err := telego.NewBot(
	token,
	telego.WithHealthCheck(ctx),
)
if err != nil {
	log.Fatalf("Health check failed: %v", err)
}

The health check respects context cancellation, allowing graceful handling of network timeouts during initialization.

Handling Errors in Tests (Mocked API)

func TestBotHealthCheckFails(t *testing.T) {
	ctrl := gomock.NewController(t)
	mockCaller := mockapi.NewMockCaller(ctrl)

	mockCaller.EXPECT().
		Call(gomock.Any(), gomock.Any(), gomock.Any()).
		Return(nil, errors.New("network error"))

	_, err := telego.NewBot(
		"123456:ABCDEF",
		telego.WithAPICaller(mockCaller),
		telego.WithHealthCheck(context.Background()),
	)
	require.Error(t, err)
}

This pattern, demonstrated in bot_options_test.go (TestWithHealthCheck, lines 92-125), allows unit testing of initialization failures without network dependencies.

Technical Architecture and Source Code

Key Files and Components

File Purpose
bot_options.go Defines WithHealthCheck (lines 33-46) and all BotOption implementations
bot.go Core Bot struct with identity caching (myID, myUsername, myOnce) and NewBot constructor (lines 86-88 define BotOption type)
examples/configuration/main.go Demonstrates health check usage in production-ready configuration (lines 31-33)
bot_options_test.go Unit tests including TestWithHealthCheck for mocked API scenarios (lines 92-125)

Functional Options Pattern and Identity Caching

Telego uses the functional options pattern where NewBot accepts variadic BotOption functions (type BotOption func(bot *Bot) error). The WithHealthCheck option leverages this to inject validation logic into the initialization sequence.

Upon successful health check, the bot's identity is cached in the Bot struct fields myID and myUsername, with the sync.Once instance myOnce marked as "done". This optimization ensures that subsequent calls to bot.ID() or bot.Username() return cached values without additional API requests, as implemented in bot.go (lines 59-62).

Summary

  • Telego health check during bot initialization validates Telegram API connectivity and token validity before NewBot returns, preventing runtime authentication failures.
  • The WithHealthCheck option in bot_options.go (lines 33-46) executes a synchronous getMe API call that caches the bot's identity and primes internal sync.Once guards.
  • Health check failures immediately abort bot creation with descriptive errors, enabling early detection of configuration issues during deployment.
  • Integration requires passing telego.WithHealthCheck(context) to NewBot, supporting standard context patterns including timeouts and cancellation for production reliability.

Frequently Asked Questions

What happens if the Telego health check fails during initialization?

If the health check fails, NewBot returns the error immediately and the bot instance is not created. This prevents your application from starting with an invalid token or unreachable network conditions, allowing you to handle the configuration error before attempting to process updates or configure webhooks.

Does using WithHealthCheck make subsequent ID() or Username() calls faster?

Yes. The health check primes the sync.Once guard and caches the bot's ID and username in the Bot struct fields (myID, myUsername). Subsequent calls to bot.ID() or bot.Username() return these cached values without making additional API requests to Telegram, reducing latency and API quota usage.

Can I use a custom timeout for the Telego health check?

Absolutely. Pass a context with timeout to WithHealthCheck. For example, use context.WithTimeout(context.Background(), 5*time.Second) to ensure the health check fails fast if the Telegram API doesn't respond within five seconds, preventing indefinite blocking during initialization and allowing graceful degradation.

Is the health check required for all Telego bots?

No, the health check is optional. It is provided as a BotOption that you can pass to NewBot. However, it is highly recommended for production deployments to validate tokens and API connectivity early, avoiding runtime errors during message processing, webhook setup, or long polling initialization.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →