telegram

package
v0.171.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0 Imports: 23 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 Caprock's client for the Telegram Bot API, used with a bot the user created themselves (ADR-047), and the bridge that lets the owner talk to their sessions through it.

It speaks plain HTTPS to one documented host and nothing else: getMe to check a token, getUpdates (long polling, so nothing listens for inbound connections) to hear the pairing code, replies and button presses, sendMessage, sendPhoto (a share card, only on the user's click), editMessageReplyMarkup, editMessageText, setMessageReaction, setMyCommands and answerCallbackQuery, and getFile with its download for a photo, file or voice note forwarded to the bot (ADR-081). No webhook, no relay of ours.

The token is in every request URL, so it is in every transport error's text. Nothing this package returns carries it: errors are scrubbed before they leave, because they are logged and shown on the Settings screen.

Index

Constants

View Source
const (
	// ModuleCollection is the module-store collection answers land in.
	ModuleCollection = "telegram"
	// ModuleTextMax bounds a module message's own text, in characters; the
	// header and Telegram's limit leave room above it.
	ModuleTextMax = 3500
)
View Source
const (
	// DefaultGap is the least time between two messages to the chat.
	DefaultGap = time.Second

	// MaxText is Telegram's limit on one message, in characters (UTF-16
	// units, which a rune count bounds from below for everything but
	// astral-plane emoji; the margin below covers them).
	MaxText = 4096
)

Telegram's documented limits for a bot: about one message a second to one chat, bursts allowed, and a 429 with retry_after past that. The outbox keeps under the first and obeys the second, so a run of alerts from five sessions finishing at once arrives as a few messages a second apart rather than a refused burst.

View Source
const CodeDigits = 6

CodeDigits is the length of a pairing code.

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

DefaultBase is the only host this package contacts unless a test or a preview stand points it at a stand-in.

View Source
const (
	// DefaultBurstWait is how long the chat must be quiet before a burst of
	// forwards is asked about.
	DefaultBurstWait = 2 * time.Second
)
View Source
const MaxCaption = 1024

MaxCaption is the longest photo caption Telegram takes, in characters.

View Source
const MaxDownload = 20 << 20

MaxDownload is the largest file the Bot API lets a bot fetch.

View Source
const (
	// PairFor is how long a pairing code works.
	PairFor = 10 * time.Minute
)
View Source
const PremiumURL = "https://caprock.dev/premium/"

PremiumURL is where the Premium line points.

View Source
const StateFile = "telegram.json"

StateFile is the bridge's own file in the data directory, mode 0600. The bot token and the chat id stay in config.json where the weekly report and the alerts have always read them (ADR-024); this holds what the bridge learns as it runs, so a restart neither replays old updates nor forgets which message belongs to which session.

Variables

View Source
var Commands = []Command{
	{"sessions", "Live sessions, numbered"},
	{"new", "Start Claude Code: /new <project> <message>"},
	{"stop", "Stop a session: /stop <number>"},
	{"mute", "Mute a session, or all: /mute <number|all>"},
	{"unmute", "Hear a session again: /unmute <number|all>"},
	{"help", "What this bot can do"},
}

Commands is the bot's menu.

View Source
var ErrBypassConsent = errors.New("bypass needs a one-time consent first: in Caprock on your computer, start a session in Bypass and accept the warning")

ErrBypassConsent is Start refusing a Bypass start that would open on Claude Code's own warning (ADR-041).

View Source
var ErrExpired = errors.New("telegram: dropped, too late to be useful")

ErrExpired is an Out dropped because it waited past its Expires.

View Source
var ErrModuleMessage = errors.New("telegram: not a module message")

ErrModuleMessage is a module message that is not one: no text, too long, or a bad button. Wrapped with what is wrong.

View Source
var ErrMuted = errors.New("telegram: muted with /mute all; send /unmute in the chat")

ErrMuted is a module message refused because the chat is silenced with /mute all.

View Source
var ErrNoToken = errors.New("telegram: no bot token")

ErrNoToken is a call made with no token at all.

View Source
var ErrNotModuleMessage = errors.New("telegram: not a message this module sent")

ErrNotModuleMessage is a message id that is not one this module sent: an unknown one, another module's, the bridge's own, or one sent so long ago that the bridge no longer remembers it.

View Source
var ErrNotPaired = errors.New("telegram: connect a bot and pair a chat in Settings first")

ErrNotPaired is a photo asked for with no bot or no chat set up.

View Source
var ErrStopped = errors.New("telegram: the bot token was refused")

ErrStopped is Run's result when the token was refused: polling with a revoked token only fills the log, so the poller gives up.

View Source
var ErrTokenRefused error = sentence("Telegram does not recognise this token. Copy it again from @BotFather.")

ErrTokenRefused is Connect's answer when Telegram does not know a token. Written for the person reading it on the Settings screen.

Functions

func Escape

func Escape(s string) string

Escape escapes text for Telegram's HTML parse mode, which needs exactly these three.

func MaskToken

func MaskToken(token string) string

MaskToken is how a token is ever shown: "••••••" and its last four characters, enough to tell two bots apart and useless to anyone else.

func ModuleText added in v0.147.0

func ModuleText(name, text string) string

ModuleText is the message as Telegram gets it, in HTML: the module's name on the first line, then its text, escaped.

func NewCode

func NewCode() (string, error)

NewCode returns a random pairing code of CodeDigits digits.

func StartLink(bot, code string) string

StartLink is the t.me link that opens the bot and sends "/start <code>" in one tap.

func TooLarge added in v0.137.0

func TooLarge(err error) bool

TooLarge reports whether err is Download refusing a file for its size.

func Unauthorized

func Unauthorized(err error) bool

Unauthorized reports whether err is Telegram refusing the token itself.

Types

type APIError

type APIError struct {
	Code        int
	Description string
	// RetryAfter is set on a 429: how long Telegram asked us to wait.
	RetryAfter time.Duration
}

APIError is Telegram refusing a call, in its own words: "Unauthorized", "chat not found", "bot was blocked by the user" are all things only the user can fix, and worth reading verbatim.

func (*APIError) Error

func (e *APIError) Error() string

type Bridge

type Bridge struct {
	Host  Host
	Store *Store
	Out   *Outbox
	Log   *slog.Logger
	// Base overrides the API host (tests, preview stands); BaseFrom, when
	// Base is empty, is asked per call.
	Base     string
	BaseFrom func() string
	// PollWait is one long poll; 0 is 25 seconds.
	PollWait time.Duration
	Now      func() time.Time
	// ModuleAnswer writes an answer to a module's message into that
	// module's store (collection ModuleCollection, document doc); it refuses
	// a module the admin key no longer names. nil keeps none (module.go).
	ModuleAnswer func(ctx context.Context, module, doc string, data map[string]any) error

	// Forwards (forward.go): the burst being gathered, the pickers posted,
	// the newest one, and queued forwards by their queue id.
	BurstWait time.Duration
	// contains filtered or unexported fields
}

Bridge runs the bot. Construct with New, then Run.

func New

func New(host Host, dir string, log *slog.Logger) *Bridge

New returns a bridge for host, keeping its state in dir.

func (*Bridge) Active

func (b *Bridge) Active() bool

Active reports whether two-way chat works right now: licensed, switched on, and a chat paired.

func (*Bridge) CancelPairing

func (b *Bridge) CancelPairing()

CancelPairing ends a pairing in progress.

func (*Bridge) Connect

func (b *Bridge) Connect(ctx context.Context, token string) (User, error)

Connect checks a token with getMe and, when Telegram knows it, stores it. A different bot than the one stored starts over: its chat and messages belong to the old one.

func (*Bridge) Converse

func (b *Bridge) Converse(id string)

Converse marks a session as one the owner talks to from Telegram: its replies and questions go there at once, not after the alert's minute.

func (*Bridge) Conversing

func (b *Bridge) Conversing(id string) bool

Conversing reports whether the owner typed into a session from Telegram within the last hour.

func (*Bridge) Deliver

func (b *Bridge) Deliver(m Out, ref Ref, done func(error))

Deliver queues a message about a session and remembers it, so a reply or a button press finds the session again. done, when set, hears the outcome.

func (*Bridge) Disconnect

func (b *Bridge) Disconnect() error

Disconnect forgets the bot, the chat and everything learned about them.

func (*Bridge) EditModule added in v0.148.0

func (b *Bridge) EditModule(ctx context.Context, e ModuleEdit) error

EditModule changes the text, the buttons or both of a message the module sent: editMessageText for new text (keeping the buttons it shows unless new ones are given), editMessageReplyMarkup for buttons alone; then pins or unpins it when Pin says so. A press on new buttons is written to the module's store as one on the first ones. Telegram's "message is not modified" is success. ErrModuleMessage for a bad edit, ErrNotModuleMessage for a message the module did not send, ErrNotPaired without a bot and a chat. /mute all does not hold an edit back: it changes a message already in the chat and makes no sound.

func (*Bridge) Muted

func (b *Bridge) Muted(id string) bool

Muted reports whether a session sends nothing to Telegram.

func (*Bridge) QueuedSent added in v0.137.0

func (b *Bridge) QueuedSent(queued int64)

QueuedSent is the message queue typing a held forward in: its picker says it went.

func (*Bridge) ReplyOnce added in v0.137.0

func (b *Bridge) ReplyOnce(id string)

ReplyOnce asks for a session's next answer in Telegram: the turn a forward started, with Reply here on.

func (*Bridge) Replying added in v0.137.0

func (b *Bridge) Replying(id string) bool

Replying reports a session whose answer goes to Telegram for a forward, or just went: the rules' finished alert about it would say it twice.

func (*Bridge) Run

func (b *Bridge) Run(ctx context.Context)

Run polls and sends until ctx ends.

func (*Bridge) SendModule added in v0.147.0

func (b *Bridge) SendModule(ctx context.Context, m ModuleMessage) (int64, error)

SendModule sends a module's message to the paired chat and returns its Telegram message id. ErrNotPaired without a bot and a chat, ErrMuted under /mute all.

func (*Bridge) SendPhoto added in v0.122.0

func (b *Bridge) SendPhoto(ctx context.Context, png []byte, caption string) error

SendPhoto sends a PNG with a caption to the paired chat, now: a share card the owner chose to send with a click (POST /v1/telegram/photo). It does not go through the outbox — the person is watching the button and wants the outcome, not a queue — and needs only a bot and a chat, not the alerts or the two-way chat switched on.

func (*Bridge) StartPairing

func (b *Bridge) StartPairing() (Pairing, error)

StartPairing makes a new code; the first private chat to send it becomes the bridge's only chat.

func (*Bridge) Status

func (b *Bridge) Status() Status

Status reports the bridge's state.

func (*Bridge) TakeReplyOnce added in v0.137.0

func (b *Bridge) TakeReplyOnce(id string) bool

TakeReplyOnce reports, once, that a session's answer was asked for.

func (*Bridge) Wake

func (b *Bridge) Wake()

Wake makes the bridge re-read its settings now: a token saved, a pairing started, a switch turned. A poll in flight is cut short.

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 press of an inline button.

type Chat

type Chat struct {
	ID        int64  `json:"id"`
	Type      string `json:"type"` // private, group, supergroup, channel
	Title     string `json:"title,omitempty"`
	Username  string `json:"username,omitempty"`
	FirstName string `json:"first_name,omitempty"`
	LastName  string `json:"last_name,omitempty"`
}

Chat is where a message was sent.

func PairAttempt

func PairAttempt(u Update, code string) (chat Chat, ok, match bool)

PairAttempt reads a message as an attempt to pair. ok says it was one at all (code-shaped); match says it carried this code. Only a message — not an edit, a channel post or a button — can pair, and a bot cannot pair itself.

func (Chat) Name

func (c Chat) Name() string

Name is how a chat reads on the Settings screen: a group's title, or a person's name.

type Client

type Client struct {
	Token string
	// Base overrides DefaultBase (tests, preview stands).
	Base string
	// HTTP is the transport; nil uses one with no overall timeout, because
	// each call sets its own deadline (a long poll outlives a send).
	HTTP *http.Client
	// MaxRetryWait overrides maxRetryWait; 0 keeps it, negative never waits.
	MaxRetryWait time.Duration
}

Client calls the Bot API as one bot. The zero value with a Token is usable.

func (*Client) AnswerCallbackQuery

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

AnswerCallbackQuery stops a pressed button's spinner, with an optional toast.

func (*Client) Call

func (c *Client) Call(ctx context.Context, method string, params, out any) error

Call invokes one Bot API method with params as its JSON body and decodes the result into out (which may be nil). A 429 is waited out and retried while Telegram's retry_after fits in the client's limit and ctx allows it.

func (*Client) Download added in v0.137.0

func (c *Client) Download(ctx context.Context, fileID string, limit int64) ([]byte, error)

Download fetches a file someone sent the bot: getFile for its path on Telegram's file server, then the bytes, at most limit of them (a larger file is refused, not cut). The token is in the file URL too, so errors are scrubbed as every other call's are.

func (*Client) EditMarkup

func (c *Client) EditMarkup(ctx context.Context, chatID string, messageID int64, markup *Markup) error

EditMarkup replaces a sent message's buttons — how an answered question shows it was answered, without resending its text. A nil markup removes them all.

func (*Client) EditText added in v0.137.0

func (c *Client) EditText(ctx context.Context, chatID string, messageID int64, text, parseMode string, markup *Markup) error

EditText replaces a sent message's text and buttons; a nil markup removes the buttons.

func (*Client) GetMe

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

GetMe returns the bot the token belongs to — the check that a pasted token is real.

func (*Client) GetUpdates

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

GetUpdates long-polls for up to wait (whole seconds) for updates after offset-1. Updates below offset are confirmed and never returned again.

func (*Client) Pin added in v0.148.0

func (c *Client) Pin(ctx context.Context, chatID string, messageID int64) error

Pin pins a message in the chat without a notification.

func (*Client) React

func (c *Client) React(ctx context.Context, chatID string, messageID int64, emoji string) error

React puts one emoji reaction on a message: how a reply that reached its session says so without another message in the chat.

func (*Client) SendMessage

func (c *Client) SendMessage(ctx context.Context, s Send) (Message, error)

SendMessage posts one message and returns it (its id is what an edit needs).

func (*Client) SendPhoto added in v0.122.0

func (c *Client) SendPhoto(ctx context.Context, chatID string, png []byte, caption string) (Message, error)

SendPhoto posts one PNG with a plain-text caption to a chat (multipart/form-data, as the Bot API takes a file upload). The caption is cut to MaxCaption characters rather than refused.

func (*Client) SetCommands

func (c *Client) SetCommands(ctx context.Context, cmds []Command) error

SetCommands sets the menu Telegram shows under "/" in the bot's chat.

func (*Client) Unpin added in v0.148.0

func (c *Client) Unpin(ctx context.Context, chatID string, messageID int64) error

Unpin unpins one message in the chat, leaving every other pin.

type Command

type Command struct {
	Command     string `json:"command"`
	Description string `json:"description"`
}

Command is one entry of the bot's command menu.

type FileRef added in v0.137.0

type FileRef struct {
	FileID   string `json:"file_id"`
	FileName string `json:"file_name,omitempty"`
	MimeType string `json:"mime_type,omitempty"`
	FileSize int64  `json:"file_size,omitempty"`
	Duration int    `json:"duration,omitempty"`
}

FileRef is a document, voice note, audio or video in a message: what getFile needs to fetch it, and what it says about itself.

type ForceReply

type ForceReply struct {
	ForceReply  bool   `json:"force_reply"`
	Placeholder string `json:"input_field_placeholder,omitempty"`
}

ForceReply opens the reply field on the reader's phone under the message, so answering a session is one tap.

type ForwardOrigin added in v0.137.0

type ForwardOrigin struct {
	Type           string `json:"type"`
	Date           int64  `json:"date,omitempty"`
	SenderUser     *User  `json:"sender_user,omitempty"`
	SenderUserName string `json:"sender_user_name,omitempty"`
	SenderChat     *Chat  `json:"sender_chat,omitempty"`
	Chat           *Chat  `json:"chat,omitempty"`
}

ForwardOrigin is where a forwarded message came from: a person ("user", or "hidden_user" when they hide their account), a chat or a channel.

func (*ForwardOrigin) Name added in v0.137.0

func (o *ForwardOrigin) Name() string

Name is the forwarded message's author as Telegram tells it, or "".

type Host

type Host interface {
	// Bot is the stored token and chat id ("" when not set up).
	Bot() (token, chatID string)
	// SaveBot stores a checked token; SaveChat the paired chat. Empty clears.
	SaveBot(token string) error
	SaveChat(chatID string) error
	// Licensed reports an active licence; ChatOn the two-way switch;
	// AlertsOn whether any alert kind is switched on.
	Licensed() bool
	ChatOn() bool
	AlertsOn() bool

	// Sessions lists the live sessions, newest first.
	Sessions(ctx context.Context) ([]Live, error)
	// Session describes one session; ok false when it is unknown.
	Session(ctx context.Context, id string) (Live, bool)
	// Type types text into a session Caprock started and presses Enter.
	Type(id, text string) error
	// Answer answers the permission prompt promptID the way the app's card
	// does: read off the screen, never a blind digit.
	Answer(id, promptID string, allow bool) error
	// Stop ends a session Caprock started.
	Stop(id string) error
	// Projects lists the owner's projects, for /new.
	Projects(ctx context.Context) ([]Project, error)
	// SpawnMode is the mode new sessions start in ("" for Claude Code's own
	// default).
	SpawnMode() string
	// Start starts Claude Code in dir with a first message, in mode.
	Start(ctx context.Context, dir, prompt, mode string) (string, error)

	// Forward sends a message forwarded from Telegram to a session Caprock
	// started, through the message queue: typed in now (queued 0) or held
	// until the turn ends (queued is its id), marked as from Telegram.
	Forward(ctx context.Context, id, text string) (queued int64, err error)
	// StartChat starts a new chat (no project, ADR-071) in mode with text
	// as its first message.
	StartChat(ctx context.Context, text, mode string) (string, error)
	// Continue carries on a session Caprock ended for sitting idle, with
	// text as its next message (--resume under its own id).
	Continue(ctx context.Context, id, text string) error
	// SaveFile writes a file fetched from Telegram where pasted files go
	// and returns its path; an error when its type is not one Caprock keeps.
	SaveFile(name, mimeType string, data []byte) (string, error)
}

Host is what the bridge needs from the daemon.

type InlineButton

type InlineButton struct {
	Text         string `json:"text"`
	CallbackData string `json:"callback_data,omitempty"`
	URL          string `json:"url,omitempty"`
}

InlineButton is one button under a message: a callback the bridge answers, or a URL Telegram opens.

type Live

type Live struct {
	ID string
	// Header is the session's line in HTML: "🟠 Claude Code · caprock · Fix
	// the cache test".
	Header string
	// Title is the session's name alone, plain, for a reply placeholder.
	Title string
	// Owned is a session Caprock started; Alive that its process runs.
	Owned, Alive bool
	// Waiting says a permission prompt is open.
	Waiting bool
	// State is a word or two: "working", "waiting for approval", "idle".
	State string
	// Working says a turn runs; Chat that it is a chat (ADR-071), not
	// work; LastAt when it last did anything. The forward picker sorts and
	// labels by them.
	Working bool
	Chat    bool
	LastAt  time.Time
	// IdleEnded says Caprock ended it for sitting idle with no tab: a reply
	// continues it rather than being refused.
	IdleEnded bool
}

Live is a session as the bridge shows it.

type Markup

type Markup struct {
	InlineKeyboard [][]InlineButton `json:"inline_keyboard"`
}

Markup is an inline keyboard: rows of buttons.

type Message

type Message struct {
	MessageID int64  `json:"message_id"`
	From      *User  `json:"from,omitempty"`
	Chat      Chat   `json:"chat"`
	Date      int64  `json:"date"`
	Text      string `json:"text,omitempty"`
	// ReplyTo is the message this one answers, when the sender used
	// Telegram's Reply: how a reply finds its session.
	ReplyTo *Message `json:"reply_to_message,omitempty"`

	// What a forwarded or shared message carries (ADR-081): who wrote it
	// first, the caption under a photo or file, the album it belongs to,
	// and its photo (every size, smallest first), file, voice note, audio or
	// video.
	ForwardOrigin *ForwardOrigin `json:"forward_origin,omitempty"`
	Caption       string         `json:"caption,omitempty"`
	MediaGroupID  string         `json:"media_group_id,omitempty"`
	Photo         []PhotoSize    `json:"photo,omitempty"`
	Document      *FileRef       `json:"document,omitempty"`
	Voice         *FileRef       `json:"voice,omitempty"`
	Audio         *FileRef       `json:"audio,omitempty"`
	Video         *FileRef       `json:"video,omitempty"`
}

Message is a received or sent message.

type ModuleButton added in v0.147.0

type ModuleButton struct {
	ID    string `json:"id"`
	Label string `json:"label"`
}

ModuleButton is one button a module puts under its message.

type ModuleEdit added in v0.148.0

type ModuleEdit struct {
	// Module is the module's id; Name what the first line calls it.
	Module, Name string
	MessageID    int64
	Text         *string
	Buttons      *[]ModuleButton
	// Pin true pins the message (unpinning the module's previous pin),
	// false unpins it; nil leaves the pin as it is.
	Pin *bool
}

ModuleEdit is what a module asks to change in a message it sent. Nil leaves a part as it is; a non-nil empty Buttons removes them all.

func (ModuleEdit) Check added in v0.148.0

func (e ModuleEdit) Check() error

Check reports what is wrong with a module's edit, nil when nothing is: the same limits as a message, and at least one part to change.

type ModuleMessage added in v0.147.0

type ModuleMessage struct {
	// Module is the module's id; Name what the first line calls it.
	Module, Name string
	Text         string
	Buttons      []ModuleButton
	// Reply opens the reply field under the message (when it has no
	// buttons; Telegram takes one or the other). A swipe-reply to any
	// module message is the module's either way.
	Reply bool
	// ReplyTo threads the message under one this module sent; 0 is none.
	// Any other message is ErrNotModuleMessage.
	ReplyTo int64
	// Pin pins the message once sent, unpinning the module's previous pin.
	Pin bool
}

ModuleMessage is what a module asks to send.

func (ModuleMessage) Check added in v0.147.0

func (m ModuleMessage) Check() error

Check reports what is wrong with a module message, nil when nothing is.

type Out

type Out struct {
	Text      string
	ParseMode string
	Markup    *Markup
	// ForceReply opens the reply field under the message (used when Markup
	// is nil).
	ForceReply *ForceReply
	ReplyTo    int64
	// Expires drops the message unsent when it would arrive later than this:
	// a "waiting for approval" a minute late is worse than none (ADR-036).
	// Zero never expires.
	Expires time.Time
	// Sent hears the outcome once: the message as Telegram stored it (its id
	// is what a reply and a button refer to), or why it was not sent. Called
	// from the outbox's goroutine; nil is fine.
	Sent func(Message, error)
}

Out is one message waiting to be sent.

type Outbox

type Outbox struct {
	Client func() (*Client, string) // the bot and chat to send to, read per send
	// Gap overrides DefaultGap (tests).
	Gap time.Duration
	Now func() time.Time
	// contains filtered or unexported fields
}

Outbox sends messages to one chat at Telegram's pace. Safe for concurrent use; Run sends.

func NewOutbox

func NewOutbox(client func() (*Client, string)) *Outbox

NewOutbox returns an outbox reading its bot and chat from client.

func (*Outbox) Pending

func (o *Outbox) Pending() int

Pending is how many messages wait.

func (*Outbox) Queue

func (o *Outbox) Queue(m Out)

Queue adds a message behind the ones waiting.

func (*Outbox) Run

func (o *Outbox) Run(ctx context.Context)

Run sends until ctx ends, one message per gap.

func (*Outbox) Send

func (o *Outbox) Send(ctx context.Context, m Out) (Message, error)

Send queues a message and waits for its outcome.

type Pairing

type Pairing struct {
	Code      string `json:"code"`
	Link      string `json:"link,omitempty"`
	ExpiresMs int64  `json:"expires_ms"`
}

Pairing is a pairing in progress, as the Settings screen shows it.

type PhotoSize added in v0.137.0

type PhotoSize struct {
	FileID   string `json:"file_id"`
	Width    int    `json:"width,omitempty"`
	Height   int    `json:"height,omitempty"`
	FileSize int64  `json:"file_size,omitempty"`
}

PhotoSize is one size of a photo; a message carries several.

type PinError added in v0.148.0

type PinError struct {
	MessageID int64
	Err       error
}

PinError is a message sent but not pinned: Telegram refused the pin (the bot may lack the right). MessageID is the message that was sent.

func (*PinError) Error added in v0.148.0

func (e *PinError) Error() string

func (*PinError) Unwrap added in v0.148.0

func (e *PinError) Unwrap() error

type Poller

type Poller struct {
	Client *Client
	// Wait is how long one getUpdates call holds; 0 is 25 seconds.
	Wait time.Duration
	// MinBackoff and MaxBackoff bound the wait after a failure; 0 is 1s and
	// a minute. Offline, the poller retries at the slow end forever.
	MinBackoff, MaxBackoff time.Duration
	// OnError hears every failure (scrubbed of the token), and nil when a
	// call succeeds again, so a screen can show "no network" and clear it.
	OnError func(error)
}

Poller reads updates with getUpdates long polling: the daemon asks Telegram, so nothing on this machine listens for Telegram (rule 4 — loopback only).

func (*Poller) Run

func (p *Poller) Run(ctx context.Context, offset int64, handle func(Update) bool) (int64, error)

Run polls until ctx ends, handle returns true, or the token is refused. It returns the offset after the last update handled, so a later poll does not see the same updates again.

type Project

type Project struct{ Name, Root string }

Project is a folder /new can start in.

type Ref

type Ref struct {
	MessageID int64  `json:"message_id"`
	SessionID string `json:"session_id,omitempty"`
	// PromptID is the permission prompt an Approve or Deny under the message
	// answers; empty when it has no such buttons.
	PromptID string `json:"prompt_id,omitempty"`
	// Kind is what the message is: "alert", "reply", "stop" (a /stop
	// confirmation), "new" (a /new waiting for confirmation), "list".
	Kind string `json:"kind,omitempty"`
	At   int64  `json:"at"`
	// Module is the private module a "module" message came from; Buttons
	// its buttons' labels by id, Order their ids top to bottom; Chosen the
	// button pressed, whose "✓ <label>" the message now shows; Answers how
	// many answers it has had. Kept in telegram.json, so a module may edit
	// or reply under its message after a restart (ADR-076, amended
	// 2026-10-22).
	Module  string            `json:"module,omitempty"`
	Buttons map[string]string `json:"buttons,omitempty"`
	Order   []string          `json:"order,omitempty"`
	Chosen  string            `json:"chosen,omitempty"`
	Answers int               `json:"answers,omitempty"`
}

Ref is what one message the bot sent is about.

type Send

type Send struct {
	ChatID    string `json:"chat_id"`
	Text      string `json:"text"`
	ParseMode string `json:"parse_mode,omitempty"`
	// Markup is the buttons under the message; ForceReply, when Markup is
	// nil, asks for a reply instead. Telegram takes one or the other.
	Markup      *Markup     `json:"-"`
	ForceReply  *ForceReply `json:"-"`
	ReplyMarkup any         `json:"reply_markup,omitempty"`
	// ReplyTo threads a message under the one it answers.
	ReplyTo int64 `json:"reply_to_message_id,omitempty"`
	// Previews are always off: a session link or a URL in a command must not
	// make Telegram fetch it.
	DisablePreview bool `json:"disable_web_page_preview"`
}

Send is a message to send. ParseMode "HTML" means the caller escaped Text.

type State

type State struct {
	// BotID and BotUsername are the bot the stored token belongs to, from
	// getMe; empty until a token was checked.
	BotID       int64  `json:"bot_id,omitempty"`
	BotUsername string `json:"bot_username,omitempty"`
	// ChatName is the paired chat as the Settings screen names it; ChatID is
	// the chat it was read from, so a chat id typed by hand (before pairing
	// existed) is told apart from a paired one.
	ChatName string `json:"chat_name,omitempty"`
	ChatID   string `json:"chat_id,omitempty"`
	PairedAt int64  `json:"paired_at,omitempty"`
	// Offset is the next update to read; everything below it was handled.
	Offset int64 `json:"offset,omitempty"`
	Refs   []Ref `json:"refs,omitempty"`
	// Muted sessions send nothing to Telegram; MuteAll silences every one.
	Muted   map[string]int64 `json:"muted,omitempty"`
	MuteAll bool             `json:"mute_all,omitempty"`
	// PremiumNoteAt is when a reply or command last got the one line that
	// says it is a Premium feature, so it is said at most once a day.
	PremiumNoteAt int64 `json:"premium_note_at,omitempty"`
	// ModulePins is the one message each private module has pinned in the
	// chat, by module id (ADR-076, amended 2026-10-22).
	ModulePins map[string]int64 `json:"module_pins,omitempty"`
	// ForwardReply is the forward picker's *Reply here* switch, as the
	// owner last left it (ADR-081); off until turned on.
	ForwardReply bool `json:"forward_reply,omitempty"`
}

State is the bridge's persisted state.

type Status

type Status struct {
	BotSet      bool   `json:"bot_set"`
	TokenMasked string `json:"token_masked,omitempty"`
	BotUsername string `json:"bot_username,omitempty"`
	ChatSet     bool   `json:"chat_set"`
	// ChatName is the paired chat's name; empty for a chat id typed by hand
	// before pairing existed, which ManualChat then says.
	ChatName   string   `json:"chat_name,omitempty"`
	ManualChat bool     `json:"manual_chat,omitempty"`
	Pairing    *Pairing `json:"pairing,omitempty"`
	Polling    bool     `json:"polling"`
	LastError  string   `json:"last_error,omitempty"`
	MuteAll    bool     `json:"mute_all,omitempty"`
	Muted      int      `json:"muted,omitempty"`
}

Status is what Settings shows about the bridge. Never the token.

type Store

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

Store keeps State in memory and on disk. Safe for concurrent use.

func OpenStore

func OpenStore(dir string) *Store

OpenStore reads dir's state file; a missing or unreadable one is an empty state (the bridge relearns everything it holds).

func (*Store) Get

func (s *Store) Get() State

Get returns a copy of the state.

func (*Store) IsMuted

func (s *Store) IsMuted(sessionID string) bool

IsMuted reports whether a session sends nothing.

func (*Store) Lookup

func (s *Store) Lookup(messageID int64) (Ref, bool)

Lookup finds what a sent message is about.

func (*Store) NextAnswer added in v0.147.0

func (s *Store) NextAnswer(messageID int64) int

NextAnswer counts one more answer to a sent message and returns the count.

func (*Store) Remember

func (s *Store) Remember(r Ref)

Remember records what a sent message is about.

func (*Store) Reset

func (s *Store) Reset() error

Reset forgets everything: a new bot, or the bridge switched off.

func (*Store) Update

func (s *Store) Update(f func(*State)) error

Update changes the state and writes it.

func (*Store) UpdateRef added in v0.148.0

func (s *Store) UpdateRef(messageID int64, f func(*Ref)) bool

UpdateRef changes the latest record of a sent message and writes it; false when no such message is remembered.

type Update

type Update struct {
	UpdateID      int64          `json:"update_id"`
	Message       *Message       `json:"message,omitempty"`
	CallbackQuery *CallbackQuery `json:"callback_query,omitempty"`
}

Update is one item from getUpdates.

type User

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

User is a Telegram account; for getMe, the bot itself.

Directories

Path Synopsis
Package telegramtest is a stand-in for the Telegram Bot API, for tests and preview stands: nothing in the suite ever talks to api.telegram.org.
Package telegramtest is a stand-in for the Telegram Bot API, for tests and preview stands: nothing in the suite ever talks to api.telegram.org.

Jump to

Keyboard shortcuts

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