telegram

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: AGPL-3.0 Imports: 32 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 is the Bot API client of Telegram Connections (C-14.FR-1, FR-10 to FR-12): calls to `<base>/bot<token>/<method>` through internal/outbound with the Connection's proxy, in the client class of the caller (ADR-0015), with the bot token registered for redaction so that every error and log line carries `bot[redacted]`; the step-by-step connection check with its dry probe; and the receiving of updates — long polling on the Leader or the webhook endpoint with its secret token — and the update router both modes share; the Destination check of a Telegram Destination and the delivery adapter of its Root messages.

Index

Constants

View Source
const (
	StepDryProbe       = "dry_probe"
	StepGetMe          = "get_me"
	StepGetWebhookInfo = "get_webhook_info"
)

The steps of the connection check of a Telegram Connection (C-14.FR-11).

View Source
const (
	MessageNotBotAPI    = "This is not a Bot API."
	MessageWrongPrefix  = "Wrong path prefix: the server answered 404."
	MessageProxyRefused = delivery.MessageProxyRefused
	MessageTokenInvalid = "The bot token is not valid." //nolint:gosec // G101: a message, not a credential

)

The messages of the steps that failed: what answered the dry probe, and a token getMe refused.

View Source
const (
	CodeNotBotAPI        = "not_bot_api"
	CodeWrongPrefix      = "wrong_path_prefix"
	CodeUnexpectedStatus = "unexpected_status"
	CodeTokenInvalid     = "token_invalid"
	CodeWebhookSet       = "webhook_set"
)

The codes of the messages above (ConnectionCheckStep.code, DestinationCheckItem.code), which clients translate: the dry probe that reached no Bot API, a token getMe refused, and a webhook that is set. The DNS, TLS, timeout and proxy failures of the dry probe, and any other failure, have the codes of delivery.FailureCode.

View Source
const (
	ViaDirect = "direct"
	ViaProxy  = "proxy"
)

The paths of a Connection's requests (ConnectionPath).

View Source
const (
	StatusCreator       = "creator"
	StatusAdministrator = "administrator"
)

The statuses of a chat member that may write to the chat as an admin.

View Source
const (
	StepChannelExists    = "channel_exists"
	StepDiscussionGroup  = "discussion_group"
	StepBotRightsChannel = "bot_rights_channel"
	StepBotRightsGroup   = "bot_rights_group"
)

The steps of the Destination check of a Telegram Destination (C-14.FR-14).

View Source
const (
	MessageChannelNotFound = "The channel was not found, or the bot cannot see it."
	MessageNotChannel      = "This chat is not a channel."
	MessageNoComments      = "Comments are not enabled for this channel. Enable comments in the channel settings in " +
		"Telegram; this creates its discussion group."
	MessageChannelNotAdmin = "The bot is not an admin of the channel."
	MessageMayNotPost      = "The bot may not post messages in the channel."
	MessageMayNotEdit      = "The bot may not edit messages in the channel."
	MessageMoved           = "The channel or its discussion group changed since the Destination was saved. Save the " +
		"Destination again."
)

The messages of the steps that failed; the two of the discussion group are those of reference.md.

View Source
const (
	CodeChannelNotFound = "channel_not_found"
	CodeNotChannel      = "not_a_channel"
	CodeNoComments      = "comments_disabled"
	CodeChannelNotAdmin = "bot_not_channel_admin"
	CodeMayNotPost      = "bot_may_not_post"
	CodeMayNotEdit      = "bot_may_not_edit"
	CodeGroupNotAdmin   = "bot_not_group_admin"
	CodeMoved           = "changed_since_saved"
)

The codes of the messages above (DestinationCheckItem.code), which clients translate; a token getMe refused has CodeTokenInvalid, and any other failure the code of delivery.FailureCode.

View Source
const (
	// KindCallbackQuery is a button press.
	KindCallbackQuery = "callback_query"
	// KindChatMessage is a message, an edit or a post in a channel or a group, such as the automatic copy of a channel
	// post in its discussion group, which Copies processes.
	KindChatMessage = "chat_message"
	// KindPrivateMessage is a message to the bot in a private chat, such as `/start <token>`, which Start, the
	// handler of Account links, processes.
	KindPrivateMessage = "private_message"
	// KindMyChatMember is a change of the bot's own membership in a chat.
	KindMyChatMember = "my_chat_member"
	// KindOther is any other update.
	KindOther = "other"
)

The kinds of updates the router hands on (C-14.FR-1, FR-8).

View Source
const (
	WebhookPath    = "/api/v1/callbacks/telegram/"
	WebhookPattern = "POST " + WebhookPath + "{connection_id}"
	// SecretTokenHeader carries the secret token Muster registered with setWebhook.
	SecretTokenHeader = "X-Telegram-Bot-Api-Secret-Token" //nolint:gosec // G101: a header name, not a credential
)

The webhook endpoint of Telegram Connections on the ingest listener, telegramWebhook (C-14.AC-11): Telegram posts the updates of a Connection in the webhook mode to WebhookPath followed by its public_id.

View Source
const (

	// CallTimeout bounds every call but a long poll; the dry probe names it when nothing answered within it.
	CallTimeout = 10 * time.Second
)

The timeouts of a call and the largest answer read.

View Source
const ConnectionWindow = 60 * time.Second

ConnectionWindow is how close two 429s of different Destinations of a Connection are for the second to hold the whole Connection.

View Source
const DefaultBaseURL = "https://api.telegram.org"

DefaultBaseURL is connection.telegram.bot_api_base_url: Telegram's cloud Bot API.

View Source
const LengthLimit = 4096

LengthLimit is the longest text of a message (C-14.FR-13, C-12.FR-11). Telegram counts UTF-16 code units after it parsed the entities; Muster counts the UTF-16 code units of the HTML it sends, which are never fewer.

View Source
const MaxAnswerLength = 200

MaxAnswerLength is the longest text of an answer to a press, in characters (C-14.FR-5).

View Source
const ParallelUpdates = 2

ParallelUpdates is telegram.parallel_updates (P-52): the most updates one process routes at a time, over all its Telegram Connections and both update modes; the others wait for a slot. An update being routed holds a connection of the main pool for its update lock while its handler takes one more at a time, so two take at most four of the default ten (pool_max_conns), next to the half of the pool that the processing lanes may take.

View Source
const (
	PollTimeout = 25 * time.Second
)

PollTimeout is the long-poll timeout of getUpdates: how long the Bot API holds a getUpdates open while no update comes. The request itself may take pollMargin longer.

View Source
const PressMaxAge = time.Hour

PressMaxAge is telegram.press_max_age (C-14.FR-4): a press whose update arrives after the Connection received no updates for longer is dropped.

View Source
const (
	// ReadInterval is how often the poller reads the Connections again when no change woke it.
	ReadInterval = 30 * time.Second
)
View Source
const StepMessage = "message"

StepMessage is the step of a test and the item of a preview that is the Root message.

View Source
const WarningBaseURLUsesHTTP = "base_url_uses_http"

WarningBaseURLUsesHTTP is the warning of a Connection whose Bot API base URL is http (C-14.FR-10): the bot token travels unencrypted.

Variables

View Source
var AllowedUpdates = []string{"message", "edited_message", "channel_post", "callback_query", "my_chat_member"}

AllowedUpdates are the update types Muster asks for, explicitly, in getUpdates and setWebhook (C-14.FR-1).

View Source
var ErrBaseURL = errors.New("the Bot API base URL is not an absolute http or https URL without user information, " +
	"query or fragment")

ErrBaseURL is a Bot API base URL that breaks the rules of C-14.FR-10.

View Source
var ErrNoTarget = errors.New("the destination has no telegram connection")

ErrNoTarget is a Destination that has no Telegram Connection to send through: it, or its Connection, no longer exists, or it is not a Telegram Destination.

View Source
var ErrNoWebhook = errors.New("no such telegram connection")

ErrNoWebhook is a webhook request for a Connection that does not exist, is deleted or is not a Telegram one.

Functions

func BaseURLWarnings

func BaseURLWarnings(base string) []string

BaseURLWarnings are the warnings of a normalized base URL: WarningBaseURLUsesHTTP for http.

func MessageGroupNotAdmin

func MessageGroupNotAdmin(group string) string

MessageGroupNotAdmin is the message of a discussion group whose admins do not include the bot.

func NewSecret

func NewSecret() (logging.Secret, error)

NewSecret is a new random secret token for a webhook.

func NewWebhook

func NewWebhook(cfg WebhookConfig) http.Handler

NewWebhook is the webhook endpoint (C-14.FR-1, AC-11): it answers 401 and changes nothing unless the Connection exists, is in the webhook mode and the header X-Telegram-Bot-Api-Secret-Token equals its secret token, compared in constant time; otherwise it hands the update to the router and answers 200. A body that is not an update is 400; a router that failed is 500, and Telegram sends the update again. A request for a known Connection is in its Request log, refused ones included, through the annotation of requestlog.Inbound (C-23.FR-1).

In the webhook mode a quiet period is no gap: Telegram posts each update as it comes. Only Muster not running is (C-14.FR-4, journal D293): an update that reaches this replica before any other of its Connection, within telegram.press_max_age of the replica's start, gets as its gap the outage just before that start, if any — from its start to the replica's start, since the replica could receive from then on. A press dropped for it receives nothing, so that the presses Telegram kept meanwhile are dropped until another update of the Connection arrives.

func Origin

func Origin(base string) string

Origin is what log lines show of a base URL (C-14.FR-12, C-02.FR-20): its scheme and host only, never its path prefix, which may be a secret of a reverse proxy.

func ParseBaseURL

func ParseBaseURL(raw string) (string, error)

ParseBaseURL checks a Bot API base URL (C-14.FR-10) and returns it normalized: an absolute http or https URL with a host and without user information, query or fragment, whose path prefix is kept without its trailing slashes, so that requests go to `<base>/bot<token>/<method>`.

Types

type Adapter

type Adapter struct {
	Targets Targets
	Clock   clock.Clock
	// contains filtered or unexported fields
}

Adapter is the delivery adapter of Telegram Destinations (C-11.FR-7, C-14): Publish and Update of Root messages as channel posts, Reply into the comment Thread in the discussion group, called by the delivery worker and the interactive path only, in the client class of their Call; and Check, the Destination check of C-14.FR-14 for the Broken probe. Clock is the real clock of the window in which two 429s of a Connection hold all of it; nil is the system's.

func (*Adapter) Check

func (a *Adapter) Check(ctx context.Context, c delivery.Call) delivery.Outcome

Check runs the Destination check of C-14.FR-14 at once, in the client class of c: the Broken probe calls it in the delivery class. A check that finds another channel or discussion group than the stored ones fails with MessageMoved, so that the probe does not end a Broken state that the next send would start again.

func (*Adapter) LengthLimit

func (a *Adapter) LengthLimit() int

LengthLimit is the longest message, which a Root message is shortened to (C-14.FR-13).

func (*Adapter) Markup

func (a *Adapter) Markup() messages.Markup

Markup is the markup of Telegram messages.

func (*Adapter) Publish

Publish creates the Root message m as a channel post with its keyboard (C-14.FR-2, FR-16): the Mentions of a Loud call after its heading, and disable_notification on a Quiet one (C-14.FR-6, F-012). The channel carries only Root messages and Storm summaries; Muster never replies inside it (F-015).

func (*Adapter) Reply

Reply sends m into the Thread of root in the discussion group (C-14.FR-3): a reply to the post's automatic copy while the Thread is attached, which makes it a comment under the post (F-007); a reply to the last link of an unattached chain; or, as the first link of a chain, no reply at all. Muster never replies inside the channel (F-015). The Mentions of a Loud call come first, and only a Loud one carries them (C-12.FR-8); a Quiet one carries disable_notification (C-14.FR-6, F-012). A reply to a copy or link that is gone is refused, as a lost Thread (F-008). A Reminder carries the keyboard "Still on it" and "Unack" on one row (C-14.FR-4), which is never edited: a reply is sent once, and a key rotation re-signs Root messages only.

func (*Adapter) Update

func (a *Adapter) Update(ctx context.Context, c delivery.Call, messageID string, m delivery.Message) delivery.Outcome

Update edits the Root message messageID to m, always with the whole keyboard of its new state (C-14.FR-15, F-011), which an empty one removes on purpose. An edit notifies nobody and mentions nobody (F-012). It never waits for a press: the delivery worker calls it only when no update of the Connection is being handled, and reschedules the edit otherwise, so that a press is answered before the edit its Command causes (C-14.FR-5, AC-18).

type Bindings

type Bindings interface {
	TelegramPressBinding(ctx context.Context, connectionID int64, groupPublicID string, chatID, messageID int64) (
		delivery.Binding, error)
	TelegramReplyBinding(ctx context.Context, connectionID int64, groupPublicID string, chatID, messageID int64) (
		delivery.Binding, error)
}

Bindings are delivery's read of what a press is bound to; *delivery.Service implements it.

type Bots

type Bots struct {
	Conns ConnLookup
	Path  Path
}

Bots read the bots of Telegram Connections for starting an Account link (C-18.FR-2); they implement accountlinks.TelegramBots.

func (Bots) Username

func (b Bots) Username(ctx context.Context, publicID string) (string, error)

Username reads the username of the bot of the Connection publicID with getMe on the interactive path, for a Connection whose check has not stored it yet. No limiter token within the budget, and a 429, are a *delivery.LimitedError; another failure is an *accountlinks.MessengerError without Telegram's text.

type CallbackQuery

type CallbackQuery struct {
	ID      string   `json:"id"`
	From    User     `json:"from"`
	Message *Message `json:"message,omitempty"`
	Data    string   `json:"data,omitempty"`
}

CallbackQuery is a button press.

type Chat

type Chat struct {
	ID       int64  `json:"id"`
	Type     string `json:"type"`
	Title    string `json:"title,omitempty"`
	Username string `json:"username,omitempty"`
}

Chat is the chat of a message.

type ChatInfo

type ChatInfo struct {
	Chat
	LinkedChatID int64 `json:"linked_chat_id,omitempty"`
}

ChatInfo is a chat as getChat answers it: a channel names its discussion group in linked_chat_id only while comments are enabled (F-002).

type ChatMember

type ChatMember struct {
	Status          string `json:"status"`
	CanPostMessages bool   `json:"can_post_messages"`
	CanEditMessages bool   `json:"can_edit_messages"`
}

ChatMember is a membership as getChatMember answers it; the rights to post and edit are named for channels only.

type Check

type Check struct {
	Steps   []Step
	Bot     *User
	Webhook *WebhookInfo
}

Check is the result of a connection check: its three steps, the bot once getMe passed and the webhook once getWebhookInfo passed.

func RunCheck

func RunCheck(ctx context.Context, saved, probe *Client, run Runner, realClock clock.Clock) (Check, error)

RunCheck runs the connection check (C-14.FR-11) through run, timing each step on the real clock:

  1. dry_probe — `GET <base>/bot0:x/getMe` without the token, which passes on a 401 answer with a JSON body and otherwise names what answered;
  2. get_me — with the token: the bot;
  3. get_webhook_info — whether a webhook is set, with its host in the message, and the pending updates.

With probe set — the client of an address the token may not go to, which has no token — only the dry probe runs, against it, and steps 2 and 3 are skipped, on the path of probe: a stored token never reaches another address than its saved base URL (C-13.FR-14). saved may then be nil, for a check without any token. A dry probe that fails skips steps 2 and 3 too, so that the token never goes to a server that is not a Bot API; a getMe that fails skips step 3.

func (Check) Failed

func (c Check) Failed() (Step, bool)

Failed is the first step that failed, if any.

func (Check) OK

func (c Check) OK() bool

OK reports whether no step failed; skipped steps do not fail a check.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client calls the Bot API of one Connection, in the interactive and the delivery client classes, and in the background class for long polling and muster doctor; the outbound client of a class is built on its first call.

func NewClient

func NewClient(n Network, s Settings) (*Client, error)

NewClient builds the client of the Connection s, checking its settings with the interactive class. Its requests go to the Bot API base URL, or to what s.Route answers for it and the bot token when it answers. The bot token and the proxy password are registered for redaction.

func (*Client) BotID

func (c *Client) BotID(ctx context.Context, class outbound.Class) (int64, Result)

BotID is the user id of the bot, read with getMe on first use and kept with the client.

func (*Client) DeleteWebhook

func (c *Client) DeleteWebhook(ctx context.Context, class outbound.Class) Result

DeleteWebhook removes the webhook, so that long polling works again; pending updates are kept.

func (*Client) DryProbe

func (c *Client) DryProbe(ctx context.Context, class outbound.Class) Result

DryProbe is `GET <base>/bot0:x/getMe` without the token (C-14.FR-11): a Bot API answers it 401 with a JSON body. The Result is the raw answer, which the check names; a 429 is Transient, never a RetryAfter.

func (*Client) GetChat

func (c *Client) GetChat(ctx context.Context, class outbound.Class, chat string) (ChatInfo, Result)

GetChat reads the chat named by an id or an @username.

func (*Client) GetChatMember

func (c *Client) GetChatMember(ctx context.Context, class outbound.Class, chat string, user int64) (ChatMember,
	Result)

GetChatMember reads the membership of the user in the chat; outside a supergroup the bot gets 403 (F-003).

func (*Client) GetMe

func (c *Client) GetMe(ctx context.Context, class outbound.Class) (User, Result)

GetMe reads the bot: the check of its token.

func (*Client) GetUpdates

func (c *Client) GetUpdates(ctx context.Context, offset *int64, timeout time.Duration) ([]Update, Result)

GetUpdates makes one long poll in the background class: the updates from offset, when it is set, of the types of AllowedUpdates, waiting up to timeout for one. The background class retries transient failures and 429 until ctx ends; a 409 from a second poller or a set webhook ends the call at once.

func (*Client) GetWebhookInfo

func (c *Client) GetWebhookInfo(ctx context.Context, class outbound.Class) (WebhookInfo, Result)

GetWebhookInfo reads whether a webhook is set, which makes long polling fail with 409, and how many updates wait.

func (*Client) Origin

func (c *Client) Origin() string

Origin is the scheme and host of the client's base URL, all that log lines show of it.

func (*Client) SetWebhook

func (c *Client) SetWebhook(ctx context.Context, class outbound.Class, hookURL string, secret logging.Secret) Result

SetWebhook sets the webhook at hookURL with the secret token header secret and AllowedUpdates, one connection at a time, so that updates arrive in order. Its record in the Request log masks the secret token.

func (*Client) Via

func (c *Client) Via() string

Via is how the requests of the client travel: ViaDirect or ViaProxy.

type Commands

type Commands interface {
	Acknowledge(ctx context.Context, c groups.Caller, publicID string) (groups.Result, error)
	Unacknowledge(ctx context.Context, c groups.Caller, publicID string) (groups.Result, error)
	Resolve(ctx context.Context, c groups.Caller, publicID string, note *string) (groups.Result, error)
	Snooze(ctx context.Context, c groups.Caller, publicID string, end groups.SnoozeEnd) (groups.Result, error)
	Unsnooze(ctx context.Context, c groups.Caller, publicID string) (groups.Result, error)
	AnswerReminder(ctx context.Context, c groups.Caller, publicID string) (groups.Result, error)
}

Commands are the Commands a button runs; *groups.Service implements it.

type Conn

type Conn struct {
	ID       int64
	PublicID string
	Client   *Client
}

Conn is a Telegram Connection as the update path knows it: its ids and its client.

type ConnLookup

type ConnLookup interface {
	TelegramConn(ctx context.Context, publicID string) (Conn, error)
}

ConnLookup finds a Telegram Connection that is not deleted with its client; *connections.Service implements it.

type Copies

type Copies struct {
	Learner CopyLearner
}

Copies is the handler of the messages of channels and groups (KindChatMessage) on the update router (C-14.FR-3): a group message with is_automatic_forward whose forward_origin is a channel is the automatic copy of the post forward_origin.message_id (F-005), and a group message that replies to such a copy is a person's comment, which teaches the same copy (F-007). The edit_date a copy carries from the start changes nothing, and neither does the edited_message Telegram sends when it mirrors an edit of the post onto the copy (F-005, F-006): a copy is never an edit. Every other message is ignored. It is one short transaction of delivery and touches no connections row, as the router asks of its handlers.

func (Copies) Handle

func (h Copies) Handle(ctx context.Context, c Conn, u Update) error

Handle learns the copy that u teaches, if any; a failure leaves the update to come again, but a copy that can never be learned is dropped.

type CopyLearner

type CopyLearner interface {
	LearnCopy(ctx context.Context, c delivery.Copy) error
}

CopyLearner learns the automatic copy of a channel post, declared by its consumer; *delivery.Service implements it, since only delivery writes the copy buffer and the deliveries whose Threads the copy attaches.

type DestinationCheck

type DestinationCheck struct {
	Steps        []DestinationStep
	ChannelID    int64
	ChannelTitle string
	GroupID      int64
	GroupTitle   string
	Outcome      delivery.Outcome
}

DestinationCheck is the result of a Destination check: the steps that ran; once the channel was read its numeric id and title, and once its discussion group was found the group's id and title; and the outcome of the whole — ok, or the outcome of the step that failed — for the Broken probe.

func CheckDestination

func CheckDestination(ctx context.Context, c *Client, run Runner, channel string) (DestinationCheck, error)

CheckDestination runs the Destination check of the channel, an id or an @username, without sending a message (C-14.FR-14): getChat on the channel — it exists and is a channel — whose linked_chat_id is its discussion group (F-002); getChatMember for the bot in the channel — an admin allowed to post and edit messages (F-001); then getChat on the group for its title and getChatMember for the bot there — an admin, who may always post in a group; a bot outside the group gets 403 (F-003). The bot's id comes from getMe once per client, which later checks skip. A step that fails ends the check: a refusal that a person must fix is Fatal with the step's message, which the Broken probe keeps as the reason; an answer that says nothing of the chat, such as a timeout, keeps its own outcome. Each failure has its code: the code of its message, or the code of Result.FailureCode for the masked text of an answer.

func (DestinationCheck) Moved

func (c DestinationCheck) Moved(channelID, groupID int64) bool

Moved reports whether a check that passed found another channel or discussion group than the ids stored with the Destination, 0 for one not known: comments were linked to another group, or the @username moved to another channel. Muster sends to the stored ids, which a save of the Destination updates.

func (DestinationCheck) OK

func (c DestinationCheck) OK() bool

OK reports whether every step passed.

type DestinationStep

type DestinationStep struct {
	Name    string
	OK      bool
	Message string
	Code    string
	Outcome delivery.Outcome
}

DestinationStep is one step of a Destination check: whether it passed, and when it failed the message for the person, in English, its code, which clients translate, and the outcome for delivery.

type Handler

type Handler func(ctx context.Context, c Conn, u Update) error

Handler processes the updates of one kind. An error leaves the update unconfirmed, so that it comes again: with long polling at the next poll, with a webhook when Telegram retries it. A handler runs under the Connection's update lock — a transaction advisory lock keyed by the Connection, not its connections row — so it may run while a save of the Connection holds that row; it must be short, since the next update of the Connection waits for it and every edit of its Root messages is rescheduled until it ends.

type Hooks

type Hooks interface {
	Hooked(ctx context.Context, publicID string) (Conn, logging.Secret, error)
}

Hooks find the Connection of a webhook request and its secret token; a Telegram Connection that is not in the webhook mode, or has no secret token, is returned with an empty one, which the endpoint refuses; one that is unknown, deleted or not a Telegram one is ErrNoWebhook. *connections.Service implements it.

type Linker

type Linker interface {
	LinkTelegram(ctx context.Context, conn accountlinks.TelegramConnection, token string,
		from accountlinks.TelegramAccount, reply func(ctx context.Context, text string) error) error
}

Linker links the Telegram account that sent `/start <token>`; *accountlinks.Service implements it.

type Links interface {
	Lookup(ctx context.Context, identitySpace, externalID string) (accountlinks.User, error)
}

Links map a Telegram account to its User; *accountlinks.Service implements it.

type Message

type Message struct {
	MessageID int64  `json:"message_id"`
	Chat      Chat   `json:"chat"`
	From      *User  `json:"from,omitempty"`
	Text      string `json:"text,omitempty"`
}

Message is a message or a channel post, with the fields the router reads; handlers read the rest from Raw.

type Network

type Network struct {
	Policy   outbound.PolicySource
	Log      *logging.Logger
	Real     clock.Clock
	Resolver outbound.Resolver
	Recorder outbound.Recorder
}

Network is what a Client needs besides its Connection: the outbound address policy, the logger, the real clock of the outbound metrics, a resolver (nil: the system resolver) and the Request log, nil for none (C-23.FR-1). Its fields are those of mattermost.Network, so that one converts into the other.

type Offsets

type Offsets interface {
	// HandleOnce runs f for the update updateID of the Connection id unless the stored offset is past it, holding the
	// Connection's update lock meanwhile, so that a second poller or a webhook request with the same update waits and
	// then skips it; once f succeeded it raises the offset to updateID+1. It reports whether f ran. An error of f
	// stores nothing.
	HandleOnce(ctx context.Context, id, updateID int64, f func(ctx context.Context) error) (bool, error)
}

Offsets keep the offset of each Connection's updates, connections.telegram_update_offset: the id after the last update handed to the router. Both update modes share it, so that an update is handled once.

type Outage

type Outage struct {
	AliveAt       time.Time
	DowntimeStart time.Time
	DowntimeEnd   time.Time
}

Outage is when Muster was last known not to run, as the Leader recorded it: its alive mark, and the start and end of the latest downtime period; the zero time for none.

type Outages

type Outages interface {
	Outage(ctx context.Context) (Outage, error)
}

Outages read the Outage; *connections.Service implements it.

type Path

type Path interface {
	Do(ctx context.Context, s delivery.Subject, op delivery.Op) (delivery.Outcome, error)
}

Path is the interactive path, declared by its consumer; *delivery.Interactive implements it.

type Polled

type Polled struct {
	Conn
	Version int64
	Offset  *int64
}

Polled is a Telegram Connection in the long-polling mode: its client, its version, which restarts its poller when it changes, and its stored offset.

type Poller

type Poller struct {
	Source Source
	Router *Router
	Log    *logging.Logger
	// Outages say whether Muster was not running before a run starts; nil is never.
	Outages Outages
	// Clock is the business clock the gaps are measured on; nil measures none.
	Clock clock.Clock
	// Every is how often the Connections are read again without a wake; 0 is ReadInterval.
	Every time.Duration
	// contains filtered or unexported fields
}

Poller is the long polling of an Organization's Telegram Connections (C-14.FR-1), the Leader task telegram_polling (C-02.FR-10): one poller per Connection in the long-polling mode calls getUpdates with the stored offset, the long-poll timeout and AllowedUpdates, hands the updates to the router, which stores the offset after each, so that a new Leader resumes where the old one stopped. A 409 from a second poller or a set webhook only backs off with jitter and logs telegram_poll_conflict (F-018); any other failure logs telegram_poll_failed and backs off. Neither is a delivery outcome or makes anything Broken. Running it on two replicas at once is safe: Telegram answers one of the pollers 409, and the router handles an update once.

It keeps in memory, per Connection, when its updates were last received — the end of the last successful poll — and gives each update the gap before the poll that brought it (C-14.FR-4, journal D293): a poll that failed receives nothing, and a full batch, which may have left more waiting, passes its gap on to the next poll. A Connection that a run polls from its first listing on, and that this process has not polled yet, is measured from the start of the run, or from the start of the outage just before it that the Outages name: the updates Telegram kept while Muster was not running arrive after that gap. A Connection that enters long polling later in a run is measured from then, and one that leaves it is forgotten. Without a Clock no gap is measured.

func (*Poller) Run

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

Run polls until ctx ends, which is when the Leader loses the lock or stops, and stops every poller before it returns. A failed read of the Connections stops them too and returns its error, so that the Leader task runs again.

func (*Poller) Wake

func (p *Poller) Wake()

Wake reads the Connections again at once: a Connection changed, maybe on another replica.

type Presses

type Presses struct {
	Bindings Bindings
	Links    Links
	Commands Commands
	// Roles are the Permissions of each Role, which the linked User presses with.
	Roles auth.Roles
	// Keys verify the signed button data: the Keyring.
	Keys buttons.Keys
	// Path answers the presses on the interactive path.
	Path Path
	// Business is the business clock, from which a Snooze lasts its duration.
	Business clock.Clock
	// PublicURL is MUSTER_PUBLIC_URL, the base of the profile link.
	PublicURL string
	Log       *logging.Logger
}

Presses is the handler of button presses, the callback_query updates of the router (C-14.FR-4, FR-5).

func (*Presses) Handle

func (p *Presses) Handle(ctx context.Context, c Conn, u Update) error

Handle handles one callback_query of the Connection c (C-14.FR-4, FR-5). A press whose update arrived after the Connection received no updates for longer than PressMaxAge is dropped unanswered and logged telegram_press_dropped. Otherwise the button data — at most 64 bytes: the compact action id, the key id and the signature — is verified with any key of the Keyring and must name the Alert Group whose Root message is the channel post pressed, in the channel of a Telegram Destination of the Connection, or whose Reminder is the message pressed in its discussion group; anything else is answered "This button could not be verified; nothing was changed." A press on a Reminder whose key left the Keyring is answered "This button has expired; use the buttons on the Alert Group's message" (C-17.FR-6). The Telegram account from.id is mapped to its User through its Account link in the one identity space of Telegram; the Command runs as that User through the dispatcher with the Transport telegram, and the press is answered with answerCallbackQuery — "Done: {command}" ("Done: Still on it" for a Reminder's answer), the refusal, or for an account without a link the link to the profile — cut to MaxAnswerLength characters, in the language of the Route. The Root message is edited through delivery, never here, and only after the answer: the handler runs under the Connection's update lock, which the delivery worker tries before an edit, rescheduling the edit while it is held. The update is confirmed whatever the press led to, so that a press never runs twice; only a cancelled context leaves it unconfirmed. A press of a test message, whose verified data name the Destination under test, changes nothing and is answered "This is a test message; nothing was changed" (C-16.FR-3).

type Result

type Result struct {
	Outcome     delivery.Outcome
	Status      int
	Code        int
	Description string
	NotJSON     bool
	Network     string
	Detail      string
	Blocked     bool
	// Body is the answer as received, which only a Destination test shows, masked (C-16.FR-2).
	Body []byte
}

Result is how a call ended: its outcome for delivery, classified as C-14.FR-7 says; the status of the answer, 0 without one; the error_code and description of an `ok: false` answer, the description untrusted and masked; whether the answer was not JSON; when the call got no answer, what failed (outbound.Network*) and its masked detail; and whether the outbound address policy refused the address.

func (Result) Conflict

func (r Result) Conflict() bool

Conflict reports whether the call was refused with 409: a second poller on the token (F-018) or a set webhook.

func (Result) FailureCode

func (r Result) FailureCode() string

FailureCode is the check code of a call that failed for a reason its check does not name (delivery.FailureCode).

func (Result) OK

func (r Result) OK() bool

OK reports whether the call succeeded.

type Route

type Route func(baseURL string, token logging.Secret) string

Route names the base URL a Connection's requests go to instead of its Bot API base URL, by that address and the bot token: under `muster dev` the fake Telegram server for the default address with one of its published tokens; an empty answer is the Connection's own address.

type Router

type Router struct {
	Offsets Offsets
	Log     *logging.Logger
	// contains filtered or unexported fields
}

Router is the one entry of updates for both modes (C-14.FR-1): it ignores an update the Connection has already handled, hands each kind to the handler registered for it — the messages of channels and groups to Copies, the presses and private messages to theirs — and drops a kind without a handler with telegram_update_dropped; then it stores the offset after the update. It routes at most ParallelUpdates updates at a time.

func (*Router) Handle

func (r *Router) Handle(kind string, h Handler)

Handle registers h for the updates of kind, replacing an earlier handler.

func (*Router) Route

func (r *Router) Route(ctx context.Context, c Conn, u Update) (bool, error)

Route hands u of the Connection c on and reports whether it was new, once a slot of ParallelUpdates is free. An update before the stored offset was handled already and changes nothing. A handler's error stores no offset, so that the update comes again.

type Runner

type Runner func(ctx context.Context, f func(ctx context.Context, c delivery.Call) delivery.Outcome) (delivery.Outcome,
	error)

Runner makes one request of a check with the Call it is made in: on the interactive path when a person waits for it, at once for muster doctor. Its error is the runner's own — no limiter token within the budget — and ends the check.

func Direct

func Direct(c delivery.Call) Runner

Direct is the Runner that calls at once with c: muster doctor, which waits for no token.

func Interactive

func Interactive(in Path, s delivery.Subject) Runner

Interactive is the Runner of a check a person waits for: each request through the interactive path, limited by s.

type Settings

type Settings struct {
	BaseURL string
	Token   logging.Secret
	Proxy   *outbound.Proxy
	Owner   outbound.Owner
	Route   Route
}

Settings are a Connection as its client needs it: the normalized Bot API base URL, the bot token — empty for the client of the dry probe of an unsaved base URL — and the proxy, nil for none; the Connection whose Request log keeps its requests, none for a client that records nothing; and the Route of `muster dev`, nil outside it.

type Source

type Source interface {
	Polling(ctx context.Context) ([]Polled, error)
}

Source lists the Telegram Connections of the Organization that are not deleted and are in the long-polling mode; *connections.Service implements it.

type Start

type Start struct {
	Links Linker
	// Path is the interactive path the bot's replies go through, on the Connection's limiter.
	Path Path
}

Start is the handler of the private messages of the router (C-14.FR-8, C-18.FR-2): `/start <token>`, which Telegram sends when a person follows the deep link of their profile and presses Start, links that person's account. Any other private message, an edit, and a message of a bot are ignored without an answer.

func (*Start) Handle

func (s *Start) Handle(ctx context.Context, c Conn, u Update) error

Handle hands `/start <token>`, or `/start@<bot> <token>`, to the Linker with the account that sent it and a reply to its private chat; like every update it runs under the Connection's update lock. An error of the Linker — a database failure — leaves the update unconfirmed, so that it comes again.

type Step

type Step struct {
	Name    string
	OK      bool
	Skipped bool
	Latency time.Duration
	Via     string
	Message string
	Code    string
}

Step is one step of a check: whether it passed or was skipped, its latency and path, and what answered when it failed, or the host of a webhook that is set, in English, with its code, which clients translate.

type Target

type Target struct {
	Client       *Client
	ConnectionID int64
	Channel      string
	ChannelID    int64
	GroupID      int64
}

Target is where a Telegram Destination sends: the client of its Connection and the Connection's id; the channel as entered, and the numeric ids of the channel and of its discussion group that its Destination check learned, 0 when unknown.

type Targets

type Targets interface {
	TelegramTarget(ctx context.Context, destinationID int64) (Target, error)
}

Targets find the Target of a Destination by its id, declared by their consumer; *connections.Service implements them. A Destination without one is ErrNoTarget.

type TestRenderer

type TestRenderer interface {
	TestRoot(src *messages.Source, markup messages.Markup, destination string) messages.Rendered
}

TestRenderer renders the Root message of a test or a preview, declared by its consumer; *messages.Renderer implements it.

type Tester

type Tester struct {
	Adapter  *Adapter
	Path     Path
	Renderer TestRenderer
	Budget   time.Duration
	Real     clock.Clock
}

Tester is the Destination test and the preview of Telegram Destinations, on the interactive path Path, the test within Budget (delivery.interactive_budget; zero is delivery.InteractiveBudget), timed on the real clock Real.

func (*Tester) Preview

func (t *Tester) Preview(ctx context.Context, in delivery.TestInput) ([]delivery.PreviewItem, error)

Preview renders, without sending anything, the Root message of the source of in as the Telegram Destination would receive it (C-16.FR-4): the item message in HTML, its text the message and its request the sendMessage call, with the keyboard a test message would carry, whose presses change nothing.

func (*Tester) Test

Test runs the test of the Telegram Destination of in (C-16.FR-1): the step message, sent again as plain text once when Telegram rejects its markup, within the one budget. A Destination whose Connection cannot be read fails it.

type Update

type Update struct {
	UpdateID      int64           `json:"update_id"`
	Message       *Message        `json:"message,omitempty"`
	EditedMessage *Message        `json:"edited_message,omitempty"`
	ChannelPost   *Message        `json:"channel_post,omitempty"`
	CallbackQuery *CallbackQuery  `json:"callback_query,omitempty"`
	MyChatMember  json.RawMessage `json:"my_chat_member,omitempty"`
	Raw           json.RawMessage `json:"-"`
	// Gap is how long the Connection had received no updates before the poll or the webhook request that brought this
	// one, as far as this replica knows (C-14.FR-4): a press after a gap longer than telegram.press_max_age is dropped.
	Gap time.Duration `json:"-"`
}

Update is a Bot API Update: its id, the parts the router reads, and the whole update as it came, for handlers.

func ParseUpdate

func ParseUpdate(b []byte) (Update, error)

ParseUpdate reads an update; it must carry an integer update_id. Unknown fields are kept in Raw only.

func (Update) Kind

func (u Update) Kind() string

Kind is what the update is, for the router: a press, a message of a channel or group, a private message, a change of the bot's membership, or other.

type User

type User struct {
	ID        int64  `json:"id"`
	IsBot     bool   `json:"is_bot"`
	FirstName string `json:"first_name"`
	Username  string `json:"username"`
}

User is the bot as getMe answers it.

type WebhookConfig

type WebhookConfig struct {
	Connections Hooks
	Router      *Router
	// Outages say whether Muster was not running before this replica started; nil is never.
	Outages Outages
	// Clock is the business clock the gaps are measured on; nil measures none.
	Clock clock.Clock
	// BodyLimit bounds the body of an update.
	BodyLimit int64
	Log       *logging.Logger
}

WebhookConfig is what the webhook endpoint needs.

type WebhookInfo

type WebhookInfo struct {
	URL                string `json:"url"`
	PendingUpdateCount int64  `json:"pending_update_count"`
}

WebhookInfo is the answer of getWebhookInfo: the webhook's URL, empty when none is set, and the updates waiting.

Jump to

Keyboard shortcuts

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