/lumex:lumexfrom lumex
Guides building Telegram bots with the kbgod/lumex Go framework: typed Bot API client, router (handlers, filters, middleware, FSM), Context helpers, menu/rich-message builders, and long-polling/webhook wiring.
Ships in lumex. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
lumex is two layers under module github.com/kbgod/lumex/v2:
lumex): Bot, every Bot API method, all
types, InputFile, sealed union types, and hand-written builders (menu.go,
richmessage.go). This layer is code-generated + a small runtime; see CLAUDE.md.router (routing + Context), dispatcher (long-polling),
middleware, log.Import the framework subpackages you need:
import (
"github.com/kbgod/lumex/v2"
"github.com/kbgod/lumex/v2/router"
"github.com/kbgod/lumex/v2/dispatcher"
)
NewBot takes the token plus variadic functional options — there is NO
second nil/options-struct argument (that is the old v1 API). Pass nothing, or
comma-separated With… options:
bot, err := lumex.NewBot(token) // typical
bot, err := lumex.NewBot(token, lumex.WithoutTokenCheck())
bot, err := lumex.NewBot(token,
lumex.WithClientOptions(lumex.WithAPIHost("https://api.example.com")),
lumex.WithTokenCheckTimeout(3*time.Second),
)
The bot's own account is on the Bot itself: NewBot calls getMe, which
returns a BotFullInfo (Bot API 10.5), and Bot embeds it — so bot.Username,
bot.ID, bot.CanJoinGroups, bot.ActiveUsernames, bot.HasTopicSidebar, …
There is no bot.User any more, and lumex.User no longer has the getMe-only
flags (CanJoinGroups, SupportsInlineQueries, …). In a test, build one with
&lumex.Bot{Username: "my_bot"} — since Go 1.27 a composite literal can set
promoted fields directly.
DON'T write lumex.NewBot(token, nil). It's the old v1 signature; with the
variadic options it compiles but panics at runtime (the nil gets invoked as
an option). BotOptions: WithClient, WithClientOptions, WithoutTokenCheck,
WithTokenCheckTimeout. The lower-level client mirrors this —
lumex.NewClient(token, ...ClientOption) with WithAPIHost, WithHTTPClient,
WithMarshaler, WithUnmarshaler, WithRequestTimeout, WithUploadTimeout.
Timeouts. Every Bot API call is bounded by default: 30s
(DefaultRequestTimeout), or 5m (DefaultUploadTimeout) when it uploads files.
A deadline already on the call's ctx replaces that limit, longer or shorter — so
one slow call (a big video upload, a hand-rolled long-polling GetUpdates with
Timeout > 30s) passes its own context.WithTimeout. GetUpdatesChan already
does. <= 0 disables a limit. Don't set http.Client.Timeout via
WithHTTPClient — it can't tell these calls apart.
bot, err := lumex.NewBot(token, lumex.WithClientOptions(
lumex.WithRequestTimeout(10*time.Second),
lumex.WithUploadTimeout(15*time.Minute),
))
Functional options everywhere; no options
structs, never a trailing nil — this applies to NewBot, NewClient, and
GetUpdatesChan(ctx, ...PollingOption).
Two ways, both fine:
bot.SendMessage(ctx, chatID, "hi")
bot.SendMessage(ctx, chatID, "hi", lumex.SendMessageOpts{ParseMode: lumex.ParseModeHTML})
lumex.Call) — XxxRequest embeds
XxxOpts, and since Go 1.27 one literal sets both:
lumex.SendPhotoRequest{ChatID: id, Photo: p, Caption: "hi"}."Message or True" methods (EditMessageText, StopMessageLiveLocation,
SetGameScore, …) return (*Message, bool, error) — a message, or true for
inline messages.
Pointer options: when zero means something. A few optional fields are
*bool / *string / *int64 instead of plain values, because Telegram treats
their zero value differently from leaving them out — e.g. every SetMySettingsOpts
field ("settings that aren't specified remain unchanged"), SendPollOpts.IsAnonymous
(defaults to true), EditMessageWidgetDataOpts.PublicData/ChatData ("" clears),
ChatPermissions.CanManageTopics, KeyboardButtonRequestUsers.UserIsBot. Set them
with Go 1.26's new(value); nil leaves the field out:
// Bot API 10.5: change the bot's own settings — only what you pass changes.
bot.SetMySettings(ctx, lumex.SetMySettingsOpts{
SupportsInlineQueries: new(true),
InlineQueryPlaceholder: new(""), // "" = back to the default placeholder
CanJoinGroups: new(false), // false is sent, not dropped
CallbackQueryMode: lumex.SetMySettingsCallbackQueryModeInline,
})
bot.SendPoll(ctx, chatID, "Lunch?", options, lumex.SendPollOpts{IsAnonymous: new(false)})
Inside a handler always call the API through ctx.Bot, never a captured
bot variable. ctx.Bot is the bot that received this update, which matters
for multi-bot webhooks (§8). Pass ctx.Context() as the context:
ctx.Bot.SendChatAction(ctx.Context(), ctx.ChatID(), lumex.ChatActionTyping)
InputFileID(id), InputFileURL(url), InputFileReader(name, r)
return *InputFile; InputFilePath(path) opens the file and returns
(*InputFile, error). Files nested in
SendMediaGroup upload automatically; no reflection, nothing to implement.lumex.NewMenu() / lumex.NewInlineMenu() build reply/inline
keyboards fluently: menu.Row().TextBtn(..), .URLBtn, .CallbackBtn,
.WebAppBtn, .Fill(cols, buttons...), .SetPlaceholder(..); on the inline
builder .DisabledBtn(text) (10.3) and .SetForceReply(bool) (10.3, also on
Menu). Send with the context menu helpers (§3) or pass menu as a
ReplyMarkup in opts. Package button ctor: lumex.CallbackBtn(text, data).
A WebAppBtn opens a Mini App; authenticating its users on your backend
(initData) is covered by the mini-app-auth skill.lumex.HTMLRichMessage(html),
MarkdownRichMessage(md), BlocksRichMessage(blocks...), chained with
.RTL(), .SkipEntities(), .AddMedia(RichMedia(id, media)); PlainText(s)
/ RichSequence(parts...) / TONAddress(address, text...) (10.4) wrap a string
as the RichText union for the block builders. Send with bot.SendRichMessage(ctx, chatID, msg).
For anything beyond a quick message — blocks, tables, media, inline
formatting, buttons, drafts, limits — read the rich-messages skill.
.AddMedia(RichMedia("id", media)) is referenced from the text by a
tg://photo?id=id / tg://video?id=id / tg://audio?id=id /
tg://document?id=id (the last new in 10.3) link. In Markdown the syntax is
the image form  and the square brackets MUST be empty — a
description inside [] is not allowed. A caption goes as a quoted string
after the URL: . A direct URL
works the same way: .lumex.NewRichMenu() builds the new buttons
block fluently: .CallbackBtn, .URLBtn, .WebAppBtn, .LoginBtn,
.SwitchInlineQueryBtn, each stylable via a RichMessageButtonStyle*
(danger/success/primary/link) arg; .SetAlign(..) / WithRichMenuAlign(..);
.Unwrap() returns an InputRichBlock to drop into BlocksRichMessage.lumex.NewInputRichBlockExpandableBlockQuotation([]lumex.InputRichBlock{…}),
like NewInputRichBlockBlockQuotation — paragraphs, lists, nested quotes.bot.SendWidget(ctx, chatID, html, opts) / SendSharedWidget, answered with
ctx.AnswerWidget(data) and updated with ctx.EditWidgetData(opts) /
bot.EditSharedWidgetData(...); route the queries with OnWidgetQuery /
OnSharedWidgetQuery (§4). Check the HTML with lumex.ValidateWidgetHTML(html)
before sending — 32768 bytes raw and 4096 compressed are hard limits, and
the constants (lumex.WidgetHTMLMaxBytes, WidgetDataMaxBytes,
WidgetAnswerTimeout, …) live in widget.go, with ValidateWidgetData for the
state. A live widget (ticker, scoreboard) is a shared one: send it with
IsShared: true, then bot.EditSharedWidgetData(ctx, widgetID, state, opts)
updates every copy with one call — see examples/tour-10.4. Writing the widget's HTML/CSS/JS
is a subject of its own — read the telegram-widgets skill for the sandbox's
rules, the window.TelegramWidget API and the request cycle. In production a
widget goes only to a private chat with the bot.A handler is func(ctx *router.Context) error. Context gives:
Raw fields — ctx.Update is the full *lumex.Update Telegram sent, and
ctx.Bot is the receiving *lumex.Bot. Everything about the current update is on
ctx: to log or inspect the raw update, read ctx.Update — never open lumex's
source to "find" the update, it's a plain exported field.
Getters (work across update kinds, return nil/zero when absent):
ctx.Message(), ctx.Sender() *User, ctx.Chat() *Chat, ctx.ChatID() int64,
ctx.CommandArgs() []string, ctx.CallbackData(), ctx.CallbackID(),
ctx.Query() (inline), ctx.QueryID(), ctx.InlineMessageID() (callback
query, chosen inline result or widget query from an inline message).
Callback queries without a message. Since Bot API 10.5 a bot can set
setMySettings callback_query_mode to "inline" (or "auto"): a callback
query from a button in the bot's own message then carries inline_message_id
instead of message. ctx.EditMessageText handles both (it edits by
InlineMessageID() when there is no message), but ctx.Message() and
ctx.Chat() are nil for such a query, and ctx.ChatID() falls back to the
sender — right in a private chat, wrong in a group. Don't depend on
ctx.Message() in callback handlers of a bot that uses those modes.
ctx.ShiftCallbackData(sep) / ctx.ShiftInlineQuery(sep) split off the leading
segment — handy with prefix routes: after OnCallbackPrefix("product"), data
"product:42" → ctx.ShiftCallbackData(":") is "42".
Entities — Telegram's entity offsets are UTF-16 units, so never slice
msg.Text with them. ctx.Message().ParseEntities() (nil-safe) returns
[]lumex.ParsedMessageEntity with the entity's Text and UTF-8 Offset/Length
(a url entity also gets URL). Also ParseCaptionEntities(),
ParseAnyEntities() (caption, poll, checklist, game, gift texts too),
ParseEntity(e), and …Types(map[lumex.MessageEntityType]struct{}{…}) filters;
for any other text use lumex.ParseEntities(text, entities).
Reply/action helpers — each has a …Void variant that drops the returned
value and returns only error (convenient for return):
Reply(text, opts…), ReplyWithMenu(text, menu, opts…)ReplyPhoto / ReplyVideo (+ …WithMenu)Answer / AnswerAlert (answer a callback query), AnswerQuery(results…)
(answer an inline query)EditMessageText(text, opts…) (*Message, bool, error), DeleteMessage()ReplyEmojiReaction(emoji…), ReplyEmojiBigReaction(emoji…)ctx.SetParseMode(lumex.ParseModeHTML) sets a default parse mode for the reply
helpers on this context (overridden by an explicit ParseMode in opts).
ctx.Context() / ctx.SetContext(...) carry the context.Context; attach
request-scoped values there from middleware.
ctx is pooled and reused per update — don't retain it after the handler
returns.
r := router.New(bot, router.WithErrorHandler(func(ctx *router.Context, err error) {
log.Error("handler failed", "err", err)
}))
Register routes with On(filter, handlers...) or the OnX shortcuts
(OnStart, OnCommand, OnAnyCommand, OnAnyCommandWithAt, OnMessage,
OnText, OnNonCommandText, OnCaption, OnTextOrCaption, OnContact,
OnCallbackQuery, OnCallbackPrefix, OnCallbackQuerySuffix, OnCallbackQueryEquals, OnInlineQuery, OnPhoto, OnGuestMessage,
OnRichMessage, OnMyChatMember, OnChatMember, OnChatJoinRequest,
OnWidgetQuery, OnSharedWidgetQuery, OnAnyWidgetQuery, OnWidgetDataPrefix,
OnWidget, OnTONWalletTransfer, OnPaidMessagesWaived, OnBotInvite
(10.5: a user the owner invited via https://t.me/botinvite/<bot_username>;
Message.WriteAccessAllowed.Inviter is the owner, and the bot may write to the
user), OnUpdate, …). Each returns a *Route (chain .Name("...") for diagnostics).
A command is text, so OnText matches /foo too. When a route should take
free-form text but not commands (wizard steps especially), use OnNonCommandText.
How an update flows (know this cold):
HandleUpdate runs the global middleware (everything added with
r.Use(...)), in order, for every update. Each middleware MUST call
ctx.Next() to continue — returning without it short-circuits the update
(nothing else runs). Global middleware runs even when no route ends up
matching.ctx.Next(). The final handler
need not call Next().HandleUpdate returns router.ErrRouteNotFound
(delivered to the error handler if one is set). A handler error is likewise
delivered to the error handler.Handler / filter / error types:
type Handler func(*Context) error
type RouteFilter func(*Context) bool
type ErrorHandler func(*Context, error)
r.Use(mw...). Runs for every update, before routing, always.
Use for cross-cutting concerns: logging, loading the user, loading FSM state.
A global middleware controls flow with ctx.Next(). Logging every update is
just this — the raw update is ctx.Update, no need to touch lumex internals:
r.Use(func(ctx *router.Context) error {
log.Info("update", "id", ctx.Update.UpdateID, "payload", ctx.Update)
return ctx.Next() // MUST call Next() or the update is dropped
})
(To also time it: start := time.Now(); err := ctx.Next(); log(time.Since(start)); return err.)On/OnX
(r.OnMessage(mw, handler)) or to r.Group(mw...). These live on the route
and run only if that route's filter matched. Use for auth/validation that
only makes sense for specific routes.admin := r.Group(requireAdmin) // requireAdmin runs only for these routes, on match
admin.OnCommand("ban", banHandler)
admin.OnCommand("stats", statsHandler)
Sub-routers compose. Group(mw...) and UseState(state, mw...) both return a
sub-router that carries its middlewares, and they nest freely in any order: a
route runs the global r.Use middlewares, then every enclosing sub-router's
middlewares outermost-first (each once), then its own handlers.
admin := r.Group(requireAdmin)
editing := admin.UseState("editing", loadDraft)
editing.OnMessage(saveDraft) // global mws → requireAdmin → loadDraft → saveDraft
A sub-router fixes its middleware chain when it is created and when each
route is registered: call sub.Use(mw) before sub.On…, since it reaches only
routes registered on sub afterwards (not earlier routes, not child groups
created before it).
Routes are matched top-to-bottom, first match wins. A broad route declared early shadows narrower ones declared later:
// BUG: "p" matches any callback starting with p, so "products" never runs.
r.OnCallbackPrefix("p", handleP)
r.OnCallbackPrefix("products", handleProducts) // dead
// BUG: AnyUpdate matches everything → nothing below ever runs.
r.OnUpdate(logEverything)
r.OnStart(startHandler) // dead
Rules of thumb:
OnUpdate/OnMessage) last, as a deliberate
fallback — not first.ErrRouteNotFound; add a final OnUpdate
fallback or handle that error in the error handler to avoid noise.Built-in filters live in router (Command, CommandWithAt, AnyCommand,
AnyCommandWithAt, Message, Text, NonCommandText, Caption, TextOrCaption,
Contact, CallbackQuery, CallbackPrefix, CallbackQuerySuffix, CallbackQueryEquals, TextPrefix, TextEquals,
TextContains, Photo, Video, Document, GuestMessage, RichMessage,
MyChatMember, ChatMember, ChatJoinRequest, ForwardedChannelMessage,
WidgetQuery, SharedWidgetQuery, AnyWidgetQuery, WidgetDataPrefix, Widget,
TONWalletTransfer, PaidMessagesWaived, …).
When none fit, a filter is just a
func(*Context) bool — write your own and pass it to On:
func FromAdmin(ids ...int64) router.RouteFilter {
return func(ctx *router.Context) bool {
s := ctx.Sender()
return s != nil && slices.Contains(ids, s.ID)
}
}
r.On(FromAdmin(1, 2, 3), adminHandler)
// combine by composing filters:
func And(fs ...router.RouteFilter) router.RouteFilter {
return func(ctx *router.Context) bool {
for _, f := range fs { if !f(ctx) { return false } }
return true
}
}
r.On(And(router.Message(), FromAdmin(1)), handler)
r.UseState("name") returns a sub-router whose routes are gated on state:
they match only when the context's state equals "name". Stateless routes
(everything on the base router) match regardless of state. Like Group, it takes
optional middlewares (r.UseState("name", mw...)) and keeps those of the group it
is called on (§5).
ask := r.UseState("ask_name")
ask.OnMessage(saveNameThenAskAge)
State is per-update and in-memory. ctx.SetState(s) only affects the current
update; ctx.GetState() reads it. To drive a real multi-step dialog you must
persist state yourself (DB/Redis/etc.) and load it in a global middleware:
r.Use(func(ctx *router.Context) error {
if s := store.Load(ctx.Sender().ID); s != "" {
ctx.SetState(s) // makes UseState(s) routes eligible this update
}
return ctx.Next()
})
r.OnStart(startHandler) // stateless: always eligible (e.g. reset flow)
ask := r.UseState("ask_name")
ask.OnMessage(func(ctx *router.Context) error {
store.SaveName(ctx.Sender().ID, ctx.Message().Text)
store.SetState(ctx.Sender().ID, "ask_age") // advance the flow (persisted)
return ctx.ReplyVoid("How old are you?")
})
age := r.UseState("ask_age")
age.OnMessage(finishSignup)
Uses: wizard-style dialogs (each step is a state), and separating roles — set
state "admin" in middleware for admins and hang admin routes under
r.UseState("admin").
UseState is only an extra filter (the state must also match) — registration
order still decides. A stateless route registered above a state route with the
same filter wins even when the user is in that state:
r.OnCommand("test", stateless) // ← fires for /test even while in "s"
s := r.UseState("s")
s.OnCommand("test", inState) // shadowed by the line above; never runs
So order by intent:
r.OnCommand("exit", cancelFlow) keeps /exit working
mid-dialog because it's checked before every state route.UseState route; it runs only if none matched.A UseState route only wins when its state matches AND no earlier (stateless or
other-state) route already matched — exactly the same first-match rule as §6,
with state as one more condition.
Pick your update types — allowed_updates. By default Telegram delivers a
subset: it does NOT send chat_member, message_reaction, or
message_reaction_count unless you ask. Set AllowedUpdates on GetUpdatesOpts
(polling) or SetWebhookOpts (webhook):
AllowedUpdates: []string{"message", "callback_query", "chat_member"}AllowedUpdates: make([]string, 0) (or []string{})nil / unset → keep the previous setting.This is the #1 reason a brand-new update type never arrives. A token that was
ever polled with an explicit list keeps that list, and a list written before the
type existed cannot contain it — so e.g. a 10.4 widget just reports TIMEOUT
while the bot sees nothing. When you start handling a new update type, name it
(or send []string{}) instead of leaving AllowedUpdates unset.
d.StartPolling(100, lumex.WithGetUpdatesOpts(lumex.GetUpdatesOpts{
AllowedUpdates: []string{"message", "callback_query", "chat_member"},
}))
The field is tagged omitzero, so an empty []string{} is sent as [] (with
plain omitempty it would be silently dropped). Honored by encoding/json on
Go 1.24+; a custom Marshaler must support omitzero.
Long polling — use the dispatcher (router.Listen is deprecated):
d := dispatcher.New(bot, r)
go func() { _ = d.StartPolling(100) }() // 100 worker goroutines
// on shutdown, within a grace period:
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = d.Stop(ctx)
(examples/common.Run packages exactly this — token from BOT_TOKEN, router,
polling, graceful shutdown — so an example is just handlers.)
Webhook — in your HTTP handler, decode a lumex.Update and hand it to the
router:
func webhook(r *router.Router) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
var update lumex.Update
if err := json.NewDecoder(req.Body).Decode(&update); err != nil {
http.Error(w, "bad update", http.StatusBadRequest)
return
}
_ = r.HandleUpdate(req.Context(), &update)
}
}
Multi-bot on one webhook endpoint (a bot factory / SaaS): resolve which bot
the request is for, inject it via router.BotContextKey{}, and the router will
expose it as ctx.Bot:
bot := factory.Resolve(req) // by token/path/etc.
ctx := context.WithValue(req.Context(), router.BotContextKey{}, bot)
_ = r.HandleUpdate(ctx, &update)
This is exactly why handlers must call the API through ctx.Bot — a single
router serves many bots, and ctx.Bot is the right one per update.
HandleUpdate may only be called on the root router; calling it on a group
or state sub-router returns ErrGroupCannotHandleUpdates.
lumex.NewBot(token) or NewBot(token, opts...); DON'T write NewBot(token, nil) — variadic options, nil panics (same for NewClient, GetUpdatesChan).ctx.Bot in handlers; DON'T capture an outer bot.ctx.Update (log/inspect it there); DON'T open lumex's source to access it — it's a public Context field.ctx.Next() in global middleware; forgetting it silently drops the update.OnUpdate/broad prefixes first./exit) above UseState routes and the fallback last; a stateless route above a state route shadows it even in that state (UseState is just an extra filter, order still wins).ctx.SetState alone doesn't survive to the next update.ErrRouteNotFound (fallback route or error handler) if unmatched updates are expected.menu/richmessage/InputFile* builders before hand-writing structs.What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub kbgod/lumex --plugin lumex5 skills in this plugin
/dialog-flowsBest practices for building multi-step conversation flows (wizards / FSM) with the kbgod/lumex Telegram framework — collecting inputs across states (ask name → city → photo → confirm), local fallbacks for invalid input, cancel/back navigation, state persistence, and naming conventions. Use whenever the user wants a bot that asks the user for information step by step, a multi-step form, a wizard, or a stateful dialog. Pairs with the `lumex` skill (framework reference); this one is the flow playbook./mini-app-authHow to authenticate Telegram Mini App (Web App) users on a Go backend next to a kbgod/lumex bot: send Telegram.WebApp.initData (never initDataUnsafe) to the server, parse it into a map of every field — not a fixed struct, or new fields break verification — and verify it either with the bot token (HMAC "hash", for your own bot) or with Telegram's Ed25519 public key ("signature", for another bot's Mini App, with an allowlist of bot ids); the exact data-check-string rules for each, auth_date freshness, constant-time comparison, duplicate keys, the test-environment key, sessions and replay. Use whenever a Mini App calls a backend, or a service accepts initData from Telegram. Pairs with the `lumex` skill (framework reference)./rich-messagesHow to build, send, edit and read Telegram rich messages with kbgod/lumex: choosing HTML, Markdown or explicit blocks; the ready-made constructors (HTMLRichMessage, MarkdownRichMessage, BlocksRichMessage, RichMedia, PlainText, RichSequence, TONAddress, NewRichMenu and the generated NewInputRichBlock* constructors); inline formatting with the RichText types; media, tables, lists, quotations, details, maps, formulas and in-message buttons; streaming drafts; the limits (32768 characters, 500 blocks, 16 nesting levels, 50 media, 20 table columns); and the usual mistakes. Use whenever a bot sends, edits or reads a rich message (sendRichMessage, rich_message, RichBlock, RichText). Pairs with the `lumex` skill (framework reference).Other plugins' skills for the same job