ext

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 7, 2026 License: MIT Imports: 10 Imported by: 0

README

ext package quick start

ext provides PTB-like app-layer routing on top of tgbot.Bot:

  • Application
  • Handler
  • Filter
  • webhook http.Handler
  • long-polling runner via Application.RunPolling
  • optional non-blocking polling dispatch via WithPollingNonBlockingDispatch()

Minimal Setup

package main

import (
    "context"
    "net/http"

    "github.com/cloudapp3/tgbot"
    "github.com/cloudapp3/tgbot/ext"
)

func main() {
    bot, _ := tgbot.NewBot("<BOT_TOKEN>")
    app, _ := ext.NewApplication(bot)

    app.AddHandler(ext.NewCommandHandler("start", func(ctx context.Context, c *ext.Context) error {
        msg := c.EffectiveMessage()
        if msg == nil || msg.Chat == nil {
            return nil
        }
        _, err := c.Bot.SendMessage(ctx, &tgbot.SendMessageParams{
            ChatID: msg.Chat.ID,
            Text:   "hello",
        })
        return err
    }))

    http.Handle("/telegram/webhook", app.WebhookHandler("<SECRET_TOKEN>"))
    _ = http.ListenAndServe(":8080", nil)
}

Long Polling

package main

import (
    "context"
    "os"
    "os/signal"
    "syscall"

    "github.com/cloudapp3/tgbot"
    "github.com/cloudapp3/tgbot/ext"
)

func main() {
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
    defer stop()

    bot, _ := tgbot.NewBot("<BOT_TOKEN>")
    app, _ := ext.NewApplication(bot)

    app.AddHandler(ext.NewCommandHandler("start", func(ctx context.Context, c *ext.Context) error {
        return nil
    }))

    _ = app.RunPolling(ctx,
        ext.WithPollingAllowedUpdates(
            ext.UpdateTypeMessage,
            ext.UpdateTypeCallbackQuery,
        ),
        ext.WithPollingNonBlockingDispatch(),
    )
}

Useful Helpers

  • Handlers:
    • NewAnyHandler
    • NewTypeHandler
    • NewMessageHandler
    • NewCommandHandler
    • NewCallbackQueryHandler
  • Filters:
    • TextFilter
    • CommandFilter
    • RegexFilter
    • UpdateTypeFilter
    • And/Or/Not

Documentation

Index

Constants

This section is empty.

Variables

AllUpdateTypes lists every currently supported Telegram update type.

Functions

This section is empty.

Types

type Application

type Application struct {
	// contains filtered or unexported fields
}

Application provides PTB-like update routing on top of tg.Bot.

func NewApplication

func NewApplication(bot *tg.Bot, opts ...Option) (*Application, error)

NewApplication creates an update dispatcher bound to a bot instance.

func (*Application) AddHandler

func (app *Application) AddHandler(handler Handler)

AddHandler appends a handler to the routing chain.

func (*Application) Bot

func (app *Application) Bot() *tg.Bot

Bot returns the bound bot instance.

func (*Application) ProcessUpdate

func (app *Application) ProcessUpdate(ctx context.Context, update *Update) error

ProcessUpdate routes an update through all matching handlers.

func (*Application) RunPolling

func (app *Application) RunPolling(ctx context.Context, opts ...PollingOption) error

RunPolling starts long polling in the background and routes updates through the application.

func (*Application) SetErrorHandler

func (app *Application) SetErrorHandler(handler ErrorHandler)

SetErrorHandler updates the global handler error callback.

func (*Application) WebhookHandler

func (app *Application) WebhookHandler(secretToken string) http.Handler

WebhookHandler returns an http.Handler for Telegram webhook callbacks. If secretToken is non-empty, requests must pass X-Telegram-Bot-Api-Secret-Token.

type Context

type Context struct {
	Bot    *tg.Bot
	Update *Update
}

Context holds routing state for handlers.

func (*Context) Command

func (ctx *Context) Command() (string, string, bool)

Command extracts command and args from the effective message text.

func (*Context) EffectiveMessage

func (ctx *Context) EffectiveMessage() *tg.Message

EffectiveMessage returns the first message-like payload.

func (*Context) UpdateType

func (ctx *Context) UpdateType() UpdateType

UpdateType returns the concrete update type.

type ErrorHandler

type ErrorHandler func(context.Context, *Context, error)

ErrorHandler handles errors produced by routed handlers.

type Filter

type Filter interface {
	Match(*Context) bool
}

Filter decides whether a message-like update should be handled.

func And

func And(filters ...Filter) Filter

And matches when all provided filters match.

func AnyFilter

func AnyFilter() Filter

AnyFilter matches every context.

func CommandFilter

func CommandFilter() Filter

CommandFilter matches updates whose effective message contains a command.

func Not

func Not(filter Filter) Filter

Not negates a filter.

func Or

func Or(filters ...Filter) Filter

Or matches when any provided filter matches.

func RegexFilter

func RegexFilter(pattern *regexp.Regexp) Filter

RegexFilter matches updates whose effective message text matches the regexp.

func TextFilter

func TextFilter() Filter

TextFilter matches updates whose effective message has non-empty text.

func UpdateTypeFilter

func UpdateTypeFilter(updateTypes ...UpdateType) Filter

UpdateTypeFilter matches the provided update types.

type FilterFunc

type FilterFunc func(*Context) bool

FilterFunc is an adapter for inline filter callbacks.

func (FilterFunc) Match

func (fn FilterFunc) Match(ctx *Context) bool

Match evaluates the filter.

type Handler

type Handler interface {
	Match(*Context) bool
	Handle(context.Context, *Context) error
}

Handler is the routing contract used by Application.

func NewAnyHandler

func NewAnyHandler(fn HandlerFunc) Handler

NewAnyHandler registers a handler that receives all updates.

func NewCallbackQueryHandler

func NewCallbackQueryHandler(pattern *regexp.Regexp, fn HandlerFunc) Handler

NewCallbackQueryHandler registers a callback query handler. If pattern is nil, every callback query will match.

func NewCommandHandler

func NewCommandHandler(command string, fn HandlerFunc) Handler

NewCommandHandler registers a handler for a specific command name.

func NewMessageHandler

func NewMessageHandler(filter Filter, fn HandlerFunc) Handler

NewMessageHandler registers a handler for message-like updates.

func NewTypeHandler

func NewTypeHandler(updateType UpdateType, fn HandlerFunc) Handler

NewTypeHandler registers a handler for a specific update type.

type HandlerFunc

type HandlerFunc func(context.Context, *Context) error

HandlerFunc is an adapter for handler callbacks.

type Option

type Option func(*Application)

Option configures Application.

func WithContinueOnError

func WithContinueOnError(enabled bool) Option

WithContinueOnError controls whether dispatcher continues after a handler error.

func WithErrorHandler

func WithErrorHandler(handler ErrorHandler) Option

WithErrorHandler sets a global error callback.

func WithWebhookBodyLimit

func WithWebhookBodyLimit(limit int64) Option

WithWebhookBodyLimit overrides max webhook body size.

type PollingOption

type PollingOption = tg.UpdatePollerOption

PollingOption configures Application.RunPolling.

func WithPollingAllowedUpdates

func WithPollingAllowedUpdates(updateTypes ...UpdateType) PollingOption

WithPollingAllowedUpdates converts ext update types into poller allowed_updates values.

func WithPollingNonBlockingDispatch

func WithPollingNonBlockingDispatch() PollingOption

WithPollingNonBlockingDispatch enables non-blocking dispatch for Application.RunPolling.

type Update

type Update struct {
	UpdateID                int64                           `json:"update_id"`
	Message                 *tg.Message                     `json:"message,omitempty"`
	EditedMessage           *tg.Message                     `json:"edited_message,omitempty"`
	ChannelPost             *tg.Message                     `json:"channel_post,omitempty"`
	EditedChannelPost       *tg.Message                     `json:"edited_channel_post,omitempty"`
	BusinessConnection      *tg.BusinessConnection          `json:"business_connection,omitempty"`
	BusinessMessage         *tg.Message                     `json:"business_message,omitempty"`
	EditedBusinessMessage   *tg.Message                     `json:"edited_business_message,omitempty"`
	DeletedBusinessMessages *tg.BusinessMessagesDeleted     `json:"deleted_business_messages,omitempty"`
	MessageReaction         *tg.MessageReactionUpdated      `json:"message_reaction,omitempty"`
	MessageReactionCount    *tg.MessageReactionCountUpdated `json:"message_reaction_count,omitempty"`
	InlineQuery             *tg.InlineQuery                 `json:"inline_query,omitempty"`
	ChosenInlineResult      *tg.ChosenInlineResult          `json:"chosen_inline_result,omitempty"`
	CallbackQuery           *tg.CallbackQuery               `json:"callback_query,omitempty"`
	ShippingQuery           *tg.ShippingQuery               `json:"shipping_query,omitempty"`
	PreCheckoutQuery        *tg.PreCheckoutQuery            `json:"pre_checkout_query,omitempty"`
	PurchasedPaidMedia      *tg.PaidMediaPurchased          `json:"purchased_paid_media,omitempty"`
	Poll                    *tg.Poll                        `json:"poll,omitempty"`
	PollAnswer              *tg.PollAnswer                  `json:"poll_answer,omitempty"`
	MyChatMember            *tg.ChatMemberUpdated           `json:"my_chat_member,omitempty"`
	ChatMember              *tg.ChatMemberUpdated           `json:"chat_member,omitempty"`
	ChatJoinRequest         *tg.ChatJoinRequest             `json:"chat_join_request,omitempty"`
	ChatBoost               *tg.ChatBoostUpdated            `json:"chat_boost,omitempty"`
	RemovedChatBoost        *tg.ChatBoostRemoved            `json:"removed_chat_boost,omitempty"`
}

Update is the complete Telegram update envelope used by the application layer.

func DecodeUpdate

func DecodeUpdate(data []byte) (*Update, error)

DecodeUpdate parses a Telegram update payload.

func DecodeUpdateFromReader

func DecodeUpdateFromReader(reader io.Reader) (*Update, error)

DecodeUpdateFromReader parses a Telegram update payload from a reader.

func WrapUpdate

func WrapUpdate(update tg.Update) *Update

WrapUpdate converts a root tgbot.Update into an ext.Update.

func (*Update) Command

func (update *Update) Command() (string, string, bool)

Command extracts command and args from the effective message text.

func (*Update) EffectiveMessage

func (update *Update) EffectiveMessage() *tg.Message

EffectiveMessage returns the first message-like payload for routing helpers.

func (*Update) Payload

func (update *Update) Payload() any

Payload returns the typed payload matching the update type.

func (*Update) Type

func (update *Update) Type() UpdateType

Type returns the concrete type of the update.

type UpdateType

type UpdateType string

UpdateType is Telegram update discriminator used by the application dispatcher.

const (
	UpdateTypeUnknown                 UpdateType = ""
	UpdateTypeMessage                 UpdateType = "message"
	UpdateTypeEditedMessage           UpdateType = "edited_message"
	UpdateTypeChannelPost             UpdateType = "channel_post"
	UpdateTypeEditedChannelPost       UpdateType = "edited_channel_post"
	UpdateTypeBusinessConnection      UpdateType = "business_connection"
	UpdateTypeBusinessMessage         UpdateType = "business_message"
	UpdateTypeEditedBusinessMessage   UpdateType = "edited_business_message"
	UpdateTypeDeletedBusinessMessages UpdateType = "deleted_business_messages"
	UpdateTypeMessageReaction         UpdateType = "message_reaction"
	UpdateTypeMessageReactionCount    UpdateType = "message_reaction_count"
	UpdateTypeInlineQuery             UpdateType = "inline_query"
	UpdateTypeChosenInlineResult      UpdateType = "chosen_inline_result"
	UpdateTypeCallbackQuery           UpdateType = "callback_query"
	UpdateTypeShippingQuery           UpdateType = "shipping_query"
	UpdateTypePreCheckoutQuery        UpdateType = "pre_checkout_query"
	UpdateTypePurchasedPaidMedia      UpdateType = "purchased_paid_media"
	UpdateTypePoll                    UpdateType = "poll"
	UpdateTypePollAnswer              UpdateType = "poll_answer"
	UpdateTypeMyChatMember            UpdateType = "my_chat_member"
	UpdateTypeChatMember              UpdateType = "chat_member"
	UpdateTypeChatJoinRequest         UpdateType = "chat_join_request"
	UpdateTypeChatBoost               UpdateType = "chat_boost"
	UpdateTypeRemovedChatBoost        UpdateType = "removed_chat_boost"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL