telegram-bot-api Golang Bindings

repository·master·Indexed 40 days ago

https://github.com/ovyflash/telegram-bot-api

Golang bindings for the Telegram Bot API providing complete API coverage with a simple interface and minimal dependencies. It supports both long polling via GetUpdatesChan and webhook integration, functional configuration options via NewBotAPIWithOptions, and comprehensive file handling through the RequestFileData interface. The library includes utilities for escaping text for HTML and Markdown modes, as well as high-level methods for sending content using Chattable objects.

Tokens
39.3K
Snippets
117
Records
190
Agent score
100%

What's inside telegram-bot-api

  1. Use BaseChat to simplify Chat configurations

    master

    Instead of manually defining fields like ChatID, ChannelUsername, ReplyToMessageID, ReplyMarkup, and DisableNotification for every message-related endpoint, you can embed the BaseChat struct into your custom configuration.

    Embedding BaseChat automatically provides these fields and its implementation of the params() method. You can then extend the params() method by calling the embedded base method first.

    type MessageConfig struct {
    	BaseChat
    	Text                  string
    	ParseMode             string
    	DisableWebPagePreview bool
    }
    
    func (config MessageConfig) params() (Params, error) {
    	params, err := config.BaseChat.params()
    	if err != nil {
    		return params, err
    	}
    
    	params.AddNonEmpty("text", config.Text)
    	return params, nil
    }
    type MessageConfig struct {
    	BaseChat
    	Text                  string
    	ParseMode             string
    	DisableWebPagePreview bool
    }
    
    func (config MessageConfig) params() (Params, error) {
    	params, err := config.BaseChat.params()
    	if err != nil {
    		return params, err
    	}
    
    	params.AddNonEmpty("text", config.Text)
    	// Add your other fields
    
    	return params, nil
    }
  2. Execute requests using Methods

    master

    Methods are the execution layer that sends your constructed Configs to the Telegram API.

    • Request: The primary low-level method. It accepts a Chattable parameter and automatically handles file uploads if the config implements Fileable. It returns an APIResponse.
    • Specific Methods: Many endpoints have specialized methods that return more specific types than a general APIResponse. For example:
      • getFile returns a File.
      • Most other methods return a Message.
    • Send: A utility used to obtain a Message from the response of various methods.

    Note: Avoid using MakeRequest. It is a low-level method that requires manual endpoint and parameter management and is intended for internal library use only.

  3. Use static file fields for simple uploads

    master

    For endpoints that expect a single file or a fixed set of files (e.g., sendPhoto or sendDocument), you can use static fields. The library maps these fields directly to the expected API field names.

    For example, sendDocument might use a document field and an optional thumbnail field. The library automatically determines if the provided value should be a string parameter or a multipart file part based on the type used (e.g., tgbotapi.FilePath vs tgbotapi.FileURL).

  4. Use Configs to structure Telegram API requests

    master

    Configs are structs containing the fields required for a specific Telegram endpoint.

    • Naming Pattern: They are named by removing the send prefix from the endpoint name and adding the Config suffix (e.g., sendMessage $\rightarrow$ MessageConfig).
    • Interfaces:
      • Configs that require a destination chat implement the Chattable interface.
      • Configs that support file uploads implement the Fileable interface.

    Use Configs when you need fine-grained control over every parameter in a request.

  5. Understand how file uploads are handled in the library

    master

    The library distinguishes between two types of file references when constructing requests to the Telegram Bot API:

    1. Non-uploaded files: If you provide a FileID, FileURL, or an existing attach:// reference, these are treated as regular string fields in the request parameters.
    2. Uploaded files: If you provide a FilePath, FileBytes, or FileReader, the library treats these as multipart file parts to be uploaded.

    When preparing a request, the library generates an 'upload plan' that synchronizes the JSON parameters with the multipart form data using the attach:// syntax.

  6. How to specify files in Telegram requests

    master

    Telegram supports multiple ways to specify files. All file types in this library implement the RequestFileData interface, allowing them to be used interchangeably in API methods that require file data.

    Available types include:

    • FilePath: A local path to a file on your filesystem.
    • FileID: An ID of a file already existing on Telegram's servers (reusable only by the same bot; thumbnails cannot be reused).
    • FileURL: A URL to a file (must be served with the correct MIME type).
    • FileReader: An io.Reader for lazy reading (recommended for memory efficiency).
    • FileBytes: A []byte containing the raw data (use with caution due to high memory usage).
    /* All file types implement the RequestFileData interface */
  7. Understand the relationship between Configs, Helpers, and Methods

    master

    The library follows a three-tier pattern for interacting with the Telegram Bot API:

    1. Configs: Structs that represent the payload for a specific Telegram endpoint (e.g., MessageConfig for sendMessage). They follow a naming convention where the send prefix is removed and the Config suffix is added.
    2. Helpers: Functions used to instantiate Configs quickly. They typically replace the send prefix with New (e.g., NewMessage instead of sendMessage). These return a Config struct that you can further customize.
    3. Methods: Functions used to execute the request. You pass a constructed Config to a Method to send it to Telegram.

    Workflow Example: Use a Helper to create a Config, then pass that Config to a Method to execute the request.

  8. Use Helpers to quickly construct Configs

    master

    Helpers provide a convenient way to initialize Configs with their mandatory parameters. This prevents errors caused by forgetting required fields like ChatID or Text.

    • Naming Pattern: Helpers are named after the corresponding method, but with send replaced by New (e.g., NewMessage for the sendMessage endpoint).
    • Usage: Call the helper with the required arguments to get a Config struct, then manually set any additional optional fields on that struct.
  9. Use dynamic fields and the attach:// syntax for media groups

    master

    Methods like sendMediaGroup require dynamic fields because each item in the group might be attached to a different field name. To handle this, the library uses the attach:// syntax.

    When you provide media objects (like InputMediaPhoto) containing uploadable files, the library:

    1. Clones the media objects to avoid mutating your original data.
    2. Rewrites uploadable file fields to a reference like attach://file-%d (where %d is an index).
    3. Maps these references to multipart parts in the request using the matching field name (e.g., file-0).

    This ensures the JSON payload and the multipart files remain synchronized.

    // Create media with a local file
    photo := tgbotapi.NewInputMediaPhoto(tgbotapi.FilePath("tests/image.jpg"))
    
    // Create media with a URL (will be sent as a string, not uploaded)
    url := tgbotapi.NewInputMediaPhoto(tgbotapi.FileURL("https://i.imgur.com/unQLJIb.jpg"))
    
    // Create the media group
    mediaGroup := NewMediaGroup(ChatID, []interface{}{
        photo,
        url,
    })
  10. Moderate Reactions

    master

    Admin bots can manage reactions on messages:

    • Remove a specific reaction: Use tgbotapi.NewDeleteMessageReaction(chatID, messageID) and optionally specify a UserID to target a specific user's reaction.
    • Clear recent reactions: Use tgbotapi.NewDeleteAllMessageReactions(chatID) and optionally specify a UserID to clear recent reactions from a user or actor in the chat.
    // Remove a specific user's reaction
    reaction := tgbotapi.NewDeleteMessageReaction(chatID, messageID)
    reaction.UserID = userID
    _, err := bot.DeleteMessageReaction(reaction)
    
    // Clear all recent reactions for a user
    clearRecent := tgbotapi.NewDeleteAllMessageReactions(chatID)
    clearRecent.UserID = userID
    err = bot.DeleteAllMessageReactions(clearRecent)