mirror of
https://github.com/lukaszraczylo/go-telegram.git
synced 2026-06-05 22:43:59 +00:00
3c04d7b0b1
The Telegram docs describe many string fields and parameters with
phrases like "can be ..., or ...", "must be one of ...", or "always X",
yet the generated Go API surface used raw `string` for every one of
them. Callers had to write magic strings or `string(api.ChatTypePrivate)`
to satisfy the field type. This change makes those fields typed Go
string enums emitted from the IR, so the IDE autocompletes valid values
and breaking-value drift surfaces at compile time.
Pipeline changes:
- internal/spec/ir.go: Field gains EnumValues []string. Empty for non-
enum fields; otherwise the wire-level values in doc order, deduped.
- cmd/scrape/enums.go: extractEnumValues recognises the curly-quoted
patterns Telegram uses ("can be either", "currently can be", "one
of", "must be", "always X") and rejects free-text quoted refs (e.g.
"Can be available only for X") via a tight gap check between the
trigger phrase and the first quoted value. parse_mode parameters
get the canonical Markdown / MarkdownV2 / HTML triple injected
because Telegram links to a separate formatting-options section
instead of listing values inline.
- cmd/genapi/enums.go: planEnums groups fields by sorted value-tuple,
picks a canonical Go enum name (most-common candidate, parent-
prefixed beats plain, shortest beats longer, alphabetical for
determinism), resolves cross-group name collisions by parent prefix.
- cmd/genapi/emitter.go + templates: goField rewrites the field type
to the planned enum name; multipartFieldEntry casts typed enum
values back to string when composing the wire map; enums.tmpl now
iterates the planned enums instead of hardcoding four hand-curated
ones; sentinelForField produces typed-constant test fixtures.
- api/enums.gen.go: regenerated from the live IR. 66 enum types, 155
constants. ParseMode, ChatType, MessageEntityType, ChatMember /
MessageOrigin / PaidMedia / Background / StoryAreaType / Reaction /
TransactionPartner / PassportElement variant Status & Type fields
are now typed.
- api/enums.go: hand-coded UpdateType (used by transport.LongPoller).
The Telegram docs do not enumerate Update payload kinds inline, so
the codegen pipeline cannot synthesise this enum.
- api/types.gen.go, api/methods.gen.go, api/methods_gen_test.go: 137
field declarations rewritten string -> typed enum.
- dispatch/, examples/: dropped every string(api.<Const>) cast. The
HasEntity filter now takes api.MessageEntityType; ChatType filter
compares typed values directly. ChatMember discriminator filter
casts variant.Status (typed per variant) to string for comparison.
- internal/spec/api.json, testdata/golden/*: regenerated and
refreshed. make regen-from-fixture is byte-deterministic across
runs.
Renames (no compat shims; v1 pre-public):
- EntityX -> MessageEntityTypeX (e.g. EntityBotCommand -> MessageEntityTypeBotCommand)
- EntityStrike -> MessageEntityTypeStrikethrough (full wire name)
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.).