Documentation
¶
Overview ¶
Package tgkit provides reusable Telegram bot, channel, Mini App, and payment building blocks.
Bot wraps the complete Telegram Bot API client and implements servekit's Listener contract for long polling and webhook workers. Channel adds channel-scoped helpers, MiniApp handles launch controls and authenticated initialization data, and Payments covers one-time invoices, Telegram Stars subscriptions, refunds, and renewal management.
Telegram bots and channels must still be provisioned in Telegram. The Bot API can operate a bot and administer channels to which it has been added, but it does not provision bot accounts or create channel chats.
Example ¶
package main
import (
"context"
"fmt"
telegram "github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
"github.com/marsolab/servekit/tgkit"
)
func main() {
handler := func(ctx context.Context, bot *telegram.Bot, update *models.Update) {
if update.Message == nil {
return
}
_, _ = bot.SendMessage(ctx, &telegram.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Hello from ServeKit.",
})
}
bot, err := tgkit.New(
"123456:development-token",
tgkit.WithSkipIdentityCheck(),
tgkit.WithDefaultHandler(handler),
)
if err != nil {
panic(err)
}
fmt.Println(bot.Mode())
}
Output: 0
Index ¶
- Constants
- Variables
- func MiniAppLink(botUsername string, shortName string, startParameter string, mode MiniAppMode) (string, error)
- type Bot
- type Channel
- func (c *Channel) Administrators(ctx context.Context, includeBots bool) ([]models.ChatMember, error)
- func (c *Channel) ApproveJoinRequest(ctx context.Context, userID int64) error
- func (c *Channel) CreateInviteLink(ctx context.Context, invite InviteLink) (*models.ChatInviteLink, error)
- func (c *Channel) CreateSubscriptionInviteLink(ctx context.Context, subscription ChannelSubscription) (*models.ChatInviteLink, error)
- func (c *Channel) DeclineJoinRequest(ctx context.Context, userID int64) error
- func (c *Channel) DeleteMessage(ctx context.Context, messageID int) error
- func (c *Channel) EditSubscriptionInviteLink(ctx context.Context, inviteLink string, name string) (*models.ChatInviteLink, error)
- func (c *Channel) ID() any
- func (c *Channel) Info(ctx context.Context) (*models.ChatFullInfo, error)
- func (c *Channel) Member(ctx context.Context, userID int64) (*models.ChatMember, error)
- func (c *Channel) MemberCount(ctx context.Context) (int, error)
- func (c *Channel) PinMessage(ctx context.Context, messageID int, disableNotification bool) error
- func (c *Channel) RevokeInviteLink(ctx context.Context, inviteLink string) (*models.ChatInviteLink, error)
- func (c *Channel) Send(ctx context.Context, params telegram.SendMessageParams) (*models.Message, error)
- func (c *Channel) SetDescription(ctx context.Context, description string) error
- func (c *Channel) SetTitle(ctx context.Context, title string) error
- func (c *Channel) UnpinMessage(ctx context.Context, messageID int) error
- type ChannelSubscription
- type CreateInvoiceLinkParams
- type HTTPClient
- type Handler
- type InviteLink
- type LabeledPrice
- type Middleware
- type MiniApp
- func (a *MiniApp) AnswerQuery(ctx context.Context, queryID string, result models.InlineQueryResult) (*models.SentWebAppMessage, error)
- func (a *MiniApp) InlineButton(text string) (models.InlineKeyboardButton, error)
- func (a *MiniApp) InlineQueryButton(text string) (models.InlineQueryResultsButton, error)
- func (a *MiniApp) KeyboardButton(text string) (models.KeyboardButton, error)
- func (a *MiniApp) MenuButton(text string) (models.MenuButtonWebApp, error)
- func (a *MiniApp) SetMenuButton(ctx context.Context, chatID any, text string) error
- func (a *MiniApp) URL() string
- type MiniAppChat
- type MiniAppEnvironment
- type MiniAppInitData
- type MiniAppMode
- type MiniAppSignatureValidator
- type MiniAppUser
- type MiniAppValidator
- type Mode
- type Option
- func WithAllowedUpdates(updates ...string) Option
- func WithDefaultHandler(handler Handler) Option
- func WithErrorHandler(handler func(error)) Option
- func WithHTTPClient(pollTimeout time.Duration, client HTTPClient) Option
- func WithMiddlewares(middlewares ...Middleware) Option
- func WithMode(mode Mode) Option
- func WithServerURL(serverURL string) Option
- func WithSkipIdentityCheck() Option
- func WithTelegramOptions(options ...telegram.Option) Option
- func WithWebhook(secretToken string) Option
- func WithWorkers(workers int) Option
- type PaymentEvent
- type PaymentKind
- type Payments
- func (p *Payments) ApprovePreCheckout(ctx context.Context, queryID string) error
- func (p *Payments) CancelSubscription(ctx context.Context, userID int64, chargeID string) error
- func (p *Payments) CreateInvoiceLink(ctx context.Context, params CreateInvoiceLinkParams) (string, error)
- func (p *Payments) CreateSubscriptionLink(ctx context.Context, params CreateInvoiceLinkParams) (string, error)
- func (p *Payments) RefundStars(ctx context.Context, userID int64, chargeID string) error
- func (p *Payments) RejectPreCheckout(ctx context.Context, queryID, message string) error
- func (p *Payments) ResumeSubscription(ctx context.Context, userID int64, chargeID string) error
- func (p *Payments) SendInvoice(ctx context.Context, params SendInvoiceParams) (*models.Message, error)
- type PreCheckoutQuery
- type RefundEvent
- type RefundedPayment
- type SendInvoiceParams
- type SuccessfulPayment
- type Update
Examples ¶
Constants ¶
const ( // MonthlySubscriptionPeriod is Telegram's currently supported recurring // billing period for bot and channel subscriptions. MonthlySubscriptionPeriod = 30 * 24 * time.Hour // MaxStarsSubscriptionPrice is Telegram's maximum monthly subscription // price in Stars. MaxStarsSubscriptionPrice = 10000 )
const ( // MiniAppInitDataHeader is the default HTTP header read by Mini App // authentication middleware. MiniAppInitDataHeader = "X-Telegram-Init-Data" // DefaultMiniAppInitDataMaxAge is the recommended default validity window // for authenticated Mini App initialization data. DefaultMiniAppInitDataMaxAge = 5 * time.Minute )
const (
// StarsCurrency is Telegram's ISO-like currency code for Telegram Stars.
StarsCurrency = "XTR"
)
Variables ¶
var ( // ErrInvalidMode is returned when a bot has an unsupported update mode. ErrInvalidMode = errors.New("invalid telegram update mode") // ErrInvalidBotConfig is returned when a bot option would produce an invalid // runtime configuration. ErrInvalidBotConfig = errors.New("invalid telegram bot configuration") )
var ( // ErrInvalidChatID is returned when a channel chat ID is empty or unsupported. ErrInvalidChatID = errors.New("invalid telegram chat id") // ErrInvalidInviteLink is returned when invite-link settings violate the // Telegram Bot API constraints. ErrInvalidInviteLink = errors.New("invalid telegram invite link") // ErrInvalidSubscription is returned when subscription settings violate the // Telegram Bot API constraints. ErrInvalidSubscription = errors.New("invalid telegram subscription") // ErrRequestRejected is returned when Telegram responds with a false result // without a more specific API error. ErrRequestRejected = errors.New("telegram request rejected") )
var ( // ErrInvalidMiniApp is returned when a Mini App URL, button, or direct link // is invalid. ErrInvalidMiniApp = errors.New("invalid telegram mini app") // ErrMiniAppNotBound is returned when an API operation is attempted on a // standalone MiniApp that is not associated with a Bot. ErrMiniAppNotBound = errors.New("telegram mini app is not bound to a bot") )
var ( // ErrInvalidMiniAppInitData is returned for malformed, incomplete, or // unauthenticated Mini App initialization data. ErrInvalidMiniAppInitData = errors.New("invalid telegram mini app init data") // ErrExpiredMiniAppInitData is returned when authenticated initialization // data is older than the configured validity window. ErrExpiredMiniAppInitData = errors.New("expired telegram mini app init data") // ErrFutureMiniAppInitData is returned when initialization data has an // auth_date unreasonably far in the future. ErrFutureMiniAppInitData = errors.New("future telegram mini app init data") )
var ErrInvalidInvoice = errors.New("invalid telegram invoice")
ErrInvalidInvoice is returned when invoice settings violate Telegram's payment constraints.
Functions ¶
func MiniAppLink ¶
func MiniAppLink( botUsername string, shortName string, startParameter string, mode MiniAppMode, ) (string, error)
MiniAppLink builds a t.me direct link for a main or named Mini App. The bot username must contain 5-32 ASCII letters, digits, or underscores and end in "bot". Leave shortName empty to link to the bot's main Mini App.
Example ¶
package main
import (
"fmt"
"github.com/marsolab/servekit/tgkit"
)
func main() {
link, err := tgkit.MiniAppLink(
"@example_bot",
"store",
"campaign-42",
tgkit.MiniAppModeCompact,
)
if err != nil {
panic(err)
}
fmt.Println(link)
}
Output: https://t.me/example_bot/store?startapp=campaign-42&mode=compact
Types ¶
type Bot ¶
Bot is a ServeKit-compatible Telegram bot.
The embedded Telegram client exposes the complete Bot API, including handler registration and methods not covered by tgkit's higher-level helpers.
type Channel ¶
type Channel struct {
// contains filtered or unexported fields
}
Channel provides channel-scoped Telegram Bot API operations.
The bot must be a member or administrator with the rights required by each operation. Telegram's Bot API does not create the channel chat itself.
func (*Channel) Administrators ¶
func (c *Channel) Administrators(ctx context.Context, includeBots bool) ([]models.ChatMember, error)
Administrators returns the channel's administrators.
func (*Channel) ApproveJoinRequest ¶
ApproveJoinRequest approves a user's pending request to join the channel.
func (*Channel) CreateInviteLink ¶
func (c *Channel) CreateInviteLink(ctx context.Context, invite InviteLink) (*models.ChatInviteLink, error)
CreateInviteLink creates an additional channel invite link.
func (*Channel) CreateSubscriptionInviteLink ¶
func (c *Channel) CreateSubscriptionInviteLink( ctx context.Context, subscription ChannelSubscription, ) (*models.ChatInviteLink, error)
CreateSubscriptionInviteLink creates a paid monthly channel invite link.
func (*Channel) DeclineJoinRequest ¶
DeclineJoinRequest declines a user's pending request to join the channel.
func (*Channel) DeleteMessage ¶
DeleteMessage deletes a message from the channel.
func (*Channel) EditSubscriptionInviteLink ¶
func (c *Channel) EditSubscriptionInviteLink( ctx context.Context, inviteLink string, name string, ) (*models.ChatInviteLink, error)
EditSubscriptionInviteLink changes the display name of a paid channel invite link.
func (*Channel) MemberCount ¶
MemberCount returns the number of channel members.
func (*Channel) PinMessage ¶
PinMessage pins a channel message.
func (*Channel) RevokeInviteLink ¶
func (c *Channel) RevokeInviteLink(ctx context.Context, inviteLink string) (*models.ChatInviteLink, error)
RevokeInviteLink revokes an invite link created by the bot.
func (*Channel) Send ¶
func (c *Channel) Send(ctx context.Context, params telegram.SendMessageParams) (*models.Message, error)
Send sends a message to the channel. The channel ID in params is ignored.
func (*Channel) SetDescription ¶
SetDescription changes the channel description.
type ChannelSubscription ¶
ChannelSubscription configures a paid monthly channel invite link.
type CreateInvoiceLinkParams ¶
type CreateInvoiceLinkParams = telegram.CreateInvoiceLinkParams
CreateInvoiceLinkParams configures a one-time or recurring invoice link.
type HTTPClient ¶
HTTPClient executes Telegram Bot API requests.
type InviteLink ¶
InviteLink configures a regular channel invite link.
type LabeledPrice ¶
type LabeledPrice = models.LabeledPrice
LabeledPrice is one component of an invoice price.
type Middleware ¶
type Middleware = telegram.Middleware
Middleware decorates a Telegram update handler.
type MiniApp ¶
type MiniApp struct {
// contains filtered or unexported fields
}
MiniApp provides launch controls and Bot API operations for a Telegram Mini App.
func NewMiniApp ¶
NewMiniApp creates standalone Mini App launch controls for an HTTPS URL.
func (*MiniApp) AnswerQuery ¶
func (a *MiniApp) AnswerQuery( ctx context.Context, queryID string, result models.InlineQueryResult, ) (*models.SentWebAppMessage, error)
AnswerQuery sends an inline result on behalf of a Mini App user and closes the Mini App session.
func (*MiniApp) InlineButton ¶
func (a *MiniApp) InlineButton(text string) (models.InlineKeyboardButton, error)
InlineButton creates an inline-keyboard button that launches the Mini App.
func (*MiniApp) InlineQueryButton ¶
func (a *MiniApp) InlineQueryButton(text string) (models.InlineQueryResultsButton, error)
InlineQueryButton creates an inline-mode result button that launches the Mini App.
func (*MiniApp) KeyboardButton ¶
func (a *MiniApp) KeyboardButton(text string) (models.KeyboardButton, error)
KeyboardButton creates a reply-keyboard button that launches the Mini App.
func (*MiniApp) MenuButton ¶
func (a *MiniApp) MenuButton(text string) (models.MenuButtonWebApp, error)
MenuButton creates a bot menu button that launches the Mini App.
func (*MiniApp) SetMenuButton ¶
SetMenuButton configures this Mini App as the bot menu button for a chat. A nil chatID configures the default menu button for all users.
type MiniAppChat ¶
type MiniAppChat struct {
ID int64 `json:"id"`
Type string `json:"type"`
Title string `json:"title"`
Username string `json:"username,omitempty"`
PhotoURL string `json:"photo_url,omitempty"`
}
MiniAppChat contains chat data authenticated from Mini App initData.
type MiniAppEnvironment ¶
type MiniAppEnvironment uint8
MiniAppEnvironment selects Telegram's Ed25519 signature-verification key.
const ( // MiniAppEnvironmentProduction validates data from Telegram production. MiniAppEnvironmentProduction MiniAppEnvironment = iota // MiniAppEnvironmentTest validates data from Telegram's test environment. MiniAppEnvironmentTest )
type MiniAppInitData ¶
type MiniAppInitData struct {
QueryID string
User *MiniAppUser
Receiver *MiniAppUser
Chat *MiniAppChat
ChatType string
ChatInstance string
StartParam string
CanSendAfter time.Duration
AuthDate time.Time
Hash string
Signature string
Values map[string]string
Raw string
}
MiniAppInitData is parsed and authenticated Telegram.WebApp.initData.
func MiniAppInitDataFromContext ¶
func MiniAppInitDataFromContext(ctx context.Context) (*MiniAppInitData, bool)
MiniAppInitDataFromContext returns authenticated Mini App data installed by the authentication middleware.
type MiniAppMode ¶
type MiniAppMode string
MiniAppMode controls the initial height of a Mini App opened by direct link.
const ( // MiniAppModeDefault uses the Mini App's configured opening mode. MiniAppModeDefault MiniAppMode = "" // MiniAppModeCompact opens the Mini App at half-screen height. MiniAppModeCompact MiniAppMode = "compact" )
type MiniAppSignatureValidator ¶
type MiniAppSignatureValidator struct {
// contains filtered or unexported fields
}
MiniAppSignatureValidator authenticates Mini App initData for a third party using Telegram's public Ed25519 key and a bot ID.
func NewMiniAppSignatureValidator ¶
func NewMiniAppSignatureValidator( botID int64, environment MiniAppEnvironment, maxAge time.Duration, ) (*MiniAppSignatureValidator, error)
NewMiniAppSignatureValidator creates a third-party Mini App data validator for Telegram's production or test environment.
func (*MiniAppSignatureValidator) Middleware ¶
func (v *MiniAppSignatureValidator) Middleware(next http.Handler) http.Handler
Middleware authenticates third-party Mini App initData from MiniAppInitDataHeader and stores it in the request context. Invalid requests receive HTTP 401.
func (*MiniAppSignatureValidator) Validate ¶
func (v *MiniAppSignatureValidator) Validate(raw string) (*MiniAppInitData, error)
Validate authenticates and parses Mini App initData using Telegram's public signature and the current time.
func (*MiniAppSignatureValidator) ValidateAt ¶
func (v *MiniAppSignatureValidator) ValidateAt(raw string, now time.Time) (*MiniAppInitData, error)
ValidateAt authenticates and parses Mini App initData using Telegram's public signature at a supplied time.
type MiniAppUser ¶
type MiniAppUser struct {
ID int64 `json:"id"`
IsBot bool `json:"is_bot,omitempty"`
FirstName string `json:"first_name"`
LastName string `json:"last_name,omitempty"`
Username string `json:"username,omitempty"`
LanguageCode string `json:"language_code,omitempty"`
IsPremium bool `json:"is_premium,omitempty"`
AddedToAttachmentMenu bool `json:"added_to_attachment_menu,omitempty"`
AllowsWriteToPM bool `json:"allows_write_to_pm,omitempty"`
PhotoURL string `json:"photo_url,omitempty"`
}
MiniAppUser contains user data authenticated from Mini App initData.
type MiniAppValidator ¶
type MiniAppValidator struct {
// contains filtered or unexported fields
}
MiniAppValidator authenticates Mini App initData with a private bot token.
func NewMiniAppValidator ¶
func NewMiniAppValidator(botToken string, maxAge time.Duration) (*MiniAppValidator, error)
NewMiniAppValidator creates a bot-token Mini App data validator.
func (*MiniAppValidator) Middleware ¶
func (v *MiniAppValidator) Middleware(next http.Handler) http.Handler
Middleware authenticates Mini App initData from MiniAppInitDataHeader and stores it in the request context. Invalid requests receive HTTP 401.
func (*MiniAppValidator) Validate ¶
func (v *MiniAppValidator) Validate(raw string) (*MiniAppInitData, error)
Validate authenticates and parses Mini App initData using the current time.
func (*MiniAppValidator) ValidateAt ¶
func (v *MiniAppValidator) ValidateAt(raw string, now time.Time) (*MiniAppInitData, error)
ValidateAt authenticates and parses Mini App initData at a supplied time.
type Option ¶
type Option func(*botConfig)
Option configures a Bot.
func WithAllowedUpdates ¶
WithAllowedUpdates restricts the update types Telegram should deliver.
func WithDefaultHandler ¶
WithDefaultHandler configures the fallback update handler.
func WithErrorHandler ¶
WithErrorHandler configures handling for asynchronous polling, webhook, and update-processing errors.
func WithHTTPClient ¶
func WithHTTPClient(pollTimeout time.Duration, client HTTPClient) Option
WithHTTPClient configures the HTTP client and long-poll timeout.
func WithMiddlewares ¶
func WithMiddlewares(middlewares ...Middleware) Option
WithMiddlewares configures middleware applied to every update handler.
func WithMode ¶
WithMode selects how the bot receives Telegram updates. Webhook mode also requires WithWebhook to configure a validated secret token.
func WithServerURL ¶
WithServerURL configures a Telegram Bot API server URL. It supports both the official endpoint and self-hosted Bot API servers.
func WithSkipIdentityCheck ¶
func WithSkipIdentityCheck() Option
WithSkipIdentityCheck skips the getMe request made when the bot is created. It is intended for tests and specialized self-hosted Bot API setups.
func WithTelegramOptions ¶
WithTelegramOptions applies lower-level go-telegram/bot options. Options are applied in call order and provide an escape hatch for new client features.
func WithWebhook ¶
WithWebhook selects webhook mode and configures the secret Telegram must include with webhook requests. The token must contain 1-256 ASCII letters, digits, underscores, or hyphens.
func WithWorkers ¶
WithWorkers configures the number of concurrent update workers.
type PaymentEvent ¶
type PaymentEvent struct {
Kind PaymentKind
UserID int64
ChatID int64
MessageID int
Payment *models.SuccessfulPayment
}
PaymentEvent is a successful payment extracted from a Telegram update. Payment.TelegramPaymentChargeID is the stable idempotency key applications should persist before granting an entitlement.
func PaymentFromUpdate ¶
func PaymentFromUpdate(update *models.Update) (PaymentEvent, bool)
PaymentFromUpdate extracts a successful payment and classifies recurring subscription charges.
func (PaymentEvent) IdempotencyKey ¶
func (e PaymentEvent) IdempotencyKey() string
IdempotencyKey returns Telegram's unique charge identifier for this payment.
func (PaymentEvent) SubscriptionExpiresAt ¶
func (e PaymentEvent) SubscriptionExpiresAt() (time.Time, bool)
SubscriptionExpiresAt returns the paid subscription period's expiration.
type PaymentKind ¶
type PaymentKind string
PaymentKind identifies whether a successful payment is one-time, an initial subscription payment, or a subscription renewal.
const ( // PaymentOneTime identifies a non-recurring payment. PaymentOneTime PaymentKind = "one_time" // PaymentSubscriptionStarted identifies the first subscription charge. PaymentSubscriptionStarted PaymentKind = "subscription_started" // PaymentSubscriptionRenewed identifies a later subscription charge. PaymentSubscriptionRenewed PaymentKind = "subscription_renewed" )
type Payments ¶
type Payments struct {
// contains filtered or unexported fields
}
Payments provides validated Telegram invoice and subscription operations.
func (*Payments) ApprovePreCheckout ¶
ApprovePreCheckout approves a Telegram pre-checkout query. Telegram requires the answer within ten seconds.
func (*Payments) CancelSubscription ¶
CancelSubscription prevents a Telegram Stars subscription from renewing. The current paid period remains active.
func (*Payments) CreateInvoiceLink ¶
func (p *Payments) CreateInvoiceLink(ctx context.Context, params CreateInvoiceLinkParams) (string, error)
CreateInvoiceLink creates a one-time invoice link after validating Telegram's payment constraints.
func (*Payments) CreateSubscriptionLink ¶
func (p *Payments) CreateSubscriptionLink(ctx context.Context, params CreateInvoiceLinkParams) (string, error)
CreateSubscriptionLink creates a monthly Telegram Stars subscription invoice link. Telegram currently supports only a 30-day recurring period.
func (*Payments) RefundStars ¶
RefundStars refunds a successful Telegram Stars payment.
func (*Payments) RejectPreCheckout ¶
RejectPreCheckout rejects a Telegram pre-checkout query with a user-facing explanation.
func (*Payments) ResumeSubscription ¶
ResumeSubscription allows a previously canceled Telegram Stars subscription to renew again.
func (*Payments) SendInvoice ¶
func (p *Payments) SendInvoice(ctx context.Context, params SendInvoiceParams) (*models.Message, error)
SendInvoice sends a one-time invoice after validating Telegram's payment constraints.
type PreCheckoutQuery ¶
type PreCheckoutQuery = models.PreCheckoutQuery
PreCheckoutQuery is Telegram's final checkout confirmation request.
type RefundEvent ¶
type RefundEvent struct {
UserID int64
ChatID int64
MessageID int
Refund *models.RefundedPayment
}
RefundEvent is a refunded Stars payment extracted from a Telegram update.
func RefundFromUpdate ¶
func RefundFromUpdate(update *models.Update) (RefundEvent, bool)
RefundFromUpdate extracts a refunded payment from a Telegram update.
type RefundedPayment ¶
type RefundedPayment = models.RefundedPayment
RefundedPayment is Telegram's refunded payment payload.
type SendInvoiceParams ¶
type SendInvoiceParams = telegram.SendInvoiceParams
SendInvoiceParams configures a one-time invoice sent to a Telegram chat.
type SuccessfulPayment ¶
type SuccessfulPayment = models.SuccessfulPayment
SuccessfulPayment is Telegram's successful payment payload.