telegram

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 29 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package telegram owns the concrete Telegram Bot API client and the durable long-polling runtime.

Index

Constants

This section is empty.

Variables

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

func IsDMBlocked(err error) bool

IsDMBlocked reports whether err is a normalized blocked-DM response.

func IsExpectedNoop

func IsExpectedNoop(action string, err error) bool

IsExpectedNoop reports whether a Bot API error means the action is already satisfied or no longer meaningful.

func IsForbidden

func IsForbidden(err error) bool

IsForbidden reports whether err is a normalized Telegram 403.

func IsPermanentRights

func IsPermanentRights(err error) bool

IsPermanentRights reports whether err is a non-retryable rights issue.

func IsRateLimited

func IsRateLimited(err error) bool

IsRateLimited reports whether err is a normalized 429.

func IsTimeout added in v0.2.0

func IsTimeout(err error) bool

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

func IsTransient(err error) bool

IsTransient reports whether err is worth retrying without treating the action as suspect: a request timeout or a rate limit.

func NormalizeError

func NormalizeError(method string, err error) error

NormalizeError maps Bot API errors to typed categories.

func RetryAfter

func RetryAfter(err error) (time.Duration, bool)

RetryAfter returns Telegram retry_after when err is a normalized 429.

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) Error

func (e *APIError) Error() string

func (*APIError) TelegramCategory

func (e *APIError) TelegramCategory() string

TelegramCategory exposes a stable string category to packages that should not import telegram just to classify best-effort send errors.

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

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

func (c *Client) AnswerCallbackQuery(ctx context.Context, callbackQueryID string) error

AnswerCallbackQuery acknowledges a callback query so the client clears the inline-button spinner. No user-facing text is shown.

func (*Client) ApproveChatJoinRequest

func (c *Client) ApproveChatJoinRequest(
	ctx context.Context,
	chatID, userID int64,
) error

ApproveChatJoinRequest approves one pending join request.

func (*Client) BanChatMember

func (c *Client) BanChatMember(ctx context.Context, chatID, userID int64) error

BanChatMember bans one user from a chat or channel.

func (*Client) BotID

func (c *Client) BotID() int64

BotID returns the numeric ID encoded in the token prefix.

func (c *Client) CreateChatInviteLink(
	ctx context.Context,
	params CreateChatInviteLinkParams,
) (*models.ChatInviteLink, error)

CreateChatInviteLink creates a managed invite link.

func (*Client) DeclineChatJoinRequest

func (c *Client) DeclineChatJoinRequest(
	ctx context.Context,
	chatID, userID int64,
) error

DeclineChatJoinRequest declines one pending join request.

func (*Client) DeleteWebhook

func (c *Client) DeleteWebhook(ctx context.Context) error

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) GetChat

func (c *Client) GetChat(ctx context.Context, chatID int64) (*models.ChatFullInfo, error)

GetChat returns full chat information.

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) GetMe

func (c *Client) GetMe(ctx context.Context) (*models.User, error)

GetMe verifies the token and returns the bot user.

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 (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

func (c *Client) SendMessage(ctx context.Context, chatID int64, text string) error

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

func (c *Client) SetMyCommands(ctx context.Context, ownerIDs []int64) error

SetMyCommands registers user commands globally and owner commands in each owner private chat scope.

func (*Client) SetWebhook

func (c *Client) SetWebhook(
	ctx context.Context,
	url string,
	secretToken string,
	allowedUpdates []string,
) error

SetWebhook registers Telegram webhook delivery with an explicit update set.

func (*Client) UnbanChatMember

func (c *Client) UnbanChatMember(
	ctx context.Context,
	chatID, userID int64,
	onlyIfBanned bool,
) error

UnbanChatMember unbans one user from a chat or channel.

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"
	ErrorCategoryUnauthorized    ErrorCategory = "unauthorized"
	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

func (p *Poller) HandleWebhookUpdate(ctx context.Context, raw []byte) error

HandleWebhookUpdate inserts one Telegram webhook update and routes pending updates through the same terminal state machine as polling.

func (*Poller) Run

func (p *Poller) Run(ctx context.Context) error

Run recovers pending rows, then polls Telegram until ctx is cancelled.

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(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

type RoutePreflight struct {
	Snapshot *engine.Snapshot
}

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.

func (*Router) Route

func (r *Router) Route(ctx context.Context, update *models.Update) (RouteResult, error)

Route applies domain changes for an update without calling Telegram.

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

type SourceChats struct {
	BoostyGroupID      int64
	TributeChannelID   int64
	TributeObservation bool
}

SourceChats identifies configured subscription source chats.

type SyncJob added in v0.1.1

type SyncJob struct {
	Config reconcile.Config
	Target *int64 // nil => full RunOnce; non-nil => RunUser(*Target)
}

SyncJob is a deferred reconcile pass requested by an owner /sync command. It is executed post-commit, on the pool, by the poller.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL