Skip to main content

Event System Overview

Gogram is built on an event-driven architecture. Instead of polling Telegram manually, the library listens for updates and dispatches them to registered handler functions.

Basic Usage

The primary way to handle updates is through the client.On() method, which uses flexible pattern matching.
// Basic message handler
client.On("message", func(m *telegram.NewMessage) error {
    m.Reply("Received your message.")
    return nil
})

Handler Shortcuts

For cleaner code, use the builder-style shortcut methods available on the client.
MethodDescription
client.OnMessage(pattern, handler)Registers a message handler builder.
client.OnCommand(command, handler)Registers a command handler builder.
client.OnCallback(pattern, handler)Registers a callback handler builder.
// Message Handler with Builder
client.OnMessage("", handler).
    Private().
    Filter(telegram.HasPhoto).
    Register()

// Command Handler
client.OnCommand("start", func(m *telegram.NewMessage) error {
    return m.Reply("Started!")
}).Private().Register()

Other Shortcuts

Gogram provides shortcuts for almost every event type:
MethodDescription
client.OnInlineQuery(pattern, handler)Handle inline queries.
client.OnInlineCallback(pattern, handler)Handle inline button callbacks.
client.OnEdit(pattern, handler)Handle message edits.
client.OnDelete(pattern, handler)Handle message deletions.
client.OnAlbum(handler)Handle grouped media albums.
client.OnChosenInline(handler)Handle chosen inline results.
client.OnParticipant(handler)Handle chat participant changes.
client.OnJoinRequest(handler)Handle requests to join a chat.
client.OnRaw(updateType, handler)Handle raw TL updates.
client.OnE2EMessage(handler)Handle End-to-End encrypted messages.

Middleware

Middleware allows you to wrap your handlers with cross-cutting concerns like logging, rate limiting, or authentication checks.
// Define a middleware
func LoggerMiddleware(next telegram.MessageHandler) telegram.MessageHandler {
    return func(m *telegram.NewMessage) error {
        log.Println("Handling message from:", m.SenderID())
        return next(m)
    }
}

// Apply middleware to specific handler
client.OnMessage("", handler).
    Use(LoggerMiddleware).
    Register()

// Or apply globally (hypothetically, if supported by your setup)

Pattern Matching

Gogram supports powerful pattern matching for messages and callbacks.

Command Patterns

Commands are automatically parsed handling standard prefixes (default / and !).
  • cmd:start matches /start, !start, and /start@yourbot.
  • cmd:settings matches /settings with arguments.

Regex and String Matching

You can use Regular Expressions for advanced text matching.
  • "hello": Matches the exact string “hello”.
  • "^Hello": Matches any message starting with “Hello” (Regex).
  • "(?i)hi": Case-insensitive match for “hi” (Regex).

Callback Data

  • "btn_next": Exact match for callback data.
  • "^page_\d+": Matches “page_1”, “page_2”, etc.

Managing Handlers

Groups and Execution Order

Handlers are organized into Groups to control execution flow.
  • Group 0 (Default): Concurrent execution. All handlers run in parallel.
  • Positive Groups (1, 2…): Sequential execution. Group 1 runs, then Group 2, etc.
  • Group -1: System/Conversation group. Runs before everything else.

Priority

Within a group, Priority determines the order. Higher priority runs first.
// High priority handler
client.On("message", highPrioHandler).SetPriority(100)

// Normal priority
client.On("message", normalHandler).SetPriority(0)

Stopping Propagation

To stop processing subsequent handlers in the current group, return telegram.ErrEndGroup.
client.On("cmd:admin", func(m *telegram.NewMessage) error {
    if !isAdmin(m.SenderID()) {
        return telegram.ErrEndGroup // Stop strictly here
    }
    return nil
})

Specialized Handlers

For strict typing and specific use cases, use the specialized Add...Handler methods. These return a Handle directly without the builder interface.
MethodSignatureDescription
AddMessageHandlerfunc(*NewMessage) errorGeneral messages with filters.
AddCommandHandlerfunc(*NewMessage) errorOptimized for commands.
AddEditHandlerfunc(*NewMessage) errorEdited text/media messages.
AddDeleteHandlerfunc(*DeleteMessage) errorDeleted messages.
AddCallbackHandlerfunc(*CallbackQuery) errorInline button clicks.
AddInlineHandlerfunc(*InlineQuery) errorIncoming inline queries.
AddInlineSendHandlerfunc(*InlineSend) errorResult chosen from inline query.
AddAlbumHandlerfunc(*Album) errorGrouped media (albums).
AddParticipantHandlerfunc(*ParticipantUpdate) errorUser join/leave events.
AddJoinRequestHandlerfunc(*JoinRequestUpdate) errorAdmin approval requests.
AddActionHandlerfunc(*NewMessage) errorService messages (pins, calls).
AddRawHandlerfunc(Update, *Client) errorLow-level raw update handling.
AddE2EHandlerfunc(Update, *Client) errorEnd-to-End encrypted chat updates.
// Example: Adding a strictly typed handler
client.AddCommandHandler("start", func(m *telegram.NewMessage) error {
    return m.Reply("Started!")
})

Channel Optimization

For high-traffic channels where real-time updates are critical, you can enable aggressive polling using OpenChat. This periodically actively fetches updates for that specific channel.
// Start active polling (every 5 seconds)
client.OpenChat(targetChannel, 5)

// Stop active polling
client.CloseChat(targetChannel)

Advanced Features

Handling Gaps

Gogram includes a robust Gap Recovery System. If the library detects a missing sequence in updates (PTS/QTS), it automatically fetches the difference from the server. You don’t need to write custom logic for this—it just works.

Conversations

See the dedicated Conversations page for details on building interactive stateful bots.

Error Handling

See the dedicated Error Handling page for details on how to manage errors in handlers and requests.

Data Caching (Peers)

See the dedicated Caching page for details on how Gogram caches peers and how to persist this data.

Logging

See the dedicated Logging page for details on how to configure and customize logging.

Dynamically Managing Handlers

// Add handler and keep reference
handle := client.On("message", dynamicHandler)

// Remove it later
client.RemoveHandle(handle)