How to Validate Telego Bot Token Format: Regex Rules and Go Implementation
Telego validates bot tokens using the regular expression ^\d+:[\w-]{35}$, which requires a numeric bot ID followed by a colon and exactly 35 alphanumeric characters, hyphens, or underscores.
The Telego library enforces strict token format validation immediately when you instantiate a new bot. This validation logic, implemented in bot.go, prevents runtime errors by rejecting malformed tokens before any network requests are made to the Telegram Bot API.
Telego Token Validation Logic in bot.go
The Token Regular Expression Pattern
The validation relies on a compiled regular expression defined at line 26 of bot.go:
const tokenRegexp = `^\d+:[\w-]{35}$`
This pattern enforces three specific rules:
^\d+:– The token must start with one or more digits representing the bot ID, followed by a literal colon.[\w-]{35}– After the colon, exactly 35 characters from the set[A-Za-z0-9_-](letters, digits, underscores, or hyphens).$– The string must end immediately after the 35th character; no additional characters are permitted.
The validateToken Function
The internal validateToken function, located at lines 39-43 in bot.go, applies this regex:
func validateToken(token string) bool {
return regexp.MustCompile(tokenRegexp).MatchString(token)
}
This function is unexported (lowercase) and used internally by the library. It returns true only when the supplied string matches the tokenRegexp pattern exactly.
How NewBot Validates Tokens Automatically
Validation Flow in NewBot
The NewBot constructor at lines 93-99 of bot.go implements a two-stage validation process:
if token == "" {
return nil, ErrEmptyToken
}
if !validateToken(token) {
return nil, ErrInvalidToken
}
When you call telego.NewBot(token), the function first checks for an empty string and returns ErrEmptyToken if found. If the token is non-empty but fails the regex validation, it returns ErrInvalidToken. Only tokens passing both checks proceed to bot instantiation.
Error Handling Example
Handle specific validation errors when creating a bot:
package main
import (
"errors"
"fmt"
"log"
"github.com/mymmrac/telego"
)
func main() {
token := "invalid-token-format"
bot, err := telego.NewBot(token)
if err != nil {
if errors.Is(err, telego.ErrEmptyToken) {
log.Fatal("Token cannot be empty")
}
if errors.Is(err, telego.ErrInvalidToken) {
log.Fatal("Token must match the format: digits:35-character-key")
}
log.Fatal(err)
}
fmt.Println("Bot created successfully")
}
Manual Token Validation Methods
Replicating the Regex Pattern
Since validateToken is unexported, you can replicate the validation using the same regular expression pattern:
package main
import (
"regexp"
)
const tokenRegexp = `^\d+:[\w-]{35}$`
func IsValidToken(token string) bool {
return regexp.MustCompile(tokenRegexp).MatchString(token)
}
This implementation mirrors the logic in bot.go and ensures your pre-validation checks align with the library's requirements.
Pre-validation Before Bot Creation
Validate tokens before attempting instantiation to avoid unnecessary error handling:
package main
import (
"fmt"
"regexp"
"github.com/mymmrac/telego"
)
const tokenRegexp = `^\d+:[\w-]{35}$`
func validateTokenFormat(token string) bool {
return regexp.MustCompile(tokenRegexp).MatchString(token)
}
func main() {
token := "123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi"
if !validateTokenFormat(token) {
fmt.Println("❌ Invalid token format")
return
}
bot, err := telego.NewBot(token)
if err != nil {
panic(err)
}
fmt.Println("✅ Bot token validated and bot created:", bot.Token())
}
Summary
- Telego enforces strict token validation using the regular expression
^\d+:[\w-]{35}$defined inbot.go. - Automatic validation occurs in
NewBotat lines 93-99, which returnsErrEmptyTokenfor empty strings orErrInvalidTokenfor malformed formats. - The token pattern requires a numeric bot ID, a colon separator, and exactly 35 characters from the set
[A-Za-z0-9_-]. - Manual validation can be implemented using the same regex pattern when you need to check tokens before instantiating a
Bot.
Frequently Asked Questions
What regular expression does Telego use to validate bot tokens?
Telego uses ^\d+:[\w-]{35}$, which matches strings starting with one or more digits, followed by a colon, and ending with exactly 35 characters from the class [A-Za-z0-9_-]. This pattern is compiled in bot.go and applied by the internal validateToken function.
What happens if I pass an invalid token to NewBot?
If you pass an empty string, NewBot returns nil and ErrEmptyToken. If you pass a non-empty string that fails the regex validation, it returns nil and ErrInvalidToken. In both cases, no Bot instance is created, preventing runtime API errors.
Can I validate a token without creating a Bot instance?
Yes, but you must implement the validation manually since validateToken is unexported. Copy the regular expression ^\d+:[\w-]{35}$ from bot.go and use regexp.MustCompile to match against your token string before calling NewBot.
Where are the token validation tests located in the repository?
The unit tests for token validation are located in bot_test.go, specifically in the Test_validateToken function and related test cases for NewBot error handling. These tests verify that the regex correctly accepts valid tokens and rejects malformed ones, empty strings, and edge cases.
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 →