telegram-bot-api

repository·master·Indexed 27 days ago

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

Golang bindings for the Telegram Bot API (v5). This library provides a lightweight wrapper around the official API, supporting long polling via GetUpdatesChan and webhooks via ListenForWebhook. It includes tools for sending messages and media (PhotoConfig, AudioConfig, VideoConfig, etc.), managing chat members, and handling various update types. It provides implementations for file uploads via FileBytes, FileReader, FilePath, FileURL, and FileID.

Tokens
13.6K
Snippets
32
Records
107
Agent score
91%

What's inside telegram-bot-api

  1. Understand the library structure: Configs, Helpers, and Methods

    master

    The library is organized into three primary components to interact with the Telegram Bot API:

    1. Configs: Structs that represent the parameters for a specific Telegram endpoint. There is a one-to-one relationship between endpoints and configs. They typically follow the naming pattern of removing the send prefix from the endpoint name and adding a Config suffix (e.g., MessageConfig for sendMessage).

      • Configs implementing the Chattable interface can be used with methods requiring a chat ID.
      • Configs implementing the Fileable interface support file uploads.
    2. Helpers: Functions used to simplify the creation of Configs. They are generally named by replacing the send prefix of a method with New (e.g., NewMessage instead of sendMessage). These helpers typically require the minimum necessary parameters to succeed, allowing you to set additional optional fields on the returned struct.

    3. Methods: Functions used to execute the requests.

      • Request is the primary low-level method. It accepts a Chattable parameter and handles file uploads automatically. It returns an APIResponse.
      • Specific methods exist for endpoints with unique return types (e.g., getFile returns a File).
      • Most methods return a Message, which can be processed using Send.
  2. Specify files using RequestFileData types

    master

    Telegram supports multiple file formats. All file types in this library implement the RequestFileData interface, allowing you to use them interchangeably in API requests. The available types are:

    • FilePath: A local path to a file.
    • FileID: An existing file ID on Telegram's servers (reusable only by the same bot; thumbnail IDs 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 file data (not recommended for large files due to high memory usage).
  3. Upload static file fields in API requests

    master

    For most Telegram endpoints, you can upload files by providing them in a configuration struct. These are known as static fields. For example, sendPhoto expects a field named photo, and sendDocument expects document and optionally thumb.

    When implementing custom configurations that satisfy the Fileable interface, you must return a slice of RequestFile objects where the Name matches the expected Telegram field name and Data contains the file content (e.g., via tgbotapi.FilePath or tgbotapi.File).

    func (config DocumentConfig) files() []RequestFile {
        files := []RequestFile{{
            Name: "document",
            Data: config.File,
        }}
    
        if config.Thumb != nil {
            files = append(files, RequestFile{
                Name: "thumb",
                Data: config.Thumb,
            })
        }
    
        return files
    }
  4. Use Configs to parameterize Telegram requests

    master

    To interact with a Telegram endpoint, you must use its corresponding Config struct. These structs contain all the fields required for the request.

    • Naming Convention: If the endpoint is sendMessage, the config is MessageConfig.
    • Interfaces:
      • Use configs that implement Chattable when a chat context is required.
      • Use configs that implement Fileable when you need to upload files.
    • Execution: Once the config is populated, pass it to a method like Request to send it to the API.
  5. Use Helpers to construct Configs quickly

    master

    Instead of manually initializing a Config struct and setting all required fields, use Helper functions. Helpers ensure that the minimum required parameters for a successful request are provided immediately.

    • Naming Convention: Helpers are named by replacing the send prefix of the endpoint with New (e.g., NewMessage for the sendMessage endpoint).
    • Workflow:
      1. Call the helper with required arguments (e.g., NewMessage(chatID, text)).
      2. The helper returns a pointer to the specific Config struct.
      3. Set any additional optional fields on that struct.
      4. Pass the struct to a method to execute the request.