Documentation
¶
Overview ¶
Package telegram owns the concrete Telegram Bot API client and the durable long-polling runtime.
Index ¶
- Variables
- func CheckStartupHealth(ctx context.Context, db store.DBTX, client *Client, notifier *notify.Notifier, ...) error
- func IsDMBlocked(err error) bool
- func IsExpectedNoop(action string, err error) bool
- func IsForbidden(err error) bool
- func IsPermanentRights(err error) bool
- func IsRateLimited(err error) bool
- func IsTimeout(err error) bool
- func IsTransient(err error) bool
- func NormalizeError(method string, err error) error
- func RetryAfter(err error) (time.Duration, bool)
- type APIError
- type APIErrorCount
- type Client
- func (c *Client) APIErrorCounts() []APIErrorCount
- func (c *Client) AnswerCallbackQuery(ctx context.Context, callbackQueryID string) error
- func (c *Client) ApproveChatJoinRequest(ctx context.Context, chatID, userID int64) error
- func (c *Client) BanChatMember(ctx context.Context, chatID, userID int64) error
- func (c *Client) BotID() int64
- func (c *Client) CreateChatInviteLink(ctx context.Context, params CreateChatInviteLinkParams) (*models.ChatInviteLink, error)
- func (c *Client) DeclineChatJoinRequest(ctx context.Context, chatID, userID int64) error
- func (c *Client) DeleteWebhook(ctx context.Context) error
- func (c *Client) EditMessageReplyMarkup(ctx context.Context, chatID int64, messageID int, ...) error
- func (c *Client) EditMessageText(ctx context.Context, chatID int64, messageID int, text string, ...) error
- func (c *Client) GetChat(ctx context.Context, chatID int64) (*models.ChatFullInfo, error)
- func (c *Client) GetChatMember(ctx context.Context, chatID, userID int64) (*models.ChatMember, error)
- func (c *Client) GetMe(ctx context.Context) (*models.User, error)
- func (c *Client) GetUpdates(ctx context.Context, params GetUpdatesParams) ([]FetchedUpdate, error)
- func (c *Client) RevokeChatInviteLink(ctx context.Context, chatID int64, inviteLink string) (*models.ChatInviteLink, error)
- func (c *Client) SendFormattedMessage(ctx context.Context, chatID int64, text string, parseMode string) error
- func (c *Client) SendFormattedMessageWithReplyMarkup(ctx context.Context, chatID int64, text string, parseMode string, ...) error
- func (c *Client) SendMessage(ctx context.Context, chatID int64, text string) error
- func (c *Client) SendMessageWithReplyMarkup(ctx context.Context, chatID int64, text string, replyMarkup models.ReplyMarkup) error
- func (c *Client) SetMyCommands(ctx context.Context, ownerIDs []int64) error
- func (c *Client) SetWebhook(ctx context.Context, url string, secretToken string, allowedUpdates []string) error
- func (c *Client) UnbanChatMember(ctx context.Context, chatID, userID int64, onlyIfBanned bool) error
- type ClientOption
- type CreateChatInviteLinkParams
- type ErrorCategory
- type FetchedUpdate
- type GetUpdatesParams
- type HealthChat
- type OutboundKind
- type OutboundMessage
- type Poller
- type PollerOption
- func WithPollerAdminLogChatID(chatID *int64) PollerOption
- func WithPollerAdmissionConfig(cfg admission.Config) PollerOption
- func WithPollerChatRoles(roles []commandbot.ChatRole) PollerOption
- func WithPollerOperatorLog(writer *operatorlog.Writer) PollerOption
- func WithPollerSourceChats(sourceChats SourceChats) PollerOption
- func WithPollerStatusEngine(statusEngine *engine.Engine) PollerOption
- func WithPollerSubscribeLinks(links messages.SubscribeLinks) PollerOption
- type ResourceMemberChecker
- type RoutePreflight
- type RouteResult
- type Router
- type RouterDeps
- type RouterOption
- func WithAdmissionConfig(cfg admission.Config) RouterOption
- func WithChatInfo(resolve commandbot.ChatTitleResolver) RouterOption
- func WithMemberChecker(checker engine.MemberChecker) RouterOption
- func WithOperatorLog(writer *operatorlog.Writer) RouterOption
- func WithPreflight(preflight RoutePreflight) RouterOption
- func WithSourceChats(chats SourceChats) RouterOption
- func WithStatusEngine(e *engine.Engine) RouterOption
- type SourceChats
- type SyncJob
Constants ¶
This section is empty.
Variables ¶
var DefaultAllowedUpdates = []string{ models.AllowedUpdateMessage, models.AllowedUpdateCallbackQuery, models.AllowedUpdateMyChatMember, models.AllowedUpdateChatMember, models.AllowedUpdateChatJoinRequest, }
DefaultAllowedUpdates is the explicit update surface requested from Telegram on every poll.
Functions ¶
func CheckStartupHealth ¶
func CheckStartupHealth( ctx context.Context, db store.DBTX, client *Client, notifier *notify.Notifier, chats []HealthChat, ownerIDs []int64, botID int64, logger *slog.Logger, ) error
CheckStartupHealth records bot presence and rights in every configured chat.
func IsDMBlocked ¶
IsDMBlocked reports whether err is a normalized blocked-DM response.
func IsExpectedNoop ¶
IsExpectedNoop reports whether a Bot API error means the action is already satisfied or no longer meaningful.
func IsForbidden ¶
IsForbidden reports whether err is a normalized Telegram 403.
func IsPermanentRights ¶
IsPermanentRights reports whether err is a non-retryable rights issue.
func IsRateLimited ¶
IsRateLimited reports whether err is a normalized 429.
func IsTimeout ¶ added in v0.2.0
IsTimeout reports whether err is a normalized request timeout. A timeout describes the error, never the caller's intent to stop: shutdown is decided by context state alone.
func IsTransient ¶ added in v0.2.0
IsTransient reports whether err is worth retrying without treating the action as suspect: a request timeout or a rate limit.
func NormalizeError ¶
NormalizeError maps Bot API errors to typed categories.
Types ¶
type APIError ¶
type APIError struct {
Method string
Category ErrorCategory
RetryAfter int
Err error
}
APIError wraps Bot API errors with a stable category.
func (*APIError) TelegramCategory ¶
TelegramCategory exposes a stable string category to packages that should not import telegram just to classify best-effort send errors.
type APIErrorCount ¶ added in v0.2.0
type APIErrorCount struct {
Method string
Category ErrorCategory
Count int64
}
APIErrorCount is one normalized Telegram failure counter.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the one concrete Telegram client used by the application.
func NewClient ¶
func NewClient(token string, opts ...ClientOption) (*Client, error)
NewClient creates a Telegram client without validating the token. The runtime calls GetMe explicitly so startup order stays visible.
func (*Client) APIErrorCounts ¶ added in v0.2.0
func (c *Client) APIErrorCounts() []APIErrorCount
APIErrorCounts returns the failures seen so far, ordered by method then category so the exposition is stable between scrapes.
The counters are in-process and monotonic: they reset when the process restarts, which is exactly the behaviour a Prometheus counter is defined for.
func (*Client) AnswerCallbackQuery ¶
AnswerCallbackQuery acknowledges a callback query so the client clears the inline-button spinner. No user-facing text is shown.
func (*Client) ApproveChatJoinRequest ¶
ApproveChatJoinRequest approves one pending join request.
func (*Client) BanChatMember ¶
BanChatMember bans one user from a chat or channel.
func (*Client) CreateChatInviteLink ¶
func (c *Client) CreateChatInviteLink( ctx context.Context, params CreateChatInviteLinkParams, ) (*models.ChatInviteLink, error)
CreateChatInviteLink creates a managed invite link.
func (*Client) DeclineChatJoinRequest ¶
DeclineChatJoinRequest declines one pending join request.
func (*Client) DeleteWebhook ¶
DeleteWebhook disables Telegram webhook delivery so getUpdates can run.
func (*Client) EditMessageReplyMarkup ¶
func (c *Client) EditMessageReplyMarkup( ctx context.Context, chatID int64, messageID int, replyMarkup models.ReplyMarkup, ) error
EditMessageReplyMarkup edits only an existing message's inline keyboard, leaving the text intact. Used to swap the retry button to a progress label without disturbing the message body.
func (*Client) EditMessageText ¶
func (c *Client) EditMessageText( ctx context.Context, chatID int64, messageID int, text string, replyMarkup models.ReplyMarkup, ) error
EditMessageText edits an existing message's text and inline keyboard in place using HTML parse mode. A nil replyMarkup clears the keyboard. Telegram's "message is not modified" response is treated as success because the desired state already matches the message.
func (*Client) GetChatMember ¶
func (c *Client) GetChatMember( ctx context.Context, chatID, userID int64, ) (*models.ChatMember, error)
GetChatMember returns one member status in a chat.
func (*Client) GetUpdates ¶
func (c *Client) GetUpdates( ctx context.Context, params GetUpdatesParams, ) ([]FetchedUpdate, error)
GetUpdates calls Telegram getUpdates directly. The upstream package's polling method is intentionally internal because it feeds its handler channel; this runtime must persist updates before dispatching them.
func (*Client) RevokeChatInviteLink ¶
func (c *Client) RevokeChatInviteLink( ctx context.Context, chatID int64, inviteLink string, ) (*models.ChatInviteLink, error)
RevokeChatInviteLink revokes one managed invite link.
func (*Client) SendFormattedMessage ¶
func (c *Client) SendFormattedMessage( ctx context.Context, chatID int64, text string, parseMode string, ) error
SendFormattedMessage sends a renderer-produced formatted message.
func (*Client) SendFormattedMessageWithReplyMarkup ¶
func (c *Client) SendFormattedMessageWithReplyMarkup( ctx context.Context, chatID int64, text string, parseMode string, replyMarkup models.ReplyMarkup, ) error
SendFormattedMessageWithReplyMarkup sends formatted text with reply markup.
func (*Client) SendMessage ¶
SendMessage sends a plain text message.
func (*Client) SendMessageWithReplyMarkup ¶
func (c *Client) SendMessageWithReplyMarkup( ctx context.Context, chatID int64, text string, replyMarkup models.ReplyMarkup, ) error
SendMessageWithReplyMarkup sends a plain text message with reply markup.
func (*Client) SetMyCommands ¶
SetMyCommands registers user commands globally and owner commands in each owner private chat scope.
type ClientOption ¶
type ClientOption func(*clientOptions)
ClientOption configures Client construction.
func WithAllowedUpdates ¶
func WithAllowedUpdates(updates []string) ClientOption
WithAllowedUpdates replaces the default explicit allowed_updates list.
func WithHTTPClient ¶
func WithHTTPClient(client *http.Client) ClientOption
WithHTTPClient replaces the default HTTP client.
func WithServerURL ¶
func WithServerURL(url string) ClientOption
WithServerURL points the client to a Bot API-compatible endpoint.
type CreateChatInviteLinkParams ¶
type CreateChatInviteLinkParams = invite.CreateChatInviteLinkParams
CreateChatInviteLinkParams keeps the Telegram client surface stable while the invite package owns the consumer-side request shape.
type ErrorCategory ¶
type ErrorCategory string
ErrorCategory is a caller-facing Telegram error class.
const ( ErrorCategoryRateLimited ErrorCategory = "rate_limited" ErrorCategoryTimeout ErrorCategory = "timeout" ErrorCategoryCanceled ErrorCategory = "canceled" ErrorCategoryDMBlocked ErrorCategory = "dm_blocked" ErrorCategoryPermanentRights ErrorCategory = "permanent_rights" ErrorCategoryForbidden ErrorCategory = "forbidden" ErrorCategoryConflict ErrorCategory = "conflict" ErrorCategoryBadRequest ErrorCategory = "bad_request" ErrorCategoryNotFound ErrorCategory = "not_found" ErrorCategoryOther ErrorCategory = "other" )
type FetchedUpdate ¶
type FetchedUpdate struct {
Raw json.RawMessage
Update *models.Update
}
FetchedUpdate is one raw getUpdates result plus its decoded model.
type GetUpdatesParams ¶
type GetUpdatesParams struct {
Offset int64 `json:"offset,omitempty"`
Limit int `json:"limit,omitempty"`
Timeout int `json:"timeout,omitempty"`
AllowedUpdates []string `json:"allowed_updates,omitempty"`
}
GetUpdatesParams is the subset of getUpdates fields used by the poller.
type HealthChat ¶
type HealthChat struct {
Key string
Name string
ID int64
Source string
Resource string
Severity string
RequiresManageRight bool
// PostingOnly marks a feed chat (EVENT_LOG_CHAT_ID) where the bot only
// needs to be a member able to send messages — administrator status is
// not required, so a plain member with posting rights is healthy.
PostingOnly bool
}
HealthChat describes one configured chat whose bot rights are checked.
func EventLogHealthChat ¶
func EventLogHealthChat(cfg config.Config) HealthChat
EventLogHealthChat describes the operator event-log feed chat. The bot only needs posting rights there (member or admin), and a problem is severity error: the feed is observability, not an access-control resource, and MUST NOT be treated as one of the four source/club chats.
func HealthChatsFromConfig ¶
func HealthChatsFromConfig(cfg config.Config) []HealthChat
HealthChatsFromConfig returns the four chats required by the product.
type OutboundKind ¶
type OutboundKind string
OutboundKind tells the poller how to deliver a post-commit effect.
const ( OutboundChatMessage OutboundKind = "chat_message" OutboundDM OutboundKind = "dm" )
type OutboundMessage ¶
type OutboundMessage struct {
Kind OutboundKind
ChatID int64
TGID int64
Text string
ParseMode string
Plain bool
Buttons [][]commandbot.Button
// AlertID links the message to the operational alert it reports on, when
// there is one. It is what makes the durable row cancellable: resolving the
// alert retires the delivery instead of letting it arrive hours later,
// describing a problem that is already over.
AlertID *int64
}
OutboundMessage is a Telegram call to make after handleTx commits.
type Poller ¶
type Poller struct {
// contains filtered or unexported fields
}
Poller runs the durable long-polling loop.
func NewPoller ¶
func NewPoller( db *sql.DB, client *Client, notifier *notify.Notifier, chats []HealthChat, ownerIDs []int64, logger *slog.Logger, opts ...PollerOption, ) *Poller
NewPoller returns a durable sequential Telegram update poller.
func (*Poller) HandleWebhookUpdate ¶
HandleWebhookUpdate inserts one Telegram webhook update and routes pending updates through the same terminal state machine as polling.
type PollerOption ¶
type PollerOption func(*Poller)
PollerOption configures optional poller integrations.
func WithPollerAdminLogChatID ¶
func WithPollerAdminLogChatID(chatID *int64) PollerOption
WithPollerAdminLogChatID attaches an optional alert delivery chat.
func WithPollerAdmissionConfig ¶
func WithPollerAdmissionConfig(cfg admission.Config) PollerOption
WithPollerAdmissionConfig attaches managed resource admission config.
func WithPollerChatRoles ¶
func WithPollerChatRoles(roles []commandbot.ChatRole) PollerOption
WithPollerChatRoles attaches configured chat roles for owner commands.
func WithPollerOperatorLog ¶
func WithPollerOperatorLog(writer *operatorlog.Writer) PollerOption
WithPollerOperatorLog attaches the operator event-log writer forwarded to each per-update router.
func WithPollerSourceChats ¶
func WithPollerSourceChats(sourceChats SourceChats) PollerOption
WithPollerSourceChats attaches source chat routing config.
func WithPollerStatusEngine ¶
func WithPollerStatusEngine(statusEngine *engine.Engine) PollerOption
WithPollerStatusEngine attaches the status engine.
func WithPollerSubscribeLinks ¶
func WithPollerSubscribeLinks(links messages.SubscribeLinks) PollerOption
WithPollerSubscribeLinks attaches the deployment subscription URLs forwarded to each per-update router for the /boosty and /tribute pages.
type ResourceMemberChecker ¶
type ResourceMemberChecker struct {
// contains filtered or unexported fields
}
ResourceMemberChecker maps managed resources to Telegram chat membership.
func NewClubMemberChecker ¶
func NewClubMemberChecker( client resourceMemberClient, clubChatID int64, clubChannelID int64, ) *ResourceMemberChecker
NewClubMemberChecker maps managed club resources to Telegram chat IDs for engine protection checks.
func (*ResourceMemberChecker) GetChatMember ¶
func (c *ResourceMemberChecker) GetChatMember( ctx context.Context, resource domain.Resource, tgID int64, ) (*models.ChatMember, error)
type RoutePreflight ¶
RoutePreflight contains network reads performed before handleTx.
type RouteResult ¶
type RouteResult struct {
Status store.TelegramUpdateStatus
Effects []OutboundMessage
// PostCommitSync, when set, is a reconcile pass the poller must run on the
// pool AFTER this update's transaction commits. Running reconcile inside the
// update transaction would deadlock the single SQLite connection during the
// live decide phase (see adminSync).
PostCommitSync *SyncJob
}
RouteResult describes how an update reached a terminal state.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router dispatches persisted updates to phase-specific handlers.
func NewRouter ¶
func NewRouter( deps RouterDeps, chats []HealthChat, ownerIDs []int64, logger *slog.Logger, opts ...RouterOption, ) *Router
NewRouter returns a router bound to one handleTx repository set.
type RouterDeps ¶
type RouterDeps struct {
DB store.DBTX
Users *store.Users
Subscriptions *store.Subscriptions
Grants *store.Grants
Meta *store.Meta
Audit *store.Audit
Alerts *store.Alerts
Whitelist *store.Whitelist
Revocations *store.Revocations
Outbox *store.Outbox
Invites *store.Invites
Ops *store.Ops
UpdateID int64
AdminLogChatID *int64
ChatRoles []commandbot.ChatRole
SubscribeLinks messages.SubscribeLinks
}
RouterDeps are transaction-bound repositories for one update.
type RouterOption ¶
type RouterOption func(*Router)
RouterOption configures optional routes.
func WithAdmissionConfig ¶
func WithAdmissionConfig(cfg admission.Config) RouterOption
WithAdmissionConfig attaches managed club-resource admission config.
func WithChatInfo ¶
func WithChatInfo(resolve commandbot.ChatTitleResolver) RouterOption
WithChatInfo attaches a live chat-title resolver for owner /chats output.
func WithMemberChecker ¶
func WithMemberChecker(checker engine.MemberChecker) RouterOption
WithMemberChecker attaches live club membership checks for revocation safety.
func WithOperatorLog ¶
func WithOperatorLog(writer *operatorlog.Writer) RouterOption
WithOperatorLog attaches the operator event-log writer so admission, engine and owner-command paths can emit operator events durably.
func WithPreflight ¶
func WithPreflight(preflight RoutePreflight) RouterOption
WithPreflight attaches pre-transaction live observations.
func WithSourceChats ¶
func WithSourceChats(chats SourceChats) RouterOption
WithSourceChats attaches source-chat routing config.
func WithStatusEngine ¶
func WithStatusEngine(e *engine.Engine) RouterOption
WithStatusEngine attaches the status engine to the router.
type SourceChats ¶
SourceChats identifies configured subscription source chats.