Files
go-telegram/examples
lukaszraczylo 0ee539e991 perf(dispatch): typed Context.Command/CommandArgs/RegexMatch fields
Move the three conventional Values keys ("command", "command_args", "regex_match") to typed fields on Context. Router and group routing write the fields directly; the Values map is allocated lazily via the new Set method and reserved for user-defined custom keys.

Allocation impact (M4 Max, b.Loop()):

  DispatchCommand:   5 allocs/op -> 1, 153ns -> 69ns (-55%)

  DispatchTextRegex: 5 allocs/op -> 2, 181ns -> 107ns (-41%)

  DispatchFilter:    2 allocs/op -> 1, 32ns -> 19ns (-41%)

  NewContext:        5.79ns -> 1.60ns

Trade-off: Context struct grew from ~48B to ~96B (three new fields), so filter-only paths pay ~50B more per dispatch. Command/regex paths save ~320B + 4 allocs each, which dominates for typical bot workloads.

Handlers reading c.Values["command"], c.Values["command_args"], or c.Values["regex_match"] now get nil; the typed fields c.Command, c.CommandArgs, c.RegexMatch are the new accessors. Custom keys still work via c.Set(k, v) and c.Values[k].
2026-05-10 02:35:24 +01:00
..
2026-05-09 13:09:27 +01:00
2026-05-09 13:09:27 +01:00
2026-05-09 13:09:27 +01:00
2026-05-09 13:09:27 +01:00
2026-05-09 13:09:27 +01:00
2026-05-09 13:09:27 +01:00
2026-05-09 13:09:27 +01:00

Examples

Each subdirectory contains a self-contained sample bot demonstrating one feature area.

Example What it shows
echo Long-poll bot that echoes text back to the sender
webhook Webhook delivery with secret-token verification
callback Inline keyboard with callback queries and counter state
conversation Multi-step conversation flow with dispatch/conversation
files Upload and download files via api.DownloadFile
inline Inline-mode bot returning search-style results
middleware Custom middleware chains via Router.Use
stateful Per-user state managed via closures
welcome Greet new chat members; detect and log departures
moderation /kick, /ban, /mute, /warn with admin permission checks
polls Create polls and tally answers via OnPollAnswer
payments Telegram Payments: sendInvoice → pre_checkout_query → successful_payment
pagination Multi-page inline keyboard with stateless prev/next navigation
admin Auth middleware allowlisting specific user IDs via Router.Use

Running

All examples follow the same pattern:

export TELEGRAM_BOT_TOKEN=123456:ABC...
go run ./examples/<name>

Webhook examples need a public HTTPS endpoint (use Cloudflare Tunnel, ngrok, or similar).

Common patterns

Retry-safe HTTP — every example wraps the HTTP client with client.NewRetryDoer, which automatically honours Telegram's retry_after field on 429 responses.

Graceful shutdown — all examples use signal.NotifyContext so the bot drains cleanly on SIGINT/SIGTERM.

Structured logging — for production, wire a logger via client.WithLogger and wrap the process in supervision (systemd unit, k8s liveness probe, etc.).