telego Documentation

repository·main·Indexed 22 days ago

https://github.com/mymmrac/telego

A high-performance Golang library for interacting with the Telegram Bot API. Telego provides a one-to-one mapping of official Telegram types and methods, utilizing fasthttp and go-json by default for optimized performance. It includes support for long polling, webhooks, a predicate-based handler system via the telegohandler package, and utility helpers in the telegoutil package for easier parameter construction.

Tokens
35.1K
Snippets
139
Records
176
Agent score
76%

What's inside telego

  1. Overview of Telego

    main

    Telego is a Telegram Bot API library for Golang that provides a one-to-one implementation of the official Telegram Bot API. It aims to mirror the actual Telegram Bot API's types and methods exactly.

    Key technical details:

    • Core types and methods are defined in types.go and methods.go.
    • By default, it uses fasthttp instead of net/http and go-json instead of encoding/json for high performance, though these can be changed.
  2. Use telegoutil for easier parameter construction

    main

    The telegoutil package (aliased as tu) provides helper functions to simplify the creation of complex Telegram parameter structs.

    Common utility methods include:

    • Message(chatID, text) => SendMessageParams
    • Photo(chatID, photoFile) => SendPhotoParams
    • Location(chatID, latitude, longitude) => SendLocationParams
    • ID(intID) => ChatID
    • File(namedReader) => InputFile

    Utility sub-packages:

    • telegoutil/methods: Methods helpers
    • telegoutil/types: Types helpers
    • telegoutil/handler: Handler helpers
    • telegoutil/api: API helpers
    import tu "github.com/mymmrac/telego/telegoutil"
    
    // Example usage:
    msg := tu.Message(
    	tu.ID(123),
    	"Hello World",
    )
  3. Use Middleware and Groups in Bot Handlers

    main

    Telego's handler system supports middleware and groups:

    • Middleware: Functions that wrap handlers. Global middleware is applied to all updates in the order it was added. Use ctx.Next(update) to pass the update to the next handler.
    • Groups: You can create groups of handlers that share a common predicate. Middleware can also be attached to specific groups.
    • Execution Flow: Updates are checked by groups first, then by handlers (group -> ... -> group -> handler).
    // Global middleware
    bh.Use(func(ctx *th.Context, update telego.Update) error {
    	fmt.Println("Global middleware")
    	return ctx.Next(update)
    })
    
    // Group with predicate and group-specific middleware
    task := bh.Group(th.TextContains("task"))
    task.Use(func(ctx *th.Context, update telego.Update) error {
    	fmt.Println("Group-based middleware")
    	return ctx.Next(update)
    })
    
    // Handler within the group
    task.HandleMessage(func(ctx *th.Context, message telego.Message) error {
    	fmt.Println("Task handled")
    	return nil
    })
  4. Use Telegram Methods

    main

    Telego provides access to all Telegram Bot API methods. Methods follow the pattern <MethodName> and accept a parameter struct named <MethodName>Params. If a method has optional parameters, you can pass nil for the parameter struct.

    // Example: Sending a message using the SendMessage method
    // and telegoutil for easier parameter construction.
    import (
    	"context"
    	"github.com/mymmrac/telego"
    	tu "github.com/mymmrac/telego/telegoutil"
    )
    
    // ... inside main
    // bot.SendMessage(ctx, tu.Message(tu.ID(chatID), "text"))
  5. Use Bot Handlers for processing updates

    main

    Instead of manually looping through updates, you can use the telegohandler package (aliased as th) to register handlers based on predicates.

    Key features:

    • Predicates: Define conditions for a handler to trigger (e.g., th.CommandEqual("start"), th.AnyCommand()).
    • Ordering: Handlers are checked in the order they are registered. More specific predicates should be registered before general ones.
    • Parallelism: All handlers (but not their predicates) are processed in parallel.
    • Specific Handlers: You can use specialized handlers like HandleMessage or HandleCallbackQuery for cleaner code.
    package main
    
    import (
    	"context"
    	"os"
    
    	"github.com/mymmrac/telego"
    	th "github.com/mymmrac/telego/telegohandler"
    	tu "github.com/mymmrac/telego/telegoutil"
    )
    
    func main() {
    	ctx := context.Background()
    	bot, _ := telego.NewBot(os.Getenv("TOKEN"))
    	updates, _ := bot.UpdatesViaLongPolling(ctx, nil)
    
    	// Create bot handler
    	bh, _ := th.NewBotHandler(bot, updates)
    	defer bh.Stop()
    
    	// Register a handler for the /start command
    	bh.Handle(func(ctx *th.Context, update telego.Update) error {
    		return nil
    	}, th.CommandEqual("start"))
    
    	// Start handling
    	_ = bh.Start()
    }
  6. Get Updates via Webhook

    main

    Webhooks are the recommended way to receive updates in production. This involves:

    1. Setting the webhook on the Telegram side using bot.SetWebhook with a SetWebhookParams object containing your URL and SecretToken.
    2. Creating an HTTP server (e.g., using http.NewServeMux).
    3. Using bot.UpdatesViaWebhook with telego.WebhookHTTPServeMux to link the Telegram webhook to your HTTP mux.

    For local testing, tools like Ngrok can be used to tunnel your localhost to a public URL.

    package main
    
    import (
    	"context"
    	"net/http"
    	"os"
    
    	"github.com/mymmrac/telego"
    )
    
    func main() {
    	ctx := context.Background()
    	botToken := os.Getenv("TOKEN")
    
    	bot, err := telego.NewBot(botToken)
    	if err != nil {
    		os.Exit(1)
    	}
    
    	// Set up a webhook on Telegram side
    	_ = bot.SetWebhook(ctx, &telego.SetWebhookParams{
    		URL:         "https://example.com/bot",
    		SecretToken: bot.SecretToken(),
    	})
    
    	// Create http serve mux
    	mux := http.NewServeMux()
    
    	// Get an update channel from webhook
    	updates, _ := bot.UpdatesViaWebhook(ctx, telego.WebhookHTTPServeMux(mux, "/bot", bot.SecretToken()))
    
    	// Start server for receiving requests
    	go func() {
    		_ = http.ListenAndServe(":443", mux)
    	}()
    
    	for update := range updates {
    		// Process update
    	}
    }
  7. Maintain security by using the latest Telego version

    main
    Telego only supports the latest version. To ensure you have the most recent security patches and bug fixes, always update to the latest version of the library. Older versions are not supported and will not receive security patches.
  8. Basic Bot Setup

    main

    To initialize a bot, use telego.NewBot with your Telegram Bot token. You can optionally enable debugging information using telego.WithDefaultDebugLogger(). Note that the default logger may expose sensitive information and should only be used during development.

    After initialization, you can call Telegram methods like GetMe to verify the bot's identity.

    package main
    
    import (
    	"context"
    	"fmt"
    	"os"
    
    	"github.com/mymmrac/telego"
    )
    
    func main() {
    	// Get Bot token from environment variables
    	botToken := os.Getenv("TOKEN")
    
    	// Create bot and enable debugging info
    	bot, err := telego.NewBot(botToken, telego.WithDefaultDebugLogger())
    	if err != nil {
    		fmt.Println(err)
    		os.Exit(1)
    	}
    
    	// Call method getMe
    	botUser, err := bot.GetMe(context.Background())
    	if err != nil {
    		fmt.Println("Error:", err)
    	}
    
    	// Print Bot information
    	fmt.Printf("Bot user: %+v\n", botUser)
    }
  9. Get Updates via Long Polling

    main

    Long polling is the easiest method for receiving updates, making it ideal for local testing. Use bot.UpdatesViaLongPolling to get a channel of updates.

    package main
    
    import (
    	"context"
    	"os"
    
    	"github.com/mymmrac/telego"
    )
    
    func main() {
    	botToken := os.Getenv("TOKEN")
    	bot, err := telego.NewBot(botToken)
    	if err != nil {
    		os.Exit(1)
    	}
    
    	// Get updates channel
    	updates, _ := bot.UpdatesViaLongPolling(context.Background(), nil)
    
    	// Loop through all updates when they came
    	for update := range updates {
    		// Process update
    	}
    }
  10. Configure JSON encoding/decoding

    main

    Telego allows you to choose different JSON encoding/decoding libraries via Go build tags:

    • No tags: Uses goccy/go-json (default).
    • sonic: Uses bytedance/sonic (high performance, but check platform compatibility).
    • stdjson: Uses the standard encoding/json library.

    You can also set custom marshal/unmarshal methods globally using SetJSONMarshal and SetJSONUnmarshal.