How to Initialize a Telego Bot with a Token: A Complete Guide
Initializing a Telego bot requires passing a valid Telegram bot token to telego.NewBot(), which validates the token format and returns a configured *Bot instance that you can enhance with functional options like debug loggers or custom HTTP clients.
The mymmrac/telego library provides a robust Go interface to the Telegram Bot API. When you initialize a Telego bot with a token, the constructor handles validation, sets up default components for HTTP communication, and applies any customization options you provide. This process ensures your bot is ready to send and receive messages immediately after initialization.
Understanding the NewBot Constructor
The NewBot function in main/bot.go serves as the primary entry point for bot initialization. It implements a functional options pattern that allows flexible configuration while enforcing strict token validation.
Token Validation
Before allocating any resources, NewBot invokes the internal validateToken function to verify that your token matches Telegram's required format. The validation uses the regular expression ^\d+:[\w-]{35}$, which ensures the token consists of numeric digits, a colon, and exactly 35 alphanumeric characters or hyphens. This check occurs at lines 39-44 in main/bot.go.
Default Components
Once validation passes, the constructor allocates a Bot struct with sensible defaults:
- Token: The validated token string
- API Server URL:
https://api.telegram.org - Logger: A default logger that masks the token for security (
newDefaultLogger) - HTTP Caller:
FastHTTPCallerfor high-performance requests - Request Constructor:
ta.DefaultConstructorfor building API payloads
This initialization happens in the struct literal at lines 101-107 of main/bot.go.
Applying Bot Options
After establishing defaults, NewBot iterates through all provided BotOption functions and applies them sequentially. This loop at lines 109-113 allows you to override any default component, such as replacing the HTTP client or enabling debug logging.
Token Requirements and Validation
Telegram bot tokens follow a strict format that Telego enforces during initialization. The token must:
- Start with numeric digits representing the bot ID
- Contain a colon separator
- End with exactly 35 characters consisting of letters, numbers, or hyphens
If your token fails this validation, NewBot returns an error immediately, preventing initialization with malformed credentials. This validation logic is defined in main/bot.go within the validateToken helper function.
Configuration Options for Initialization
The bot_options.go file defines the BotOption type and numerous helper functions that customize bot behavior during initialization. These options use the functional options pattern to keep the API clean while providing extensive flexibility.
Debug Logging
The WithDefaultDebugLogger() option replaces the default token-masking logger with one that prints detailed request and response information. This is essential during development for troubleshooting API interactions.
Custom HTTP Clients
You can replace the default FastHTTPCaller with alternative implementations using either WithAPICaller(customCaller) for complete control over the HTTP layer, or WithHTTPClient(customHTTPClient) for simpler cases where you only need to adjust timeouts or transport settings.
Custom API Servers
The WithAPIServer(url) option redirects requests to a custom Telegram Bot API server instance. This is useful when running the Bot API locally for higher file size limits or lower latency.
Code Examples
Minimal Initialization
The simplest way to initialize a Telego bot requires only the token:
package main
import (
"log"
"github.com/mymmrac/telego"
)
func main() {
bot, err := telego.NewBot("123456789:ABCdefGhIJKlmNoPQRstuVWXyz1234567")
if err != nil {
log.Fatal(err)
}
// Bot is ready to use
_ = bot
}
With Debug Logging
Following the pattern from examples/basic/main.go, you should enable debug logging during development:
package main
import (
"log"
"os"
"github.com/mymmrac/telego"
)
func main() {
bot, err := telego.NewBot(
os.Getenv("TOKEN"),
telego.WithDefaultDebugLogger(),
)
if err != nil {
log.Fatal(err)
}
// Use the bot...
_ = bot
}
With Custom HTTP Client and API Server
For production environments requiring specific timeouts or proxy configurations:
package main
import (
"net/http"
"time"
"github.com/mymmrac/telego"
)
func main() {
customHTTP := &http.Client{
Timeout: 10 * time.Second,
}
bot, err := telego.NewBot(
"123456789:ABCdefGhIJKlmNoPQRstuVWXyz1234567",
telego.WithHTTPClient(customHTTP),
telego.WithAPIServer("https://my-proxy.example.com"),
)
if err != nil {
panic(err)
}
_ = bot
}
Verifying the Connection
After initialization, verify the bot is properly configured by calling the GetMe method:
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/mymmrac/telego"
)
func main() {
bot, err := telego.NewBot(os.Getenv("TOKEN"), telego.WithDefaultDebugLogger())
if err != nil {
log.Fatal(err)
}
me, err := bot.GetMe(context.Background())
if err != nil {
log.Fatal("Failed to get bot info:", err)
}
fmt.Printf("Bot initialized successfully: @%s (ID: %d)\n", me.Username, me.ID)
}
Summary
- Use
telego.NewBot()to initialize a Telego bot with a token, located inmain/bot.go. - Token validation occurs automatically using the regex
^\d+:[\w-]{35}$to ensure Telegram compatibility. - Default components include
FastHTTPCaller, a token-masking logger, and the standard Telegram API server URL. - Functional options defined in
bot_options.goallow customization of loggers, HTTP clients, and API endpoints without breaking the API. - Always handle errors returned by
NewBot()to catch invalid tokens or configuration issues before runtime.
Frequently Asked Questions
What happens if I pass an invalid token to NewBot?
NewBot returns an error immediately without allocating the bot instance. The internal validateToken function checks that your token matches the required format ^\d+:[\w-]{35}$ (digits, colon, 35 alphanumeric characters). If your token is empty, malformed, or contains invalid characters, the function returns an error before any network components are initialized.
Can I change the HTTP client after initializing the bot?
No, the HTTP client must be configured during initialization using the WithHTTPClient() or WithAPICaller() options in bot_options.go. The Bot struct stores the caller implementation as a private field set during construction. If you need different timeout settings or transport configurations, you must create a new bot instance with the updated client options.
How do I enable debug logging to see API requests?
Pass telego.WithDefaultDebugLogger() as an option to NewBot(). This replaces the default logger (which masks the token for security) with a debug implementation that prints detailed request and response information, including HTTP methods, URLs, and payload data. This option is defined in bot_options.go and is recommended for development environments only.
Is it possible to use a local Telegram Bot API server instead of the cloud?
Yes, use the WithAPIServer(url) option when calling NewBot(). This option overrides the default https://api.telegram.org endpoint with your custom URL, such as http://localhost:8081 for a local Bot API server instance. This is useful for handling larger file uploads or reducing latency when running the bot infrastructure geographically close to the API server.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →