gotgbot

repository·v2·Indexed 20 days ago

https://github.com/paulsonoflars/gotgbot

A type-safe, code-generated Golang wrapper for the Telegram Bot API. Designed to be lightweight using only the standard library, it provides high concurrency by processing updates in individual goroutines. The library includes support for webhooks, stateful bot implementations using structs, conversation handlers, and middleware for intercepting API requests.

Tokens
76.2K
Snippets
256
Records
349
Agent score
72%

What's inside gotgbot

  1. Overview of available sample bots

    v2

    The samples/ directory contains several specialized bot implementations to serve as learning resources:

    SamplePurpose
    callbackqueryBotDemonstrates handling Telegram callback queries (e.g., button presses) and editing messages via callbacks.
    commandBotDemonstrates handling Telegram commands (e.g., /start, /source).
    conversationBotDemonstrates stateful conversation handlers for multi-step interactions.
    echoBotA basic bot that repeats input; includes examples of implementing the gotgbot.BotClient interface for testing.
    echoMultiBotDemonstrates running multiple bot instances simultaneously and using Updater.Stop() for graceful shutdown.
    echoWebhookBotDemonstrates bot operation via webhooks instead of long polling.
    inlinequeryBotDemonstrates basic inline query functionality.
    metricsBotShows how to collect Prometheus metrics from the dispatcher and bot client.
    middlewareBotDemonstrates using middlewares to intercept and modify API requests.
    paymentsBotDemonstrates Telegram's in-app purchase methods (Invoices, Checkouts) using Telegram Stars.
    statefulClientBotDemonstrates using structs with methods to pass dependencies (DB, cache) to handlers without global variables.
    webappBotDemonstrates serving a WebApp and using the updater's handler within a user-provided server.
  2. Implement a stateful bot using structs

    v2
    Instead of using global variables or changing function signatures to pass data to handlers, you can use a struct with methods. This allows the bot client to store and access dependencies like database clients, cache clients, or in-memory clients across all handlers. This pattern is demonstrated in the statefulClientBot sample.
  3. Use middlewares to intercept API requests

    v2

    Middlewares can be used to modify or intercept HTTP requests sent to the Telegram Bot API server. For example, you can use middleware to:

    • Set specific parameters (like allow_sending_without_reply) for certain methods.
    • Log all error messages returned by the API.

    This pattern is demonstrated in the middlewareBot sample.

  4. Implement conversation handlers for stateful interactions

    v2
    Conversation handlers allow you to track states across multiple messages from a single user. This is useful for multi-step workflows, such as asking a user for their name and then their age in sequence. This pattern is demonstrated in the conversationBot sample.
  5. Set up a Telegram WebApp bot

    v2

    WebApps require a running webserver and an HTTPS domain. You can use ngrok to facilitate local development.

    1. Start an ngrok tunnel: ngrok http 8080
    2. Copy the HTTPS URL provided by ngrok.
    3. Run the bot using the following command: URL="<your_url_here>" TOKEN="<your_token_here>" go run .

    Replace <your_url_here> with your ngrok HTTPS URL and <your_token_here> with your Telegram Bot Token.

    URL="<your_url_here>" TOKEN="<your_token_here>" go run .
  6. Set up a Telegram Bot using Webhooks

    v2

    To run a bot using webhooks instead of long polling, you need a running webserver and an HTTPS domain. For local development, it is recommended to use a tool like ngrok to expose your local port to the internet.

    1. Install ngrok and start a tunnel to your local port (e.g., 8080): ngrok http 8080
    2. Copy the HTTPS URL provided by ngrok.
    3. Run the bot by providing the required environment variables: TOKEN="<your_token_here>" WEBHOOK_DOMAIN="<your_domain_here>" WEBHOOK_SECRET="<random_string_here>" go run .

    Replace <your_domain_here> with the HTTPS URL obtained from ngrok.

    TOKEN="<your_token_here>" WEBHOOK_DOMAIN="<your_domain_here>" WEBHOOK_SECRET="<random_string_here>" go run .
  7. Explore example bot implementations

    v2

    The repository provides several sample bots in the ./samples directory to demonstrate different patterns:

    • Command Bot: Demonstrates basic command handling.
    • Webhook Bot: Shows how to set up webhooks for receiving updates.
    • Stateful Client Bot: Demonstrates how to pass shared data through the bot lifecycle without relying on global variables.
  8. Regenerate the library code from the API specification

    v2

    The library's types and methods are code-generated from a Telegram Bot API specification. If you need to regenerate the code based on the currently pinned commit in the spec_commit file, run go generate from the repository root.

    To upgrade to the latest available version by fetching the newest commit SHA from the specification repository and then regenerating, use the GOTGBOT_UPGRADE=true environment variable.

    # Regenerate using the currently pinned commit
    go generate
    
    # Upgrade to the latest specification commit and regenerate
    GOTGBOT_UPGRADE=true go generate
  9. Use MergedBackgroundType for simplified background type access

    v2

    The MergedBackgroundType struct is a helper designed to simplify interactions with various BackgroundType subtypes. Instead of type-casting, you can use this struct to access all potential background properties.

    Fields in MergedBackgroundType:

    • Type: The type of background (fill, wallpaper, pattern, or chat_theme).
    • Fill: The BackgroundFill (Only for fill, pattern).
    • DarkThemeDimming: 0-100 percentage (Only for fill, wallpaper).
    • Document: The Document used (Only for wallpaper, pattern).
    • IsBlurred: Whether the wallpaper is blurred (Only for wallpaper).
    • IsMoving: Whether the background moves on tilt (Only for wallpaper, pattern).
    • Intensity: 0-100 intensity (Only for pattern).
    • IsInverted: Whether the fill is applied only to the pattern (Only for pattern).
    • ThemeName: The name of the chat theme (Only for chat_theme).
  10. How InputPollOptionMedia works

    v2

    The InputPollOptionMedia interface represents the media attached to a poll option. It can be one of the following types:

    • InputMediaAnimation
    • InputMediaLink
    • InputMediaLivePhoto
    • InputMediaLocation
    • InputMediaPhoto
    • InputMediaSticker
    • InputMediaVenue
    • InputMediaVideo
  11. Handle MessageOrigin using MergedMessageOrigin

    v2

    The MessageOrigin interface describes where a message originated. Because it is an interface with multiple subtypes (MessageOriginUser, MessageOriginHiddenUser, MessageOriginChat, MessageOriginChannel), the library provides a MergedMessageOrigin helper struct to simplify access in a non-generic way.

    Instead of type-asserting the interface, call .MergeMessageOrigin() on any MessageOrigin instance to get a flat struct containing all possible fields.

    MergedMessageOrigin fields:

    • Type: The origin type (user, hidden_user, chat, or channel).
    • Date: Unix timestamp of the original message.
    • SenderUser: (Optional) The User if type is user.
    • SenderUserName: (Optional) The name if type is hidden_user.
    • SenderChat: (Optional) The Chat if type is chat.
    • AuthorSignature: (Optional) Signature for chat or channel origins.
    • Chat: (Optional) The Chat if type is channel.
    • MessageId: (Optional) The message ID if type is channel.
    // Example of using the merge helper
    origin := message.MessageOrigin.MergeMessageOrigin()
    if origin.GetType() == "user" {
        fmt.Printf("Sent by: %s", origin.SenderUser.FirstName)
    }