Overview
The Telegram Bot integration allows you to send messages, notifications, and alerts to a Telegram chat. This is useful for monitoring your application, receiving error alerts, and tracking important events in real-time.
This integration is optional and simple to set up. It’s recommended for development and monitoring purposes.
Prerequisites
- A Telegram account
- Create a bot using @BotFather
- Get your bot token from BotFather
- Get your chat ID (see instructions below)
Setting Up Your Telegram Bot
Step 1: Create a Bot
- Open Telegram and search for @BotFather
- Send
/newbot command
- Follow the prompts to choose a name and username
- BotFather will give you a bot token (looks like
123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ)
Step 2: Get Your Chat ID
- Send a message to your bot in Telegram
- Visit:
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates
- Look for the
chat.id field in the JSON response
- Copy your chat ID (it’s a number like
123456789)
Alternatively, use @userinfobot:
- Send
/start to @userinfobot
- It will reply with your user ID (this is your chat ID)
Add these to your .env file:
TELEGRAM_BOT_ID=your_bot_token_here
TELEGRAM_CHAT_ID=your_chat_id_here
Example:
TELEGRAM_BOT_ID=123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ
TELEGRAM_CHAT_ID=987654321
Available Functions
Send Message
func SendTelegramMessage(message string)
Sends a text message to the configured Telegram chat.
Parameters:
message - The text message to send (supports Unicode and emojis)
Returns:
- No return value (fire-and-forget)
- Errors are logged but don’t stop execution
Example:
import "backend/integrations"
// Send a simple notification
integrations.SendTelegramMessage("Server started successfully!")
// Send an error alert
integrations.SendTelegramMessage("ERROR: Database connection failed")
// Send formatted message
msg := fmt.Sprintf("New user registered: %s (%s)", user.Name, user.Email)
integrations.SendTelegramMessage(msg)
Use Cases
1. Error Notifications
Get immediate alerts when errors occur:
func ProcessPayment(c echo.Context) error {
result, err := processPayment(data)
if err != nil {
// Alert team immediately
msg := fmt.Sprintf("Payment processing failed: %v", err)
integrations.SendTelegramMessage(msg)
log.Printf("Payment error: %v", err)
return c.JSON(http.StatusInternalServerError, map[string]string{
"error": "Payment failed",
})
}
return c.JSON(http.StatusOK, result)
}
2. User Activity Monitoring
Track important user actions:
func RegisterUser(c echo.Context) error {
// ... registration logic ...
// Notify about new signup
msg := fmt.Sprintf("New user: %s (%s)", user.Name, user.Email)
integrations.SendTelegramMessage(msg)
return c.JSON(http.StatusCreated, user)
}
3. System Health Checks
Send periodic health status:
func StartHealthMonitor() {
ticker := time.NewTicker(1 * time.Hour)
defer ticker.Stop()
for range ticker.C {
// Check database
if !isDatabaseHealthy() {
integrations.SendTelegramMessage("WARNING: Database health check failed")
}
// Check external services
if !areServicesHealthy() {
integrations.SendTelegramMessage("WARNING: External service unavailable")
}
}
}
4. Critical Transaction Alerts
Monitor high-value transactions:
func ProcessTransaction(amount int, user string) {
if amount > 1000000 { // Alert for transactions over 1M
msg := fmt.Sprintf("High-value transaction: %d RWF by %s", amount, user)
integrations.SendTelegramMessage(msg)
}
// ... process transaction ...
}
5. Deployment Notifications
Notify when the app starts:
func main() {
// ... setup code ...
// Notify on startup
env := configs.AppEnv()
msg := fmt.Sprintf("Application started in %s mode", env)
integrations.SendTelegramMessage(msg)
// Start server
e.Logger.Fatal(e.Start(":8080"))
}
Telegram supports basic text formatting:
// Bold text (using Unicode)
msg := "*Important:* Server restarted"
integrations.SendTelegramMessage(msg)
// Emojis
msg := "✅ Payment successful"
integrations.SendTelegramMessage(msg)
msg := "❌ Authentication failed"
integrations.SendTelegramMessage(msg)
msg := "⚠️ Warning: High CPU usage"
integrations.SendTelegramMessage(msg)
// Multiline messages
msg := `Server Status:
✅ Database: Connected
✅ Redis: Connected
⚠️ CPU: 85%`
integrations.SendTelegramMessage(msg)
URL encoding is automatically handled by the HTTP client. You can include special characters and spaces in your messages.
Error Handling
The function logs errors but doesn’t return them to avoid disrupting your application flow:
func SendTelegramMessage(message string) {
url := "https://api.telegram.org/bot" + configs.TelegramBotId() + "/sendMessage?chat_id=" + configs.TelegramChatID() + "&text=" + message
_, err := http.Get(url)
if err != nil {
log.Printf("Error sending telegram message: %v", err)
}
}
If sending fails (e.g., network issues), the error is logged but your application continues normally.
Advanced: Group Notifications
To send messages to a group chat:
- Add your bot to a Telegram group
- Get the group chat ID using the same method as above
- Use the group chat ID in your
.env file
Note: Group chat IDs are negative numbers (e.g., -123456789)
Advanced: Custom Notification Helper
Create a helper for common notification patterns:
package notifications
import (
"backend/integrations"
"fmt"
)
func NotifyError(context string, err error) {
msg := fmt.Sprintf("❌ ERROR in %s: %v", context, err)
integrations.SendTelegramMessage(msg)
}
func NotifySuccess(message string) {
msg := fmt.Sprintf("✅ %s", message)
integrations.SendTelegramMessage(msg)
}
func NotifyWarning(message string) {
msg := fmt.Sprintf("⚠️ WARNING: %s", message)
integrations.SendTelegramMessage(msg)
}
func NotifyInfo(message string) {
msg := fmt.Sprintf("ℹ️ %s", message)
integrations.SendTelegramMessage(msg)
}
Usage:
import "backend/notifications"
// In your handlers
notifications.NotifyError("payment processing", err)
notifications.NotifySuccess("User registered successfully")
notifications.NotifyWarning("Database connection slow")
notifications.NotifyInfo("Scheduled backup started")
Rate Limiting
Telegram Bot API has rate limits:
- 30 messages per second to different users
- 1 message per second to the same user/group
For high-frequency notifications, consider:
- Batching messages
- Using a queue
- Aggregating alerts
Example with batching:
type NotificationBatcher struct {
messages []string
ticker *time.Ticker
}
func (nb *NotificationBatcher) Add(msg string) {
nb.messages = append(nb.messages, msg)
}
func (nb *NotificationBatcher) Start() {
nb.ticker = time.NewTicker(5 * time.Second)
go func() {
for range nb.ticker.C {
if len(nb.messages) > 0 {
combined := strings.Join(nb.messages, "\n")
integrations.SendTelegramMessage(combined)
nb.messages = nil
}
}
}()
}
Best Practices
- Don’t spam: Only send important notifications
- Use emojis: Make messages easier to scan
- Include context: Add timestamps, user IDs, or request IDs
- Test in development: Use a separate bot for dev/prod
- Handle errors gracefully: Don’t let Telegram failures crash your app
- Batch when possible: Reduce API calls
- Use environment-specific bots: Different bots for staging/production
Testing
Test your integration:
func TestTelegramIntegration(c echo.Context) error {
integrations.SendTelegramMessage("Test message from Go React Scaffold")
return c.JSON(http.StatusOK, map[string]string{
"message": "Test message sent - check your Telegram",
})
}
Add this route temporarily:
e.GET("/test/telegram", TestTelegramIntegration)
Visit http://localhost:8080/test/telegram and check your Telegram chat.
Troubleshooting
Messages not arriving
- Verify bot token is correct
- Verify chat ID is correct
- Make sure you’ve sent
/start to your bot first
- Check logs for error messages
- Test with curl:
curl "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/sendMessage?chat_id=<YOUR_CHAT_ID>&text=Test"
Invalid chat ID error
- Chat ID must be a number (no quotes in .env)
- For groups, use negative chat ID
- Send a message to the bot first to activate it
Security Considerations
Keep your bot token secret! Anyone with your token can send messages as your bot.
- Never commit
.env file with real tokens
- Don’t log the bot token
- Rotate tokens if compromised
- Use different bots for dev/staging/prod
- Limit who has access to the Telegram chat
Alternatives
If you need more features, consider:
- Full Telegram Bot SDK: For interactive bots with commands and callbacks
- Slack Integration: Similar concept, different platform
- Email Alerts: For less urgent notifications
- SMS: For critical alerts
Support