mirror of
https://github.com/lukaszraczylo/go-telegram.git
synced 2026-06-05 22:43:59 +00:00
ac7cae8fa7
A fully-generated, strongly-typed Go client for the Telegram Bot API. * 176 methods + 301 types generated from Bot API v10.0 * 1408 auto-generated tests (8 scenarios per method) * Typed unions throughout — no 'any' in the public surface * Pluggable HTTP transport and JSON codec (default goccy/go-json) * Built-in retry middleware honouring Telegram's retry_after * Generic dispatcher with filters and conversation handlers * Self-verifying codegen pipeline (regen → audit → emit → run tests) * 14 example bots covering common patterns
5.5 KiB
5.5 KiB
Changelog
All notable changes to this project will be documented in this file. The format follows Keep a Changelog and this project adheres to Semantic Versioning.
[Unreleased]
[1.0.0] - 2026-05-09
Initial public release. Built against Telegram Bot API v10.0 (176 methods, 301 types).
Library surface
client.Botwith pluggableHTTPDoer,Codec(defaultgithub.com/goccy/go-json), andLoggerinterfaces.- Generic
client.Call[Req, Resp]andclient.CallRaw[Req]helpers — every API method funnels through one of these. client.RetryDoermiddleware — exponential backoff with jitter; honours Telegram'sretry_after; replays request bodies across attempts. Configurable viaRetryOptionfunctions (WithMaxAttempts,WithBase,WithMax,WithFactor,WithJitter).- Typed errors:
*APIError(sentinel-mapped:ErrUnauthorized,ErrForbidden,ErrTooManyRequests,ErrChatNotFound,ErrMessageNotModified,ErrBadRequest,ErrUserNotFound,ErrMessageNotFound),*NetworkError,*ParseError. Bot tokens redacted from error messages.
Update delivery
transport.LongPoller— getUpdates loop withExponentialBackoff, retry-after honouring, graceful shutdown viaStop.transport.WebhookServer—http.Handler+ListenAndServe; secret-token verification (constant-time); 1 MiB body cap; in-flight handler tracking viaWaitGroup.
Dispatcher
- Generic
dispatch.Handler[T]anddispatch.Middleware[T]. - 21 typed handler registrations:
OnCommand,OnText,OnCallback,OnInlineQuery,OnEditedMessage,OnChannelPost,OnEditedChannelPost,OnMyChatMember,OnChatMember,OnChatJoinRequest,OnPreCheckoutQuery,OnShippingQuery,OnPoll,OnPollAnswer,OnChosenInlineResult,OnMessageReaction,OnMessageReactionCount,OnChatBoost,OnRemovedChatBoost,OnBusinessConnection,OnPurchasedPaidMedia. Filter variants available for message, callback, inline-query, chat-member, chat-join-request, and pre-checkout-query types. - Composable filters in
dispatch/filters/{message,callback,inline,chatmember,chatjoinrequest,precheckoutquery}packages withAnd/Or/Not/All/Anycombinators and 20+ filter helpers. dispatch/conversation— multi-step state machines withStorageinterface (MemoryStoragedefault), pluggableKeyStrategy(KeyByUser,KeyByChat,KeyByUserAndChat), entry/state/exit/fallback steps,AllowReEntry.Next(state)andEnd()sentinel errors drive transitions.Conversation.Dispatchintegrates as middleware viarouter.Use.- Per-update goroutine pool (default 50; configurable via
WithMaxConcurrency). Pass0for serial dispatch. - Handler groups with
EndGroups/ContinueGroupsflow control. NamedHandlers[T]for runtime registration and replacement.- Panic-recovery middleware + automatic handler-error logging registered by default.
Generated API
- Full Bot API v10.0 surface in
api/*.gen.go— 176 methods, 301 types, regenerated from a committed HTML snapshot ofcore.telegram.org/bots/api. - Strongly typed unions:
ChatID(Integer-or-String),*InputFile(InputFile-or-String),MessageOrBool(Message-or-True returns). - 13 discriminated unions with auto-decode:
ChatMember,MessageOrigin,ReactionType,PaidMedia,BackgroundType,BackgroundFill,ChatBoostSource,RevenueWithdrawalState,TransactionPartner,MenuButton,OwnedGift,StoryAreaType,MaybeInaccessibleMessage. Parent structs containing union-typed fields auto-decode via generatedUnmarshalJSON. - Sealed-interface return types use
client.CallRaw+Unmarshal<Name>dispatch (e.g.,GetChatMemberreturnsChatMemberinterface, decoded into the correct concrete variant).
Runtime helpers
api.MeCache— concurrent-safegetMecache; zero-value safe.api.DownloadFile/api.DownloadFileByPath— fetch file contents from the Telegram CDN.(*Message).GetSender()— unifiesFrom,SenderChat, and anonymous-admin fields into a*Sender.
Codegen pipeline (cmd/scrape, cmd/genapi, cmd/audit)
- Two-stage codegen: HTML → IR (
internal/spec/api.json) → Go. internal/spec/overrides.jsonpins specific method returns/field types when scraper regex does not match a particular doc phrasing.cmd/auditreports any-typed fields, fallbackboolreturns, and signature drift vs HEAD's IR. Exit codes: 0 clean, 1 fallback, 2 drift, 3 invalid.make regenis self-verifying: clean → scrape → audit → emit (code + 1428 tests) → run tests.- Auto-generated tests cover 8 scenarios per method (1428 total): Success, APIError 429, NetworkError, ParseError, ContextCanceled, MissingRequiredFields (400 + ErrBadRequest), Forbidden (403 + ErrForbidden), ServerError (500 + IsRetryable).
Tooling
.github/workflows/ci.yml— Go matrix 1.23/1.24, vet, staticcheck, govulncheck, gosec, race tests, codegen-clean check, audit + drift detection..github/workflows/regen.yml— weekly cron + workflow_dispatch; scrapes live API, regenerates, runs tests, opens auto-PR with audit summary in body..github/workflows/release.yml— semver-generator-driven version bump; dual tagging (library SemVer +bot-api-v<X.Y>marker); GoReleaser..goreleaser.yaml— shipstg-scrape,tg-genapi,tg-auditbinaries for Linux/macOS/Windows × amd64/arm64.
Examples (14)
echo, webhook, callback, conversation, files, inline, middleware, stateful, welcome, moderation, polls, payments, pagination, admin.